@firstpick/pi-package-webui 0.6.9 → 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,3 +1,7 @@
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 = {
@@ -420,6 +424,7 @@ let appRunnerFileBrowserState = { open: false, loading: false, path: "", data: n
420
424
  let optionsMenuOpen = false;
421
425
  let availableCommands = [];
422
426
  let rawAvailableCommands = [];
427
+ const commandCatalogsByTab = new Map();
423
428
  let commandSuggestions = [];
424
429
  let pathSuggestions = [];
425
430
  let bangSuggestions = [];
@@ -680,6 +685,10 @@ const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
680
685
  const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
681
686
  const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
682
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;
683
692
  const GIT_CHANGES_RENDER_ROW_LIMIT = 4000;
684
693
  const GIT_PULL_RESULT_FILE_LIMIT = 48;
685
694
  const LAST_USER_PROMPT_STORAGE_KEY = "pi-webui-last-user-prompts";
@@ -801,6 +810,7 @@ const optionalFeatureAvailability = {
801
810
  gitWorkflow: false,
802
811
  releaseNpm: false,
803
812
  releaseAur: false,
813
+ aurReview: false,
804
814
  workflows: false,
805
815
  safetyGuard: false,
806
816
  statsCommand: false,
@@ -857,6 +867,13 @@ const OPTIONAL_FEATURES = [
857
867
  capabilityLabel: "/release-aur",
858
868
  description: "Publish menu action, setup helpers, skills, and AUR release widgets.",
859
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
+ },
860
877
  {
861
878
  id: "workflows",
862
879
  label: "Workflows",
@@ -940,7 +957,7 @@ const OPTIONAL_FEATURE_SECTIONS = [
940
957
  id: "workflows-releases",
941
958
  label: "Workflows & releases",
942
959
  description: "Guided workflows, task runners, and publishing actions with visible execution state.",
943
- featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur"],
960
+ featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur", "aurReview"],
944
961
  },
945
962
  {
946
963
  id: "safety-access",
@@ -973,6 +990,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
973
990
  ["pr", "gitWorkflow"],
974
991
  ["release-npm", "releaseNpm"],
975
992
  ["release-aur", "releaseAur"],
993
+ ["aur-review", "aurReview"],
976
994
  ["workflow", "workflows"],
977
995
  ["workflow-clear", "workflows"],
978
996
  ["safety-guard", "safetyGuard"],
@@ -1058,6 +1076,17 @@ function resetGitWorkflowManualCommitDefaultPatch() {
1058
1076
  };
1059
1077
  }
1060
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
+
1061
1090
  function gitWorkflowManualCommitInputMessage(workflow) {
1062
1091
  return String(workflow?.manualCommitMessage || "").trim() || String(workflow?.manualCommitMessageDefault || "").trim();
1063
1092
  }
@@ -1090,6 +1119,8 @@ function createGitWorkflowState() {
1090
1119
  prBranch: "",
1091
1120
  pr: null,
1092
1121
  prRequestedAt: 0,
1122
+ ...resetGuidedGitReviewPatch({ retainDeclinedStagedContentHash: false }),
1123
+ guidedReviewRequired: false,
1093
1124
  preferences: null,
1094
1125
  verificationConfirmed: false,
1095
1126
  };
@@ -1138,6 +1169,7 @@ function clearGitWorkflowForTab(tabId) {
1138
1169
 
1139
1170
  const GIT_WORKFLOW_PROCESSES = [
1140
1171
  { value: "stage", label: "Stage" },
1172
+ { value: "review", label: "Review" },
1141
1173
  { value: "message", label: "Message" },
1142
1174
  { value: "commit", label: "Commit" },
1143
1175
  { value: "push", label: "Push" },
@@ -1161,18 +1193,20 @@ const ACTION_FEEDBACK_REACTIONS = {
1161
1193
  const ACTION_FEEDBACK_SNIPPET_LIMIT = 1200;
1162
1194
  const GIT_WORKFLOW_ACTIVE_INDEX = {
1163
1195
  add: 0,
1164
- generate: 1,
1165
- generating: 1,
1166
- message: 2,
1167
- branchNaming: 2,
1168
- branching: 2,
1169
- committing: 2,
1170
- push: 3,
1171
- pushing: 3,
1172
- prGenerating: 3,
1173
- prReview: 3,
1174
- prCreating: 3,
1175
- 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,
1176
1210
  };
1177
1211
  const GIT_INIT_WORKFLOW_ACTIVE_INDEX = {
1178
1212
  initSetup: 0,
@@ -1906,6 +1940,7 @@ function setThinkingOutputVisible(visible, { announce = false } = {}) {
1906
1940
  renderThinkingVisibilityToggle();
1907
1941
  if (!thinkingOutputVisible) removeStreamingThinkingBubble();
1908
1942
  renderAllMessages({ preserveScroll: true });
1943
+ if (subagentOverlaySelection?.tabId === activeTabId) renderWidgets();
1909
1944
  if (announce) addEvent(thinkingOutputVisible ? "thinking output shown" : "thinking output hidden", thinkingOutputVisible ? "info" : "warn");
1910
1945
  }
1911
1946
 
@@ -7076,7 +7111,7 @@ function setFileViewerMode(mode = "source") {
7076
7111
  }
7077
7112
 
7078
7113
  function setFileViewerDirty(dirty) {
7079
- if (!activeFileViewer) return;
7114
+ if (!activeFileViewer || activeFileViewer.readOnly) return;
7080
7115
  activeFileViewer.dirty = !!dirty;
7081
7116
  if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = !activeFileViewer.dirty;
7082
7117
  if (activeFileViewer.dirty) setFileViewerStatus("Unsaved file edits.", "warn");
@@ -7110,17 +7145,18 @@ function updateFileViewerUi() {
7110
7145
  }
7111
7146
  if (elements.fileViewerEditor) {
7112
7147
  elements.fileViewerEditor.hidden = mode !== "source";
7148
+ elements.fileViewerEditor.readOnly = viewer.readOnly === true;
7113
7149
  if (elements.fileViewerEditor.value !== viewer.content) elements.fileViewerEditor.value = viewer.content || "";
7114
7150
  }
7115
7151
  if (elements.fileViewerPreview) {
7116
7152
  elements.fileViewerPreview.hidden = mode !== "preview";
7117
7153
  if (mode === "preview") renderMarkdown(elements.fileViewerPreview, viewer.content || "");
7118
7154
  }
7119
- if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = !viewer.dirty;
7155
+ if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = viewer.readOnly === true || !viewer.dirty;
7120
7156
  if (elements.fileViewerOpenDefaultButton) {
7121
7157
  const viewerPath = normalizeFileTreePath(viewer.path || "");
7122
7158
  elements.fileViewerOpenDefaultButton.dataset.path = viewerPath;
7123
- elements.fileViewerOpenDefaultButton.disabled = !viewerPath;
7159
+ elements.fileViewerOpenDefaultButton.disabled = viewer.readOnly === true || !viewerPath;
7124
7160
  }
7125
7161
  renderFileViewerSelectionBar();
7126
7162
  }
@@ -7252,7 +7288,10 @@ function closeFileViewer() {
7252
7288
  updateFileViewerResizeHandle();
7253
7289
  if (elements.fileViewerPane) elements.fileViewerPane.hidden = true;
7254
7290
  if (elements.fileViewerOpenDefaultButton) elements.fileViewerOpenDefaultButton.dataset.path = "";
7255
- if (elements.fileViewerEditor) elements.fileViewerEditor.value = "";
7291
+ if (elements.fileViewerEditor) {
7292
+ elements.fileViewerEditor.value = "";
7293
+ elements.fileViewerEditor.readOnly = false;
7294
+ }
7256
7295
  if (elements.fileViewerPreview) elements.fileViewerPreview.replaceChildren();
7257
7296
  setFileViewerStatus("");
7258
7297
  }
@@ -7278,6 +7317,7 @@ async function openFileInViewer(path = "") {
7278
7317
  language: data.language || "text",
7279
7318
  mode: data.language === "markdown" ? "preview" : "source",
7280
7319
  dirty: false,
7320
+ readOnly: false,
7281
7321
  };
7282
7322
  if (elements.fileViewerEditor) elements.fileViewerEditor.value = activeFileViewer.content;
7283
7323
  clearFileViewerSelection();
@@ -7291,8 +7331,47 @@ async function openFileInViewer(path = "") {
7291
7331
  }
7292
7332
  }
7293
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
+
7294
7369
  async function saveActiveFileViewer() {
7295
7370
  if (!activeFileViewer || !elements.fileViewerEditor) return;
7371
+ if (activeFileViewer.readOnly) {
7372
+ setFileViewerStatus("This report is read-only.", "info");
7373
+ return;
7374
+ }
7296
7375
  const tabContext = activeTabContext();
7297
7376
  const content = elements.fileViewerEditor.value || "";
7298
7377
  if (elements.fileViewerSaveButton) elements.fileViewerSaveButton.disabled = true;
@@ -7395,6 +7474,7 @@ function syncTabMetadata(nextTabs = []) {
7395
7474
  remoteMicConsentTabs.delete(tabId);
7396
7475
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
7397
7476
  clearGitWorkflowForTab(tabId);
7477
+ commandCatalogsByTab.delete(tabId);
7398
7478
  }
7399
7479
  }
7400
7480
  for (const tabId of tabMessagesCache.keys()) {
@@ -7799,8 +7879,9 @@ function resetActiveTabUi() {
7799
7879
  transientMessages = [];
7800
7880
  liveToolRuns.clear();
7801
7881
  liveToolCards.clear();
7802
- availableCommands = [];
7803
- rawAvailableCommands = [];
7882
+ const commandCatalog = commandCatalogsByTab.get(activeTabId);
7883
+ availableCommands = commandCatalog?.available || [];
7884
+ rawAvailableCommands = commandCatalog?.raw || [];
7804
7885
  resetOptionalFeatureAvailability();
7805
7886
  commandSuggestions = [];
7806
7887
  pathSuggestions = [];
@@ -8496,6 +8577,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
8496
8577
  tabDrafts.delete(id);
8497
8578
  clearAttachments(id);
8498
8579
  clearGitWorkflowForTab(id);
8580
+ commandCatalogsByTab.delete(id);
8499
8581
  appRunnerDataByTab.delete(id);
8500
8582
  tabMessagesCache.delete(id);
8501
8583
  btwWidgetDismissedIdsByTab.delete(id);
@@ -14253,8 +14335,62 @@ function subagentRunElapsed(run) {
14253
14335
  return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
14254
14336
  }
14255
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
+
14256
14390
  function subagentOverlayOutputLines(data = subagentOverlayData) {
14257
14391
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
14392
+ const transcriptMessages = subagentOverlayTranscriptMessages(data);
14393
+ if (transcriptMessages.length) return subagentOverlayTranscriptOutputLines(data);
14258
14394
  const output = (Array.isArray(agent.recentOutput) ? agent.recentOutput : [])
14259
14395
  .flatMap((line) => stripAnsi(String(line ?? "")).replace(/\r/g, "").split("\n"));
14260
14396
  if (output.length) return output;
@@ -14268,6 +14404,14 @@ function subagentOverlayOutputText(data = subagentOverlayData) {
14268
14404
  return subagentOverlayOutputLines(data).join("\n").trimEnd();
14269
14405
  }
14270
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
+
14271
14415
  function appendSubagentOutputWaitingIndicator(parent) {
14272
14416
  const bubble = make("article", "message runIndicator run-indicator-message streaming subagent-output-waiting");
14273
14417
  bubble.setAttribute("role", "status");
@@ -14284,6 +14428,17 @@ function appendSubagentOutputWaitingIndicator(parent) {
14284
14428
  parent.append(bubble);
14285
14429
  }
14286
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;
14440
+ }
14441
+
14287
14442
  function subagentOverlayStateFacts(data = subagentOverlayData) {
14288
14443
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
14289
14444
  return [
@@ -14311,6 +14466,33 @@ function subagentOverlayMeaningfulSignature() {
14311
14466
  });
14312
14467
  }
14313
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
+
14314
14496
  function renderSubagentOverlayWidget() {
14315
14497
  const selection = subagentOverlaySelection;
14316
14498
  if (!selection || selection.tabId !== activeTabId) return null;
@@ -14318,9 +14500,11 @@ function renderSubagentOverlayWidget() {
14318
14500
  const agent = data?.agent || selection.agent || {};
14319
14501
  const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
14320
14502
  const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
14503
+ const transcriptMessages = subagentOverlayTranscriptMessages(data);
14504
+ const hasStructuredTranscript = transcriptMessages.length > 0;
14321
14505
  const outputText = subagentOverlayOutputText(data);
14322
- const shownText = outputText || (running && agent.currentTool ? "" : running ? "Waiting for the first agent activity…" : "No recent output was captured.");
14323
- const shownLineCount = shownText ? shownText.split("\n").length : 0;
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;
14324
14508
  const widget = make("section", `widget release-npm-widget app-runner-widget subagent-overlay-widget${running ? " app-runner-live-widget" : " app-runner-log-widget"}`);
14325
14509
  widget.setAttribute("aria-label", `Live output for subagent ${agent.name || "subagent"}`);
14326
14510
 
@@ -14335,17 +14519,22 @@ function renderSubagentOverlayWidget() {
14335
14519
  const output = make("div", "subagent-overlay-transcript");
14336
14520
  output.setAttribute("role", "log");
14337
14521
  output.setAttribute("aria-live", running ? "polite" : "off");
14338
- if (shownText) {
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) {
14339
14528
  const { bubble } = createMessageBubble({
14340
14529
  role: "assistant",
14341
14530
  title: "final output",
14342
14531
  timestamp: data?.updatedAt || Date.now(),
14343
- content: shownText,
14344
- }, { streaming: running, transient: true });
14345
- bubble.classList.add("subagent-overlay-message");
14532
+ content: visibleFallbackText,
14533
+ }, { streaming: running && !hasStructuredTranscript, transient: true });
14534
+ bubble.classList.add("subagent-overlay-message", "subagent-overlay-empty-fallback");
14346
14535
  output.append(bubble);
14347
14536
  }
14348
- if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(output);
14537
+ if (running && (agent.currentTool || (hasStructuredTranscript && renderedTranscriptMessages === 0))) appendSubagentOutputWaitingIndicator(output);
14349
14538
 
14350
14539
  const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
14351
14540
  const actions = make("div", "app-runner-output-actions");
@@ -15219,6 +15408,100 @@ function renderReleaseAurLogWidget() {
15219
15408
  return node;
15220
15409
  }
15221
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
+
15222
15505
  function parseWorkflowInspectorPayload(lines) {
15223
15506
  const raw = String(lines?.[0] || "").trim();
15224
15507
  if (!raw.startsWith(WORKFLOW_INSPECTOR_PAYLOAD_PREFIX)) return null;
@@ -17343,13 +17626,15 @@ function renderWidgets() {
17343
17626
  if (releaseAurOutput) elements.widgetArea.append(releaseAurOutput);
17344
17627
  const releaseAurLog = renderReleaseAurLogWidget();
17345
17628
  if (releaseAurLog) elements.widgetArea.append(releaseAurLog);
17629
+ const aurReviewWidget = renderAurReviewWidget();
17630
+ if (aurReviewWidget) elements.widgetArea.append(aurReviewWidget);
17346
17631
  const workflowInspectorWidget = renderWorkflowInspectorWidget();
17347
17632
  if (workflowInspectorWidget) elements.widgetArea.append(workflowInspectorWidget);
17348
17633
  const workflowSubprocessWidget = renderWorkflowSubprocessWidget();
17349
17634
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
17350
17635
  const appRunnerWidget = renderAppRunnerWidget();
17351
17636
  if (appRunnerWidget) elements.widgetArea.append(appRunnerWidget);
17352
- const subagentWidget = renderSubagentOverlayWidget();
17637
+ const subagentWidget = renderSubagentOverlayWidgetSafely();
17353
17638
  if (subagentWidget) elements.widgetArea.append(subagentWidget);
17354
17639
  const btwWidget = renderBtwOutputWidget();
17355
17640
  if (btwWidget) elements.widgetArea.append(btwWidget);
@@ -17772,6 +18057,9 @@ function gitWorkflowProcessForStep(step = gitWorkflow.step, fallback = gitWorkfl
17772
18057
  case "initialPush":
17773
18058
  case "initialPushing":
17774
18059
  return "push";
18060
+ case "reviewRequesting":
18061
+ case "review":
18062
+ return "review";
17775
18063
  case "generate":
17776
18064
  case "generating":
17777
18065
  return "message";
@@ -17828,6 +18116,7 @@ function selectGitInitWorkflowProcess(processValue, tabId, workflow) {
17828
18116
  prBranch: "",
17829
18117
  pr: null,
17830
18118
  prRequestedAt: 0,
18119
+ ...resetGuidedGitReviewPatch(),
17831
18120
  };
17832
18121
 
17833
18122
  if (process === "init") {
@@ -17865,14 +18154,23 @@ function selectGitWorkflowProcess(processValue, tabId = gitWorkflowActionTabId()
17865
18154
  return;
17866
18155
  }
17867
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;
17868
18162
  workflow.runId += 1;
17869
18163
  const runId = workflow.runId;
17870
- 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 };
17871
18165
 
17872
18166
  if (process === "stage") {
17873
18167
  setGitWorkflow({ ...base, step: "add", message: null, output: "Ready to stage all changes with git add ." }, { tabId });
17874
18168
  return;
17875
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
+ }
17876
18174
  if (process === "message") {
17877
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 });
17878
18176
  return;
@@ -17904,6 +18202,8 @@ function gitWorkflowTitle() {
17904
18202
  case "initialPush": return "Push main upstream";
17905
18203
  case "initialPushing": return "Pushing main";
17906
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";
17907
18207
  case "generate": return "Generate staged commit message";
17908
18208
  case "generating": return "Waiting for /git-staged-msg";
17909
18209
  case "message": return gitWorkflow.prMode ? "Choose PR branch commit message" : "Choose commit message";
@@ -17943,7 +18243,9 @@ function gitWorkflowHint() {
17943
18243
  case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all"
17944
18244
  ? "Step 1: explicitly stage all changes with git add ."
17945
18245
  : "Step 1: review changes, stage only intended files, then accept the current staged set.";
17946
- 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.";
17947
18249
  case "generating": return "Pi is generating dev/COMMIT/staged-commit-short.txt and staged-commit-long.txt.";
17948
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.";
17949
18251
  case "branchNaming": return "Pi is generating dev/COMMIT/staged-branch-name.txt for a PR branch worktree. Cancel will request Pi abort.";
@@ -18033,15 +18335,21 @@ function renderGitWorkflow() {
18033
18335
  elements.gitWorkflowSteps.replaceChildren();
18034
18336
  elements.gitWorkflowActions.replaceChildren();
18035
18337
 
18036
- 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;
18037
18344
  const activeIndexMap = gitWorkflow.mode === "initRepo" ? GIT_INIT_WORKFLOW_ACTIVE_INDEX : GIT_WORKFLOW_ACTIVE_INDEX;
18038
- 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);
18039
18347
  const activeProcess = gitWorkflowProcessForStep(gitWorkflow.step, gitWorkflow.process);
18040
18348
  for (const [index, process] of processes.entries()) {
18041
18349
  const item = make("button", "git-workflow-step", process.label);
18042
18350
  item.type = "button";
18043
18351
  item.dataset.gitWorkflowProcess = process.value;
18044
- item.disabled = !!gitWorkflow.busy;
18352
+ item.disabled = !!gitWorkflow.busy || !guidedGitReviewProcessNavigationAllowed(gitWorkflow, process.value);
18045
18353
  item.setAttribute("aria-pressed", String(process.value === activeProcess));
18046
18354
  if (gitWorkflowActionDone(gitWorkflow, process.value)) item.classList.add("done");
18047
18355
  if (index === activeIndex && !["done", "cancelled", "error"].includes(gitWorkflow.step)) item.classList.add("active");
@@ -18067,6 +18375,16 @@ function renderGitWorkflow() {
18067
18375
  addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "primary", false);
18068
18376
  addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "", false);
18069
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
+ }
18070
18388
  } else if (gitWorkflow.step === "generate") {
18071
18389
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
18072
18390
  addGitWorkflowAction("Run /git-staged-msg", () => runGitMessagePrompt(), "primary", false);
@@ -18155,6 +18473,208 @@ function gitWorkflowStagingReadyMessage(preferences) {
18155
18473
  }
18156
18474
  }
18157
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
+
18158
18678
  async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {}) {
18159
18679
  if (!tabId) return;
18160
18680
  if (!isOptionalFeatureEnabled("gitWorkflow")) {
@@ -18215,6 +18735,11 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
18215
18735
  prBranch: "",
18216
18736
  pr: null,
18217
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),
18218
18743
  preferences,
18219
18744
  verificationConfirmed: false,
18220
18745
  }, { tabId });
@@ -18257,6 +18782,7 @@ async function startGitInitWorkflow(tabId = activeTabId) {
18257
18782
  prBranch: "",
18258
18783
  pr: null,
18259
18784
  prRequestedAt: 0,
18785
+ ...resetGuidedGitReviewPatch(),
18260
18786
  }, { tabId });
18261
18787
  }
18262
18788
 
@@ -18522,7 +19048,7 @@ async function cancelGitWorkflow(tabId = gitWorkflowActionTabId()) {
18522
19048
  const tabContext = activeTabContext(tabId);
18523
19049
  const workflow = gitWorkflowForTab(tabId, { create: false });
18524
19050
  if (!workflow?.active) return;
18525
- 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";
18526
19052
  if (activeGitPrDialogResolve) resolveGitPrDialog(null);
18527
19053
  workflow.runId += 1;
18528
19054
  setGitWorkflow({ step: "cancelled", busy: false, error: "", output: `${workflow.output || ""}${workflow.output ? "\n\n" : ""}Cancelled by user.` }, { tabId });
@@ -18543,7 +19069,14 @@ async function runGitAdd(tabId = gitWorkflowActionTabId()) {
18543
19069
  try {
18544
19070
  const result = await gitWorkflowRequest("/api/git-workflow/add", { runId, tabId });
18545
19071
  if (!result) return;
18546
- 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
+ }
18547
19080
  if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
18548
19081
  } catch (error) {
18549
19082
  if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
@@ -18560,15 +19093,20 @@ async function acceptCurrentGitStaging(tabId = gitWorkflowActionTabId()) {
18560
19093
  const response = await api("/api/git-changes", { tabId });
18561
19094
  const staged = Number(response.data?.summary?.staged || 0);
18562
19095
  if (staged <= 0) throw new Error("No staged files are available. Use Review/select changes to stage the intended files first.");
18563
- setGitWorkflow({
18564
- step: "generate",
18565
- process: "message",
18566
- busy: false,
18567
- ...resetGitWorkflowManualCommitDefaultPatch(),
18568
- ...gitWorkflowActionDonePatch(workflow, "stage"),
18569
- output: `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}). Review the staged diff, then generate or type a commit message.`,
18570
- }, { tabId });
18571
- 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
+ }
18572
19110
  if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
18573
19111
  } catch (error) {
18574
19112
  if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
@@ -18615,6 +19153,13 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
18615
19153
  }
18616
19154
  const workflow = gitWorkflowForTab(tabId, { create: false });
18617
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
+ }
18618
19163
  const runId = workflow.runId;
18619
19164
  const requestedAt = Date.now();
18620
19165
  setGitWorkflow({
@@ -18626,7 +19171,7 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
18626
19171
  }, { tabId });
18627
19172
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
18628
19173
  try {
18629
- 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 });
18630
19175
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
18631
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 });
18632
19177
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
@@ -18711,6 +19256,13 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
18711
19256
  }
18712
19257
  const workflow = gitWorkflowForTab(tabId, { create: false });
18713
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
+ }
18714
19266
  const runId = workflow.runId;
18715
19267
  const requestedAt = Date.now();
18716
19268
  setGitWorkflow({
@@ -18722,7 +19274,7 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
18722
19274
  }, { tabId });
18723
19275
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
18724
19276
  try {
18725
- 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 });
18726
19278
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
18727
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 });
18728
19280
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
@@ -18807,10 +19359,17 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
18807
19359
  failGitWorkflow(new Error("Branch name is required to create a PR branch worktree."), "message", { tabId });
18808
19360
  return;
18809
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
+ }
18810
19369
  const runId = workflow.runId;
18811
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 });
18812
19371
  try {
18813
- 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 });
18814
19373
  if (!result) return;
18815
19374
  syncGitWorkflowWorktreeTabs(result);
18816
19375
  const targetTabId = result.tab?.id && tabs.some((tab) => tab.id === result.tab.id) ? result.tab.id : tabId;
@@ -18848,6 +19407,17 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
18848
19407
  prBranch: prBranch || branch,
18849
19408
  pr: null,
18850
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()),
18851
19421
  preferences: sourceWorkflow.preferences || gitWorkflowPreferences,
18852
19422
  verificationConfirmed: false,
18853
19423
  };
@@ -18869,8 +19439,15 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
18869
19439
  const tabContext = activeTabContext(tabId);
18870
19440
  const workflow = gitWorkflowForTab(tabId, { create: false });
18871
19441
  if (!workflow) return;
18872
- const runId = workflow.runId;
18873
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;
18874
19451
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
18875
19452
  if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
18876
19453
  const proceed = await appConfirmText([
@@ -18891,7 +19468,9 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
18891
19468
  const preview = variant === "input" ? formatInputCommitMessagePreview(inputMessage) : formatCommitMessagePreview(workflow.message);
18892
19469
  setGitWorkflow({ step: "committing", busy: true, error: "", output: `${preview}\n\nRunning native ${variant} commit…` }, { tabId });
18893
19470
  try {
18894
- const body = variant === "input" ? { variant, message: inputMessage } : { variant };
19471
+ const body = variant === "input"
19472
+ ? { variant, message: inputMessage, ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }
19473
+ : { variant, ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) };
18895
19474
  const result = await gitWorkflowRequest("/api/git-workflow/commit", { body, runId, tabId });
18896
19475
  if (!result) return;
18897
19476
  const nextAction = workflow.prMode ? "Push and Create PR." : "git push.";
@@ -22712,6 +23291,10 @@ function isCommandVisible(command) {
22712
23291
  return !featureId || isOptionalFeatureEnabled(featureId);
22713
23292
  }
22714
23293
 
23294
+ function commandCatalogForTab(tabId = activeTabId) {
23295
+ return tabId ? commandCatalogsByTab.get(tabId) || { raw: [], available: [] } : { raw: [], available: [] };
23296
+ }
23297
+
22715
23298
  function visibleCommands() {
22716
23299
  return availableCommands.filter(isCommandVisible);
22717
23300
  }
@@ -22733,34 +23316,24 @@ function canUseCommandBaseAlias(name) {
22733
23316
  return availableCommands.some((command) => commandBaseName(command.name) === name && command.invokeName && command.duplicateCount > 1);
22734
23317
  }
22735
23318
 
22736
- function resolveAvailableCommand(name, { rpcOnly = false } = {}) {
22737
- const requested = String(name || "").trim();
22738
- if (!requested) return null;
22739
- const commands = (rpcOnly ? rawAvailableCommands : availableCommands).filter((command) => !rpcOnly || command.source !== "native");
22740
- const exact = commands.find((command) => command.name === requested || command.invokeName === requested || command.duplicateNames?.includes(requested));
22741
- if (exact) return exact;
22742
- if (!canUseCommandBaseAlias(requested)) return null;
22743
- return commands.find((command) => commandNameMatches(command?.name, requested)) || null;
23319
+ function resolveAvailableCommand(name, { rpcOnly = false, tabId = activeTabId } = {}) {
23320
+ return resolveCommandForTabCatalog(commandCatalogForTab(tabId), name, { rpcOnly });
22744
23321
  }
22745
23322
 
22746
23323
  function resolveAvailableCommandName(name, options = {}) {
22747
23324
  return resolveAvailableCommand(name, options)?.name || "";
22748
23325
  }
22749
23326
 
22750
- function resolveRpcSlashCommandMessage(message) {
22751
- const text = String(message || "");
22752
- const match = text.match(/^\/([^\s]+)([\s\S]*)$/);
22753
- if (!match) return text;
22754
- const resolvedName = resolveAvailableCommandName(match[1], { rpcOnly: true });
22755
- return resolvedName && resolvedName !== match[1] ? `/${resolvedName}${match[2]}` : text;
23327
+ function resolveRpcSlashCommandMessage(message, { tabId = activeTabId } = {}) {
23328
+ return resolveRpcSlashCommandForTabCatalog(commandCatalogForTab(tabId), message);
22756
23329
  }
22757
23330
 
22758
- function hasAvailableCommand(name) {
22759
- return !!resolveAvailableCommand(name);
23331
+ function hasAvailableCommand(name, options = {}) {
23332
+ return !!resolveAvailableCommand(name, options);
22760
23333
  }
22761
23334
 
22762
- function hasLoadedRpcCommand(name) {
22763
- return !!resolveAvailableCommand(name, { rpcOnly: true });
23335
+ function hasLoadedRpcCommand(name, options = {}) {
23336
+ return !!resolveAvailableCommand(name, { ...options, rpcOnly: true });
22764
23337
  }
22765
23338
 
22766
23339
  function optionalFeatureUnavailableMessage(featureId) {
@@ -22936,6 +23509,7 @@ function updateOptionalFeatureAvailability() {
22936
23509
  optionalFeatureAvailability.gitWorkflow = hasAvailableCommand("git-staged-msg");
22937
23510
  optionalFeatureAvailability.releaseNpm = hasAvailableCommand("release-npm");
22938
23511
  optionalFeatureAvailability.releaseAur = hasAvailableCommand("release-aur");
23512
+ optionalFeatureAvailability.aurReview = hasAvailableCommand("aur-review") || optionalFeatureAvailability.aurReview || widgets.has(AUR_REVIEW_RPC_WIDGET_KEY);
22939
23513
  optionalFeatureAvailability.workflows = hasAvailableCommand("workflow") || hasAvailableCommand("workflow-clear") || optionalFeatureAvailability.workflows || widgets.has("workflow") || widgets.has("workflow:subprocess");
22940
23514
  optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || hasAvailableCommand("safety-guard-setup") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
22941
23515
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
@@ -23004,6 +23578,7 @@ function optionalFeatureWidgetFeatureId(key) {
23004
23578
  if (key.startsWith("btw:")) return "btwCommand";
23005
23579
  if (key.startsWith("release-npm:")) return "releaseNpm";
23006
23580
  if (key.startsWith("release-aur:")) return "releaseAur";
23581
+ if (key === AUR_REVIEW_RPC_WIDGET_KEY) return "aurReview";
23007
23582
  if (key === "workflow" || key.startsWith("workflow:")) return "workflows";
23008
23583
  if (key === "todo-progress") return "todoProgressWidget";
23009
23584
  if (key === "pi-remote-webui") return "remoteWebui";
@@ -23011,7 +23586,7 @@ function optionalFeatureWidgetFeatureId(key) {
23011
23586
  }
23012
23587
 
23013
23588
  function optionalFeatureWidgetHasSpecializedRenderer(key) {
23014
- 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;
23015
23590
  }
23016
23591
 
23017
23592
  function renderOptionalFeaturePanel() {
@@ -26336,9 +26911,17 @@ function renderCommands() {
26336
26911
  async function refreshCommands(tabContext = activeTabContext()) {
26337
26912
  if (!tabContext.tabId) return;
26338
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);
26339
26922
  if (!isCurrentTabContext(tabContext)) return;
26340
- rawAvailableCommands = normalizeCommands(response.data?.commands || [], { dedupe: false });
26341
- availableCommands = normalizeCommands(response.data?.commands || []);
26923
+ rawAvailableCommands = catalog.raw;
26924
+ availableCommands = catalog.available;
26342
26925
  updateOptionalFeatureAvailability();
26343
26926
  renderCommands();
26344
26927
  if (elements.commandPaletteDialog?.open) renderCommandPalette({ preserveScroll: true });
@@ -26979,7 +27562,9 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
26979
27562
  try {
26980
27563
  const prepared = attachments.length ? await prepareAttachmentsForPrompt(attachments, targetTabId) : { images: [], uploadedFiles: [], inlineImageIds: new Set() };
26981
27564
  message = composeMessageWithAttachments(originalMessage, prepared.uploadedFiles, prepared.inlineImageIds);
26982
- 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 });
26983
27568
  const bodyBase = { message };
26984
27569
  if (prepared.images.length) bodyBase.images = prepared.images;
26985
27570
  if (!message.startsWith("/")) {
@@ -27118,6 +27703,16 @@ function handleExtensionUiRequest(request) {
27118
27703
  renderWidgets();
27119
27704
  return;
27120
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
+ }
27121
27716
  if (widgetKey === "pi-remote-webui") {
27122
27717
  setWidgetForTab(requestTabId, widgetKey, { ...request, widgetLines: undefined });
27123
27718
  if (Array.isArray(request.widgetLines)) {
@@ -27270,6 +27865,13 @@ function handleInactiveTabEvent(event) {
27270
27865
  if (inspector) updateWorkflowInspectorForTab(event.tabId, inspector);
27271
27866
  setWidgetForTab(event.tabId, WORKFLOW_INSPECTOR_WIDGET_KEY, event);
27272
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();
27273
27875
  } else if (event.type === "agent_end") {
27274
27876
  notifyAgentDone(event.tabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
27275
27877
  }
@@ -27401,6 +28003,10 @@ function handleEvent(event) {
27401
28003
  case "pi_stderr":
27402
28004
  addEvent(event.text.trim(), "warn");
27403
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;
27404
28010
  case "queue_update":
27405
28011
  renderQueue(event);
27406
28012
  scheduleRefreshState();