@in-the-loop-labs/pair-review 5.3.6 → 5.4.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.
Files changed (41) hide show
  1. package/README.md +8 -0
  2. package/package.json +3 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/css/pr.css +407 -13
  7. package/public/js/components/AIPanel.js +323 -104
  8. package/public/js/components/ReviewHistoryModal.js +294 -0
  9. package/public/js/components/ReviewModal.js +131 -14
  10. package/public/js/components/SplitButton.js +14 -0
  11. package/public/js/local.js +4 -8
  12. package/public/js/modules/comment-manager.js +6 -12
  13. package/public/js/modules/comment-minimizer.js +4 -1
  14. package/public/js/modules/file-comment-manager.js +38 -74
  15. package/public/js/modules/pierre-bridge.js +36 -0
  16. package/public/js/modules/suggestion-manager.js +4 -1
  17. package/public/js/pr.js +337 -191
  18. package/public/js/utils/posted-comment.js +326 -0
  19. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  20. package/public/js/vendor/pierre-diffs.js +131 -1364
  21. package/public/local.html +1 -0
  22. package/public/pr.html +2 -0
  23. package/src/chat/api-reference.js +22 -2
  24. package/src/config.js +28 -4
  25. package/src/database.js +177 -35
  26. package/src/github/client.js +95 -16
  27. package/src/github/impl/graphql/pending-review-comments.js +118 -14
  28. package/src/github/impl/graphql/pending-review.js +8 -2
  29. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  30. package/src/github/impl/host/pending-review-comments.js +41 -10
  31. package/src/github/impl/host/review-comment-edit.js +36 -0
  32. package/src/github/impl/rest/pending-review.js +6 -2
  33. package/src/github/impl/rest/review-comment-edit.js +44 -0
  34. package/src/github/impl/review-comment-edit-utils.js +45 -0
  35. package/src/github/operations/pending-review.js +4 -3
  36. package/src/github/operations/review-comment-edit.js +35 -0
  37. package/src/github/record-submission.js +78 -0
  38. package/src/github/update-posted-comment.js +115 -0
  39. package/src/main.js +24 -38
  40. package/src/routes/mcp.js +1 -0
  41. package/src/routes/pr.js +152 -100
package/public/js/pr.js CHANGED
@@ -11,6 +11,9 @@
11
11
  // Timeout (ms) for stale check — git commands can hang on locked repos
12
12
  const STALE_TIMEOUT = 2000;
13
13
 
14
+ // Review submission route; the fetch interceptor tags it with X-Client-Id
15
+ const SUBMIT_REVIEW_URL = /\/api\/pr\/[^/]+\/[^/]+\/\d+\/submit-review(?:[?#]|$)/;
16
+
14
17
  class PRManager {
15
18
  // Forward static constants from modules for backward compatibility
16
19
  static get FOLD_UP_ICON() {
@@ -449,7 +452,8 @@ class PRManager {
449
452
 
450
453
  /**
451
454
  * Install a global fetch interceptor that adds X-Client-Id to all
452
- * mutation requests (POST/PUT/DELETE) targeting the review API.
455
+ * mutation requests (POST/PUT/DELETE) targeting the review API, and to
456
+ * review submission (POST /api/pr/:owner/:repo/:number/submit-review).
453
457
  * This is the SINGLE SOURCE of X-Client-Id injection — no individual
454
458
  * fetch call site should manually set this header.
455
459
  * This ensures that even direct fetch() calls (e.g. from page.evaluate
@@ -468,9 +472,10 @@ class PRManager {
468
472
  const url = typeof input === 'string' ? input : input?.url || '';
469
473
  const method = (init?.method || 'GET').toUpperCase();
470
474
 
471
- // Only intercept mutations to the reviews API
475
+ // Only intercept mutations to the reviews API, plus review submission
476
+ // (it broadcasts review:comments_changed too)
472
477
  if ((method === 'POST' || method === 'PUT' || method === 'DELETE') &&
473
- url.includes('/api/reviews/') && prManager._clientId) {
478
+ (url.includes('/api/reviews/') || SUBMIT_REVIEW_URL.test(url)) && prManager._clientId) {
474
479
  init = init || {};
475
480
  // Merge X-Client-Id into existing headers
476
481
  if (init.headers instanceof Headers) {
@@ -658,10 +663,10 @@ class PRManager {
658
663
  }
659
664
  });
660
665
 
661
- // Listen for filter dismissed changes from AI panel
662
- document.addEventListener('filterDismissedChanged', (e) => {
663
- const showDismissed = e.detail?.showDismissed;
664
- this.loadUserComments(showDismissed);
666
+ // Reload user comments when the reviewer changes the comment panel's
667
+ // filters (show dismissed, show posted). loadUserComments reads them.
668
+ document.addEventListener('commentFilterChanged', () => {
669
+ this.loadUserComments();
665
670
  });
666
671
  }
667
672
 
@@ -670,6 +675,17 @@ class PRManager {
670
675
  * This avoids memory leaks from attaching listeners to each textarea
671
676
  */
672
677
  setupCommentFormDelegation() {
678
+ // "Update on GitHub" on an edited posted comment, in any diff renderer
679
+ document.addEventListener('click', (e) => {
680
+ const button = e.target.closest?.('.btn-update-on-host');
681
+ if (!button || button.disabled) return;
682
+ e.preventDefault();
683
+ e.stopPropagation();
684
+ this.updatePostedCommentOnHost(button.dataset.updateCommentId).then(result => {
685
+ if (result?.ok) window.toast?.showSuccess(`Comment updated on ${window.PostedComment.escapeHtml(window.PostedComment.hostName())}`);
686
+ });
687
+ });
688
+
673
689
  document.addEventListener('keydown', (e) => {
674
690
  // Check if we're in a comment-related textarea
675
691
  const textarea = e.target;
@@ -1023,10 +1039,8 @@ class PRManager {
1023
1039
  }
1024
1040
  window.panelGroup?.setPR(`${owner}/${repo}#${number}`);
1025
1041
 
1026
- // Load saved comments using the restored filter state from AI Panel
1027
- // If AI Panel has showDismissedComments=true (restored from localStorage), use that
1028
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
1029
- await this.loadUserComments(includeDismissed);
1042
+ // Load saved comments: uses the comment panel's filters (restored from localStorage by setPR)
1043
+ await this.loadUserComments();
1030
1044
 
1031
1045
  // Initialize analysis history manager if review ID is available
1032
1046
  // The review ID is needed to fetch analysis runs from the database
@@ -1106,8 +1120,7 @@ class PRManager {
1106
1120
  * the existing mirror.
1107
1121
  */
1108
1122
  async _rerenderAllOverlays({ analysisRunId, syncExternal = false } = {}) {
1109
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
1110
- await this.loadUserComments(includeDismissed);
1123
+ await this.loadUserComments();
1111
1124
  await this.loadAISuggestions(null, analysisRunId);
1112
1125
  // Skip external-comment re-rendering entirely when the feature is off.
1113
1126
  // The manager is never populated with rows in that case, so there's
@@ -4165,8 +4178,7 @@ class PRManager {
4165
4178
 
4166
4179
  async _reanchorInlineFeedbackAfterDeferredRender() {
4167
4180
  try {
4168
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
4169
- await this.loadUserComments(includeDismissed);
4181
+ await this.loadUserComments();
4170
4182
  await this.loadAISuggestions(null, this.selectedRunId);
4171
4183
  } catch (err) {
4172
4184
  console.error('Failed to re-anchor inline feedback after deferred diff render:', err);
@@ -6121,8 +6133,7 @@ class PRManager {
6121
6133
  // Remove form annotation
6122
6134
  this.pierreBridge.removeAnnotation(fileName, annotationId);
6123
6135
  // Reload comments to show the new one
6124
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
6125
- await this.loadUserComments(includeDismissed);
6136
+ await this.loadUserComments();
6126
6137
 
6127
6138
  // Legacy-path side-effects: clear the dragged range, auto-expand in
6128
6139
  // minimize mode, and notify the AI chat context. Parity with
@@ -6318,10 +6329,7 @@ class PRManager {
6318
6329
  if (editFormEl) editFormEl.remove();
6319
6330
  commentDiv.classList.remove('editing-mode');
6320
6331
 
6321
- // Notify AI Panel about the updated comment body
6322
- if (window.aiPanel?.updateComment) {
6323
- window.aiPanel.updateComment(commentId, { body: editedText });
6324
- }
6332
+ this.patchUserComment(commentId, { body: editedText });
6325
6333
 
6326
6334
  } catch (error) {
6327
6335
  console.error('Error saving comment:', error);
@@ -6367,14 +6375,10 @@ class PRManager {
6367
6375
 
6368
6376
  const apiResult = await response.json();
6369
6377
 
6370
- // Check if dismissed comments filter is enabled for AI Panel updates
6371
- const showDismissed = window.aiPanel?.showDismissedComments || false;
6372
-
6373
6378
  // Always remove the comment from the diff view (design decision: dismissed comments never shown in diff)
6374
6379
  const commentRow = document.querySelector(`[data-comment-id="${commentId}"]`);
6375
6380
  if (commentRow) {
6376
6381
  commentRow.remove();
6377
- this.updateCommentCount();
6378
6382
  }
6379
6383
 
6380
6384
  // Also handle file-level comment cards
@@ -6385,16 +6389,11 @@ class PRManager {
6385
6389
  if (zone && this.fileCommentManager) {
6386
6390
  this.fileCommentManager.updateCommentCount(zone);
6387
6391
  }
6388
- this.updateCommentCount();
6389
6392
  }
6390
6393
 
6391
- // Update AI Panel - transition to dismissed state or remove based on filter
6392
- if (showDismissed && window.aiPanel?.updateComment) {
6393
- // Update comment status to 'inactive' so it renders with dismissed styling in AI Panel
6394
- window.aiPanel.updateComment(commentId, { status: 'inactive' });
6395
- } else if (window.aiPanel?.removeComment) {
6396
- window.aiPanel.removeComment(commentId);
6397
- }
6394
+ // Updates the counts, the minimizer, and the AI panel (dismissed styling
6395
+ // when it shows dismissed comments, otherwise removed)
6396
+ this.patchUserComment(commentId, { status: 'inactive' });
6398
6397
 
6399
6398
  // If a parent suggestion existed, the suggestion card is still collapsed/dismissed in the diff view.
6400
6399
  // Update AIPanel to show the suggestion as 'dismissed' (matching its visual state).
@@ -6412,11 +6411,6 @@ class PRManager {
6412
6411
  }
6413
6412
  }
6414
6413
 
6415
- // Refresh minimize-mode indicators so deleted comments no longer show
6416
- if (this.commentMinimizer) {
6417
- this.commentMinimizer.refreshIndicators();
6418
- }
6419
-
6420
6414
  // Show success toast
6421
6415
  if (window.toast) {
6422
6416
  window.toast.showSuccess('Comment dismissed');
@@ -6446,9 +6440,7 @@ class PRManager {
6446
6440
  if (!response.ok) throw new Error('Failed to restore comment');
6447
6441
 
6448
6442
  // Reload comments to update both the diff view and AI panel
6449
- // Pass the current filter state from the AI panel
6450
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
6451
- await this.loadUserComments(includeDismissed);
6443
+ await this.loadUserComments();
6452
6444
 
6453
6445
  // Show success toast
6454
6446
  if (window.toast) {
@@ -6479,10 +6471,8 @@ class PRManager {
6479
6471
  * Clear all user comments (soft-delete with confirmation for bulk operations)
6480
6472
  */
6481
6473
  async clearAllUserComments() {
6482
- // Count both line-level and file-level user comments
6483
- const lineCommentRows = document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)');
6484
- const fileCommentCards = document.querySelectorAll('.file-comment-card.user-comment');
6485
- const totalComments = lineCommentRows.length + fileCommentCards.length;
6474
+ const totalComments = this.getPendingCommentCount();
6475
+ const hasPosted = (this.userComments || []).some(window.PostedComment.isPostedComment);
6486
6476
 
6487
6477
  if (totalComments === 0) {
6488
6478
  if (window.toast?.showInfo) {
@@ -6498,7 +6488,7 @@ class PRManager {
6498
6488
 
6499
6489
  const dialogResult = await window.confirmDialog.show({
6500
6490
  title: 'Clear All Comments?',
6501
- message: `This will dismiss all ${totalComments} comment${totalComments !== 1 ? 's' : ''}. You can restore them later.`,
6491
+ message: `This will dismiss all ${totalComments} pending comment${totalComments !== 1 ? 's' : ''}. You can restore them later.${hasPosted ? ' Posted comments are kept.' : ''}`,
6502
6492
  confirmText: 'Clear All',
6503
6493
  confirmClass: 'btn-danger'
6504
6494
  });
@@ -6513,30 +6503,11 @@ class PRManager {
6513
6503
  if (!response.ok) throw new Error('Failed to delete comments');
6514
6504
 
6515
6505
  const result = await response.json();
6516
- const deletedCount = result.deletedCount || totalComments;
6517
-
6518
- // Remove line-level comment rows from DOM
6519
- lineCommentRows.forEach(row => row.remove());
6520
-
6521
- // Remove file-level comment cards from DOM
6522
- fileCommentCards.forEach(card => {
6523
- const zone = card.closest('.file-comments-zone');
6524
- card.remove();
6525
-
6526
- // Update the file comment zone header button state
6527
- if (zone && this.fileCommentManager) {
6528
- this.fileCommentManager.updateCommentCount(zone);
6529
- }
6530
- });
6531
-
6532
- // Remove line-level and file-level comment elements from diff view
6533
- // (They have been soft-deleted, so should not appear in the diff panel per design decision)
6534
- // The comments array will be reloaded below with proper dismissed state.
6506
+ const deletedCount = result.deletedCount ?? totalComments;
6535
6507
 
6536
6508
  // Reload comments to update both internal state and AI Panel
6537
6509
  // This shows dismissed comments in AI Panel if filter is enabled, matching individual deletion behavior
6538
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
6539
- await this.loadUserComments(includeDismissed);
6510
+ await this.loadUserComments();
6540
6511
 
6541
6512
  // Update dismissed suggestions in the diff view UI
6542
6513
  // (AI Panel is already updated by loadUserComments via setComments)
@@ -6561,41 +6532,48 @@ class PRManager {
6561
6532
  }
6562
6533
 
6563
6534
  /**
6564
- * Load user comments from API
6565
- * @param {boolean} [includeDismissed=false] - Whether to include dismissed (inactive) comments
6566
- * When true, dismissed comments are returned by the API so they can be shown in the AI Panel.
6567
- * Note: Dismissed comments are NEVER shown in the diff panel per design decision.
6568
- */
6569
- async loadUserComments(includeDismissed = false) {
6535
+ * Load user comments from API and render them.
6536
+ *
6537
+ * Every user comment is fetched, dismissed ones included, so the cache
6538
+ * matches what live edits leave in it and the hidden-comments notice can
6539
+ * count from data. What shows follows the comment panel's filters
6540
+ * (getCommentFilterState), read at render time, so reloads triggered by
6541
+ * events (live sync, tab becoming visible) keep what the panel shows.
6542
+ * Dismissed comments are NEVER shown in the diff panel (design decision);
6543
+ * they show in the AI Panel when its "Show dismissed" filter is on.
6544
+ * @returns {Promise<boolean|undefined>} true once rendered, false if the
6545
+ * reload failed, undefined when no PR is loaded. A load overtaken by a
6546
+ * newer one resolves with the newer load's result.
6547
+ */
6548
+ loadUserComments() {
6549
+ const load = this._loadUserComments();
6550
+ this._latestUserCommentsLoad = load;
6551
+ return load;
6552
+ }
6553
+
6554
+ async _loadUserComments() {
6570
6555
  if (!this.currentPR) return;
6571
6556
 
6572
- try {
6573
- const queryParam = includeDismissed ? '?includeDismissed=true' : '';
6574
- const response = await fetch(`/api/reviews/${this.currentPR.id}/comments${queryParam}`);
6575
- if (!response.ok) return;
6557
+ const generation = (this._userCommentsLoadGeneration || 0) + 1;
6558
+ this._userCommentsLoadGeneration = generation;
6576
6559
 
6577
- const data = await response.json();
6578
- this.userComments = data.comments || [];
6579
-
6580
- // Separate file-level and line-level comments for diff view rendering
6581
- // DESIGN DECISION: Dismissed comments are NEVER shown in the diff panel.
6582
- // They only appear in the AI/Review Panel when the "show dismissed" filter is ON.
6583
- // This provides cleaner UX - the diff view shows only active comments, while
6584
- // the AI Panel serves as the "inbox" where you can optionally see and restore dismissed items.
6585
- const fileLevelComments = [];
6586
- const lineLevelComments = [];
6587
-
6588
- this.userComments.forEach(comment => {
6589
- // Skip inactive (dismissed) comments - they should not appear in the diff view
6590
- if (comment.status === 'inactive') {
6591
- return;
6592
- }
6593
- if (comment.is_file_level === 1) {
6594
- fileLevelComments.push(comment);
6595
- } else {
6596
- lineLevelComments.push(comment);
6597
- }
6598
- });
6560
+ try {
6561
+ let comments;
6562
+ let fileLevelComments;
6563
+ let lineLevelComments;
6564
+ // A save, edit or dismissal that lands while this load is in flight
6565
+ // isn't in the fetched data. Rendering that data would wipe the new row,
6566
+ // so fetch again (a few times at most) until the cache stood still.
6567
+ for (let attempt = 1; ; attempt++) {
6568
+ const cacheVersion = this._userCommentsVersion || 0;
6569
+ ({ comments, fileLevelComments, lineLevelComments } = await this._fetchUserCommentsForRender());
6570
+ if (generation !== this._userCommentsLoadGeneration) return this._latestUserCommentsLoad;
6571
+ if (cacheVersion === (this._userCommentsVersion || 0) || attempt >= 3) break;
6572
+ }
6573
+
6574
+ // Assign the cache only now, next to the render: an overtaken or retried
6575
+ // load must not replace data that a save made meanwhile.
6576
+ this.userComments = comments;
6599
6577
 
6600
6578
  // Clear existing comment rows before re-rendering
6601
6579
  document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)').forEach(row => row.remove());
@@ -6607,21 +6585,6 @@ class PRManager {
6607
6585
  }
6608
6586
  }
6609
6587
 
6610
- // Ensure every comment's target line is reachable in the DOM before
6611
- // rendering. `ensureLinesVisible` handles both engines — for Pierre
6612
- // files it expands collapsed gaps via `addContextRanges` so the
6613
- // annotation row exists; for legacy files it expands hidden hunks.
6614
- // Without this, comments on lines outside the default hunks render
6615
- // nowhere on reload and "jump to comment" silently fails.
6616
- if (lineLevelComments.length > 0) {
6617
- await this.ensureLinesVisible(lineLevelComments.map(c => ({
6618
- file: c.file,
6619
- line_start: c.line_start,
6620
- line_end: c.line_end || c.line_start,
6621
- side: c.side || 'RIGHT',
6622
- })));
6623
- }
6624
-
6625
6588
  // Partition line-level comments by rendering engine
6626
6589
  const pierreComments = [];
6627
6590
  const legacyComments = [];
@@ -6669,28 +6632,125 @@ class PRManager {
6669
6632
  });
6670
6633
  }
6671
6634
 
6672
- // Load file-level comments into their zones (only active comments reach
6673
- // here). Always pass the list, even when empty, so the cards of a
6635
+ // Always pass the list, even when empty, so the cards of a
6674
6636
  // deleted or dismissed last comment are removed. null suggestions
6675
6637
  // leaves the file-level AI cards alone.
6676
6638
  if (this.fileCommentManager) {
6677
6639
  this.fileCommentManager.loadFileComments(fileLevelComments, null);
6678
6640
  }
6679
6641
 
6680
- // Populate AI Panel with all comments (including dismissed if requested)
6681
- if (window.aiPanel?.setComments) {
6682
- window.aiPanel.setComments(this.userComments);
6683
- }
6642
+ // Also refreshes the file-comment zones and minimize-mode indicators
6643
+ this.applyPostedCommentVisibility();
6684
6644
 
6685
6645
  this.updateCommentCount();
6686
-
6687
- // Refresh minimize-mode indicators (no-op when minimize mode is off)
6688
- if (this.commentMinimizer) {
6689
- this.commentMinimizer.refreshIndicators();
6690
- }
6646
+ return true;
6691
6647
  } catch (error) {
6692
6648
  console.error('Error loading user comments:', error);
6649
+ return false;
6650
+ }
6651
+ }
6652
+
6653
+ /**
6654
+ * Fetch the review's user comments, split them for rendering, and make
6655
+ * every line-level comment's target line reachable in the DOM.
6656
+ * @private
6657
+ */
6658
+ async _fetchUserCommentsForRender() {
6659
+ const response = await fetch(`/api/reviews/${this.currentPR.id}/comments?includeDismissed=true`);
6660
+ if (!response.ok) throw new Error('Failed to load comments');
6661
+
6662
+ const data = await response.json();
6663
+ const comments = data.comments || [];
6664
+
6665
+ // Separate file-level and line-level comments for diff view rendering
6666
+ // DESIGN DECISION: Dismissed comments are NEVER shown in the diff panel.
6667
+ // They only appear in the AI/Review Panel when the "show dismissed" filter is ON.
6668
+ // Posted comments remain visible unless the reviewer opts to hide them.
6669
+ const fileLevelComments = [];
6670
+ const lineLevelComments = [];
6671
+ comments.forEach(comment => {
6672
+ if (comment.status === 'inactive') {
6673
+ return;
6674
+ }
6675
+ if (comment.is_file_level === 1) {
6676
+ fileLevelComments.push(comment);
6677
+ } else {
6678
+ lineLevelComments.push(comment);
6679
+ }
6680
+ });
6681
+
6682
+ // Ensure every comment's target line is reachable in the DOM before
6683
+ // rendering. `ensureLinesVisible` handles both engines — for Pierre
6684
+ // files it expands collapsed gaps via `addContextRanges` so the
6685
+ // annotation row exists; for legacy files it expands hidden hunks.
6686
+ // Without this, comments on lines outside the default hunks render
6687
+ // nowhere on reload and "jump to comment" silently fails.
6688
+ if (lineLevelComments.length > 0) {
6689
+ await this.ensureLinesVisible(lineLevelComments.map(c => ({
6690
+ file: c.file,
6691
+ line_start: c.line_start,
6692
+ line_end: c.line_end || c.line_start,
6693
+ side: c.side || 'RIGHT',
6694
+ })));
6693
6695
  }
6696
+
6697
+ return { comments, fileLevelComments, lineLevelComments };
6698
+ }
6699
+
6700
+ /**
6701
+ * The comment panel's user-comment filters. Falls back to the panel's
6702
+ * show-dismissed flag and this review's posted setting when the panel
6703
+ * predates getCommentFilterState (or is a test stub).
6704
+ * @returns {{includeDismissed: boolean, showPosted: boolean}}
6705
+ */
6706
+ getCommentFilterState() {
6707
+ const state = window.aiPanel?.getCommentFilterState?.();
6708
+ if (state) return state;
6709
+ return {
6710
+ includeDismissed: !!window.aiPanel?.showDismissedComments,
6711
+ showPosted: !(window.PostedComment?.isHidePostedInEffect() ?? false)
6712
+ };
6713
+ }
6714
+
6715
+ /**
6716
+ * How many cached user comments the panel's filters hide, counted from the
6717
+ * comment data (never DOM rows), for the panel's hidden-comments notice.
6718
+ * @param {{includeDismissed: boolean, showPosted: boolean}} [filter]
6719
+ * @returns {{posted: number, dismissed: number}}
6720
+ */
6721
+ getHiddenCommentCounts(filter = this.getCommentFilterState()) {
6722
+ const comments = this.userComments || [];
6723
+ return {
6724
+ posted: window.PostedComment.countHiddenPostedComments(comments, !filter.showPosted),
6725
+ dismissed: filter.includeDismissed ? 0 : comments.filter(c => c.status === 'inactive').length
6726
+ };
6727
+ }
6728
+
6729
+ applyPostedCommentVisibility() {
6730
+ const { shouldHidePostedComment } = window.PostedComment;
6731
+ const filter = this.getCommentFilterState();
6732
+ const hidePosted = !filter.showPosted;
6733
+ document.querySelectorAll('[data-comment-status]').forEach(element => {
6734
+ element.classList.toggle('posted-comment-hidden',
6735
+ shouldHidePostedComment({ status: element.dataset.commentStatus, publication: element.dataset.commentPublication === 'none' ? null : { state: element.dataset.commentPublication } }, hidePosted));
6736
+ });
6737
+ window.aiPanel?.setHiddenCommentCounts?.(this.getHiddenCommentCounts(filter));
6738
+ window.aiPanel?.setComments?.((this.userComments || []).filter(c =>
6739
+ (c.status !== 'inactive' || filter.includeDismissed) &&
6740
+ !shouldHidePostedComment(c, hidePosted)
6741
+ ));
6742
+
6743
+ // Hidden posted comments must not drive the file-comment header state or
6744
+ // the minimize-mode indicators. The minimizer's observer watches childList
6745
+ // only, so a class toggle needs an explicit refresh.
6746
+ if (this.fileCommentManager) {
6747
+ document.querySelectorAll('.file-comments-zone').forEach(zone => {
6748
+ if (zone.querySelector('.file-comments-container')) {
6749
+ this.fileCommentManager.updateCommentCount(zone);
6750
+ }
6751
+ });
6752
+ }
6753
+ this.commentMinimizer?.refreshIndicators();
6694
6754
  }
6695
6755
 
6696
6756
  /**
@@ -6921,9 +6981,7 @@ class PRManager {
6921
6981
  * Notify panels and navigator after a successful adoption
6922
6982
  */
6923
6983
  _notifyAdoption(suggestionId, newComment) {
6924
- if (window.aiPanel?.addComment) {
6925
- window.aiPanel.addComment(newComment);
6926
- }
6984
+ this.registerUserComment(newComment);
6927
6985
 
6928
6986
  if (this.suggestionNavigator?.suggestions) {
6929
6987
  const updatedSuggestions = this.suggestionNavigator.suggestions.map(s =>
@@ -6935,13 +6993,6 @@ class PRManager {
6935
6993
  if (window.aiPanel) {
6936
6994
  window.aiPanel.updateFindingStatus(suggestionId, 'adopted');
6937
6995
  }
6938
-
6939
- this.updateCommentCount();
6940
-
6941
- // Refresh minimize-mode indicators so the adopted comment is reflected
6942
- if (this.commentMinimizer) {
6943
- this.commentMinimizer.refreshIndicators();
6944
- }
6945
6996
  }
6946
6997
 
6947
6998
  /**
@@ -7308,6 +7359,7 @@ class PRManager {
7308
7359
  onPreview: () => this.openPreviewModal(),
7309
7360
  onClear: () => this.clearAllUserComments(),
7310
7361
  onShare: () => this.openSharePage(),
7362
+ onHistory: window.PAIR_REVIEW_LOCAL_MODE ? null : () => this.openReviewHistory(),
7311
7363
  shareUrl: validatedShareUrl,
7312
7364
  shareIcon: shareConfig?.icon || null,
7313
7365
  shareLabel: shareConfig?.label || 'Share',
@@ -7338,6 +7390,17 @@ class PRManager {
7338
7390
  this.reviewModal.show();
7339
7391
  }
7340
7392
 
7393
+ /**
7394
+ * Open the review history: what this review posted to the host. PR mode only.
7395
+ */
7396
+ openReviewHistory() {
7397
+ if (window.PAIR_REVIEW_LOCAL_MODE || !this.currentPR?.id || !window.ReviewHistoryModal) return;
7398
+ if (!this.reviewHistoryModal) {
7399
+ this.reviewHistoryModal = new window.ReviewHistoryModal();
7400
+ }
7401
+ this.reviewHistoryModal.show(this.currentPR.id);
7402
+ }
7403
+
7341
7404
  /**
7342
7405
  * Open preview modal
7343
7406
  */
@@ -7412,14 +7475,146 @@ class PRManager {
7412
7475
  }
7413
7476
 
7414
7477
  /**
7415
- * Update comment count display
7416
- * Note: Dismissed comments are never in the diff DOM (design decision), so we simply count all visible elements.
7478
+ * Record a user comment just created (saved, adopted, or adopted with edit).
7479
+ * Call it once the comment's row or card is in the DOM: it updates the
7480
+ * comment cache, the AI panel, the comment counts and the minimize-mode
7481
+ * indicators.
7482
+ * @param {Object} comment - The new comment; status defaults to 'active'
7483
+ * @returns {Object} The comment as cached
7484
+ */
7485
+ registerUserComment(comment) {
7486
+ const stored = { status: 'active', ...comment };
7487
+ this.userComments = [...(this.userComments || []).filter(c => c.id !== stored.id), stored];
7488
+ // Lets an in-flight loadUserComments see that its data is stale
7489
+ this._userCommentsVersion = (this._userCommentsVersion || 0) + 1;
7490
+ window.aiPanel?.addComment?.(stored);
7491
+ this.updateCommentCount();
7492
+ this.commentMinimizer?.refreshIndicators();
7493
+ return stored;
7494
+ }
7495
+
7496
+ /**
7497
+ * Apply a change to a cached user comment (an edit, or a dismissal) after
7498
+ * the DOM reflects it. Updates the AI panel, the comment counts and the
7499
+ * minimize-mode indicators. A dismissed comment stays in the AI panel only
7500
+ * when it is showing dismissed comments.
7501
+ * @param {number} commentId
7502
+ * @param {Object} updates - e.g. { body } or { status: 'inactive' }
7503
+ */
7504
+ patchUserComment(commentId, updates) {
7505
+ const before = (this.userComments || []).find(c => c.id === commentId);
7506
+ this.userComments = (this.userComments || []).map(c => c.id === commentId ? { ...c, ...updates } : c);
7507
+ // Editing a posted comment changes whether it differs from what was
7508
+ // posted; only the server knows the posted text, so ask it.
7509
+ if (updates.body !== undefined && before && window.PostedComment?.isPostedComment(before)) {
7510
+ window.PostedComment.setUpdateError(commentId, null);
7511
+ this.refreshCommentPublication(commentId);
7512
+ }
7513
+ this._userCommentsVersion = (this._userCommentsVersion || 0) + 1;
7514
+ if (window.aiPanel?.setHiddenCommentCounts) {
7515
+ window.aiPanel.setHiddenCommentCounts(this.getHiddenCommentCounts());
7516
+ }
7517
+ if (updates.status === 'inactive' && !this.getCommentFilterState().includeDismissed) {
7518
+ window.aiPanel?.removeComment?.(commentId);
7519
+ } else {
7520
+ window.aiPanel?.updateComment?.(commentId, updates);
7521
+ }
7522
+ this.updateCommentCount();
7523
+ this.commentMinimizer?.refreshIndicators();
7524
+ }
7525
+
7526
+ /**
7527
+ * Replace a cached comment with the server's copy (fresh publication) and
7528
+ * re-render its edited-since-posted note in place, in every renderer.
7529
+ * @param {Object} comment - Comment from the server
7530
+ */
7531
+ applyServerComment(comment) {
7532
+ if (!comment) return;
7533
+ this.userComments = (this.userComments || []).map(c => c.id === comment.id ? { ...c, ...comment } : c);
7534
+ this._userCommentsVersion = (this._userCommentsVersion || 0) + 1;
7535
+ const cached = this.userComments.find(c => c.id === comment.id) || comment;
7536
+ // @pierre/diffs re-renders annotations from their stored data
7537
+ for (const annotation of this.pierreBridge?.getAnnotations?.(cached.file, 'comment') || []) {
7538
+ if (annotation.metadata?.data?.id === cached.id) Object.assign(annotation.metadata.data, cached);
7539
+ }
7540
+ window.PostedComment?.findRenderedComments(comment.id)
7541
+ .forEach(element => window.PostedComment.syncEditedSincePosted(element, cached));
7542
+ window.aiPanel?.updateComment?.(comment.id, { body: cached.body, publication: cached.publication });
7543
+ if (this.reviewModal?.isVisible) this.reviewModal.updateCommentCount();
7544
+ }
7545
+
7546
+ /** Fetch one comment's publication after an edit. Best effort. */
7547
+ async refreshCommentPublication(commentId) {
7548
+ const reviewId = this.currentPR?.id;
7549
+ if (!reviewId || window.PAIR_REVIEW_LOCAL_MODE) return;
7550
+ try {
7551
+ const response = await fetch(`/api/reviews/${reviewId}/comments/${commentId}`);
7552
+ if (!response.ok) return;
7553
+ this.applyServerComment(await response.json());
7554
+ } catch (error) {
7555
+ console.warn('Could not refresh comment publication:', error);
7556
+ }
7557
+ }
7558
+
7559
+ /**
7560
+ * Update an edited, already-posted comment on the host in place. Never
7561
+ * creates a comment. On failure the comment stays "Edited since posted" and
7562
+ * the server's message is shown beside it.
7563
+ * @param {number|string} commentId
7564
+ * @returns {Promise<{ok: boolean, comment?: Object, error?: Object}>}
7565
+ */
7566
+ async updatePostedCommentOnHost(commentId) {
7567
+ const PostedComment = window.PostedComment;
7568
+ const reviewId = this.currentPR?.id;
7569
+ if (!PostedComment || !reviewId) return { ok: false, error: { message: 'No review loaded' } };
7570
+ const id = Number(commentId);
7571
+ this._hostUpdatesInFlight = this._hostUpdatesInFlight || new Map();
7572
+ if (this._hostUpdatesInFlight.has(id)) return this._hostUpdatesInFlight.get(id);
7573
+
7574
+ const run = (async () => {
7575
+ PostedComment.setUpdateBusy(id, true);
7576
+ const result = await PostedComment.requestHostUpdate(reviewId, id);
7577
+ PostedComment.setUpdateError(id, result.ok ? null : result.error);
7578
+ const comment = result.ok ? result.comment
7579
+ : (this.userComments || []).find(c => c.id === id);
7580
+ // Re-rendering the note also clears the busy state
7581
+ if (comment) {
7582
+ if (result.ok) this.applyServerComment(comment);
7583
+ else PostedComment.findRenderedComments(id).forEach(el => PostedComment.syncEditedSincePosted(el, comment));
7584
+ } else {
7585
+ PostedComment.setUpdateBusy(id, false);
7586
+ }
7587
+ return result;
7588
+ })();
7589
+ this._hostUpdatesInFlight.set(id, run);
7590
+ try {
7591
+ return await run;
7592
+ } finally {
7593
+ this._hostUpdatesInFlight.delete(id);
7594
+ }
7595
+ }
7596
+
7597
+ /** Comments the next submit will post: what "will be submitted" counts. */
7598
+ getPendingCommentCount() {
7599
+ return (this.userComments || []).filter(window.PostedComment.isPendingComment).length;
7600
+ }
7601
+
7602
+ /**
7603
+ * Comments a non-draft submit will publish: the pending ones plus those
7604
+ * already saved to the pending draft review, which GitHub publishes with it.
7605
+ * Used only to decide whether a review has any comments at all.
7606
+ */
7607
+ getSubmittableCommentCount() {
7608
+ return (this.userComments || []).filter(c => window.PostedComment.isPendingComment(c) ||
7609
+ (c.status === 'active' && window.PostedComment.publicationState(c) === 'draft')).length;
7610
+ }
7611
+
7612
+ /**
7613
+ * Update comment count display independently of diff visibility.
7417
7614
  */
7418
7615
  updateCommentCount() {
7419
- // Count both line-level comments (.user-comment-row) and file-level comments (.file-comment-card.user-comment)
7420
- const lineComments = document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)').length;
7421
- const fileComments = document.querySelectorAll('.file-comment-card.user-comment').length;
7422
- const userComments = lineComments + fileComments;
7616
+ const userComments = this.getPendingCommentCount();
7617
+ if (this.reviewModal?.isVisible) this.reviewModal.updateCommentCount();
7423
7618
 
7424
7619
  if (this.splitButton) {
7425
7620
  this.splitButton.updateCommentCount(userComments);
@@ -7445,54 +7640,6 @@ class PRManager {
7445
7640
  }
7446
7641
  }
7447
7642
 
7448
- /**
7449
- * Submit review to GitHub
7450
- */
7451
- async submitReview() {
7452
- const reviewEvent = document.getElementById('review-event').value;
7453
- const reviewBody = document.getElementById('review-body').value.trim();
7454
- const submitBtn = document.getElementById('submit-review-btn');
7455
-
7456
- // Count BOTH line-level and file-level comments for validation
7457
- const lineComments = document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)').length;
7458
- const fileComments = document.querySelectorAll('.file-comment-card.user-comment').length;
7459
- const totalComments = lineComments + fileComments;
7460
- if (reviewEvent === 'REQUEST_CHANGES' && !reviewBody && totalComments === 0) {
7461
- alert('Please add comments or a review summary when requesting changes.');
7462
- return;
7463
- }
7464
-
7465
- const originalText = submitBtn.textContent;
7466
- submitBtn.textContent = 'Submitting...';
7467
- submitBtn.disabled = true;
7468
-
7469
- try {
7470
- const response = await fetch(`/api/pr/${this.currentPR.owner}/${this.currentPR.repo}/${this.currentPR.number}/submit-review`, {
7471
- method: 'POST',
7472
- headers: { 'Content-Type': 'application/json' },
7473
- body: JSON.stringify({ event: reviewEvent, body: reviewBody })
7474
- });
7475
-
7476
- if (!response.ok) {
7477
- const errorData = await response.json();
7478
- throw new Error(errorData.error || 'Failed to submit review');
7479
- }
7480
-
7481
- const result = await response.json();
7482
- alert(`Review submitted successfully! ${result.message}`);
7483
-
7484
- document.getElementById('review-body').value = '';
7485
- document.getElementById('review-event').value = 'COMMENT';
7486
-
7487
- } catch (error) {
7488
- console.error('Error submitting review:', error);
7489
- alert(`Failed to submit review: ${error.message}`);
7490
- } finally {
7491
- submitBtn.textContent = originalText;
7492
- submitBtn.disabled = false;
7493
- }
7494
- }
7495
-
7496
7643
  /**
7497
7644
  * Escape HTML characters
7498
7645
  */
@@ -8916,8 +9063,7 @@ class PRManager {
8916
9063
  // comments targeting lines in these files find their DOM targets.
8917
9064
  // loadUserComments() is idempotent (clears existing comment rows first).
8918
9065
  if (newFilesRendered) {
8919
- const includeDismissed = window.aiPanel?.showDismissedComments || false;
8920
- await this.loadUserComments(includeDismissed);
9066
+ await this.loadUserComments();
8921
9067
  }
8922
9068
  } catch (error) {
8923
9069
  console.error('Error loading context files:', error);