@firstpick/pi-package-webui 0.6.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -1,7 +1,12 @@
1
+ import { aurReviewSafePath as parsedAurReviewSafePath, parseAurReviewPayload as parseValidatedAurReviewPayload } from "./aur-review-payload.mjs";
2
+ import { guidedGitReviewAvailableForTabCatalog, resolveCommandForTabCatalog, resolveRpcSlashCommandForTabCatalog } from "./guided-git-command-state.mjs";
3
+ import { guidedGitReviewCanRequestStagedContent, guidedGitReviewHasApprovedBinding, guidedGitReviewProcessNavigationAllowed, guidedGitReviewProcessSelectionPatch, guidedGitReviewTransition, guidedGitReviewWidgetRemovalTransition } from "./guided-git-review-state.mjs";
4
+
1
5
  const $ = (selector) => document.querySelector(selector);
2
6
 
3
7
  const elements = {
4
- webuiVersionBadge: $("#webuiVersionBadge"),
8
+ piVersionButton: $("#piVersionButton"),
9
+ webuiVersionButton: $("#webuiVersionButton"),
5
10
  webuiDevBadge: $("#webuiDevBadge"),
6
11
  tabBar: $("#tabBar"),
7
12
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
@@ -256,9 +261,14 @@ const elements = {
256
261
  confirmationSummary: $("#confirmationSummary"),
257
262
  confirmationAffected: $("#confirmationAffected"),
258
263
  confirmationUndo: $("#confirmationUndo"),
259
- confirmationAlternative: $("#confirmationAlternative"),
260
264
  confirmationCancelButton: $("#confirmationCancelButton"),
261
265
  confirmationConfirmButton: $("#confirmationConfirmButton"),
266
+ piReleaseNotesDialog: $("#piReleaseNotesDialog"),
267
+ piReleaseNotesTitle: $("#piReleaseNotesTitle"),
268
+ piReleaseNotesStatus: $("#piReleaseNotesStatus"),
269
+ piReleaseNotesBody: $("#piReleaseNotesBody"),
270
+ piReleaseNotesGithubLink: $("#piReleaseNotesGithubLink"),
271
+ piReleaseNotesCloseButton: $("#piReleaseNotesCloseButton"),
262
272
  dialog: $("#extensionDialog"),
263
273
  dialogTitle: $("#dialogTitle"),
264
274
  dialogMessage: $("#dialogMessage"),
@@ -320,6 +330,8 @@ const elements = {
320
330
  statsOverlayCloseButton: $("#statsOverlayCloseButton"),
321
331
  };
322
332
 
333
+ const PI_WEBUI_NPM_URL = "https://www.npmjs.com/package/@firstpick/pi-package-webui";
334
+
323
335
  let currentState = null;
324
336
  let tabs = [];
325
337
  let activeTabId = null;
@@ -412,6 +424,7 @@ let appRunnerFileBrowserState = { open: false, loading: false, path: "", data: n
412
424
  let optionsMenuOpen = false;
413
425
  let availableCommands = [];
414
426
  let rawAvailableCommands = [];
427
+ const commandCatalogsByTab = new Map();
415
428
  let commandSuggestions = [];
416
429
  let pathSuggestions = [];
417
430
  let bangSuggestions = [];
@@ -443,6 +456,7 @@ let latestRemoteWebuiQrUrl = "";
443
456
  let remoteQrAutoPopupShown = false;
444
457
  let networkStatusLoaded = false;
445
458
  let webuiVersion = "";
459
+ let piVersion = "";
446
460
  let webuiDevServer = false;
447
461
  let latestCodexUsage = null;
448
462
  let codexUsageError = null;
@@ -671,6 +685,10 @@ const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
671
685
  const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
672
686
  const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
673
687
  const WORKFLOW_MODE_RPC_PAYLOAD_VERSION = 1;
688
+ const AUR_REVIEW_RPC_WIDGET_KEY = "aur-review:rpc";
689
+ const AUR_REVIEW_RPC_PAYLOAD_PREFIX = "AUR_REVIEW_RPC_PAYLOAD ";
690
+ const AUR_REVIEW_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-aur-review.review";
691
+ const AUR_REVIEW_RPC_PAYLOAD_VERSION = 3;
674
692
  const GIT_CHANGES_RENDER_ROW_LIMIT = 4000;
675
693
  const GIT_PULL_RESULT_FILE_LIMIT = 48;
676
694
  const LAST_USER_PROMPT_STORAGE_KEY = "pi-webui-last-user-prompts";
@@ -792,6 +810,7 @@ const optionalFeatureAvailability = {
792
810
  gitWorkflow: false,
793
811
  releaseNpm: false,
794
812
  releaseAur: false,
813
+ aurReview: false,
795
814
  workflows: false,
796
815
  safetyGuard: false,
797
816
  statsCommand: false,
@@ -848,6 +867,13 @@ const OPTIONAL_FEATURES = [
848
867
  capabilityLabel: "/release-aur",
849
868
  description: "Publish menu action, setup helpers, skills, and AUR release widgets.",
850
869
  },
870
+ {
871
+ id: "aurReview",
872
+ label: "Manual repository review",
873
+ packageName: "@firstpick/pi-extension-aur-review",
874
+ capabilityLabel: "/aur-review or aur-review:rpc widget event",
875
+ description: "Manual repository/Git review bound to an exact working-tree or staged snapshot.",
876
+ },
851
877
  {
852
878
  id: "workflows",
853
879
  label: "Workflows",
@@ -931,7 +957,7 @@ const OPTIONAL_FEATURE_SECTIONS = [
931
957
  id: "workflows-releases",
932
958
  label: "Workflows & releases",
933
959
  description: "Guided workflows, task runners, and publishing actions with visible execution state.",
934
- featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur"],
960
+ featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur", "aurReview"],
935
961
  },
936
962
  {
937
963
  id: "safety-access",
@@ -964,6 +990,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
964
990
  ["pr", "gitWorkflow"],
965
991
  ["release-npm", "releaseNpm"],
966
992
  ["release-aur", "releaseAur"],
993
+ ["aur-review", "aurReview"],
967
994
  ["workflow", "workflows"],
968
995
  ["workflow-clear", "workflows"],
969
996
  ["safety-guard", "safetyGuard"],
@@ -1049,6 +1076,17 @@ function resetGitWorkflowManualCommitDefaultPatch() {
1049
1076
  };
1050
1077
  }
1051
1078
 
1079
+ function resetGuidedGitReviewPatch({ retainDeclinedStagedContentHash = true } = {}) {
1080
+ return {
1081
+ guidedReviewStatus: "",
1082
+ guidedReviewFingerprint: "",
1083
+ guidedReviewRepoRoot: "",
1084
+ guidedReviewStagedContentHash: "",
1085
+ guidedReviewRequestedAt: 0,
1086
+ ...(retainDeclinedStagedContentHash ? {} : { guidedReviewDeclinedStagedContentHash: "" }),
1087
+ };
1088
+ }
1089
+
1052
1090
  function gitWorkflowManualCommitInputMessage(workflow) {
1053
1091
  return String(workflow?.manualCommitMessage || "").trim() || String(workflow?.manualCommitMessageDefault || "").trim();
1054
1092
  }
@@ -1081,6 +1119,8 @@ function createGitWorkflowState() {
1081
1119
  prBranch: "",
1082
1120
  pr: null,
1083
1121
  prRequestedAt: 0,
1122
+ ...resetGuidedGitReviewPatch({ retainDeclinedStagedContentHash: false }),
1123
+ guidedReviewRequired: false,
1084
1124
  preferences: null,
1085
1125
  verificationConfirmed: false,
1086
1126
  };
@@ -1129,6 +1169,7 @@ function clearGitWorkflowForTab(tabId) {
1129
1169
 
1130
1170
  const GIT_WORKFLOW_PROCESSES = [
1131
1171
  { value: "stage", label: "Stage" },
1172
+ { value: "review", label: "Review" },
1132
1173
  { value: "message", label: "Message" },
1133
1174
  { value: "commit", label: "Commit" },
1134
1175
  { value: "push", label: "Push" },
@@ -1152,18 +1193,20 @@ const ACTION_FEEDBACK_REACTIONS = {
1152
1193
  const ACTION_FEEDBACK_SNIPPET_LIMIT = 1200;
1153
1194
  const GIT_WORKFLOW_ACTIVE_INDEX = {
1154
1195
  add: 0,
1155
- generate: 1,
1156
- generating: 1,
1157
- message: 2,
1158
- branchNaming: 2,
1159
- branching: 2,
1160
- committing: 2,
1161
- push: 3,
1162
- pushing: 3,
1163
- prGenerating: 3,
1164
- prReview: 3,
1165
- prCreating: 3,
1166
- done: 4,
1196
+ reviewRequesting: 1,
1197
+ review: 1,
1198
+ generate: 2,
1199
+ generating: 2,
1200
+ message: 3,
1201
+ branchNaming: 3,
1202
+ branching: 3,
1203
+ committing: 3,
1204
+ push: 4,
1205
+ pushing: 4,
1206
+ prGenerating: 4,
1207
+ prReview: 4,
1208
+ prCreating: 4,
1209
+ done: 5,
1167
1210
  };
1168
1211
  const GIT_INIT_WORKFLOW_ACTIVE_INDEX = {
1169
1212
  initSetup: 0,
@@ -1621,7 +1664,7 @@ function terminalTabsLayoutStatusText(layout = terminalTabsLayout) {
1621
1664
  function renderTerminalTabsLayoutControl() {
1622
1665
  const layout = normalizeTerminalTabsLayout(terminalTabsLayout);
1623
1666
  if (elements.terminalTabsLayoutSelect) elements.terminalTabsLayoutSelect.value = layout;
1624
- if (elements.terminalTabsLayoutStatus) elements.terminalTabsLayoutStatus.textContent = terminalTabsLayoutStatusText(layout);
1667
+ if (elements.terminalTabsLayoutStatus) elements.terminalTabsLayoutStatus.textContent = `${terminalTabsLayoutStatusText(layout)} · saved in this browser`;
1625
1668
  }
1626
1669
 
1627
1670
  function setTerminalTabsLayout(layout, { persist = true, announce = false } = {}) {
@@ -1897,6 +1940,7 @@ function setThinkingOutputVisible(visible, { announce = false } = {}) {
1897
1940
  renderThinkingVisibilityToggle();
1898
1941
  if (!thinkingOutputVisible) removeStreamingThinkingBubble();
1899
1942
  renderAllMessages({ preserveScroll: true });
1943
+ if (subagentOverlaySelection?.tabId === activeTabId) renderWidgets();
1900
1944
  if (announce) addEvent(thinkingOutputVisible ? "thinking output shown" : "thinking output hidden", thinkingOutputVisible ? "info" : "warn");
1901
1945
  }
1902
1946
 
@@ -2686,16 +2730,15 @@ function finishApplicationConfirmation(confirmed) {
2686
2730
  resolve?.(!!confirmed);
2687
2731
  }
2688
2732
 
2689
- function appConfirm({ title = "Confirm action", summary = "Continue?", affected = "The selected item", undoable = false, alternative = "Cancel and review the action first.", confirmLabel = "Continue", danger = true } = {}) {
2733
+ function appConfirm({ title = "Confirm action", summary = "Continue?", affected = "The selected item", undoable = false, confirmLabel = "Continue", danger = true } = {}) {
2690
2734
  if (!elements.confirmationDialog?.showModal) {
2691
- return Promise.resolve(window.confirm([title, summary, affected, undoable ? "This can be undone." : "This cannot be undone.", alternative].filter(Boolean).join("\n\n")));
2735
+ return Promise.resolve(window.confirm([title, summary, affected, undoable ? "This can be undone." : "This cannot be undone."].filter(Boolean).join("\n\n")));
2692
2736
  }
2693
2737
  if (activeConfirmationResolve) finishApplicationConfirmation(false);
2694
2738
  elements.confirmationTitle.textContent = title;
2695
2739
  elements.confirmationSummary.textContent = summary;
2696
2740
  elements.confirmationAffected.textContent = affected;
2697
2741
  elements.confirmationUndo.textContent = undoable ? "This action can be undone." : "This action cannot be undone.";
2698
- elements.confirmationAlternative.textContent = alternative;
2699
2742
  elements.confirmationConfirmButton.textContent = confirmLabel;
2700
2743
  elements.confirmationConfirmButton.classList.toggle("danger", danger);
2701
2744
  elements.confirmationConfirmButton.classList.toggle("primary", !danger);
@@ -2714,7 +2757,6 @@ function appConfirmText(message, options = {}) {
2714
2757
  summary: options.summary || rest.join("\n").trim() || firstLine || "Continue?",
2715
2758
  affected: options.affected || "The current workspace, session, or server state described above",
2716
2759
  undoable: options.undoable === true,
2717
- alternative: options.alternative || "Cancel and review the affected state before continuing.",
2718
2760
  confirmLabel: options.confirmLabel || "Continue",
2719
2761
  danger: options.danger !== false,
2720
2762
  });
@@ -3449,27 +3491,51 @@ function isWebuiDevMetadata(data) {
3449
3491
  return data?.webuiDev === true || String(data?.webuiMode || "").toLowerCase() === "dev";
3450
3492
  }
3451
3493
 
3452
- function renderWebuiVersion() {
3453
- const badge = elements.webuiVersionBadge;
3454
- if (!badge) return;
3494
+ function renderPiVersionButton() {
3495
+ const button = elements.piVersionButton;
3496
+ if (!button) return;
3497
+ const label = formatWebuiVersion(piVersion);
3498
+ button.hidden = !label;
3499
+ button.textContent = label ? `Pi ${label}` : "";
3500
+ if (label) {
3501
+ button.title = `View Pi ${label} release notes`;
3502
+ button.setAttribute("aria-label", `View Pi ${label} release notes`);
3503
+ }
3504
+ }
3505
+
3506
+ function renderWebuiVersionButton() {
3507
+ const button = elements.webuiVersionButton;
3508
+ if (!button) return;
3455
3509
  const label = formatWebuiVersion(webuiVersion);
3456
- badge.hidden = !label;
3457
- badge.textContent = label;
3458
- if (label) badge.title = `Pi Web UI ${label}`;
3510
+ button.hidden = !label;
3511
+ button.textContent = label ? `Web UI ${label}` : "";
3512
+ if (label) {
3513
+ button.title = `Open Pi Web UI ${label} on npm`;
3514
+ button.setAttribute("aria-label", `Open Pi Web UI ${label} package page`);
3515
+ }
3459
3516
  }
3460
3517
 
3461
3518
  function renderWebuiDevBadge() {
3462
3519
  const badge = elements.webuiDevBadge;
3463
3520
  if (!badge) return;
3464
3521
  badge.hidden = !webuiDevServer;
3465
- badge.title = "Pi Web UI dev server";
3522
+ const version = formatWebuiVersion(webuiVersion);
3523
+ badge.title = `Pi Web UI${version ? ` ${version}` : ""} dev server`;
3466
3524
  }
3467
3525
 
3468
3526
  function setWebuiVersion(version) {
3469
3527
  const text = String(version || "").trim();
3470
3528
  if (text === webuiVersion) return;
3471
3529
  webuiVersion = text;
3472
- renderWebuiVersion();
3530
+ renderWebuiVersionButton();
3531
+ renderWebuiDevBadge();
3532
+ }
3533
+
3534
+ function setPiVersion(version) {
3535
+ const text = String(version || "").trim().replace(/^v/i, "");
3536
+ if (text === piVersion) return;
3537
+ piVersion = text;
3538
+ renderPiVersionButton();
3473
3539
  }
3474
3540
 
3475
3541
  function setWebuiDevServer(dev) {
@@ -3479,9 +3545,90 @@ function setWebuiDevServer(dev) {
3479
3545
  renderWebuiDevBadge();
3480
3546
  }
3481
3547
 
3548
+ function piReleasePageUrl(version = piVersion) {
3549
+ const cleanVersion = String(version || "").trim().replace(/^v/i, "");
3550
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(cleanVersion)) return "";
3551
+ return `https://github.com/earendil-works/pi/releases/tag/v${encodeURIComponent(cleanVersion)}`;
3552
+ }
3553
+
3554
+ function formatPiReleaseDate(value) {
3555
+ const date = new Date(value);
3556
+ if (!value || Number.isNaN(date.getTime())) return "";
3557
+ return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(date);
3558
+ }
3559
+
3560
+ function setPiReleaseNotesLink(value) {
3561
+ const link = elements.piReleaseNotesGithubLink;
3562
+ if (!link) return;
3563
+ const href = safeHttpUrl(value);
3564
+ link.hidden = !href;
3565
+ if (href) link.href = href;
3566
+ else link.removeAttribute("href");
3567
+ }
3568
+
3569
+ function openWebuiNpmPageInNewTab() {
3570
+ const href = safeHttpUrl(PI_WEBUI_NPM_URL);
3571
+ if (!href) return false;
3572
+ const anchor = document.createElement("a");
3573
+ anchor.href = href;
3574
+ anchor.target = "_blank";
3575
+ anchor.rel = "noopener noreferrer";
3576
+ anchor.hidden = true;
3577
+ document.body.append(anchor);
3578
+ anchor.click();
3579
+ anchor.remove();
3580
+ return true;
3581
+ }
3582
+
3583
+ async function confirmOpenWebuiNpmPage() {
3584
+ const confirmed = await appConfirm({
3585
+ title: "Open npm package page?",
3586
+ summary: "Open @firstpick/pi-package-webui on npm in a new browser tab?",
3587
+ affected: "A new tab will open to the public Pi Web UI package page.",
3588
+ undoable: true,
3589
+ confirmLabel: "Open npm",
3590
+ danger: false,
3591
+ });
3592
+ if (!confirmed) return;
3593
+ if (!openWebuiNpmPageInNewTab()) addEvent("Pi Web UI npm package URL is unavailable", "error");
3594
+ }
3595
+
3596
+ async function openPiReleaseNotes() {
3597
+ const dialog = elements.piReleaseNotesDialog;
3598
+ if (!dialog) return;
3599
+ const requestedVersion = piVersion;
3600
+ const label = formatWebuiVersion(requestedVersion);
3601
+ elements.piReleaseNotesTitle.textContent = label ? `Pi ${label} release notes` : "Pi release notes";
3602
+ elements.piReleaseNotesStatus.textContent = "Loading release notes from GitHub…";
3603
+ elements.piReleaseNotesBody.setAttribute("aria-busy", "true");
3604
+ elements.piReleaseNotesBody.replaceChildren(make("p", "muted", "Loading…"));
3605
+ setPiReleaseNotesLink(piReleasePageUrl(requestedVersion));
3606
+ if (!dialog.open) dialog.showModal();
3607
+
3608
+ try {
3609
+ const response = await api("/api/pi-release-notes", { scoped: false });
3610
+ if (requestedVersion !== piVersion) return;
3611
+ const release = response.data || {};
3612
+ const releaseVersion = String(release.version || "").trim().replace(/^v/i, "");
3613
+ if (requestedVersion && releaseVersion !== requestedVersion) throw new Error(`Expected Pi ${formatWebuiVersion(requestedVersion)} release notes but received ${formatWebuiVersion(releaseVersion) || "an unknown version"}`);
3614
+ const releaseLabel = formatWebuiVersion(releaseVersion || requestedVersion);
3615
+ elements.piReleaseNotesTitle.textContent = releaseLabel ? `Pi ${releaseLabel} release notes` : (release.title || "Pi release notes");
3616
+ renderMarkdown(elements.piReleaseNotesBody, release.body || "No release notes were provided for this release.");
3617
+ const published = formatPiReleaseDate(release.publishedAt);
3618
+ elements.piReleaseNotesStatus.textContent = `${published ? `Published ${published}` : "Loaded from GitHub"}${release.truncated ? " · Long notes were truncated" : ""}`;
3619
+ setPiReleaseNotesLink(release.url || piReleasePageUrl(release.version));
3620
+ } catch (error) {
3621
+ elements.piReleaseNotesStatus.textContent = "Release notes could not be loaded.";
3622
+ elements.piReleaseNotesBody.replaceChildren(make("p", "pi-release-notes-error", error.message || String(error)));
3623
+ } finally {
3624
+ elements.piReleaseNotesBody.removeAttribute("aria-busy");
3625
+ }
3626
+ }
3627
+
3482
3628
  async function refreshWebuiVersion() {
3483
3629
  const health = await api("/api/health", { scoped: false });
3484
3630
  setWebuiVersion(health.webuiVersion);
3631
+ setPiVersion(health.piVersion);
3485
3632
  setWebuiDevServer(isWebuiDevMetadata(health));
3486
3633
  }
3487
3634
 
@@ -4308,7 +4455,7 @@ function renderBackgroundControl() {
4308
4455
  : `${themeLabel}: theme default`;
4309
4456
  if (elements.backgroundChooseButton) {
4310
4457
  elements.backgroundChooseButton.disabled = customBackgroundLoading;
4311
- elements.backgroundChooseButton.textContent = active ? "Change background" : "Add background";
4458
+ elements.backgroundChooseButton.textContent = active ? "Change image" : "Choose image";
4312
4459
  }
4313
4460
  if (elements.backgroundInput) elements.backgroundInput.disabled = customBackgroundLoading;
4314
4461
  if (elements.backgroundClearButton) {
@@ -6711,7 +6858,6 @@ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6711
6858
  summary: `${sourcePath}${recursiveWarning}${dirtyWarning}`,
6712
6859
  affected: typeLabel === "directory" ? "The directory and all files beneath it" : sourcePath,
6713
6860
  undoable: false,
6714
- alternative: "Cancel and move or rename it instead.",
6715
6861
  confirmLabel: `Delete ${typeLabel}`,
6716
6862
  }))) return;
6717
6863
  const tabContext = activeTabContext();
@@ -6965,7 +7111,7 @@ function setFileViewerMode(mode = "source") {
6965
7111
  }
6966
7112
 
6967
7113
  function setFileViewerDirty(dirty) {
6968
- if (!activeFileViewer) return;
7114
+ if (!activeFileViewer || activeFileViewer.readOnly) return;
6969
7115
  activeFileViewer.dirty = !!dirty;
6970
7116
  if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = !activeFileViewer.dirty;
6971
7117
  if (activeFileViewer.dirty) setFileViewerStatus("Unsaved file edits.", "warn");
@@ -6999,17 +7145,18 @@ function updateFileViewerUi() {
6999
7145
  }
7000
7146
  if (elements.fileViewerEditor) {
7001
7147
  elements.fileViewerEditor.hidden = mode !== "source";
7148
+ elements.fileViewerEditor.readOnly = viewer.readOnly === true;
7002
7149
  if (elements.fileViewerEditor.value !== viewer.content) elements.fileViewerEditor.value = viewer.content || "";
7003
7150
  }
7004
7151
  if (elements.fileViewerPreview) {
7005
7152
  elements.fileViewerPreview.hidden = mode !== "preview";
7006
7153
  if (mode === "preview") renderMarkdown(elements.fileViewerPreview, viewer.content || "");
7007
7154
  }
7008
- if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = !viewer.dirty;
7155
+ if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = viewer.readOnly === true || !viewer.dirty;
7009
7156
  if (elements.fileViewerOpenDefaultButton) {
7010
7157
  const viewerPath = normalizeFileTreePath(viewer.path || "");
7011
7158
  elements.fileViewerOpenDefaultButton.dataset.path = viewerPath;
7012
- elements.fileViewerOpenDefaultButton.disabled = !viewerPath;
7159
+ elements.fileViewerOpenDefaultButton.disabled = viewer.readOnly === true || !viewerPath;
7013
7160
  }
7014
7161
  renderFileViewerSelectionBar();
7015
7162
  }
@@ -7141,7 +7288,10 @@ function closeFileViewer() {
7141
7288
  updateFileViewerResizeHandle();
7142
7289
  if (elements.fileViewerPane) elements.fileViewerPane.hidden = true;
7143
7290
  if (elements.fileViewerOpenDefaultButton) elements.fileViewerOpenDefaultButton.dataset.path = "";
7144
- if (elements.fileViewerEditor) elements.fileViewerEditor.value = "";
7291
+ if (elements.fileViewerEditor) {
7292
+ elements.fileViewerEditor.value = "";
7293
+ elements.fileViewerEditor.readOnly = false;
7294
+ }
7145
7295
  if (elements.fileViewerPreview) elements.fileViewerPreview.replaceChildren();
7146
7296
  setFileViewerStatus("");
7147
7297
  }
@@ -7167,6 +7317,7 @@ async function openFileInViewer(path = "") {
7167
7317
  language: data.language || "text",
7168
7318
  mode: data.language === "markdown" ? "preview" : "source",
7169
7319
  dirty: false,
7320
+ readOnly: false,
7170
7321
  };
7171
7322
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
7172
7323
  clearFileViewerSelection();
@@ -7180,8 +7331,47 @@ async function openFileInViewer(path = "") {
7180
7331
  }
7181
7332
  }
7182
7333
 
7334
+ async function openAurReviewReportInViewer(path = "", repoRoot = "") {
7335
+ const normalized = aurReviewSafePath(path);
7336
+ const expectedRepoRoot = String(repoRoot || "");
7337
+ if (!normalized || !expectedRepoRoot) return;
7338
+ const tabContext = activeTabContext();
7339
+ setFileViewerStatus(`Opening ${normalized}…`);
7340
+ try {
7341
+ const params = new URLSearchParams({ path: normalized, repoRoot: expectedRepoRoot });
7342
+ const response = await api(`/api/aur-review/report-content?${params.toString()}`, { tabId: tabContext.tabId });
7343
+ if (!isCurrentTabContext(tabContext)) return;
7344
+ const data = response.data || {};
7345
+ activeFileViewer = {
7346
+ path: normalizeFileTreePath(data.path || normalized),
7347
+ name: data.name || fileDisplayName(normalized),
7348
+ content: String(data.content || ""),
7349
+ size: Number(data.size) || 0,
7350
+ mtimeMs: Number(data.mtimeMs) || 0,
7351
+ extension: data.extension || "",
7352
+ language: data.language || "text",
7353
+ mode: data.language === "markdown" ? "preview" : "source",
7354
+ dirty: false,
7355
+ readOnly: true,
7356
+ };
7357
+ if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
7358
+ clearFileViewerSelection();
7359
+ updateFileViewerUi();
7360
+ setFileViewerStatus("Report opened in WebUI (read-only).", "success");
7361
+ } catch (error) {
7362
+ if (isCurrentTabContext(tabContext)) {
7363
+ setFileViewerStatus(error.message || String(error), "error");
7364
+ addEvent(`review report open failed: ${error.message || String(error)}`, "error");
7365
+ }
7366
+ }
7367
+ }
7368
+
7183
7369
  async function saveActiveFileViewer() {
7184
7370
  if (!activeFileViewer || !elements.fileViewerEditor) return;
7371
+ if (activeFileViewer.readOnly) {
7372
+ setFileViewerStatus("This report is read-only.", "info");
7373
+ return;
7374
+ }
7185
7375
  const tabContext = activeTabContext();
7186
7376
  const content = elements.fileViewerEditor.value || "";
7187
7377
  if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = true;
@@ -7284,6 +7474,7 @@ function syncTabMetadata(nextTabs = []) {
7284
7474
  remoteMicConsentTabs.delete(tabId);
7285
7475
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
7286
7476
  clearGitWorkflowForTab(tabId);
7477
+ commandCatalogsByTab.delete(tabId);
7287
7478
  }
7288
7479
  }
7289
7480
  for (const tabId of tabMessagesCache.keys()) {
@@ -7688,8 +7879,9 @@ function resetActiveTabUi() {
7688
7879
  transientMessages = [];
7689
7880
  liveToolRuns.clear();
7690
7881
  liveToolCards.clear();
7691
- availableCommands = [];
7692
- rawAvailableCommands = [];
7882
+ const commandCatalog = commandCatalogsByTab.get(activeTabId);
7883
+ availableCommands = commandCatalog?.available || [];
7884
+ rawAvailableCommands = commandCatalog?.raw || [];
7693
7885
  resetOptionalFeatureAvailability();
7694
7886
  commandSuggestions = [];
7695
7887
  pathSuggestions = [];
@@ -8363,11 +8555,6 @@ async function confirmCloseTerminalTabs(targetTabs, label) {
8363
8555
  summary: `${base}\n\n${warning}`,
8364
8556
  affected: tabList || label || `${count} terminal ${noun}`,
8365
8557
  undoable: false,
8366
- alternative: activeAgentTabs.length
8367
- ? "Cancel and wait for or abort the running work first."
8368
- : count === 1
8369
- ? "Cancel and keep this tab open."
8370
- : "Cancel and close individual tabs instead.",
8371
8558
  confirmLabel: activeAgentTabs.length ? "Close and stop work" : count === 1 ? "Close tab" : "Close tabs",
8372
8559
  });
8373
8560
  }
@@ -8390,6 +8577,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
8390
8577
  tabDrafts.delete(id);
8391
8578
  clearAttachments(id);
8392
8579
  clearGitWorkflowForTab(id);
8580
+ commandCatalogsByTab.delete(id);
8393
8581
  appRunnerDataByTab.delete(id);
8394
8582
  tabMessagesCache.delete(id);
8395
8583
  btwWidgetDismissedIdsByTab.delete(id);
@@ -9659,7 +9847,7 @@ function renderGitFooterVisibilityDialog() {
9659
9847
  if (!gitFooterVisibilityDirty) {
9660
9848
  setGitFooterVisibilityStatus(
9661
9849
  gitFooterVisibilityCommandAvailable()
9662
- ? "Runtime changes last until Pi/package restart. Use PI_GIT_FOOTER_WEBUI_HIDE or per-key env vars for persistence."
9850
+ ? "Changes are saved globally and reused by every Pi session. Reset WebUI removes the saved WebUI overrides."
9663
9851
  : commandUnavailableMessage("git-footer-visibility"),
9664
9852
  gitFooterVisibilityCommandAvailable() ? "muted" : "warn",
9665
9853
  );
@@ -9706,7 +9894,7 @@ async function applyGitFooterVisibilityDialog() {
9706
9894
  if (hide.length) await runGitFooterVisibilityCommand("hide", hide);
9707
9895
  if (show.length) await runGitFooterVisibilityCommand("show", show);
9708
9896
  gitFooterVisibilityDirty = false;
9709
- setGitFooterVisibilityStatus(`Applied ${hide.length + show.length} WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9897
+ setGitFooterVisibilityStatus(`Saved ${hide.length + show.length} global WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9710
9898
  requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9711
9899
  renderFooter();
9712
9900
  } catch (error) {
@@ -9723,7 +9911,7 @@ async function resetGitFooterVisibilityDialog() {
9723
9911
  try {
9724
9912
  await runGitFooterVisibilityCommand("reset");
9725
9913
  gitFooterVisibilityDirty = false;
9726
- setGitFooterVisibilityStatus("Reset WebUI footer visibility overrides.", "success");
9914
+ setGitFooterVisibilityStatus("Removed the saved global WebUI footer visibility overrides.", "success");
9727
9915
  requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9728
9916
  } catch (error) {
9729
9917
  setGitFooterVisibilityStatus(error.message || String(error), "error");
@@ -14147,8 +14335,62 @@ function subagentRunElapsed(run) {
14147
14335
  return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
14148
14336
  }
14149
14337
 
14338
+ function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
14339
+ const agent = data?.agent || subagentOverlaySelection?.agent || {};
14340
+ return (Array.isArray(agent.transcript) ? agent.transcript : [])
14341
+ .filter((message) => message && (message.role === "assistant" || message.role === "toolResult"));
14342
+ }
14343
+
14344
+ function subagentOverlayToolArguments(value) {
14345
+ if (typeof value !== "string") return value;
14346
+ try {
14347
+ const parsed = JSON.parse(value);
14348
+ return parsed && typeof parsed === "object" ? parsed : value;
14349
+ } catch {
14350
+ return value;
14351
+ }
14352
+ }
14353
+
14354
+ function subagentOverlayTranscriptDisplayMessages(messages, { includeThinking = thinkingOutputVisible } = {}) {
14355
+ const toolResults = buildToolResultMap(messages);
14356
+ const pairedToolCallIds = buildAssistantToolCallIdSet(messages);
14357
+ const displayMessages = [];
14358
+ for (const message of messages) {
14359
+ if (message.role === "toolResult") {
14360
+ if (pairedToolCallIds.has(toolResultCallId(message))) continue;
14361
+ displayMessages.push(message);
14362
+ continue;
14363
+ }
14364
+ for (const displayMessage of assistantDisplayMessages(message)) {
14365
+ if (displayMessage.role === "thinking" && !includeThinking) continue;
14366
+ if (displayMessage.role === "toolCall" && displayMessage.toolCallId) {
14367
+ const result = toolResults.get(displayMessage.toolCallId) || null;
14368
+ displayMessages.push({
14369
+ ...displayMessage,
14370
+ role: "toolExecution",
14371
+ title: `tool: ${displayMessage.toolName || "unknown"}`,
14372
+ arguments: subagentOverlayToolArguments(displayMessage.arguments),
14373
+ result,
14374
+ isError: !!result?.isError,
14375
+ });
14376
+ } else {
14377
+ displayMessages.push(displayMessage);
14378
+ }
14379
+ }
14380
+ }
14381
+ return displayMessages;
14382
+ }
14383
+
14384
+ function subagentOverlayTranscriptOutputLines(data = subagentOverlayData) {
14385
+ return subagentOverlayTranscriptDisplayMessages(subagentOverlayTranscriptMessages(data)).flatMap((message) => stripAnsi(
14386
+ messageCopyText(message),
14387
+ ).replace(/\r/g, "").split("\n"));
14388
+ }
14389
+
14150
14390
  function subagentOverlayOutputLines(data = subagentOverlayData) {
14151
14391
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
14392
+ const transcriptMessages = subagentOverlayTranscriptMessages(data);
14393
+ if (transcriptMessages.length) return subagentOverlayTranscriptOutputLines(data);
14152
14394
  const output = (Array.isArray(agent.recentOutput) ? agent.recentOutput : [])
14153
14395
  .flatMap((line) => stripAnsi(String(line ?? "")).replace(/\r/g, "").split("\n"));
14154
14396
  if (output.length) return output;
@@ -14158,16 +14400,43 @@ function subagentOverlayOutputLines(data = subagentOverlayData) {
14158
14400
  return tools;
14159
14401
  }
14160
14402
 
14403
+ function subagentOverlayOutputText(data = subagentOverlayData) {
14404
+ return subagentOverlayOutputLines(data).join("\n").trimEnd();
14405
+ }
14406
+
14407
+ function subagentOverlayEmptyTranscriptText(messages) {
14408
+ const hasThinking = messages.some((message) => message.role === "assistant" && assistantDisplayMessages(message)
14409
+ .some((displayMessage) => displayMessage.role === "thinking"));
14410
+ return hasThinking && !thinkingOutputVisible
14411
+ ? "Thinking output is hidden. Enable thinking output to view the captured transcript."
14412
+ : "No visible output was captured.";
14413
+ }
14414
+
14161
14415
  function appendSubagentOutputWaitingIndicator(parent) {
14162
- const row = make("div", "release-npm-line subagent-output-waiting");
14163
- row.setAttribute("role", "status");
14164
- row.setAttribute("aria-label", "Waiting for agent output");
14416
+ const bubble = make("article", "message runIndicator run-indicator-message streaming subagent-output-waiting");
14417
+ bubble.setAttribute("role", "status");
14418
+ bubble.setAttribute("aria-label", "Waiting for agent output");
14419
+ const body = make("div", "message-body");
14420
+ const row = make("div", "run-indicator-row");
14165
14421
  row.append(
14166
14422
  make("span", "subagent-output-waiting-dot", "."),
14167
14423
  make("span", "subagent-output-waiting-dot", "."),
14168
14424
  make("span", "subagent-output-waiting-dot", "."),
14169
14425
  );
14170
- parent.append(row);
14426
+ body.append(row);
14427
+ bubble.append(body);
14428
+ parent.append(bubble);
14429
+ }
14430
+
14431
+ function appendSubagentOverlayTranscript(parent, messages) {
14432
+ let rendered = 0;
14433
+ for (const displayMessage of subagentOverlayTranscriptDisplayMessages(messages)) {
14434
+ const { bubble } = createMessageBubble(displayMessage, { transient: true });
14435
+ bubble.classList.add("subagent-overlay-message");
14436
+ parent.append(bubble);
14437
+ rendered += 1;
14438
+ }
14439
+ return rendered;
14171
14440
  }
14172
14441
 
14173
14442
  function subagentOverlayStateFacts(data = subagentOverlayData) {
@@ -14197,6 +14466,33 @@ function subagentOverlayMeaningfulSignature() {
14197
14466
  });
14198
14467
  }
14199
14468
 
14469
+ function renderSubagentOverlayErrorWidget() {
14470
+ const widget = make("section", "widget release-npm-widget app-runner-widget subagent-overlay-widget app-runner-log-widget");
14471
+ widget.setAttribute("aria-label", "Subagent output rendering error");
14472
+ const header = make("div", "release-npm-header");
14473
+ const titleWrap = make("div", "release-npm-title-wrap");
14474
+ titleWrap.append(make("strong", "release-npm-title", "Subagent output unavailable"));
14475
+ header.append(titleWrap);
14476
+ const body = make("div", "message-body");
14477
+ appendText(body, "The live subagent output could not be rendered. Close this panel and reopen it to retry.");
14478
+ const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
14479
+ const actions = make("div", "app-runner-output-actions");
14480
+ actions.append(appRunnerActionButton("Close", closeSubagentOverlay, "subagent-overlay-close-action"));
14481
+ controls.append(actions);
14482
+ widget.append(header, body, controls);
14483
+ return widget;
14484
+ }
14485
+
14486
+ function renderSubagentOverlayWidgetSafely() {
14487
+ try {
14488
+ return renderSubagentOverlayWidget();
14489
+ } catch {
14490
+ // Keep a faulty child transcript from preventing all other widgets from
14491
+ // rendering. The recoverable panel below replaces repeated event logging.
14492
+ return renderSubagentOverlayErrorWidget();
14493
+ }
14494
+ }
14495
+
14200
14496
  function renderSubagentOverlayWidget() {
14201
14497
  const selection = subagentOverlaySelection;
14202
14498
  if (!selection || selection.tabId !== activeTabId) return null;
@@ -14204,8 +14500,11 @@ function renderSubagentOverlayWidget() {
14204
14500
  const agent = data?.agent || selection.agent || {};
14205
14501
  const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
14206
14502
  const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
14207
- const lines = subagentOverlayOutputLines(data);
14208
- const shownLines = lines.length ? lines : running && agent.currentTool ? [] : [running ? "Waiting for the first agent activity…" : "No recent output was captured."];
14503
+ const transcriptMessages = subagentOverlayTranscriptMessages(data);
14504
+ const hasStructuredTranscript = transcriptMessages.length > 0;
14505
+ const outputText = subagentOverlayOutputText(data);
14506
+ const fallbackText = outputText || (running && agent.currentTool ? "" : running ? "Waiting for the first agent activity…" : "No recent output was captured.");
14507
+ const shownLineCount = outputText ? outputText.split("\n").length : fallbackText ? fallbackText.split("\n").length : 0;
14209
14508
  const widget = make("section", `widget release-npm-widget app-runner-widget subagent-overlay-widget${running ? " app-runner-live-widget" : " app-runner-log-widget"}`);
14210
14509
  widget.setAttribute("aria-label", `Live output for subagent ${agent.name || "subagent"}`);
14211
14510
 
@@ -14216,17 +14515,31 @@ function renderSubagentOverlayWidget() {
14216
14515
  for (const fact of subagentOverlayStateFacts(data)) meta.append(make("span", "release-npm-pill", fact));
14217
14516
  header.append(titleWrap, meta);
14218
14517
 
14219
- const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLines.length, { live: running });
14220
- const terminal = make("div", "release-npm-terminal subagent-overlay-terminal");
14221
- terminal.setAttribute("role", "log");
14222
- terminal.setAttribute("aria-live", running ? "polite" : "off");
14223
- for (const line of shownLines) appendReleaseNpmTerminalLine(terminal, line);
14224
- if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(terminal);
14518
+ const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLineCount, { live: running });
14519
+ const output = make("div", "subagent-overlay-transcript");
14520
+ output.setAttribute("role", "log");
14521
+ output.setAttribute("aria-live", running ? "polite" : "off");
14522
+ const renderedTranscriptMessages = appendSubagentOverlayTranscript(output, transcriptMessages);
14523
+ const emptyTranscriptFallback = hasStructuredTranscript && renderedTranscriptMessages === 0
14524
+ ? subagentOverlayEmptyTranscriptText(transcriptMessages)
14525
+ : "";
14526
+ const visibleFallbackText = !hasStructuredTranscript ? fallbackText : emptyTranscriptFallback;
14527
+ if (visibleFallbackText) {
14528
+ const { bubble } = createMessageBubble({
14529
+ role: "assistant",
14530
+ title: "final output",
14531
+ timestamp: data?.updatedAt || Date.now(),
14532
+ content: visibleFallbackText,
14533
+ }, { streaming: running && !hasStructuredTranscript, transient: true });
14534
+ bubble.classList.add("subagent-overlay-message", "subagent-overlay-empty-fallback");
14535
+ output.append(bubble);
14536
+ }
14537
+ if (running && (agent.currentTool || (hasStructuredTranscript && renderedTranscriptMessages === 0))) appendSubagentOutputWaitingIndicator(output);
14225
14538
 
14226
14539
  const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
14227
14540
  const actions = make("div", "app-runner-output-actions");
14228
14541
  const copyButton = appRunnerActionButton("Copy output", copySubagentOverlayOutput, "subagent-overlay-copy-action");
14229
- copyButton.disabled = subagentOverlayOutputLines(data).length === 0;
14542
+ copyButton.disabled = !outputText;
14230
14543
  const refreshButton = appRunnerActionButton(subagentOverlayLoading ? "Refreshing…" : "Refresh", () => {
14231
14544
  refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
14232
14545
  }, "subagent-overlay-refresh-action");
@@ -14240,9 +14553,9 @@ function renderSubagentOverlayWidget() {
14240
14553
  subagentOverlayError,
14241
14554
  ].filter(Boolean);
14242
14555
  controls.append(actions, make("span", `app-runner-output-meta${subagentOverlayError ? " warning" : ""}`, details.join(" · ")));
14243
- const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, terminal, controls);
14556
+ const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, output, controls);
14244
14557
  widget.append(header, outputDetails);
14245
- requestAnimationFrame(() => { if (outputDetails.open) terminal.scrollTop = terminal.scrollHeight; });
14558
+ requestAnimationFrame(() => { if (outputDetails.open) output.scrollTop = output.scrollHeight; });
14246
14559
  return widget;
14247
14560
  }
14248
14561
 
@@ -14317,7 +14630,7 @@ function closeSubagentOverlay() {
14317
14630
  }
14318
14631
 
14319
14632
  async function copySubagentOverlayOutput() {
14320
- const text = subagentOverlayOutputLines().join("\n").trimEnd();
14633
+ const text = subagentOverlayOutputText();
14321
14634
  if (!text) {
14322
14635
  addEvent("subagent output is empty", "warn");
14323
14636
  return;
@@ -15095,6 +15408,100 @@ function renderReleaseAurLogWidget() {
15095
15408
  return node;
15096
15409
  }
15097
15410
 
15411
+ function aurReviewSafePath(value) {
15412
+ return parsedAurReviewSafePath(value);
15413
+ }
15414
+
15415
+ function parseAurReviewPayload(lines) {
15416
+ return parseValidatedAurReviewPayload(lines, {
15417
+ prefix: AUR_REVIEW_RPC_PAYLOAD_PREFIX,
15418
+ type: AUR_REVIEW_RPC_PAYLOAD_TYPE,
15419
+ version: AUR_REVIEW_RPC_PAYLOAD_VERSION,
15420
+ });
15421
+ }
15422
+
15423
+ function aurReviewActionButton(label, action, className = "") {
15424
+ const button = make("button", `aur-review-action ${className}`.trim(), label);
15425
+ button.type = "button";
15426
+ button.addEventListener("click", async () => {
15427
+ if (action === "review") {
15428
+ openGitChangesDialog();
15429
+ return;
15430
+ }
15431
+ const command = `/aur-review ${action}`;
15432
+ const tabContext = activeTabContext();
15433
+ try {
15434
+ await api("/api/prompt", { method: "POST", body: { message: resolveRpcSlashCommandMessage(command, { tabId: tabContext.tabId }) }, tabId: tabContext.tabId });
15435
+ if (isCurrentTabContext(tabContext)) addEvent(`${command} sent`, "info");
15436
+ } catch (error) {
15437
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
15438
+ }
15439
+ });
15440
+ return button;
15441
+ }
15442
+
15443
+ function aurReviewFileLabel(file) {
15444
+ const path = aurReviewSafePath(file?.path);
15445
+ const oldPath = aurReviewSafePath(file?.oldPath);
15446
+ const flags = [file?.staged && "staged", file?.unstaged && "unstaged", file?.untracked && "untracked", file?.deleted && "deleted", file?.renamed && "renamed"].filter(Boolean);
15447
+ return `${oldPath ? `${oldPath} → ` : ""}${path}${flags.length ? ` · ${flags.join(", ")}` : ""}`;
15448
+ }
15449
+
15450
+ function renderAurReviewWidget() {
15451
+ if (!isOptionalFeatureEnabled("aurReview")) return null;
15452
+ const payload = parseAurReviewPayload(getWidgetLines(AUR_REVIEW_RPC_WIDGET_KEY));
15453
+ if (!payload || payload.decision.state === "closed") return null;
15454
+
15455
+ const node = make("section", "widget aur-review-widget");
15456
+ node.setAttribute("aria-label", "Manual repository review");
15457
+ const header = make("div", "aur-review-header");
15458
+ const title = make("div", "aur-review-title-wrap");
15459
+ title.append(
15460
+ make("span", "aur-review-kicker", `manual ${payload.scope} repository review`),
15461
+ make("strong", "aur-review-title", payload.decision.state === "pending" ? "Review required" : `Review ${payload.decision.state}`),
15462
+ );
15463
+ const actions = make("div", "aur-review-actions");
15464
+ actions.append(
15465
+ aurReviewActionButton("Review changes", "review"),
15466
+ aurReviewActionButton("Refresh", "refresh"),
15467
+ aurReviewActionButton("Approve", "approve", "primary"),
15468
+ aurReviewActionButton("Decline", "decline", "danger"),
15469
+ aurReviewActionButton("Close", "close"),
15470
+ );
15471
+ header.append(title, actions);
15472
+
15473
+ const fingerprint = make("code", "aur-review-fingerprint", payload.fingerprint);
15474
+ const summary = make("div", "aur-review-summary");
15475
+ summary.append(
15476
+ make("span", "aur-review-status", `Status: ${payload.decision.state}`),
15477
+ make("span", "aur-review-count", `${payload.changedFileTotal} ${payload.scope} changed file${payload.changedFileTotal === 1 ? "" : "s"}`),
15478
+ make("span", "aur-review-root", `${payload.origin} · ${payload.repoRoot}`),
15479
+ fingerprint,
15480
+ );
15481
+
15482
+ const files = make("details", "aur-review-files");
15483
+ files.open = true;
15484
+ files.append(make("summary", undefined, payload.changedFilesTruncated ? `Changed files (showing ${payload.changedFiles.length} of ${payload.changedFileTotal})` : `Changed files (${payload.changedFiles.length})`));
15485
+ const list = make("ul", "aur-review-file-list");
15486
+ for (const file of payload.changedFiles) list.append(make("li", undefined, aurReviewFileLabel(file)));
15487
+ files.append(list);
15488
+
15489
+ const reports = make("div", "aur-review-reports");
15490
+ reports.append(make("strong", undefined, "Reports"));
15491
+ if (payload.reports.length === 0) reports.append(make("span", "muted", "No safe report files were found."));
15492
+ for (const report of payload.reports) {
15493
+ const reportPath = aurReviewSafePath(report.path);
15494
+ if (!reportPath) continue;
15495
+ const button = make("button", "aur-review-report", `Open ${reportPath}`);
15496
+ button.type = "button";
15497
+ button.addEventListener("click", () => openAurReviewReportInViewer(reportPath, payload.repoRoot));
15498
+ reports.append(button);
15499
+ }
15500
+
15501
+ node.append(header, summary, files, reports);
15502
+ return node;
15503
+ }
15504
+
15098
15505
  function parseWorkflowInspectorPayload(lines) {
15099
15506
  const raw = String(lines?.[0] || "").trim();
15100
15507
  if (!raw.startsWith(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX)) return null;
@@ -17219,13 +17626,15 @@ function renderWidgets() {
17219
17626
  if (releaseAurOutput) elements.widgetArea.append(releaseAurOutput);
17220
17627
  const releaseAurLog = renderReleaseAurLogWidget();
17221
17628
  if (releaseAurLog) elements.widgetArea.append(releaseAurLog);
17629
+ const aurReviewWidget = renderAurReviewWidget();
17630
+ if (aurReviewWidget) elements.widgetArea.append(aurReviewWidget);
17222
17631
  const workflowInspectorWidget = renderWorkflowInspectorWidget();
17223
17632
  if (workflowInspectorWidget) elements.widgetArea.append(workflowInspectorWidget);
17224
17633
  const workflowSubprocessWidget = renderWorkflowSubprocessWidget();
17225
17634
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
17226
17635
  const appRunnerWidget = renderAppRunnerWidget();
17227
17636
  if (appRunnerWidget) elements.widgetArea.append(appRunnerWidget);
17228
- const subagentWidget = renderSubagentOverlayWidget();
17637
+ const subagentWidget = renderSubagentOverlayWidgetSafely();
17229
17638
  if (subagentWidget) elements.widgetArea.append(subagentWidget);
17230
17639
  const btwWidget = renderBtwOutputWidget();
17231
17640
  if (btwWidget) elements.widgetArea.append(btwWidget);
@@ -17648,6 +18057,9 @@ function gitWorkflowProcessForStep(step = gitWorkflow.step, fallback = gitWorkfl
17648
18057
  case "initialPush":
17649
18058
  case "initialPushing":
17650
18059
  return "push";
18060
+ case "reviewRequesting":
18061
+ case "review":
18062
+ return "review";
17651
18063
  case "generate":
17652
18064
  case "generating":
17653
18065
  return "message";
@@ -17704,6 +18116,7 @@ function selectGitInitWorkflowProcess(processValue, tabId, workflow) {
17704
18116
  prBranch: "",
17705
18117
  pr: null,
17706
18118
  prRequestedAt: 0,
18119
+ ...resetGuidedGitReviewPatch(),
17707
18120
  };
17708
18121
 
17709
18122
  if (process === "init") {
@@ -17741,14 +18154,23 @@ function selectGitWorkflowProcess(processValue, tabId = gitWorkflowActionTabId()
17741
18154
  return;
17742
18155
  }
17743
18156
  const process = GIT_WORKFLOW_PROCESS_VALUES.has(processValue) ? processValue : "stage";
18157
+ // This repeats the disabled-button rule at the transition boundary. Later
18158
+ // processes retain a matching approval; Stage/Review deliberately clear it
18159
+ // and re-arm the requirement for a new staged snapshot.
18160
+ const guidedReviewPatch = guidedGitReviewProcessSelectionPatch(workflow, process);
18161
+ if (!guidedReviewPatch) return;
17744
18162
  workflow.runId += 1;
17745
18163
  const runId = workflow.runId;
17746
- const base = { mode: "standard", active: true, process, busy: false, error: "", githubUsername: "", repoName: "", remoteUrl: "", stack: "", readmeRequestedAt: 0, gitignoreRequestedAt: 0, initFilesStatus: null, manualCommitMessage: "", ...resetGitWorkflowManualCommitDefaultPatch(), messageRequestedAt: 0, branchName: "", branchNameRequestedAt: 0, prMode: false, prBranch: "", pr: null, prRequestedAt: 0 };
18164
+ const base = { mode: "standard", active: true, process, busy: false, error: "", githubUsername: "", repoName: "", remoteUrl: "", stack: "", readmeRequestedAt: 0, gitignoreRequestedAt: 0, initFilesStatus: null, manualCommitMessage: "", ...resetGitWorkflowManualCommitDefaultPatch(), messageRequestedAt: 0, branchName: "", branchNameRequestedAt: 0, prMode: false, prBranch: "", pr: null, prRequestedAt: 0, ...guidedReviewPatch };
17747
18165
 
17748
18166
  if (process === "stage") {
17749
18167
  setGitWorkflow({ ...base, step: "add", message: null, output: "Ready to stage all changes with git add ." }, { tabId });
17750
18168
  return;
17751
18169
  }
18170
+ if (process === "review") {
18171
+ setGitWorkflow({ ...base, step: "review", message: null, output: "Ready to request a staged manual repository review from Guided Git." }, { tabId });
18172
+ return;
18173
+ }
17752
18174
  if (process === "message") {
17753
18175
  setGitWorkflow({ ...base, step: "generate", message: null, output: "Ready to generate a commit message from the currently staged changes, or type one and commit it directly." }, { tabId });
17754
18176
  return;
@@ -17780,6 +18202,8 @@ function gitWorkflowTitle() {
17780
18202
  case "initialPush": return "Push main upstream";
17781
18203
  case "initialPushing": return "Pushing main";
17782
18204
  case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all" ? "Stage all changes" : "Review staged changes";
18205
+ case "reviewRequesting": return "Requesting staged manual review";
18206
+ case "review": return "Manual staged review";
17783
18207
  case "generate": return "Generate staged commit message";
17784
18208
  case "generating": return "Waiting for /git-staged-msg";
17785
18209
  case "message": return gitWorkflow.prMode ? "Choose PR branch commit message" : "Choose commit message";
@@ -17819,7 +18243,9 @@ function gitWorkflowHint() {
17819
18243
  case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all"
17820
18244
  ? "Step 1: explicitly stage all changes with git add ."
17821
18245
  : "Step 1: review changes, stage only intended files, then accept the current staged set.";
17822
- case "generate": return "Step 2: run /git-staged-msg, or type a commit message and use Commit input.";
18246
+ case "reviewRequesting": return "Step 2: requesting a staged manual repository review in this tab. Cancel will request Pi abort.";
18247
+ case "review": return "Step 2: inspect the staged Git diff and use the manual review card to approve or decline. Approval alone advances to commit-message generation.";
18248
+ case "generate": return "Step 3: run /git-staged-msg, or type a commit message and use Commit input.";
17823
18249
  case "generating": return "Pi is generating dev/COMMIT/staged-commit-short.txt and staged-commit-long.txt.";
17824
18250
  case "message": return gitWorkflow.prMode ? `Worktree branch ${gitWorkflow.prBranch || "created"}: choose short, long, or typed input before opening a PR.` : "Step 3/4: preview the native g-msg output, type a commit message if needed, commit here, or create a PR branch worktree first.";
17825
18251
  case "branchNaming": return "Pi is generating dev/COMMIT/staged-branch-name.txt for a PR branch worktree. Cancel will request Pi abort.";
@@ -17909,15 +18335,21 @@ function renderGitWorkflow() {
17909
18335
  elements.gitWorkflowSteps.replaceChildren();
17910
18336
  elements.gitWorkflowActions.replaceChildren();
17911
18337
 
17912
- const processes = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_PROCESSES : GIT_WORKFLOW_PROCESSES;
18338
+ // Once a flow required manual review, keep its recovery step visible even
18339
+ // if the extension was disabled or disappeared. Hiding it would suggest a
18340
+ // legacy fallback that is no longer authorized for this flow.
18341
+ const reviewStepAvailable = guidedGitReviewAvailable(activeTabId) || gitWorkflow.guidedReviewRequired === true;
18342
+ const standardProcesses = reviewStepAvailable ? GIT_WORKFLOW_PROCESSES : GIT_WORKFLOW_PROCESSES.filter((process) => process.value !== "review");
18343
+ const processes = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_PROCESSES : standardProcesses;
17913
18344
  const activeIndexMap = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_ACTIVE_INDEX : GIT_WORKFLOW_ACTIVE_INDEX;
17914
- const activeIndex = activeIndexMap[gitWorkflow.step] ?? 0;
18345
+ const reviewOffset = gitWorkflow.mode === "standard" && !reviewStepAvailable && (activeIndexMap[gitWorkflow.step] ?? 0) >= 2 ? 1 : 0;
18346
+ const activeIndex = Math.max(0, (activeIndexMap[gitWorkflow.step] ?? 0) - reviewOffset);
17915
18347
  const activeProcess = gitWorkflowProcessForStep(gitWorkflow.step, gitWorkflow.process);
17916
18348
  for (const [index, process] of processes.entries()) {
17917
18349
  const item = make("button", "git-workflow-step", process.label);
17918
18350
  item.type = "button";
17919
18351
  item.dataset.gitWorkflowProcess = process.value;
17920
- item.disabled = !!gitWorkflow.busy;
18352
+ item.disabled = !!gitWorkflow.busy || !guidedGitReviewProcessNavigationAllowed(gitWorkflow, process.value);
17921
18353
  item.setAttribute("aria-pressed", String(process.value === activeProcess));
17922
18354
  if (gitWorkflowActionDone(gitWorkflow, process.value)) item.classList.add("done");
17923
18355
  if (index === activeIndex && !["done", "cancelled", "error"].includes(gitWorkflow.step)) item.classList.add("active");
@@ -17943,6 +18375,16 @@ function renderGitWorkflow() {
17943
18375
  addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "primary", false);
17944
18376
  addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "", false);
17945
18377
  }
18378
+ } else if (gitWorkflow.step === "reviewRequesting") {
18379
+ addGitWorkflowAction("Requesting manual review…", () => {}, "primary", true);
18380
+ } else if (gitWorkflow.step === "review") {
18381
+ if (gitWorkflow.guidedReviewStatus === "pending") {
18382
+ addGitWorkflowAction("Manual review pending", () => {}, "primary", true);
18383
+ addGitWorkflowAction("Review staged changes", () => openGitChangesDialog(), "", false);
18384
+ } else {
18385
+ addGitWorkflowAction("Request staged manual review", () => requestGuidedGitReview(), "primary", false);
18386
+ addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "", false);
18387
+ }
17946
18388
  } else if (gitWorkflow.step === "generate") {
17947
18389
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
17948
18390
  addGitWorkflowAction("Run /git-staged-msg", () => runGitMessagePrompt(), "primary", false);
@@ -18031,6 +18473,208 @@ function gitWorkflowStagingReadyMessage(preferences) {
18031
18473
  }
18032
18474
  }
18033
18475
 
18476
+ function guidedGitReviewAvailable(tabId = activeTabId) {
18477
+ return guidedGitReviewAvailableForTabCatalog(commandCatalogForTab(tabId)) && !isOptionalFeatureDisabled("aurReview");
18478
+ }
18479
+
18480
+ function guidedGitReviewUnavailableMessage() {
18481
+ return "Manual staged review is still required, but aur-review is unavailable or disabled. Re-enable/install @firstpick/pi-extension-aur-review and reload this Pi/WebUI tab, then request a new review. No message, commit, worktree, or push action was performed.";
18482
+ }
18483
+
18484
+ function guidedGitReviewCommand() {
18485
+ return "/aur-review start --scope staged --origin guided-git";
18486
+ }
18487
+
18488
+ function validGuidedGitStagedContentHash(value) {
18489
+ return typeof value === "string" && /^[a-f0-9]{64}$/i.test(value);
18490
+ }
18491
+
18492
+ async function readGuidedGitStagedContent(tabId) {
18493
+ const response = await api("/api/git-workflow/staged-content", { tabId, signal: AbortSignal.timeout(12_000) });
18494
+ if (!response?.ok) throw new Error(response?.error || "Could not determine the current staged content. Reload Pi Web UI and try again.");
18495
+ const staged = response.data || {};
18496
+ if (typeof staged.hasStagedChanges !== "boolean") throw new Error("The staged-content check returned an invalid response. Reload Pi Web UI and try again.");
18497
+ if (staged.hasStagedChanges && !validGuidedGitStagedContentHash(staged.stagedContentHash)) {
18498
+ throw new Error("The staged-content check returned an invalid hash. Reload Pi Web UI and try again.");
18499
+ }
18500
+ if (!staged.hasStagedChanges && staged.stagedContentHash !== null) {
18501
+ throw new Error("The staged-content check returned an invalid empty-state hash. Reload Pi Web UI and try again.");
18502
+ }
18503
+ return staged;
18504
+ }
18505
+
18506
+ function resetGuidedGitReviewForRecovery(tabId, workflow, output, { declinedStagedContentHash } = {}) {
18507
+ resetGuidedGitReviewToStaging(tabId, workflow, output);
18508
+ if (declinedStagedContentHash !== undefined) {
18509
+ setGitWorkflow({ guidedReviewDeclinedStagedContentHash: declinedStagedContentHash || "" }, { tabId });
18510
+ }
18511
+ }
18512
+
18513
+ async function assertGuidedGitStagedContentBinding(tabId, action) {
18514
+ const workflow = gitWorkflowForTab(tabId, { create: false });
18515
+ if (!workflow) return "";
18516
+ if (workflow.guidedReviewRequired === true || !guidedGitReviewHasApprovedBinding(workflow)) {
18517
+ if (workflow.guidedReviewRequired === true || workflow.guidedReviewStatus === "approved") {
18518
+ resetGuidedGitReviewForRecovery(tabId, workflow, `Manual staged review is required before ${action}. Request a new review from Stage.`, {});
18519
+ throw new Error(`Manual staged review is required before ${action}.`);
18520
+ }
18521
+ return ""; // Legacy flow started without a required review gate.
18522
+ }
18523
+ const approvedHash = workflow.guidedReviewStagedContentHash;
18524
+ try {
18525
+ const staged = await readGuidedGitStagedContent(tabId);
18526
+ if (!staged.hasStagedChanges || staged.stagedContentHash !== approvedHash) {
18527
+ resetGuidedGitReviewForRecovery(tabId, workflow, `The staged content changed after manual approval. ${action} was blocked; review and approve the exact current staged content again.`, {});
18528
+ throw new Error(`The staged content changed after manual approval. ${action} was blocked.`);
18529
+ }
18530
+ return approvedHash;
18531
+ } catch (error) {
18532
+ if (isCurrentGitWorkflowRun(workflow.runId, tabId) && gitWorkflowForTab(tabId, { create: false })?.guidedReviewStagedContentHash === approvedHash) {
18533
+ resetGuidedGitReviewForRecovery(tabId, workflow, `Could not verify the approved staged content before ${action}. ${action} was blocked; reload Pi Web UI if this persists, then request a new review.`, {});
18534
+ }
18535
+ throw error;
18536
+ }
18537
+ }
18538
+
18539
+ async function requestGuidedGitReview(tabId = gitWorkflowActionTabId(), { output = "Staged changes are ready for manual review." } = {}) {
18540
+ const workflow = gitWorkflowForTab(tabId, { create: false });
18541
+ if (!workflow) return false;
18542
+ if (!guidedGitReviewAvailable(tabId)) {
18543
+ if (workflow.guidedReviewRequired === true) resetGuidedGitReviewForRecovery(tabId, workflow, guidedGitReviewUnavailableMessage());
18544
+ return false;
18545
+ }
18546
+
18547
+ let staged;
18548
+ try {
18549
+ staged = await readGuidedGitStagedContent(tabId);
18550
+ } catch (error) {
18551
+ resetGuidedGitReviewForRecovery(tabId, workflow, `Could not verify staged content before requesting manual review. Reload Pi Web UI and try again. ${error?.message || String(error)}`);
18552
+ return false;
18553
+ }
18554
+ if (!staged.hasStagedChanges) {
18555
+ setGitWorkflow({
18556
+ step: "add",
18557
+ process: "stage",
18558
+ busy: false,
18559
+ error: "",
18560
+ ...resetGuidedGitReviewPatch(),
18561
+ guidedReviewRequired: workflow.guidedReviewRequired === true,
18562
+ output: "git add . produced no substantive staged changes. Guided Git returned to Stage; select or edit changes before requesting manual review.",
18563
+ }, { tabId });
18564
+ return false;
18565
+ }
18566
+ if (!guidedGitReviewCanRequestStagedContent(workflow, staged.stagedContentHash)) {
18567
+ resetGuidedGitReviewForRecovery(tabId, workflow, "The staged content is unchanged from the declined review. Make and restage the requested corrections before requesting another manual review.");
18568
+ return false;
18569
+ }
18570
+
18571
+ const runId = workflow.runId;
18572
+ const requestedAt = Date.now();
18573
+ setGitWorkflow({
18574
+ step: "reviewRequesting",
18575
+ process: "review",
18576
+ busy: true,
18577
+ error: "",
18578
+ ...resetGitWorkflowManualCommitDefaultPatch(),
18579
+ ...resetGuidedGitReviewPatch(),
18580
+ guidedReviewRequired: true,
18581
+ guidedReviewStatus: "requesting",
18582
+ guidedReviewRequestedAt: requestedAt,
18583
+ ...gitWorkflowActionDonePatch(workflow, "stage"),
18584
+ output: `${output}\n\nRequesting a staged manual repository review in this tab…`,
18585
+ }, { tabId });
18586
+ try {
18587
+ await api("/api/prompt", { method: "POST", body: { message: resolveRpcSlashCommandMessage(guidedGitReviewCommand(), { tabId }) }, tabId, signal: AbortSignal.timeout(12_000) });
18588
+ const current = gitWorkflowForTab(tabId, { create: false });
18589
+ if (!current || !isCurrentGitWorkflowRun(runId, tabId) || current.guidedReviewStatus !== "requesting") return true;
18590
+ setGitWorkflow({
18591
+ step: "review",
18592
+ busy: false,
18593
+ output: `${output}\n\nManual staged review requested. Waiting for the review card; approve or decline it there.`,
18594
+ }, { tabId });
18595
+ // The extension reports command failures through its own UI, so a prompt
18596
+ // acknowledgement is not enough evidence that a card exists. Time out
18597
+ // the request state instead of allowing an invisible gate to hang forever.
18598
+ setTimeout(() => {
18599
+ const waiting = gitWorkflowForTab(tabId, { create: false });
18600
+ if (waiting && isCurrentGitWorkflowRun(runId, tabId) && waiting.guidedReviewStatus === "requesting") {
18601
+ resetGuidedGitReviewForRecovery(tabId, waiting, "Manual review did not produce a review card in time. Reload or enable aur-review, then request a new review. No message or commit was performed.");
18602
+ }
18603
+ }, 15_000);
18604
+ return true;
18605
+ } catch (error) {
18606
+ if (isCurrentGitWorkflowRun(runId, tabId)) {
18607
+ resetGuidedGitReviewForRecovery(tabId, workflow, `Manual review request failed or timed out. Reload or enable aur-review, then request a new review. ${error?.message || String(error)}`);
18608
+ }
18609
+ return false;
18610
+ }
18611
+ }
18612
+
18613
+ function resetGuidedGitReviewToStaging(tabId, workflow, output) {
18614
+ setGitWorkflow({
18615
+ step: "add",
18616
+ process: "stage",
18617
+ busy: false,
18618
+ error: "",
18619
+ ...resetGuidedGitReviewPatch(),
18620
+ guidedReviewRequired: true,
18621
+ actionsDone: createGitWorkflowActionsDone({ ...workflow.actionsDone, stage: false }),
18622
+ output,
18623
+ }, { tabId });
18624
+ }
18625
+
18626
+ function reconcileGuidedGitReviewPayload(tabId, payload) {
18627
+ const workflow = gitWorkflowForTab(tabId, { create: false });
18628
+ const transition = guidedGitReviewTransition(workflow, payload);
18629
+ if (transition === "ignore") return false;
18630
+ if (transition === "pending") {
18631
+ if (workflow.guidedReviewDeclinedStagedContentHash && payload.stagedContentHash === workflow.guidedReviewDeclinedStagedContentHash) {
18632
+ resetGuidedGitReviewForRecovery(tabId, workflow, "The review extension reported the same staged content that was declined. Make and restage the requested corrections before requesting another manual review.");
18633
+ return true;
18634
+ }
18635
+ setGitWorkflow({
18636
+ step: "review",
18637
+ process: "review",
18638
+ busy: false,
18639
+ error: "",
18640
+ guidedReviewStatus: "pending",
18641
+ guidedReviewRequired: true,
18642
+ guidedReviewFingerprint: payload.fingerprint,
18643
+ guidedReviewRepoRoot: payload.repoRoot,
18644
+ guidedReviewStagedContentHash: payload.stagedContentHash,
18645
+ output: `Staged manual repository review pending for ${payload.changedFileTotal} file${payload.changedFileTotal === 1 ? "" : "s"}. Inspect the staged Git diff, then approve or decline in the review card.`,
18646
+ }, { tabId });
18647
+ return true;
18648
+ }
18649
+ if (transition === "approved") {
18650
+ setGitWorkflow({
18651
+ step: "generate",
18652
+ process: "message",
18653
+ busy: false,
18654
+ error: "",
18655
+ guidedReviewStatus: "approved",
18656
+ guidedReviewRequired: false,
18657
+ guidedReviewDeclinedStagedContentHash: "",
18658
+ output: "Manual staged repository review approved for the exact staged snapshot. Its exact staged content will be verified again before every message, worktree, and commit action.",
18659
+ }, { tabId });
18660
+ loadGitWorkflowDefaultCommitMessage({ runId: workflow.runId, tabId });
18661
+ return true;
18662
+ }
18663
+ if (transition === "closed") {
18664
+ resetGuidedGitReviewToStaging(tabId, workflow, "Manual staged repository review was closed. It did not approve the staged changes. Review/select and restage before requesting a new staged manual review.");
18665
+ return true;
18666
+ }
18667
+ resetGuidedGitReviewForRecovery(tabId, workflow, "Manual staged repository review was declined. Make only the requested edits, then use Guided Git to review/select and restage the corrected files before requesting a new staged manual review. The unchanged declined staged content cannot be requested again. No commit or push was performed.", { declinedStagedContentHash: payload.stagedContentHash });
18668
+ return true;
18669
+ }
18670
+
18671
+ function reconcileGuidedGitReviewWidgetRemoval(tabId) {
18672
+ const workflow = gitWorkflowForTab(tabId, { create: false });
18673
+ if (guidedGitReviewWidgetRemovalTransition(workflow) !== "closed") return false;
18674
+ resetGuidedGitReviewToStaging(tabId, workflow, "Manual staged repository review card was cleared. It did not approve the staged changes. Review/select and restage before requesting a new staged manual review.");
18675
+ return true;
18676
+ }
18677
+
18034
18678
  async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {}) {
18035
18679
  if (!tabId) return;
18036
18680
  if (!isOptionalFeatureEnabled("gitWorkflow")) {
@@ -18091,6 +18735,11 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
18091
18735
  prBranch: "",
18092
18736
  pr: null,
18093
18737
  prRequestedAt: 0,
18738
+ ...resetGuidedGitReviewPatch({ retainDeclinedStagedContentHash: false }),
18739
+ // Availability at the moment this new standard flow begins determines
18740
+ // whether it is a required-review flow; later extension loss cannot turn
18741
+ // an already-required flow into the legacy path.
18742
+ guidedReviewRequired: guidedGitReviewAvailable(tabId),
18094
18743
  preferences,
18095
18744
  verificationConfirmed: false,
18096
18745
  }, { tabId });
@@ -18133,6 +18782,7 @@ async function startGitInitWorkflow(tabId = activeTabId) {
18133
18782
  prBranch: "",
18134
18783
  pr: null,
18135
18784
  prRequestedAt: 0,
18785
+ ...resetGuidedGitReviewPatch(),
18136
18786
  }, { tabId });
18137
18787
  }
18138
18788
 
@@ -18398,7 +19048,7 @@ async function cancelGitWorkflow(tabId = gitWorkflowActionTabId()) {
18398
19048
  const tabContext = activeTabContext(tabId);
18399
19049
  const workflow = gitWorkflowForTab(tabId, { create: false });
18400
19050
  if (!workflow?.active) return;
18401
- const shouldAbortPi = workflow.step === "generating" || workflow.step === "branchNaming" || workflow.step === "prGenerating" || workflow.step === "readmeGenerating" || workflow.step === "gitignoreGenerating";
19051
+ const shouldAbortPi = workflow.step === "reviewRequesting" || workflow.step === "generating" || workflow.step === "branchNaming" || workflow.step === "prGenerating" || workflow.step === "readmeGenerating" || workflow.step === "gitignoreGenerating";
18402
19052
  if (activeGitPrDialogResolve) resolveGitPrDialog(null);
18403
19053
  workflow.runId += 1;
18404
19054
  setGitWorkflow({ step: "cancelled", busy: false, error: "", output: `${workflow.output || ""}${workflow.output ? "\n\n" : ""}Cancelled by user.` }, { tabId });
@@ -18419,7 +19069,14 @@ async function runGitAdd(tabId = gitWorkflowActionTabId()) {
18419
19069
  try {
18420
19070
  const result = await gitWorkflowRequest("/api/git-workflow/add", { runId, tabId });
18421
19071
  if (!result) return;
18422
- setGitWorkflow({ step: "generate", busy: false, ...resetGitWorkflowManualCommitDefaultPatch(), ...gitWorkflowActionDonePatch(workflow, "stage"), output: `${formatGitCommandResult(result)}\n\nStaged. Next: run /git-staged-msg.` }, { tabId });
19072
+ const output = `${formatGitCommandResult(result)}\n\nStaged.`;
19073
+ if (guidedGitReviewAvailable(tabId) || workflow.guidedReviewRequired === true) {
19074
+ // A required gate never falls through to the legacy message flow just
19075
+ // because its extension was disabled or disappeared after staging.
19076
+ await requestGuidedGitReview(tabId, { output });
19077
+ } else {
19078
+ setGitWorkflow({ step: "generate", busy: false, ...resetGitWorkflowManualCommitDefaultPatch(), ...gitWorkflowActionDonePatch(workflow, "stage"), output: `${output} Next: run /git-staged-msg.` }, { tabId });
19079
+ }
18423
19080
  if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
18424
19081
  } catch (error) {
18425
19082
  if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
@@ -18436,15 +19093,20 @@ async function acceptCurrentGitStaging(tabId = gitWorkflowActionTabId()) {
18436
19093
  const response = await api("/api/git-changes", { tabId });
18437
19094
  const staged = Number(response.data?.summary?.staged || 0);
18438
19095
  if (staged <= 0) throw new Error("No staged files are available. Use Review/select changes to stage the intended files first.");
18439
- setGitWorkflow({
18440
- step: "generate",
18441
- process: "message",
18442
- busy: false,
18443
- ...resetGitWorkflowManualCommitDefaultPatch(),
18444
- ...gitWorkflowActionDonePatch(workflow, "stage"),
18445
- output: `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}). Review the staged diff, then generate or type a commit message.`,
18446
- }, { tabId });
18447
- loadGitWorkflowDefaultCommitMessage({ runId, tabId });
19096
+ const output = `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}).`;
19097
+ if (guidedGitReviewAvailable(tabId) || workflow.guidedReviewRequired === true) {
19098
+ await requestGuidedGitReview(tabId, { output });
19099
+ } else {
19100
+ setGitWorkflow({
19101
+ step: "generate",
19102
+ process: "message",
19103
+ busy: false,
19104
+ ...resetGitWorkflowManualCommitDefaultPatch(),
19105
+ ...gitWorkflowActionDonePatch(workflow, "stage"),
19106
+ output: `${output} Review the staged diff, then generate or type a commit message.`,
19107
+ }, { tabId });
19108
+ loadGitWorkflowDefaultCommitMessage({ runId, tabId });
19109
+ }
18448
19110
  if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
18449
19111
  } catch (error) {
18450
19112
  if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
@@ -18491,6 +19153,13 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
18491
19153
  }
18492
19154
  const workflow = gitWorkflowForTab(tabId, { create: false });
18493
19155
  if (!workflow) return;
19156
+ let expectedStagedContentHash;
19157
+ try {
19158
+ expectedStagedContentHash = await assertGuidedGitStagedContentBinding(tabId, "commit-message generation");
19159
+ } catch (error) {
19160
+ failGitWorkflow(error, "add", { tabId });
19161
+ return;
19162
+ }
18494
19163
  const runId = workflow.runId;
18495
19164
  const requestedAt = Date.now();
18496
19165
  setGitWorkflow({
@@ -18502,7 +19171,7 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
18502
19171
  }, { tabId });
18503
19172
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
18504
19173
  try {
18505
- const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit" }, runId, tabId });
19174
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
18506
19175
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
18507
19176
  appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the message files will be loaded.`, { tabId });
18508
19177
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
@@ -18587,6 +19256,13 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
18587
19256
  }
18588
19257
  const workflow = gitWorkflowForTab(tabId, { create: false });
18589
19258
  if (!workflow) return;
19259
+ let expectedStagedContentHash;
19260
+ try {
19261
+ expectedStagedContentHash = await assertGuidedGitStagedContentBinding(tabId, "PR branch-name generation");
19262
+ } catch (error) {
19263
+ failGitWorkflow(error, "add", { tabId });
19264
+ return;
19265
+ }
18590
19266
  const runId = workflow.runId;
18591
19267
  const requestedAt = Date.now();
18592
19268
  setGitWorkflow({
@@ -18598,7 +19274,7 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
18598
19274
  }, { tabId });
18599
19275
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
18600
19276
  try {
18601
- const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch" }, runId, tabId });
19277
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
18602
19278
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
18603
19279
  appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the branch name will be loaded.`, { tabId });
18604
19280
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
@@ -18683,10 +19359,17 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
18683
19359
  failGitWorkflow(new Error("Branch name is required to create a PR branch worktree."), "message", { tabId });
18684
19360
  return;
18685
19361
  }
19362
+ let expectedStagedContentHash;
19363
+ try {
19364
+ expectedStagedContentHash = await assertGuidedGitStagedContentBinding(tabId, "PR worktree creation");
19365
+ } catch (error) {
19366
+ failGitWorkflow(error, "add", { tabId });
19367
+ return;
19368
+ }
18686
19369
  const runId = workflow.runId;
18687
19370
  setGitWorkflow({ step: "branching", prMode: true, prBranch: branch, branchName: branch, busy: true, error: "", output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nCreating or opening branch worktree ${branch}…` }, { tabId });
18688
19371
  try {
18689
- const result = await gitWorkflowRequest("/api/git-workflow/branch", { body: { branch, sessionMode: "fork-current", openTab: true }, runId, tabId });
19372
+ const result = await gitWorkflowRequest("/api/git-workflow/branch", { body: { branch, sessionMode: "fork-current", openTab: true, ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
18690
19373
  if (!result) return;
18691
19374
  syncGitWorkflowWorktreeTabs(result);
18692
19375
  const targetTabId = result.tab?.id && tabs.some((tab) => tab.id === result.tab.id) ? result.tab.id : tabId;
@@ -18724,6 +19407,17 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
18724
19407
  prBranch: prBranch || branch,
18725
19408
  pr: null,
18726
19409
  prRequestedAt: 0,
19410
+ ...(expectedStagedContentHash
19411
+ ? {
19412
+ guidedReviewStatus: "approved",
19413
+ guidedReviewFingerprint: sourceWorkflow.guidedReviewFingerprint,
19414
+ guidedReviewRepoRoot: sourceWorkflow.guidedReviewRepoRoot,
19415
+ guidedReviewStagedContentHash: expectedStagedContentHash,
19416
+ guidedReviewDeclinedStagedContentHash: "",
19417
+ guidedReviewRequestedAt: 0,
19418
+ guidedReviewRequired: false,
19419
+ }
19420
+ : resetGuidedGitReviewPatch()),
18727
19421
  preferences: sourceWorkflow.preferences || gitWorkflowPreferences,
18728
19422
  verificationConfirmed: false,
18729
19423
  };
@@ -18745,8 +19439,15 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
18745
19439
  const tabContext = activeTabContext(tabId);
18746
19440
  const workflow = gitWorkflowForTab(tabId, { create: false });
18747
19441
  if (!workflow) return;
18748
- const runId = workflow.runId;
18749
19442
  const failureStep = variant === "input" && workflow.step === "generate" ? "generate" : "message";
19443
+ let expectedStagedContentHash;
19444
+ try {
19445
+ expectedStagedContentHash = await assertGuidedGitStagedContentBinding(tabId, "commit");
19446
+ } catch (error) {
19447
+ failGitWorkflow(error, "add", { tabId });
19448
+ return;
19449
+ }
19450
+ const runId = workflow.runId;
18750
19451
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
18751
19452
  if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
18752
19453
  const proceed = await appConfirmText([
@@ -18767,7 +19468,9 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
18767
19468
  const preview = variant === "input" ? formatInputCommitMessagePreview(inputMessage) : formatCommitMessagePreview(workflow.message);
18768
19469
  setGitWorkflow({ step: "committing", busy: true, error: "", output: `${preview}\n\nRunning native ${variant} commit…` }, { tabId });
18769
19470
  try {
18770
- const body = variant === "input" ? { variant, message: inputMessage } : { variant };
19471
+ const body = variant === "input"
19472
+ ? { variant, message: inputMessage, ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }
19473
+ : { variant, ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) };
18771
19474
  const result = await gitWorkflowRequest("/api/git-workflow/commit", { body, runId, tabId });
18772
19475
  if (!result) return;
18773
19476
  const nextAction = workflow.prMode ? "Push and Create PR." : "git push.";
@@ -21738,12 +22441,7 @@ function jumpToStickyUserPrompt() {
21738
22441
  requestAnimationFrame(updateStickyUserPromptButton);
21739
22442
  }
21740
22443
 
21741
- function appendMessage(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, reusableToolCards = null, itemKey = "" } = {}) {
21742
- const reused = reuseToolExecutionBubble(reusableToolCards, message, { streaming, messageIndex, transient });
21743
- if (reused) {
21744
- if (itemKey) reused.bubble.dataset.itemKey = itemKey;
21745
- return reused;
21746
- }
22444
+ function createMessageBubble(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, itemKey = "" } = {}) {
21747
22445
  const role = String(message.role || "message");
21748
22446
  const safeRole = role.replace(/[^a-z0-9_-]/gi, "");
21749
22447
  const bubble = make("article", `message ${safeRole}${message.level ? ` ${message.level}` : ""}${streaming ? " streaming" : ""}${animateEntry ? " action-enter" : ""}`);
@@ -21802,10 +22500,27 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
21802
22500
  attachMessageCopyButton(bubble, message, body);
21803
22501
  attachMessageEditRetryButton(bubble, message, messageIndex, { streaming, transient });
21804
22502
  if (!streaming && !transient) renderActionFeedbackControls(bubble, message, messageIndex);
21805
- appendChatMessageBubble(bubble);
21806
22503
  return { bubble, body };
21807
22504
  }
21808
22505
 
22506
+ function appendMessage(message, options = {}) {
22507
+ const {
22508
+ streaming = false,
22509
+ messageIndex = -1,
22510
+ transient = false,
22511
+ reusableToolCards = null,
22512
+ itemKey = "",
22513
+ } = options;
22514
+ const reused = reuseToolExecutionBubble(reusableToolCards, message, { streaming, messageIndex, transient });
22515
+ if (reused) {
22516
+ if (itemKey) reused.bubble.dataset.itemKey = itemKey;
22517
+ return reused;
22518
+ }
22519
+ const created = createMessageBubble(message, options);
22520
+ appendChatMessageBubble(created.bubble);
22521
+ return created;
22522
+ }
22523
+
21809
22524
  function appendTranscriptMessage(message, { streaming = false, messageIndex = -1, transient = false, animateEntry = false, reusableToolCards = null, itemKey = "" } = {}) {
21810
22525
  if (streaming || transient || message?.role !== "assistant") {
21811
22526
  return appendMessage(message, { streaming, messageIndex, transient, animateEntry, reusableToolCards, itemKey });
@@ -22576,6 +23291,10 @@ function isCommandVisible(command) {
22576
23291
  return !featureId || isOptionalFeatureEnabled(featureId);
22577
23292
  }
22578
23293
 
23294
+ function commandCatalogForTab(tabId = activeTabId) {
23295
+ return tabId ? commandCatalogsByTab.get(tabId) || { raw: [], available: [] } : { raw: [], available: [] };
23296
+ }
23297
+
22579
23298
  function visibleCommands() {
22580
23299
  return availableCommands.filter(isCommandVisible);
22581
23300
  }
@@ -22597,34 +23316,24 @@ function canUseCommandBaseAlias(name) {
22597
23316
  return availableCommands.some((command) => commandBaseName(command.name) === name && command.invokeName && command.duplicateCount > 1);
22598
23317
  }
22599
23318
 
22600
- function resolveAvailableCommand(name, { rpcOnly = false } = {}) {
22601
- const requested = String(name || "").trim();
22602
- if (!requested) return null;
22603
- const commands = (rpcOnly ? rawAvailableCommands : availableCommands).filter((command) => !rpcOnly || command.source !== "native");
22604
- const exact = commands.find((command) => command.name === requested || command.invokeName === requested || command.duplicateNames?.includes(requested));
22605
- if (exact) return exact;
22606
- if (!canUseCommandBaseAlias(requested)) return null;
22607
- return commands.find((command) => commandNameMatches(command?.name, requested)) || null;
23319
+ function resolveAvailableCommand(name, { rpcOnly = false, tabId = activeTabId } = {}) {
23320
+ return resolveCommandForTabCatalog(commandCatalogForTab(tabId), name, { rpcOnly });
22608
23321
  }
22609
23322
 
22610
23323
  function resolveAvailableCommandName(name, options = {}) {
22611
23324
  return resolveAvailableCommand(name, options)?.name || "";
22612
23325
  }
22613
23326
 
22614
- function resolveRpcSlashCommandMessage(message) {
22615
- const text = String(message || "");
22616
- const match = text.match(/^\/([^\s]+)([\s\S]*)$/);
22617
- if (!match) return text;
22618
- const resolvedName = resolveAvailableCommandName(match[1], { rpcOnly: true });
22619
- return resolvedName && resolvedName !== match[1] ? `/${resolvedName}${match[2]}` : text;
23327
+ function resolveRpcSlashCommandMessage(message, { tabId = activeTabId } = {}) {
23328
+ return resolveRpcSlashCommandForTabCatalog(commandCatalogForTab(tabId), message);
22620
23329
  }
22621
23330
 
22622
- function hasAvailableCommand(name) {
22623
- return !!resolveAvailableCommand(name);
23331
+ function hasAvailableCommand(name, options = {}) {
23332
+ return !!resolveAvailableCommand(name, options);
22624
23333
  }
22625
23334
 
22626
- function hasLoadedRpcCommand(name) {
22627
- return !!resolveAvailableCommand(name, { rpcOnly: true });
23335
+ function hasLoadedRpcCommand(name, options = {}) {
23336
+ return !!resolveAvailableCommand(name, { ...options, rpcOnly: true });
22628
23337
  }
22629
23338
 
22630
23339
  function optionalFeatureUnavailableMessage(featureId) {
@@ -22800,6 +23509,7 @@ function updateOptionalFeatureAvailability() {
22800
23509
  optionalFeatureAvailability.gitWorkflow = hasAvailableCommand("git-staged-msg");
22801
23510
  optionalFeatureAvailability.releaseNpm = hasAvailableCommand("release-npm");
22802
23511
  optionalFeatureAvailability.releaseAur = hasAvailableCommand("release-aur");
23512
+ optionalFeatureAvailability.aurReview = hasAvailableCommand("aur-review") || optionalFeatureAvailability.aurReview || widgets.has(AUR_REVIEW_RPC_WIDGET_KEY);
22803
23513
  optionalFeatureAvailability.workflows = hasAvailableCommand("workflow") || hasAvailableCommand("workflow-clear") || optionalFeatureAvailability.workflows || widgets.has("workflow") || widgets.has("workflow:subprocess");
22804
23514
  optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || hasAvailableCommand("safety-guard-setup") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
22805
23515
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
@@ -22868,6 +23578,7 @@ function optionalFeatureWidgetFeatureId(key) {
22868
23578
  if (key.startsWith("btw:")) return "btwCommand";
22869
23579
  if (key.startsWith("release-npm:")) return "releaseNpm";
22870
23580
  if (key.startsWith("release-aur:")) return "releaseAur";
23581
+ if (key === AUR_REVIEW_RPC_WIDGET_KEY) return "aurReview";
22871
23582
  if (key === "workflow" || key.startsWith("workflow:")) return "workflows";
22872
23583
  if (key === "todo-progress") return "todoProgressWidget";
22873
23584
  if (key === "pi-remote-webui") return "remoteWebui";
@@ -22875,7 +23586,7 @@ function optionalFeatureWidgetFeatureId(key) {
22875
23586
  }
22876
23587
 
22877
23588
  function optionalFeatureWidgetHasSpecializedRenderer(key) {
22878
- return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
23589
+ return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === AUR_REVIEW_RPC_WIDGET_KEY || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
22879
23590
  }
22880
23591
 
22881
23592
  function renderOptionalFeaturePanel() {
@@ -23119,9 +23830,9 @@ function syncRemoteWebuiControlVisibility(hasRemoteWebuiCommand = isOptionalFeat
23119
23830
  if (!elements.networkControlField) return;
23120
23831
  elements.networkControlField.hidden = !hasRemoteWebuiCommand;
23121
23832
  elements.networkControlField.classList.toggle("feature-unavailable", !hasRemoteWebuiCommand);
23122
- const label = elements.networkControlField.querySelector("label");
23833
+ const heading = elements.networkControlField.querySelector("#remoteAccessControlsTitle");
23123
23834
  const payload = remoteWebuiControlsPayload();
23124
- if (label) label.textContent = payload?.title || "Remote WebUI";
23835
+ if (heading) heading.textContent = payload?.title || "Remote access";
23125
23836
  elements.networkControlField.title = hasRemoteWebuiCommand
23126
23837
  ? payload?.description || "Remote WebUI controls are provided by @firstpick/pi-package-remote-webui."
23127
23838
  : optionalFeatureUnavailableMessage("remoteWebui");
@@ -23304,7 +24015,6 @@ function closeNativeCommandDialog({ force = false } = {}) {
23304
24015
  summary: "Your changes have not been applied.",
23305
24016
  affected: "All changed fields in this settings window",
23306
24017
  undoable: false,
23307
- alternative: "Cancel and choose Apply to keep the changes.",
23308
24018
  confirmLabel: "Discard changes",
23309
24019
  }).then((confirmed) => {
23310
24020
  if (!confirmed) return;
@@ -26201,9 +26911,17 @@ function renderCommands() {
26201
26911
  async function refreshCommands(tabContext = activeTabContext()) {
26202
26912
  if (!tabContext.tabId) return;
26203
26913
  const response = await api("/api/commands", { tabId: tabContext.tabId });
26914
+ const catalog = {
26915
+ raw: normalizeCommands(response.data?.commands || [], { dedupe: false }),
26916
+ available: normalizeCommands(response.data?.commands || []),
26917
+ };
26918
+ // Keep results for their originating tab even when the active tab changed
26919
+ // while this request was in flight. Guided Git must never borrow another
26920
+ // tab's extension availability or duplicate-command alias.
26921
+ commandCatalogsByTab.set(tabContext.tabId, catalog);
26204
26922
  if (!isCurrentTabContext(tabContext)) return;
26205
- rawAvailableCommands = normalizeCommands(response.data?.commands || [], { dedupe: false });
26206
- availableCommands = normalizeCommands(response.data?.commands || []);
26923
+ rawAvailableCommands = catalog.raw;
26924
+ availableCommands = catalog.available;
26207
26925
  updateOptionalFeatureAvailability();
26208
26926
  renderCommands();
26209
26927
  if (elements.commandPaletteDialog?.open) renderCommandPalette({ preserveScroll: true });
@@ -26443,7 +27161,6 @@ async function openToNetwork() {
26443
27161
  summary: "This changes Pi Web UI from local-only to reachable by devices on your network.",
26444
27162
  affected: `${interfaceName}, port ${port}, ${latestNetwork?.auth?.enabled ? "PIN authentication enabled" : "PIN authentication disabled"}`,
26445
27163
  undoable: true,
26446
- alternative: "Keep local-only access and use this browser on the host machine.",
26447
27164
  confirmLabel: "Open remote access",
26448
27165
  });
26449
27166
  if (!confirmed) return;
@@ -26543,7 +27260,6 @@ async function restartServer() {
26543
27260
  summary: "Browser clients disconnect briefly while the server restarts.",
26544
27261
  affected: "All connected browser clients and Pi tabs managed by this Web UI",
26545
27262
  undoable: false,
26546
- alternative: "Cancel and continue using the current server process.",
26547
27263
  confirmLabel: "Restart server",
26548
27264
  }))) return;
26549
27265
 
@@ -26591,7 +27307,6 @@ async function stopServer() {
26591
27307
  summary: "The Web UI becomes unavailable until the server is started again.",
26592
27308
  affected: "All connected browser clients and Pi tabs managed by this Web UI",
26593
27309
  undoable: false,
26594
- alternative: "Cancel, or restart instead if you only need to reload the server.",
26595
27310
  confirmLabel: "Stop server",
26596
27311
  }))) return;
26597
27312
 
@@ -26847,7 +27562,9 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
26847
27562
  try {
26848
27563
  const prepared = attachments.length ? await prepareAttachmentsForPrompt(attachments, targetTabId) : { images: [], uploadedFiles: [], inlineImageIds: new Set() };
26849
27564
  message = composeMessageWithAttachments(originalMessage, prepared.uploadedFiles, prepared.inlineImageIds);
26850
- if (kind === "prompt" && attachments.length === 0) message = resolveRpcSlashCommandMessage(message);
27565
+ // Dispatch against the captured target tab, never the tab that happened
27566
+ // to become active while attachments/requests were resolving.
27567
+ if (kind === "prompt" && attachments.length === 0) message = resolveRpcSlashCommandMessage(message, { tabId: targetTabId });
26851
27568
  const bodyBase = { message };
26852
27569
  if (prepared.images.length) bodyBase.images = prepared.images;
26853
27570
  if (!message.startsWith("/")) {
@@ -26986,6 +27703,16 @@ function handleExtensionUiRequest(request) {
26986
27703
  renderWidgets();
26987
27704
  return;
26988
27705
  }
27706
+ if (widgetKey === AUR_REVIEW_RPC_WIDGET_KEY) {
27707
+ const payload = parseAurReviewPayload(request.widgetLines);
27708
+ if (payload) reconcileGuidedGitReviewPayload(requestTabId, payload);
27709
+ else if (!Array.isArray(request.widgetLines)) reconcileGuidedGitReviewWidgetRemoval(requestTabId);
27710
+ if (!setWidgetForTab(requestTabId, widgetKey, request)) return;
27711
+ updateOptionalFeatureAvailability();
27712
+ renderTabs();
27713
+ renderWidgets();
27714
+ return;
27715
+ }
26989
27716
  if (widgetKey === "pi-remote-webui") {
26990
27717
  setWidgetForTab(requestTabId, widgetKey, { ...request, widgetLines: undefined });
26991
27718
  if (Array.isArray(request.widgetLines)) {
@@ -27138,6 +27865,13 @@ function handleInactiveTabEvent(event) {
27138
27865
  if (inspector) updateWorkflowInspectorForTab(event.tabId, inspector);
27139
27866
  setWidgetForTab(event.tabId, WORKFLOW_INSPECTOR_WIDGET_KEY, event);
27140
27867
  renderTabs();
27868
+ } else if (event.type === "extension_ui_request" && event.method === "setWidget" && (event.widgetKey || event.id) === AUR_REVIEW_RPC_WIDGET_KEY) {
27869
+ const payload = parseAurReviewPayload(event.widgetLines);
27870
+ if (payload) reconcileGuidedGitReviewPayload(event.tabId, payload);
27871
+ else if (!Array.isArray(event.widgetLines)) reconcileGuidedGitReviewWidgetRemoval(event.tabId);
27872
+ setWidgetForTab(event.tabId, AUR_REVIEW_RPC_WIDGET_KEY, event);
27873
+ updateOptionalFeatureAvailability();
27874
+ renderTabs();
27141
27875
  } else if (event.type === "agent_end") {
27142
27876
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
27143
27877
  }
@@ -27155,6 +27889,7 @@ function handleEvent(event) {
27155
27889
  switch (event.type) {
27156
27890
  case "webui_connected":
27157
27891
  setWebuiVersion(event.version);
27892
+ setPiVersion(event.piVersion);
27158
27893
  setWebuiDevServer(isWebuiDevMetadata(event));
27159
27894
  if (Object.prototype.hasOwnProperty.call(event, "activeRun")) {
27160
27895
  setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: event.activeRun });
@@ -27168,6 +27903,12 @@ function handleEvent(event) {
27168
27903
  applyTabMetadata(event.tab || { id: event.tabId, title: event.tabTitle, activity: event.tabActivity });
27169
27904
  addEvent(`${event.previousTabTitle || "terminal"} renamed to ${event.tabTitle || "terminal"}`);
27170
27905
  break;
27906
+ case "webui_recovery_opened":
27907
+ addEvent(`opened ${event.recoveryTabTitle || "recovery plan"}`);
27908
+ refreshTabs()
27909
+ .then(() => switchTab(event.recoveryTabId))
27910
+ .catch((error) => addEvent(error.message, "error"));
27911
+ break;
27171
27912
  case "pi_process_start":
27172
27913
  addEvent(`started pi rpc pid ${event.pid}`);
27173
27914
  refreshTabs().catch((error) => addEvent(error.message, "error"));
@@ -27262,6 +28003,10 @@ function handleEvent(event) {
27262
28003
  case "pi_stderr":
27263
28004
  addEvent(event.text.trim(), "warn");
27264
28005
  break;
28006
+ case "pi_stderr_sink_error":
28007
+ case "pi_stdout_line_too_large":
28008
+ addEvent(event.error || "Pi RPC transport diagnostic", "error");
28009
+ break;
27265
28010
  case "queue_update":
27266
28011
  renderQueue(event);
27267
28012
  scheduleRefreshState();
@@ -28097,7 +28842,6 @@ elements.newSessionButton.addEventListener("click", async () => {
28097
28842
  summary: "The active tab switches to a fresh conversation.",
28098
28843
  affected: "The active tab; the previous session remains resumable.",
28099
28844
  undoable: false,
28100
- alternative: "Cancel and open a separate tab to keep both sessions visible.",
28101
28845
  confirmLabel: "Start new session",
28102
28846
  }))) return;
28103
28847
  try {
@@ -28266,6 +29010,13 @@ if (elements.terminalTabsLayoutSelect) {
28266
29010
  setTerminalTabsLayout(elements.terminalTabsLayoutSelect.value, { announce: true });
28267
29011
  });
28268
29012
  }
29013
+ elements.piVersionButton?.addEventListener("click", () => {
29014
+ openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
29015
+ });
29016
+ elements.webuiVersionButton?.addEventListener("click", () => {
29017
+ confirmOpenWebuiNpmPage().catch((error) => addEvent(error.message || String(error), "error"));
29018
+ });
29019
+ elements.piReleaseNotesCloseButton?.addEventListener("click", () => elements.piReleaseNotesDialog?.close());
28269
29020
  elements.toggleSidePanelButton.addEventListener("click", () => {
28270
29021
  setSidePanelCollapsed(true);
28271
29022
  });