@in-the-loop-labs/pair-review 4.1.1 → 5.0.1

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 (71) hide show
  1. package/README.md +81 -13
  2. package/package.json +6 -2
  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/plugin-pair-loop/skills/loop/SKILL.md +17 -8
  7. package/public/css/ai-summary-modal.css +1 -1
  8. package/public/css/analysis-config.css +33 -49
  9. package/public/css/council-card.css +118 -0
  10. package/public/css/council-dropdown.css +164 -0
  11. package/public/css/pr.css +668 -393
  12. package/public/css/repo-settings.css +15 -305
  13. package/public/css/settings.css +1141 -0
  14. package/public/css/snippet-manager.css +233 -0
  15. package/public/index.html +40 -59
  16. package/public/js/components/AIPanel.js +82 -16
  17. package/public/js/components/ChatPanel.js +401 -5
  18. package/public/js/components/CouncilCard.js +202 -0
  19. package/public/js/components/CouncilDropdown.js +292 -0
  20. package/public/js/components/DiffOptionsDropdown.js +177 -4
  21. package/public/js/components/SnippetManager.js +463 -0
  22. package/public/js/index.js +7 -30
  23. package/public/js/local.js +20 -2
  24. package/public/js/modules/comment-manager.js +8 -1
  25. package/public/js/modules/comment-minimizer.js +249 -190
  26. package/public/js/modules/diff-renderer.js +16 -4
  27. package/public/js/modules/external-comment-manager.js +414 -48
  28. package/public/js/modules/file-comment-manager.js +28 -21
  29. package/public/js/modules/hunk-summary-renderer.js +155 -29
  30. package/public/js/modules/pierre-bridge.js +2513 -0
  31. package/public/js/modules/pierre-context.js +345 -0
  32. package/public/js/modules/suggestion-manager.js +176 -20
  33. package/public/js/modules/tour-renderer.js +400 -184
  34. package/public/js/pr.js +1614 -158
  35. package/public/js/repo-settings.js +60 -284
  36. package/public/js/settings.js +1086 -0
  37. package/public/js/theme-bootstrap.js +40 -0
  38. package/public/js/theme.js +247 -0
  39. package/public/js/utils/provider-model.js +3 -3
  40. package/public/js/utils/suggestion-ui.js +157 -8
  41. package/public/local.html +20 -31
  42. package/public/pr.html +14 -23
  43. package/public/repo-settings.html +24 -14
  44. package/public/settings.html +138 -0
  45. package/public/setup.html +8 -13
  46. package/src/chat/api-reference.js +9 -5
  47. package/src/chat/prompt-builder.js +8 -1
  48. package/src/config.js +15 -6
  49. package/src/database.js +307 -14
  50. package/src/external/github-adapter.js +39 -5
  51. package/src/headless/delegate.js +682 -0
  52. package/src/local-review.js +10 -10
  53. package/src/local-scope.js +9 -0
  54. package/src/main.js +276 -157
  55. package/src/mcp-stdio.js +24 -1
  56. package/src/review-config.js +93 -25
  57. package/src/routes/chat.js +2 -2
  58. package/src/routes/config.js +12 -10
  59. package/src/routes/external-comments.js +5 -1
  60. package/src/routes/local.js +2 -4
  61. package/src/routes/mcp.js +18 -13
  62. package/src/routes/reviews.js +223 -4
  63. package/src/routes/settings.js +252 -0
  64. package/src/routes/setup.js +80 -1
  65. package/src/routes/shared.js +31 -29
  66. package/src/routes/snippets.js +154 -0
  67. package/src/routes/stack-analysis.js +17 -14
  68. package/src/server.js +86 -18
  69. package/src/settings/global-settings-service.js +472 -0
  70. package/src/settings/registry.js +624 -0
  71. package/src/utils/db-identity.js +44 -0
package/public/js/pr.js CHANGED
@@ -57,6 +57,20 @@ class PRManager {
57
57
  return window.HunkParser?.AUTO_EXPAND_THRESHOLD || 6;
58
58
  }
59
59
 
60
+ static PIERRE_HIGHLIGHT_MAX_PATCH_CHARS = 300 * 1024;
61
+ static PIERRE_HIGHLIGHT_MAX_PATCH_LINES = 3000;
62
+ static PIERRE_HIGHLIGHT_TOTAL_CHARS = 900 * 1024;
63
+ static PIERRE_HIGHLIGHT_TOTAL_LINES = 18000;
64
+ static PIERRE_AUTO_RENDER_MAX_PATCH_CHARS = 500 * 1024;
65
+ static PIERRE_AUTO_RENDER_MAX_PATCH_LINES = 20000;
66
+ static PIERRE_UPGRADE_MAX_PATCH_CHARS = 120 * 1024;
67
+ static PIERRE_UPGRADE_MAX_PATCH_LINES = 3000;
68
+ static PIERRE_UPGRADE_MAX_CONTENT_CHARS = 400 * 1024;
69
+ static PIERRE_UPGRADE_MAX_CONTENT_LINES = 12000;
70
+ static PIERRE_UPGRADE_CONCURRENCY = 4;
71
+ static PIERRE_BACKGROUND_UPGRADE_DELAY_MS = 1000;
72
+ static PIERRE_POINTER_UPGRADE_DELAY_MS = 10000;
73
+
60
74
  // Logo icon - infinity loop rotated for "in-the-loop" branding
61
75
  static LOGO_ICON = `
62
76
  <svg class="logo-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" width="24" height="24">
@@ -98,7 +112,9 @@ class PRManager {
98
112
  this.loadingState = false;
99
113
  this.expandedFolders = new Set();
100
114
  this.expandedSections = new Set();
101
- this.currentTheme = localStorage.getItem('theme') || 'light';
115
+ // Resolved theme ('light'|'dark') — the diff renderer needs a concrete
116
+ // value, never the 'system' preference. Kept in sync by initTheme().
117
+ this.currentTheme = window.PairReviewTheme.resolvePreference();
102
118
  this.suggestionNavigator = null;
103
119
  // AI analysis state
104
120
  this.isAnalyzing = false;
@@ -123,6 +139,16 @@ class PRManager {
123
139
  this.canonicalFileOrder = new Map();
124
140
  // Raw per-file patch text for chat context enrichment
125
141
  this.filePatches = new Map();
142
+ // Current rendered changed files keyed by path. Used to materialize
143
+ // deferred diffs and lazily fetch full-file metadata for line anchors.
144
+ this.changedFilesByPath = new Map();
145
+ this._fileContentsUpgradeState = null;
146
+ this._pierreContentUpgradePromises = new Map();
147
+ // Eligible-by-size files that should get background content upgrade as their
148
+ // lazy Pierre bodies render (set in _upgradeFilesWithContents, reset in
149
+ // renderDiff). Null when no upgrade session is active.
150
+ this._pierreUpgradeCandidates = null;
151
+ this._deferredDiffRenderPromises = new Map();
126
152
  // Analysis history manager - for switching between analysis runs
127
153
  this.analysisHistoryManager = null;
128
154
  // Currently selected analysis run ID (null = latest)
@@ -271,6 +297,76 @@ class PRManager {
271
297
  this.suggestionManager = new window.SuggestionManager(this);
272
298
  this.fileCommentManager = window.FileCommentManager ? new window.FileCommentManager(this) : null;
273
299
 
300
+ // Initialize PierreBridge for @pierre/diffs rendering.
301
+ // Read the persisted diff-view preference so the first render uses the
302
+ // saved style (no flash, no double render). localStorage is the single
303
+ // source of truth shared with DiffOptionsDropdown; readPersistedDiffView
304
+ // (from DiffOptionsDropdown.js, loaded first) owns the key + validation.
305
+ const initialDiffStyle = window.readPersistedDiffView
306
+ ? window.readPersistedDiffView()
307
+ : (localStorage.getItem('pair-review-diff-view') === 'split' ? 'split' : 'unified');
308
+ this.pierreBridge = window.PierreBridge ? new window.PierreBridge({
309
+ theme: this.currentTheme,
310
+ diffStyle: initialDiffStyle,
311
+ onCommentClick: (fileName, lineNumber, side, target) => {
312
+ // target.isRange is true when the user selected multiple lines
313
+ const diffPosition = this.pierreBridge.getDiffPosition(fileName, target.start, target.side);
314
+ if (target.isRange) {
315
+ this.showCommentForm(null, target.start, fileName, diffPosition, target.end, target.side);
316
+ } else {
317
+ this.showCommentForm(null, lineNumber, fileName, diffPosition, null, side);
318
+ }
319
+ },
320
+ onChatClick: (fileName, lineNumber, side, target) => {
321
+ if (!window.chatPanel) return;
322
+ window.chatPanel.open({
323
+ commentContext: {
324
+ type: 'line',
325
+ body: null,
326
+ file: fileName || '',
327
+ line_start: target.start,
328
+ line_end: target.end,
329
+ side: target.side || side || 'RIGHT',
330
+ source: 'user'
331
+ }
332
+ });
333
+ },
334
+ onHunkExpand: (fileName, hunkIndex, direction, lineCount) => {
335
+ // @pierre/diffs handles expansion natively
336
+ },
337
+ onCommentEdit: (comment) => {
338
+ if (this.commentManager) {
339
+ this.commentManager.editComment(comment.id);
340
+ }
341
+ },
342
+ onCommentDelete: (comment) => {
343
+ if (this.commentManager) {
344
+ this.commentManager.deleteComment(comment.id);
345
+ }
346
+ },
347
+ onSuggestionAdopt: (suggestion) => {
348
+ if (this.suggestionManager) {
349
+ this.suggestionManager.adoptSuggestion(suggestion.id);
350
+ }
351
+ },
352
+ onSuggestionDismiss: (suggestion) => {
353
+ if (this.suggestionManager) {
354
+ this.suggestionManager.dismissSuggestion(suggestion.id);
355
+ }
356
+ },
357
+ onCommentFormSubmit: (fileName, annotationId, data, body) => {
358
+ this._handleCommentFormSubmit(fileName, annotationId, data, body);
359
+ },
360
+ onCommentFormCancel: (fileName, annotationId, data) => {
361
+ this.pierreBridge.removeAnnotation(fileName, annotationId);
362
+ },
363
+ onSuggestionInsert: (textarea, button) => {
364
+ if (this.commentManager) {
365
+ this.commentManager.insertSuggestionBlock(textarea, button);
366
+ }
367
+ },
368
+ }) : null;
369
+
274
370
  // Line range selection state - delegate to lineTracker
275
371
  Object.defineProperty(this, 'rangeSelectionStart', {
276
372
  get: () => this.lineTracker.rangeSelectionStart,
@@ -323,6 +419,12 @@ class PRManager {
323
419
  this.diffOptionsDropdown = new window.DiffOptionsDropdown(diffOptionsBtn, {
324
420
  onToggleWhitespace: (hide) => this.handleWhitespaceToggle(hide),
325
421
  onToggleMinimize: (minimized) => this.handleMinimizeToggle(minimized),
422
+ onDiffViewChange: (mode) => this.handleDiffViewChange(mode),
423
+ diffView: initialDiffStyle,
424
+ // Only offer the Unified/Split control when a Pierre render path can
425
+ // apply it. Without the bridge, handleDiffViewChange no-ops and the
426
+ // legacy renderer stays unified, so a selection would desync.
427
+ diffViewAvailable: Boolean(this.pierreBridge && !this.pierreBridge._disabled),
326
428
  });
327
429
  }
328
430
 
@@ -422,11 +524,7 @@ class PRManager {
422
524
  * Set up event handlers
423
525
  */
424
526
  setupEventHandlers() {
425
- // Theme toggle
426
- const themeToggle = document.getElementById('theme-toggle');
427
- if (themeToggle) {
428
- themeToggle.addEventListener('click', () => this.toggleTheme());
429
- }
527
+ // Theme toggle is wired by the shared helper in initTheme() (js/theme.js).
430
528
 
431
529
  // Analyze button
432
530
  const analyzeBtn = document.getElementById('analyze-btn');
@@ -1306,6 +1404,128 @@ class PRManager {
1306
1404
  for (const filePath of filesWithMounts) this._refreshFileSummaryToggle(filePath);
1307
1405
  }
1308
1406
 
1407
+ /**
1408
+ * Compute per-hunk summary anchor positions for a Pierre-rendered file.
1409
+ *
1410
+ * Legacy rendering (`renderPatch`) captures the first `<tr>` of each hunk as
1411
+ * the anchor. Pierre renders into a shadow DOM we don't own, so instead we
1412
+ * derive each hunk's first rendered line from the patch text and let
1413
+ * PierreBridge slot the summary card below it. Positions come purely from the
1414
+ * patch — the canonical content hashes still come from the backend.
1415
+ *
1416
+ * Anchor rules (mirrors renderPatch's first-rendered-row):
1417
+ * - first line is an addition (`+`) or context (` `) → side 'RIGHT', at the
1418
+ * hunk's NEW start line (the line exists in the new file);
1419
+ * - first line is a deletion (`-`), e.g. a pure-deletion hunk → side
1420
+ * 'LEFT', at the hunk's OLD start line.
1421
+ *
1422
+ * Fails closed on hash/hunk count drift (the same `?w=1` divergence
1423
+ * renderPatch guards against): returns an empty map so summaries simply don't
1424
+ * anchor rather than anchor to the wrong hunk.
1425
+ *
1426
+ * @param {string} patch - Unified diff patch text
1427
+ * @param {string[]|null} hunkHashes - Canonical per-hunk hashes, parallel to
1428
+ * the blocks `parseDiffIntoBlocks` returns
1429
+ * @returns {Map<string, {lineNumber: number, side: string}>}
1430
+ */
1431
+ _computePierreHunkAnchors(patch, hunkHashes) {
1432
+ const anchors = new Map();
1433
+ if (!patch || !Array.isArray(hunkHashes) || hunkHashes.length === 0) return anchors;
1434
+ if (!window.HunkParser?.parseDiffIntoBlocks) return anchors;
1435
+
1436
+ const blocks = window.HunkParser.parseDiffIntoBlocks(patch);
1437
+ // Fail closed on length drift — a misaligned hash would anchor the summary
1438
+ // to the wrong hunk. Symmetric with renderPatch's guard.
1439
+ if (hunkHashes.length !== blocks.length) {
1440
+ if (!this._warnedHunkHashLengthMismatch) {
1441
+ this._warnedHunkHashLengthMismatch = true;
1442
+ console.warn(
1443
+ `[HunkSummary] hunk_hashes length mismatch (pierre): ${hunkHashes.length} ` +
1444
+ `canonical hashes, ${blocks.length} rendered blocks. Dropping hashes for this file.`
1445
+ );
1446
+ }
1447
+ return anchors;
1448
+ }
1449
+
1450
+ blocks.forEach((block, blockIndex) => {
1451
+ const hash = hunkHashes[blockIndex];
1452
+ if (!hash) return; // no canonical hash for this hunk → can't anchor
1453
+ // First rendered line of the hunk (renderPatch skips undefined/null but
1454
+ // treats '' as a blank context line).
1455
+ const firstLine = block.lines.find(line => line || line === '');
1456
+ if (firstLine == null) return; // empty hunk — nothing to anchor to
1457
+ let side, lineNumber;
1458
+ if (firstLine.startsWith('-')) {
1459
+ side = 'LEFT';
1460
+ lineNumber = block.oldStart;
1461
+ } else {
1462
+ // Addition or context — present on the NEW side.
1463
+ side = 'RIGHT';
1464
+ lineNumber = block.newStart;
1465
+ }
1466
+ anchors.set(hash, { lineNumber, side });
1467
+ });
1468
+
1469
+ return anchors;
1470
+ }
1471
+
1472
+ /**
1473
+ * Wire a Pierre-rendered file's hunk anchors to their canonical content
1474
+ * hashes, then mount any summary that already arrived for those hunks. The
1475
+ * Pierre analogue of _registerHunkAnchorsForFile: it stores position-based
1476
+ * anchor records (`{pierre, fileName, lineNumber, side}`) instead of `<tr>`
1477
+ * rows, and mounts via PierreBridge annotations.
1478
+ *
1479
+ * Called once per file from renderFileDiff's Pierre branch (the file is in
1480
+ * `pierreBridge.files` by then). Idempotent — re-running re-sets the same
1481
+ * map entries and re-drains an already-empty pending queue.
1482
+ * @param {Object} file - A changed_files entry with `.file`, `.patch`, `.hunk_hashes`
1483
+ */
1484
+ _registerPierreHunkAnchorsForFile(file) {
1485
+ if (!file || !file.patch) return;
1486
+ const fileName = file.file;
1487
+ // Only meaningful for files actually Pierre-rendered — addAnnotation needs
1488
+ // a live fileState, and legacy files use _registerHunkAnchorsForFile.
1489
+ if (!this.pierreBridge?.files?.has(fileName)) return;
1490
+
1491
+ const positions = this._computePierreHunkAnchors(file.patch, file.hunk_hashes);
1492
+ if (positions.size === 0) return;
1493
+
1494
+ let anchors = this._summaryAnchorsByHash.get(fileName);
1495
+ if (!anchors) {
1496
+ anchors = new Map();
1497
+ this._summaryAnchorsByHash.set(fileName, anchors);
1498
+ }
1499
+ let bucket = this._summaryHashesByFile.get(fileName);
1500
+ if (!bucket) {
1501
+ bucket = new Set();
1502
+ this._summaryHashesByFile.set(fileName, bucket);
1503
+ }
1504
+
1505
+ const filesWithMounts = new Set();
1506
+ for (const [hash, pos] of positions) {
1507
+ // Scope by file so a hash shared across files can't cross-wire anchors,
1508
+ // mirroring the legacy path.
1509
+ anchors.set(hash, { pierre: true, fileName, lineNumber: pos.lineNumber, side: pos.side });
1510
+ bucket.add(hash);
1511
+
1512
+ const pending = this._takePendingSummary(fileName, hash);
1513
+ if (pending) {
1514
+ const mounted = this._renderOneSummary(pending, fileName);
1515
+ if (mounted) {
1516
+ this._summariesGenerated = true;
1517
+ this._summariesAvailable = true;
1518
+ filesWithMounts.add(fileName);
1519
+ }
1520
+ // If it couldn't mount, _renderOneSummary re-queued it scoped to
1521
+ // fileName for a later pass.
1522
+ }
1523
+ }
1524
+
1525
+ if (this._summariesGenerated) this._syncSummaryToolbarButton();
1526
+ for (const filePath of filesWithMounts) this._refreshFileSummaryToggle(filePath);
1527
+ }
1528
+
1309
1529
  /**
1310
1530
  * Load the review's hunk summaries from the server and apply them to the
1311
1531
  * anchors that exist so far (gated by `summaries.enabled` in `/api/config`).
@@ -1581,13 +1801,34 @@ class PRManager {
1581
1801
  if (!summary.summary_text) return null; // trivial / opt-out — nothing to show
1582
1802
  const hash = summary.content_hash;
1583
1803
  const anchor = this._findSummaryAnchor(filePath, hash);
1584
- if (!anchor || !anchor.isConnected) {
1585
- // Anchor missing or detached (stale render) → defer; the next render
1586
- // pass that re-establishes the hash will drain this map.
1804
+ if (!anchor) {
1805
+ // Anchor not registered yet (lazy body / deferred render) → defer; the
1806
+ // next render pass that re-establishes the hash will drain this map.
1587
1807
  this._queuePendingSummary(filePath, summary);
1588
1808
  return null;
1589
1809
  }
1590
1810
  if (!this.hunkSummaryRenderer) return null;
1811
+
1812
+ // Pierre-rendered files anchor by position and mount via a bridge
1813
+ // annotation rather than a DOM `<tr>`. `anchor.pierre` distinguishes the
1814
+ // two flavors of record populated by _registerPierreHunkAnchorsForFile
1815
+ // (position object) vs _registerHunkAnchorsForFile (a `<tr>`).
1816
+ if (anchor.pierre) {
1817
+ // The file may have been destroyed/re-deferred since its anchor was
1818
+ // registered; addAnnotation is a no-op without a live fileState, so
1819
+ // requeue rather than silently drop.
1820
+ if (!this.pierreBridge?.files?.has(anchor.fileName)) {
1821
+ this._queuePendingSummary(filePath, summary);
1822
+ return null;
1823
+ }
1824
+ return this.hunkSummaryRenderer.renderPierre(anchor.fileName, anchor, summary);
1825
+ }
1826
+
1827
+ if (!anchor.isConnected) {
1828
+ // Legacy DOM anchor detached (stale render) → defer.
1829
+ this._queuePendingSummary(filePath, summary);
1830
+ return null;
1831
+ }
1591
1832
  return this.hunkSummaryRenderer.renderInline(anchor, summary);
1592
1833
  }
1593
1834
 
@@ -2528,6 +2769,9 @@ class PRManager {
2528
2769
  // Render diff using the existing renderDiff method
2529
2770
  this.renderDiff({ changed_files: sortedFiles });
2530
2771
 
2772
+ // Progressively fetch full file contents for hunk expansion
2773
+ this._upgradeFilesWithContents(sortedFiles);
2774
+
2531
2775
  } else {
2532
2776
  const diffContainer = document.getElementById('diff-container');
2533
2777
  if (diffContainer) {
@@ -2585,6 +2829,51 @@ class PRManager {
2585
2829
  }
2586
2830
  }
2587
2831
 
2832
+ /**
2833
+ * Handle the diff-view toggle (Unified / Split) from DiffOptionsDropdown.
2834
+ *
2835
+ * Unlike handleWhitespaceToggle, this does NOT re-fetch the diff — it asks
2836
+ * PierreBridge to re-render the existing file instances in the new style.
2837
+ * Per the bridge contract, setDiffStyle preserves annotations (user
2838
+ * comments, AI suggestions, external comments) across the re-render, so
2839
+ * there is no need to invoke _rerenderAllOverlays here — doing so would
2840
+ * duplicate work the bridge already handles. Scroll position can shift when
2841
+ * rows change height between unified/split, so we save and restore it.
2842
+ * Shared by both PR mode and local mode (local.js patches PRManager).
2843
+ *
2844
+ * The diff pane scrolls inside `.diff-view` (overflow-y: auto), the same
2845
+ * scroll root `_createFileBodyObserver` uses — not the window — so
2846
+ * `window.scrollY` is ~0 here and restoring it is a no-op. Capture and
2847
+ * restore that container's `scrollTop`, falling back to the window only when
2848
+ * the container can't be resolved.
2849
+ *
2850
+ * Note: split mode collapses N+M unified rows into max(N,M) rows, so content
2851
+ * above the viewport can change height and the restored offset may drift.
2852
+ * A precise fix would re-anchor on the topmost visible file+line, but there
2853
+ * is no existing helper to resolve that through the Pierre shadow DOM, so we
2854
+ * restore the raw scrollTop and accept minor drift.
2855
+ * @param {('unified'|'split')} mode
2856
+ */
2857
+ handleDiffViewChange(mode) {
2858
+ // No bridge means no renderer can apply the swap. Report failure so the
2859
+ // dropdown rolls back its selection instead of persisting a mode the diff
2860
+ // won't reflect. (The dropdown also hides the control via
2861
+ // diffViewAvailable, so this is defense in depth.)
2862
+ if (!this.pierreBridge) return false;
2863
+ const scrollContainer = document.querySelector?.('.diff-view') || null;
2864
+ const scrollTop = scrollContainer ? scrollContainer.scrollTop : window.scrollY;
2865
+ this.pierreBridge.setDiffStyle(mode);
2866
+ // Restore scroll position after the DOM settles
2867
+ requestAnimationFrame(() => {
2868
+ if (scrollContainer) {
2869
+ scrollContainer.scrollTop = scrollTop;
2870
+ } else {
2871
+ window.scrollTo(0, scrollTop);
2872
+ }
2873
+ });
2874
+ return true;
2875
+ }
2876
+
2588
2877
  /**
2589
2878
  * Parse unified diff to extract per-file patches
2590
2879
  * @param {string} diff - Full unified diff
@@ -2619,10 +2908,14 @@ class PRManager {
2619
2908
  this.loadingState = loading;
2620
2909
  const container = document.getElementById('pr-container');
2621
2910
  if (container) {
2911
+ // State flag only — must not be `loading`, which is the visual
2912
+ // placeholder class (padding + centered text). The diff paints inside
2913
+ // this container before loading finishes, so placeholder styles here
2914
+ // cause a visible centered-then-left layout shift.
2622
2915
  if (loading) {
2623
- container.classList.add('loading');
2916
+ container.classList.add('is-loading');
2624
2917
  } else {
2625
- container.classList.remove('loading');
2918
+ container.classList.remove('is-loading');
2626
2919
  }
2627
2920
  }
2628
2921
  }
@@ -2945,10 +3238,15 @@ class PRManager {
2945
3238
  const displayPRs = [...stackPRs].reverse();
2946
3239
  for (const stackPR of displayPRs) {
2947
3240
  const isCurrent = stackPR.prNumber === pr.number;
2948
- const item = document.createElement('div');
3241
+ // Render as a real anchor so right-click / cmd-click / middle-click can
3242
+ // open the PR in a new tab natively. The current PR gets no href (not a
3243
+ // link to itself).
3244
+ const item = document.createElement('a');
2949
3245
  item.className = 'stack-nav-item';
2950
3246
  if (isCurrent) {
2951
3247
  item.classList.add('current');
3248
+ } else {
3249
+ item.href = `/pr/${encodeURIComponent(pr.owner)}/${encodeURIComponent(pr.repo)}/${stackPR.prNumber}`;
2952
3250
  }
2953
3251
  item.dataset.pr = stackPR.prNumber;
2954
3252
 
@@ -2986,10 +3284,20 @@ class PRManager {
2986
3284
 
2987
3285
  item.appendChild(textCol);
2988
3286
 
2989
- // Navigate on click
2990
- item.addEventListener('click', () => {
2991
- if (stackPR.prNumber !== pr.number) {
2992
- window.location.href = `/pr/${encodeURIComponent(pr.owner)}/${encodeURIComponent(pr.repo)}/${stackPR.prNumber}`;
3287
+ // Navigation is handled natively by the anchor's href (enabling
3288
+ // open-in-new-tab). A plain left-click follows the link and unloads the
3289
+ // page; for modified clicks (cmd/ctrl/middle → new tab) or the current
3290
+ // PR, just close the menu without navigating the current tab.
3291
+ item.addEventListener('click', (e) => {
3292
+ // Modified clicks open a new tab — leave the current page as-is.
3293
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) {
3294
+ dropdown.classList.remove('open');
3295
+ trigger.setAttribute('aria-expanded', 'false');
3296
+ return;
3297
+ }
3298
+ // Current PR has no href; nothing to navigate to.
3299
+ if (stackPR.prNumber === pr.number) {
3300
+ e.preventDefault();
2993
3301
  }
2994
3302
  dropdown.classList.remove('open');
2995
3303
  trigger.setAttribute('aria-expanded', 'false');
@@ -3323,11 +3631,315 @@ class PRManager {
3323
3631
  }
3324
3632
  }
3325
3633
 
3634
+ /**
3635
+ * Count logical lines without allocating a large split array.
3636
+ * @param {string} text
3637
+ * @returns {number}
3638
+ */
3639
+ _countLines(text) {
3640
+ if (!text) return 0;
3641
+ let lines = 1;
3642
+ for (let i = 0; i < text.length; i++) {
3643
+ if (text.charCodeAt(i) === 10) lines++;
3644
+ }
3645
+ return lines;
3646
+ }
3647
+
3648
+ /**
3649
+ * Return cached size metrics for a patch.
3650
+ * @param {Object} file
3651
+ * @returns {{chars: number, lines: number}}
3652
+ */
3653
+ _getPatchMetrics(file) {
3654
+ if (!file) return { chars: 0, lines: 0 };
3655
+ if (file._patchMetrics) return file._patchMetrics;
3656
+ const patch = file.patch || '';
3657
+ file._patchMetrics = {
3658
+ chars: patch.length,
3659
+ lines: this._countLines(patch),
3660
+ };
3661
+ return file._patchMetrics;
3662
+ }
3663
+
3664
+ _createPierreRenderBudget() {
3665
+ return {
3666
+ remainingChars: PRManager.PIERRE_HIGHLIGHT_TOTAL_CHARS,
3667
+ remainingLines: PRManager.PIERRE_HIGHLIGHT_TOTAL_LINES,
3668
+ };
3669
+ }
3670
+
3671
+ /**
3672
+ * Decide how to render a file with @pierre/diffs.
3673
+ *
3674
+ * Normal-sized files get syntax highlighting. Larger files still use the
3675
+ * Pierre layout, but are forced to plain text so worker highlighting cannot
3676
+ * swamp the UI. Extremely large patches are deferred until the user opts in.
3677
+ *
3678
+ * @param {Object} file
3679
+ * @param {Object} [options]
3680
+ * @param {boolean} [options.forceRender] - Render even when above the automatic render budget
3681
+ * @returns {{usePierre: boolean, forcePlainText: boolean, deferDiff: boolean}}
3682
+ */
3683
+ _getPierreRenderDecision(file, options = {}) {
3684
+ if (!this.pierreBridge || this.pierreBridge._disabled || !file?.patch || file.binary) {
3685
+ return { usePierre: false, forcePlainText: false, deferDiff: false };
3686
+ }
3687
+
3688
+ const metrics = this._getPatchMetrics(file);
3689
+ if (
3690
+ !options.forceRender &&
3691
+ (
3692
+ metrics.chars > PRManager.PIERRE_AUTO_RENDER_MAX_PATCH_CHARS ||
3693
+ metrics.lines > PRManager.PIERRE_AUTO_RENDER_MAX_PATCH_LINES
3694
+ )
3695
+ ) {
3696
+ return { usePierre: false, forcePlainText: true, deferDiff: true };
3697
+ }
3698
+
3699
+ const exceedsFileHighlightBudget =
3700
+ metrics.chars > PRManager.PIERRE_HIGHLIGHT_MAX_PATCH_CHARS ||
3701
+ metrics.lines > PRManager.PIERRE_HIGHLIGHT_MAX_PATCH_LINES;
3702
+
3703
+ let exceedsTotalHighlightBudget = false;
3704
+ const budget = this._pierreRenderBudget;
3705
+ if (!exceedsFileHighlightBudget && budget) {
3706
+ if (metrics.chars > budget.remainingChars || metrics.lines > budget.remainingLines) {
3707
+ exceedsTotalHighlightBudget = true;
3708
+ } else {
3709
+ budget.remainingChars -= metrics.chars;
3710
+ budget.remainingLines -= metrics.lines;
3711
+ }
3712
+ }
3713
+
3714
+ const forcePlainText = !!options.forceRender || exceedsFileHighlightBudget || exceedsTotalHighlightBudget;
3715
+ return { usePierre: true, forcePlainText, deferDiff: false };
3716
+ }
3717
+
3718
+ _isPatchEligibleForContentUpgrade(file) {
3719
+ const metrics = this._getPatchMetrics(file);
3720
+ return (
3721
+ metrics.chars <= PRManager.PIERRE_UPGRADE_MAX_PATCH_CHARS &&
3722
+ metrics.lines <= PRManager.PIERRE_UPGRADE_MAX_PATCH_LINES
3723
+ );
3724
+ }
3725
+
3726
+ _isContentEligibleForPierreUpgrade(oldContents, newContents) {
3727
+ const values = [oldContents, newContents].filter(v => v != null);
3728
+ return values.every(value =>
3729
+ value.length <= PRManager.PIERRE_UPGRADE_MAX_CONTENT_CHARS &&
3730
+ this._countLines(value) <= PRManager.PIERRE_UPGRADE_MAX_CONTENT_LINES
3731
+ );
3732
+ }
3733
+
3734
+ _getPierreContentUpgradeFiles(files, options = {}) {
3735
+ if (!this.pierreBridge?.files) return [];
3736
+ const forceFiles = options.forceFiles || new Set();
3737
+ return files.filter(f => {
3738
+ if (!f.patch || f.binary || !this.pierreBridge.files.has(f.file)) return false;
3739
+ return forceFiles.has(f.file) || this._isPatchEligibleForContentUpgrade(f);
3740
+ });
3741
+ }
3742
+
3743
+ _getChangedFile(filePath) {
3744
+ return this.changedFilesByPath?.get(filePath) || null;
3745
+ }
3746
+
3747
+ async _fetchAndUpgradePierreFileContents(file, signal, options = {}) {
3748
+ if (signal?.aborted) return false;
3749
+
3750
+ const reviewId = this.currentPR?.id;
3751
+ if (!reviewId || !file?.patch || file.binary) return false;
3752
+ if (this.pierreBridge?.files?.get(file.file)?.baseMetadata) return true;
3753
+
3754
+ // Use diff header metadata (not insertion/deletion counts) to determine
3755
+ // true file status. Only check before the first @@ hunk marker to avoid
3756
+ // matching code content that happens to contain these strings. If the
3757
+ // patch has no @@ marker (empty added/deleted files, mode-only changes)
3758
+ // the whole patch is header.
3759
+ const atIdx = file.patch.indexOf('@@');
3760
+ const diffHeader = atIdx === -1 ? file.patch : file.patch.substring(0, atIdx);
3761
+ const status = diffHeader.includes('new file mode') ? 'added'
3762
+ : diffHeader.includes('deleted file mode') ? 'deleted'
3763
+ : 'modified';
3764
+ let url = `/api/reviews/${reviewId}/file-contents/${encodeURIComponent(file.file)}?status=${encodeURIComponent(status)}`;
3765
+ if (file.renamedFrom) {
3766
+ url += `&oldPath=${encodeURIComponent(file.renamedFrom)}`;
3767
+ }
3768
+
3769
+ try {
3770
+ const fetchOptions = signal ? { signal } : undefined;
3771
+ const resp = await fetch(url, fetchOptions);
3772
+ if (!resp.ok || signal?.aborted) return false;
3773
+ const data = await resp.json();
3774
+ if (data.tooLarge || data.binary || signal?.aborted) return false;
3775
+ if (!this._isContentEligibleForPierreUpgrade(data.oldContents, data.newContents)) return false;
3776
+
3777
+ const oldFile = data.oldContents != null
3778
+ ? { name: data.oldPath || file.renamedFrom || file.file, contents: data.oldContents }
3779
+ : null;
3780
+ const newFile = data.newContents != null
3781
+ ? { name: file.file, contents: data.newContents }
3782
+ : null;
3783
+
3784
+ if (!oldFile && !newFile) return false;
3785
+ await this._yieldForDiffWork(signal);
3786
+ if (signal?.aborted) return false;
3787
+ if (options.waitForPointerIdle !== false) {
3788
+ await this._waitForPierrePointerIdle(file.file, signal);
3789
+ }
3790
+ if (signal?.aborted) return false;
3791
+ if (this.pierreBridge?.files?.get(file.file)?.baseMetadata) return true;
3792
+ return this.pierreBridge.upgradeFileContents(file.file, oldFile, newFile);
3793
+ } catch (err) {
3794
+ if (err.name === 'AbortError') return false;
3795
+ console.error(`Failed to fetch file contents for ${file.file}:`, err);
3796
+ return false;
3797
+ }
3798
+ }
3799
+
3800
+ async _waitForPierrePointerIdle(filePath, signal) {
3801
+ if (!this.pierreBridge?.isPointerOverFile?.(filePath)) return;
3802
+
3803
+ const start = Date.now();
3804
+ while (
3805
+ !signal?.aborted &&
3806
+ this.pierreBridge?.isPointerOverFile?.(filePath) &&
3807
+ Date.now() - start < PRManager.PIERRE_POINTER_UPGRADE_DELAY_MS
3808
+ ) {
3809
+ await new Promise(resolve => setTimeout(resolve, 100));
3810
+ }
3811
+ }
3812
+
3813
+ _getOrStartPierreContentUpgrade(file, signal, options = {}) {
3814
+ if (!file?.file) return Promise.resolve(false);
3815
+ if (!this._pierreContentUpgradePromises) {
3816
+ this._pierreContentUpgradePromises = new Map();
3817
+ }
3818
+ // The immediate (user-driven) and background paths are keyed separately ON
3819
+ // PURPOSE. Do NOT merge them into one key: sharing the background promise
3820
+ // would make an immediate, user-driven upgrade inherit that promise's
3821
+ // pointer-idle wait (_waitForPierrePointerIdle), stalling it behind idle
3822
+ // throttling. The known cost of the split is a duplicate fetch + JSON parse
3823
+ // when navigation races an in-flight background upgrade for the same file
3824
+ // (cheap once metadata lands, thanks to the baseMetadata early-return). A
3825
+ // future improvement could piggyback on the in-flight background fetch while
3826
+ // still skipping the pointer-idle wait for the immediate path.
3827
+ const cacheKey = options.waitForPointerIdle === false
3828
+ ? `${file.file}\0immediate`
3829
+ : file.file;
3830
+ const existing = this._pierreContentUpgradePromises.get(cacheKey);
3831
+ if (existing) return existing;
3832
+
3833
+ let promise;
3834
+ promise = this._fetchAndUpgradePierreFileContents(file, signal, options)
3835
+ .finally(() => {
3836
+ if (this._pierreContentUpgradePromises.get(cacheKey) === promise) {
3837
+ this._pierreContentUpgradePromises.delete(cacheKey);
3838
+ }
3839
+ });
3840
+ this._pierreContentUpgradePromises.set(cacheKey, promise);
3841
+ return promise;
3842
+ }
3843
+
3844
+ async _ensurePierreContentUpgrade(filePath) {
3845
+ const fileState = this.pierreBridge?.files?.get(filePath);
3846
+ if (!fileState) return false;
3847
+ if (fileState.baseMetadata) return true;
3848
+
3849
+ const file = this._getChangedFile(filePath);
3850
+ if (!file?.patch || file.binary) return false;
3851
+
3852
+ this._prioritizePierreContentUpgrade(filePath);
3853
+ await this._getOrStartPierreContentUpgrade(file, this._fileContentsAbort?.signal || null, {
3854
+ waitForPointerIdle: false,
3855
+ });
3856
+ return !!this.pierreBridge?.files?.get(filePath)?.baseMetadata;
3857
+ }
3858
+
3859
+ _yieldForDiffWork(signal) {
3860
+ if (signal?.aborted) return Promise.resolve();
3861
+ return new Promise(resolve => {
3862
+ const done = () => resolve();
3863
+ if (typeof window !== 'undefined' && window.requestIdleCallback) {
3864
+ window.requestIdleCallback(done, { timeout: 200 });
3865
+ } else {
3866
+ setTimeout(done, 16);
3867
+ }
3868
+ });
3869
+ }
3870
+
3871
+ _startFileContentUpgradeQueue(files, worker, signal) {
3872
+ if (signal.aborted || this._fileContentsAbort?.signal !== signal) return;
3873
+ const state = {
3874
+ pending: [...files],
3875
+ inFlight: new Set(),
3876
+ completed: new Set(),
3877
+ active: 0,
3878
+ worker,
3879
+ signal,
3880
+ };
3881
+ this._fileContentsUpgradeState = state;
3882
+ this._drainFileContentUpgradeQueue(state);
3883
+ }
3884
+
3885
+ _drainFileContentUpgradeQueue(state) {
3886
+ if (!state || state !== this._fileContentsUpgradeState || state.signal.aborted) return;
3887
+
3888
+ const concurrency = Math.max(1, PRManager.PIERRE_UPGRADE_CONCURRENCY);
3889
+ while (!state.signal.aborted && state.active < concurrency && state.pending.length > 0) {
3890
+ const file = state.pending.shift();
3891
+ if (!file || state.completed.has(file.file) || state.inFlight.has(file.file)) continue;
3892
+
3893
+ state.active++;
3894
+ state.inFlight.add(file.file);
3895
+ Promise.resolve()
3896
+ .then(() => state.worker(file))
3897
+ .catch(err => {
3898
+ console.error(`Failed to upgrade file contents for ${file.file}:`, err);
3899
+ })
3900
+ .finally(async () => {
3901
+ state.inFlight.delete(file.file);
3902
+ state.completed.add(file.file);
3903
+ state.active--;
3904
+ await this._yieldForDiffWork(state.signal);
3905
+ this._drainFileContentUpgradeQueue(state);
3906
+ });
3907
+ }
3908
+
3909
+ if (state.active === 0 && state.pending.length === 0 && this._fileContentsUpgradeState === state) {
3910
+ this._fileContentsUpgradeState = null;
3911
+ }
3912
+ }
3913
+
3914
+ _prioritizePierreContentUpgrade(filePath) {
3915
+ const state = this._fileContentsUpgradeState;
3916
+ if (!state || state.signal.aborted || state.completed.has(filePath) || state.inFlight.has(filePath)) {
3917
+ return false;
3918
+ }
3919
+
3920
+ const index = state.pending.findIndex(file => file.file === filePath);
3921
+ if (index === -1) return false;
3922
+ if (index > 0) {
3923
+ const [file] = state.pending.splice(index, 1);
3924
+ state.pending.unshift(file);
3925
+ }
3926
+ this._drainFileContentUpgradeQueue(state);
3927
+ return true;
3928
+ }
3929
+
3326
3930
  /**
3327
3931
  * Render diff for the PR
3328
3932
  * @param {Object} pr - PR data with files
3329
3933
  */
3330
3934
  renderDiff(pr) {
3935
+ // Abort any in-flight file content fetches from progressive loading
3936
+ this._fileContentsAbort?.abort();
3937
+ this._fileContentsAbort = null;
3938
+ this._fileContentsUpgradeState = null;
3939
+ this._pierreContentUpgradePromises = new Map();
3940
+ this._pierreUpgradeCandidates = null;
3941
+ this._deferredDiffRenderPromises = new Map();
3942
+
3331
3943
  const diffContainer = document.getElementById('diff-container');
3332
3944
  if (!diffContainer) return;
3333
3945
 
@@ -3342,6 +3954,11 @@ class PRManager {
3342
3954
  this._exitTour();
3343
3955
  }
3344
3956
 
3957
+ // Clean up existing @pierre/diffs instances before clearing the container
3958
+ if (this.pierreBridge) {
3959
+ this.pierreBridge.destroyAll();
3960
+ }
3961
+
3345
3962
  diffContainer.innerHTML = '';
3346
3963
 
3347
3964
  // Reset hunk-summary tracking — `renderPatch` will populate this as it
@@ -3379,57 +3996,296 @@ class PRManager {
3379
3996
 
3380
3997
  // Use changed_files array from API
3381
3998
  const files = pr.changed_files || pr.files || [];
3999
+ this.changedFilesByPath = new Map(files.map(file => [file.file, file]));
4000
+ this._pierreRenderBudget = this._createPierreRenderBudget();
3382
4001
 
3383
- // Collect generated files info before rendering
3384
- if (files.length > 0) {
3385
- files.forEach(file => {
3386
- if (file.generated) {
3387
- this.generatedFiles.set(file.file, {
3388
- insertions: file.insertions,
3389
- deletions: file.deletions
3390
- });
3391
- }
3392
- });
4002
+ try {
4003
+ // Collect generated files info before rendering
4004
+ if (files.length > 0) {
4005
+ files.forEach(file => {
4006
+ if (file.generated) {
4007
+ this.generatedFiles.set(file.file, {
4008
+ insertions: file.insertions,
4009
+ deletions: file.deletions
4010
+ });
4011
+ }
4012
+ });
4013
+ }
4014
+
4015
+ // Parse each file's diff
4016
+ if (files.length > 0) {
4017
+ files.forEach(file => {
4018
+ const fileWrapper = this.renderFileDiff(file);
4019
+ if (fileWrapper) {
4020
+ diffContainer.appendChild(fileWrapper);
4021
+ }
4022
+ });
4023
+
4024
+ // NOTE: end-of-file gap validation runs per-file inside _renderFileBodyNow
4025
+ // now (legacy bodies render lazily), not once globally here.
4026
+
4027
+ // Measure the now-rendered sticky file header so navigation can offset
4028
+ // targets below it (scroll-margin-top in pr.css).
4029
+ this._measureFileHeaderHeight();
4030
+ } else {
4031
+ diffContainer.innerHTML = '<div class="no-diff">No files changed</div>';
4032
+ }
4033
+
4034
+ // Load context files after diff is rendered
4035
+ this.contextFiles = [];
4036
+ this.loadContextFiles();
4037
+
4038
+ // Fetch hunk summaries (Phase 5). Fire-and-forget — the diff is fully
4039
+ // usable while summaries arrive asynchronously. Anchors are wired lazily
4040
+ // as each file body renders (_registerHunkAnchorsForFile); this just loads
4041
+ // the server's summary map and applies it to whatever has rendered so far.
4042
+ if (this.hunkSummaryRenderer) {
4043
+ this._fetchHunkSummaryMap().catch((err) => {
4044
+ console.warn('[HunkSummary] summary fetch failed:', err);
4045
+ });
4046
+ }
4047
+
4048
+ // Probe tour endpoint after diff is rendered. `currentPR.id` is now
4049
+ // set (init()/LocalManager populates it before calling renderDiff),
4050
+ // so the toolbar button can reflect the right state.
4051
+ if (this._toursEnabled === true) {
4052
+ this._loadAndStashTour().catch(() => {});
4053
+ }
4054
+ } finally {
4055
+ this._pierreRenderBudget = null;
3393
4056
  }
4057
+ }
3394
4058
 
3395
- // Parse each file's diff
3396
- if (files.length > 0) {
3397
- files.forEach(file => {
3398
- const fileWrapper = this.renderFileDiff(file);
3399
- if (fileWrapper) {
3400
- diffContainer.appendChild(fileWrapper);
3401
- }
3402
- });
4059
+ /**
4060
+ * Progressively fetch full file contents and upgrade Pierre-rendered files
4061
+ * to enable hunk expansion. Eligible files flow through one bounded idle
4062
+ * queue, and sidebar navigation can move a file to the front of the queue.
4063
+ *
4064
+ * With lazy Pierre rendering, files enter pierreBridge.files only as their
4065
+ * bodies render (on scroll/expand) — so the queue cannot be seeded from
4066
+ * pierreBridge.files up front. Instead we record the eligible-by-size
4067
+ * candidate set + the abort signal here, and each Pierre body enqueues itself
4068
+ * as it renders (_renderPierreFileBodyNow → _enqueuePierreContentUpgrade). A
4069
+ * delayed catch-up sweep also enqueues anything that rendered in the meantime
4070
+ * (e.g. the initially-visible files, once the observer has fired), so both
4071
+ * routes funnel through the de-duping _enqueuePierreContentUpgrade.
4072
+ * @param {Array} files - The sorted changed_files array
4073
+ */
4074
+ _upgradeFilesWithContents(files) {
4075
+ if (!this.pierreBridge || this.pierreBridge._disabled) return;
4076
+
4077
+ const reviewId = this.currentPR?.id;
4078
+ if (!reviewId) return;
3403
4079
 
3404
- // NOTE: end-of-file gap validation runs per-file inside _renderFileBodyNow
3405
- // now (bodies render lazily), not once globally here.
4080
+ const controller = new AbortController();
4081
+ this._fileContentsAbort = controller;
4082
+ const signal = controller.signal;
3406
4083
 
3407
- // Measure the now-rendered sticky file header so navigation can offset
3408
- // targets below it (scroll-margin-top in pr.css).
3409
- this._measureFileHeaderHeight();
3410
- } else {
3411
- diffContainer.innerHTML = '<div class="no-diff">No files changed</div>';
4084
+ this._pierreUpgradeCandidates = new Set(
4085
+ files
4086
+ .filter(f => f.patch && !f.binary && this._isPatchEligibleForContentUpgrade(f))
4087
+ .map(f => f.file)
4088
+ );
4089
+ if (this._pierreUpgradeCandidates.size === 0) return;
4090
+
4091
+ const scheduleUpgrade = window.requestIdleCallback || ((cb) => setTimeout(cb, 50));
4092
+ setTimeout(() => scheduleUpgrade(() => {
4093
+ if (signal.aborted || this._fileContentsAbort?.signal !== signal) return;
4094
+ // Catch-up: enqueue any candidate whose body already rendered by now.
4095
+ // Later-rendering files are enqueued from _renderPierreFileBodyNow.
4096
+ for (const file of this._getPierreContentUpgradeFiles(files)) {
4097
+ this._enqueuePierreContentUpgrade(file);
4098
+ }
4099
+ }), PRManager.PIERRE_BACKGROUND_UPGRADE_DELAY_MS);
4100
+ }
4101
+
4102
+ /**
4103
+ * Enqueue a single (now-rendered) Pierre file for background content upgrade,
4104
+ * reusing the in-flight bounded queue when one exists so the concurrency cap
4105
+ * is honored and nothing is double-scheduled. Called both from the delayed
4106
+ * catch-up sweep and from _renderPierreFileBodyNow as bodies render.
4107
+ * @param {Object} file - A changed_files entry
4108
+ */
4109
+ _enqueuePierreContentUpgrade(file) {
4110
+ if (!file?.patch || file.binary) return;
4111
+ if (!this._pierreUpgradeCandidates?.has(file.file)) return;
4112
+ const signal = this._fileContentsAbort?.signal;
4113
+ if (!signal || signal.aborted) return;
4114
+
4115
+ const worker = (f) => this._getOrStartPierreContentUpgrade(f, signal);
4116
+ const state = this._fileContentsUpgradeState;
4117
+ if (state && state.signal === signal && !signal.aborted) {
4118
+ if (state.completed.has(file.file) || state.inFlight.has(file.file)) return;
4119
+ if (state.pending.some(f => f.file === file.file)) return;
4120
+ state.pending.push(file);
4121
+ this._drainFileContentUpgradeQueue(state);
4122
+ return;
3412
4123
  }
4124
+ // No live queue (initial enqueue, or the previous one drained empty). Start
4125
+ // a fresh one seeded with this file; subsequent enqueues reuse it above.
4126
+ this._startFileContentUpgradeQueue([file], worker, signal);
4127
+ }
3413
4128
 
3414
- // Load context files after diff is rendered
3415
- this.contextFiles = [];
3416
- this.loadContextFiles();
4129
+ async _reanchorInlineFeedbackAfterDeferredRender() {
4130
+ try {
4131
+ const includeDismissed = window.aiPanel?.showDismissedComments || false;
4132
+ await this.loadUserComments(includeDismissed);
4133
+ await this.loadAISuggestions(null, this.selectedRunId);
4134
+ } catch (err) {
4135
+ console.error('Failed to re-anchor inline feedback after deferred diff render:', err);
4136
+ }
4137
+ }
3417
4138
 
3418
- // Fetch hunk summaries (Phase 5). Fire-and-forget — the diff is fully
3419
- // usable while summaries arrive asynchronously. Anchors are wired lazily
3420
- // as each file body renders (_registerHunkAnchorsForFile); this just loads
3421
- // the server's summary map and applies it to whatever has rendered so far.
3422
- if (this.hunkSummaryRenderer) {
3423
- this._fetchHunkSummaryMap().catch((err) => {
3424
- console.warn('[HunkSummary] summary fetch failed:', err);
3425
- });
4139
+ _formatDiffSize(bytes) {
4140
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
4141
+ return `${Math.ceil(bytes / 1024)} KB`;
4142
+ }
4143
+
4144
+ _renderLegacyFileDiffBody(file) {
4145
+ const table = document.createElement('table');
4146
+ table.className = 'd2h-diff-table';
4147
+
4148
+ const tbody = document.createElement('tbody');
4149
+ if (file.patch) {
4150
+ this.renderPatch(tbody, file.patch, file.file, file.hunk_hashes || null);
4151
+ } else if (file.binary) {
4152
+ const row = document.createElement('tr');
4153
+ row.innerHTML = '<td colspan="2" class="binary-file">Binary file</td>';
4154
+ tbody.appendChild(row);
3426
4155
  }
4156
+ table.appendChild(tbody);
3427
4157
 
3428
- // Probe tour endpoint after diff is rendered. `currentPR.id` is now
3429
- // set (init()/LocalManager populates it before calling renderDiff),
3430
- // so the toolbar button can reflect the right state.
3431
- if (this._toursEnabled === true) {
3432
- this._loadAndStashTour().catch(() => {});
4158
+ const fileBody = document.createElement('div');
4159
+ fileBody.className = 'd2h-file-body';
4160
+ fileBody.appendChild(table);
4161
+ return fileBody;
4162
+ }
4163
+
4164
+ _createDeferredDiffPlaceholder(file, wrapper) {
4165
+ const metrics = this._getPatchMetrics(file);
4166
+ const placeholder = document.createElement('div');
4167
+ placeholder.className = 'no-diff large-diff-placeholder';
4168
+
4169
+ const message = document.createElement('span');
4170
+ message.textContent = `Large diff (${this._formatDiffSize(metrics.chars)}, ${metrics.lines.toLocaleString()} lines)`;
4171
+
4172
+ const loadButton = document.createElement('button');
4173
+ loadButton.type = 'button';
4174
+ loadButton.className = 'btn btn-sm btn-secondary large-diff-load-btn';
4175
+ loadButton.textContent = 'Load diff';
4176
+ loadButton.addEventListener('click', async () => {
4177
+ loadButton.disabled = true;
4178
+ loadButton.textContent = 'Loading...';
4179
+ // Route through _materializeDeferredDiff so the manual click shares the
4180
+ // _deferredDiffRenderPromises cache and de-dupes with the auto-materialize
4181
+ // path (ensureLinesVisible/expandForSuggestion). Rendering directly here
4182
+ // could race a concurrent auto-materialize and run two _renderDeferredDiff
4183
+ // calls on the same file. Request reanchor:true because a manual click is
4184
+ // NOT inside a loadUserComments/loadAISuggestions reanchor flow, so inline
4185
+ // comments/suggestions must be re-anchored to the freshly rendered diff.
4186
+ await this._materializeDeferredDiff(file.file, { reanchor: true });
4187
+ });
4188
+
4189
+ placeholder.appendChild(message);
4190
+ placeholder.appendChild(loadButton);
4191
+ return placeholder;
4192
+ }
4193
+
4194
+ async _materializeDeferredDiff(filePath, options = {}) {
4195
+ // reanchor defaults to false to preserve the auto-materialize callers
4196
+ // (ensureLinesVisible/expandForSuggestion), which perform reanchoring at a
4197
+ // higher level. The manual "Load diff" click passes reanchor:true. Shared-
4198
+ // cache dedup: whichever call populates _deferredDiffRenderPromises first
4199
+ // wins its reanchor setting — acceptable, because if auto-materialize
4200
+ // (reanchor:false) wins, its caller reanchors anyway.
4201
+ const { reanchor = false } = options;
4202
+ if (!filePath) return false;
4203
+ if (this.pierreBridge?.files?.has(filePath)) return true;
4204
+ if (!this._deferredDiffRenderPromises) {
4205
+ this._deferredDiffRenderPromises = new Map();
4206
+ }
4207
+
4208
+ const existing = this._deferredDiffRenderPromises.get(filePath);
4209
+ if (existing) return existing;
4210
+
4211
+ const wrapper = this.findFileElement(filePath);
4212
+ const placeholder = wrapper?.querySelector('.large-diff-placeholder');
4213
+ const file = this._getChangedFile(filePath);
4214
+ if (!wrapper || !placeholder || !file) return false;
4215
+
4216
+ let promise;
4217
+ promise = (async () => {
4218
+ const signal = this._fileContentsAbort?.signal || null;
4219
+ await this._yieldForDiffWork(signal);
4220
+ // If renderDiff() re-ran during the idle yield, the review was torn down and
4221
+ // rebuilt: the placeholder/wrapper we captured are now detached from the
4222
+ // document (renderDiff clears the container), and the abort signal is flipped.
4223
+ // Bail in that case so we don't clobber the freshly rendered file state.
4224
+ if (signal?.aborted || !wrapper.isConnected || !placeholder.isConnected) {
4225
+ return false;
4226
+ }
4227
+ await this._renderDeferredDiff(file, wrapper, placeholder, { reanchor });
4228
+ return true;
4229
+ })().finally(() => {
4230
+ if (this._deferredDiffRenderPromises.get(filePath) === promise) {
4231
+ this._deferredDiffRenderPromises.delete(filePath);
4232
+ }
4233
+ });
4234
+ this._deferredDiffRenderPromises.set(filePath, promise);
4235
+ return promise;
4236
+ }
4237
+
4238
+ async _renderDeferredDiff(file, wrapper, placeholder, options = {}) {
4239
+ const { reanchor = true } = options;
4240
+ const isCollapsed = wrapper.classList.contains('collapsed');
4241
+ const pierreDecision = this._getPierreRenderDecision(file, { forceRender: true });
4242
+
4243
+ if (pierreDecision.usePierre) {
4244
+ const diffBody = document.createElement('div');
4245
+ diffBody.className = 'pierre-diff-body';
4246
+ placeholder.replaceWith(diffBody);
4247
+ try {
4248
+ this.pierreBridge.renderFile(file.file, diffBody, file.patch, {
4249
+ collapsed: isCollapsed,
4250
+ forcePlainText: true,
4251
+ });
4252
+ // The file is only now in pierreBridge.files — wire its hunk-summary
4253
+ // anchors so summaries mount on materialized large diffs too (the
4254
+ // eager render path does this in renderFileDiff's Pierre branch).
4255
+ this._registerPierreHunkAnchorsForFile(file);
4256
+ if (reanchor) {
4257
+ await this._reanchorInlineFeedbackAfterDeferredRender();
4258
+ }
4259
+ } catch (err) {
4260
+ console.error(`Failed to render large diff for ${file.file}:`, err);
4261
+ const retryPlaceholder = this._createDeferredDiffPlaceholder(file, wrapper);
4262
+ const message = retryPlaceholder.querySelector('span');
4263
+ if (message) message.textContent = 'Failed to render large diff';
4264
+ diffBody.replaceWith(retryPlaceholder);
4265
+ }
4266
+ return;
4267
+ }
4268
+
4269
+ // Legacy fallback (bridge unavailable). Swap the pending-record buffer so
4270
+ // this eager render's hunk anchors register for this file only, mirroring
4271
+ // _renderFileBodyNow — and register only after the body is attached, so
4272
+ // anchor rows are connected when queued summaries try to mount.
4273
+ const prevPending = this._pendingHunkRecords;
4274
+ this._pendingHunkRecords = [];
4275
+ let legacyBody;
4276
+ let hunkRecords;
4277
+ try {
4278
+ legacyBody = this._renderLegacyFileDiffBody(file);
4279
+ } finally {
4280
+ hunkRecords = this._pendingHunkRecords;
4281
+ this._pendingHunkRecords = prevPending;
4282
+ }
4283
+ placeholder.replaceWith(legacyBody);
4284
+ if (hunkRecords.length > 0) {
4285
+ this._registerHunkAnchorsForFile(hunkRecords);
4286
+ }
4287
+ if (reanchor) {
4288
+ await this._reanchorInlineFeedbackAfterDeferredRender();
3433
4289
  }
3434
4290
  }
3435
4291
 
@@ -3566,10 +4422,69 @@ class PRManager {
3566
4422
  }
3567
4423
  }
3568
4424
 
3569
- // Create diff table with an EMPTY tbody. The rows are NOT rendered here —
3570
- // see the lazy-body machinery below. This is the core large-PR perf fix:
3571
- // building + syntax-highlighting every line of every (often collapsed)
3572
- // file up front froze the browser on big diffs.
4425
+ const pierreDecision = this._getPierreRenderDecision(file);
4426
+
4427
+ if (pierreDecision.deferDiff) {
4428
+ wrapper.appendChild(this._createDeferredDiffPlaceholder(file, wrapper));
4429
+ return wrapper;
4430
+ }
4431
+
4432
+ // Create container for @pierre/diffs rendering. Built EMPTY here — the
4433
+ // actual `pierreBridge.renderFile()` (patch parse + FileDiff instance +
4434
+ // shadow-DOM build) is deferred to _renderPierreFileBodyNow, driven by the
4435
+ // same IntersectionObserver + ensureFileBodyRendered machinery as legacy
4436
+ // bodies. Rendering every (often collapsed/generated) file's Pierre body up
4437
+ // front froze the browser on large PRs; now collapsed bodies (display:none)
4438
+ // never intersect and stay unrendered until expanded, and expanded-offscreen
4439
+ // bodies render only as they near the viewport.
4440
+ if (pierreDecision.usePierre) {
4441
+ const diffBody = document.createElement('div');
4442
+ diffBody.className = 'pierre-diff-body';
4443
+ wrapper.appendChild(diffBody);
4444
+
4445
+ // Reserve approximate height for EXPANDED-but-unrendered bodies so the
4446
+ // scrollbar stays roughly stable as bodies fill in. Collapsed bodies are
4447
+ // `display:none` (see pr.css .collapsed .pierre-diff-body) so contribute
4448
+ // no height and need no placeholder. Cleared when the body renders.
4449
+ if (!isCollapsed && file.patch) {
4450
+ const approxLines = file.patch.split('\n').length;
4451
+ diffBody.style.minHeight = (approxLines * PRManager.APPROX_DIFF_LINE_PX) + 'px';
4452
+ }
4453
+
4454
+ // Register the lazy entry. `pierre:true` routes _renderFileBodyNow to the
4455
+ // Pierre render path; `forcePlainText` is captured here so the highlight
4456
+ // budget decision (consumed above in _getPierreRenderDecision, at
4457
+ // registration time) is honored at actual render. `file` is the full
4458
+ // changed_files entry, needed for renderFile + hunk-anchor wiring.
4459
+ this._lazyFileBodies.set(file.file, {
4460
+ fileName: file.file,
4461
+ file,
4462
+ pierre: true,
4463
+ forcePlainText: pierreDecision.forcePlainText,
4464
+ patch: file.patch || null,
4465
+ binary: !!file.binary,
4466
+ hunkHashes: file.hunk_hashes || null,
4467
+ fileBody: diffBody,
4468
+ wrapper,
4469
+ rendered: false,
4470
+ renderPromise: null,
4471
+ gen: this._renderGen
4472
+ });
4473
+
4474
+ // Observe the body so it renders as it nears the viewport. Collapsed
4475
+ // bodies (display:none) never intersect → stay unrendered until expanded.
4476
+ if ((file.patch || file.binary) && this._fileBodyObserver) {
4477
+ this._fileBodyObserver.observe(diffBody);
4478
+ }
4479
+
4480
+ return wrapper;
4481
+ }
4482
+
4483
+ // Fallback: old table-based rendering (used when PierreBridge is not
4484
+ // available). Created with an EMPTY tbody — the rows are NOT rendered
4485
+ // here; see the lazy-body machinery below. This is the core large-PR
4486
+ // perf fix: building + syntax-highlighting every line of every (often
4487
+ // collapsed) file up front froze the browser on big diffs.
3573
4488
  const table = document.createElement('table');
3574
4489
  table.className = 'd2h-diff-table';
3575
4490
  const tbody = document.createElement('tbody');
@@ -3726,6 +4641,11 @@ class PRManager {
3726
4641
  if (entry.rendered) return entry.fileBody;
3727
4642
  if (this._fileBodyObserver) this._fileBodyObserver.unobserve(entry.fileBody);
3728
4643
 
4644
+ // Pierre-rendered files build a FileDiff into a shadow DOM rather than a
4645
+ // <tbody>; they have their own render path (no renderPatch / hunk records /
4646
+ // EOF-gap machinery, which are legacy-table concepts).
4647
+ if (entry.pierre) return this._renderPierreFileBodyNow(entry);
4648
+
3729
4649
  const tbody = entry.fileBody.querySelector('tbody');
3730
4650
 
3731
4651
  // Capture only THIS file's hunk anchor records (renderPatch appends to
@@ -3779,6 +4699,63 @@ class PRManager {
3779
4699
  return entry.fileBody;
3780
4700
  }
3781
4701
 
4702
+ /**
4703
+ * Synchronously build a Pierre-rendered file's body: run
4704
+ * `pierreBridge.renderFile()` (or the binary placeholder), clear the height
4705
+ * placeholder, wire hunk-summary anchors, and enqueue background content
4706
+ * upgrade. The Pierre analogue of the legacy branch in _renderFileBodyNow.
4707
+ * Idempotent (caller guards on entry.rendered).
4708
+ *
4709
+ * The `collapsed` option reflects the LIVE wrapper state, not the value at
4710
+ * registration: a file expanded via toggleFileCollapse materializes here
4711
+ * BEFORE `.collapsed` is removed, so it renders collapsed (zero shadow lines)
4712
+ * and setCollapsed(false) then rerenders to fill lines in — exactly the
4713
+ * pre-lazy eager-render-then-expand sequence.
4714
+ * @param {object} entry - a _lazyFileBodies value with pierre:true
4715
+ * @returns {HTMLElement} the file body element
4716
+ */
4717
+ _renderPierreFileBodyNow(entry) {
4718
+ const diffBody = entry.fileBody;
4719
+
4720
+ // Superseded render: renderDiff already ran pierreBridge.destroyAll() and
4721
+ // detached this body via innerHTML=''. Rendering now would re-insert a dead
4722
+ // file into pierreBridge.files (leaking it, and polluting later lookups).
4723
+ // Mark done and skip — matches the legacy path's stale-gen wiring skip.
4724
+ if (entry.gen !== this._renderGen) {
4725
+ diffBody.style.minHeight = '';
4726
+ entry.rendered = true;
4727
+ entry.renderPromise = null;
4728
+ return diffBody;
4729
+ }
4730
+
4731
+ const collapsed = entry.wrapper?.classList?.contains('collapsed') || false;
4732
+ if (entry.patch) {
4733
+ this.pierreBridge.renderFile(entry.fileName, diffBody, entry.patch, {
4734
+ collapsed,
4735
+ forcePlainText: entry.forcePlainText,
4736
+ });
4737
+ } else if (entry.binary) {
4738
+ this.pierreBridge.renderBinaryFile(diffBody);
4739
+ }
4740
+
4741
+ diffBody.style.minHeight = '';
4742
+ entry.rendered = true;
4743
+ entry.renderPromise = null;
4744
+
4745
+ if (entry.patch) {
4746
+ // Wire hunk-summary anchors now that the file is in pierreBridge.files —
4747
+ // any summary that arrived (WS/fetch) before this body rendered was queued
4748
+ // in _pendingSummariesByHash and is drained here.
4749
+ this._registerPierreHunkAnchorsForFile(entry.file);
4750
+ // Enqueue background content upgrade (enables hunk expansion). With lazy
4751
+ // rendering the upgrade queue can't be seeded up front (the file wasn't in
4752
+ // pierreBridge.files yet), so files are fed to it as they render.
4753
+ this._enqueuePierreContentUpgrade(entry.file);
4754
+ }
4755
+
4756
+ return diffBody;
4757
+ }
4758
+
3782
4759
  /**
3783
4760
  * Parse and render a unified diff patch
3784
4761
  * @param {HTMLElement} tbody - Table body element
@@ -4137,6 +5114,11 @@ class PRManager {
4137
5114
  if (header) {
4138
5115
  window.DiffRenderer.updateFileHeaderState(header, !wrapper.classList.contains('collapsed'));
4139
5116
  }
5117
+
5118
+ // Sync collapsed state with @pierre/diffs instance
5119
+ if (this.pierreBridge && this.pierreBridge.files.has(filePath)) {
5120
+ this.pierreBridge.setCollapsed(filePath, wrapper.classList.contains('collapsed'));
5121
+ }
4140
5122
  }
4141
5123
 
4142
5124
  /**
@@ -4157,6 +5139,10 @@ class PRManager {
4157
5139
  if (header) {
4158
5140
  window.DiffRenderer.updateFileHeaderState(header, false);
4159
5141
  }
5142
+ // Sync with @pierre/diffs
5143
+ if (this.pierreBridge && this.pierreBridge.files.has(filePath)) {
5144
+ this.pierreBridge.setCollapsed(filePath, true);
5145
+ }
4160
5146
  }
4161
5147
  } else {
4162
5148
  this.viewedFiles.delete(filePath);
@@ -4170,6 +5156,10 @@ class PRManager {
4170
5156
  if (header) {
4171
5157
  window.DiffRenderer.updateFileHeaderState(header, true);
4172
5158
  }
5159
+ // Sync with @pierre/diffs
5160
+ if (this.pierreBridge && this.pierreBridge.files.has(filePath)) {
5161
+ this.pierreBridge.setCollapsed(filePath, false);
5162
+ }
4173
5163
  }
4174
5164
  }
4175
5165
 
@@ -4180,6 +5170,98 @@ class PRManager {
4180
5170
  this.saveViewedState();
4181
5171
  }
4182
5172
 
5173
+ /**
5174
+ * Collapse/viewed state key for a context entry. Context entries share a
5175
+ * file path with a possible diff entry for the same file, so their state
5176
+ * is tracked under a namespaced key to keep the two independent.
5177
+ * @param {string} filePath - Path of the file
5178
+ * @returns {string}
5179
+ */
5180
+ _contextStateKey(filePath) {
5181
+ return `context:${filePath}`;
5182
+ }
5183
+
5184
+ /**
5185
+ * Find the context-entry wrapper for a file path. Unlike findFileElement,
5186
+ * this never resolves to the diff wrapper for the same file.
5187
+ * @param {string} filePath - Path of the file
5188
+ * @returns {Element|null}
5189
+ */
5190
+ findContextFileWrapper(filePath) {
5191
+ return document.querySelector(
5192
+ `.d2h-file-wrapper.context-file[data-file-name="${CSS.escape(filePath)}"]`
5193
+ );
5194
+ }
5195
+
5196
+ /**
5197
+ * Toggle collapse state of a context entry.
5198
+ *
5199
+ * Context entries must not route through toggleFileCollapse: that resolves
5200
+ * by file path, which finds the diff wrapper when the same file also has a
5201
+ * diff entry — collapsing the context entry would expand the viewed diff
5202
+ * instead (#540). Context bodies are built eagerly and are not managed by
5203
+ * the pierre bridge, so no lazy render or bridge sync is needed here.
5204
+ * @param {string} filePath - Path of the file
5205
+ */
5206
+ toggleContextFileCollapse(filePath) {
5207
+ const wrapper = this.findContextFileWrapper(filePath);
5208
+ if (!wrapper) return;
5209
+
5210
+ const key = this._contextStateKey(filePath);
5211
+ const collapsed = wrapper.classList.toggle('collapsed');
5212
+ if (collapsed) {
5213
+ this.collapsedFiles.add(key);
5214
+ } else {
5215
+ this.collapsedFiles.delete(key);
5216
+ }
5217
+
5218
+ const header = wrapper.querySelector('.d2h-file-header');
5219
+ if (header) {
5220
+ window.DiffRenderer.updateFileHeaderState(header, !collapsed);
5221
+ }
5222
+ }
5223
+
5224
+ /**
5225
+ * Toggle viewed state of a context entry, independent of the diff entry
5226
+ * for the same file. Persists through the same viewedFiles storage as
5227
+ * diff entries, under the context-scoped key.
5228
+ * @param {string} filePath - Path of the file
5229
+ * @param {boolean} isViewed - Whether the context entry is now viewed
5230
+ */
5231
+ toggleContextFileViewed(filePath, isViewed) {
5232
+ const wrapper = this.findContextFileWrapper(filePath);
5233
+ const key = this._contextStateKey(filePath);
5234
+ const header = wrapper ? wrapper.querySelector('.d2h-file-header') : null;
5235
+
5236
+ if (isViewed) {
5237
+ this.viewedFiles.add(key);
5238
+ // Auto-collapse when marking as viewed
5239
+ if (wrapper && !wrapper.classList.contains('collapsed')) {
5240
+ wrapper.classList.add('collapsed');
5241
+ this.collapsedFiles.add(key);
5242
+ if (header) {
5243
+ window.DiffRenderer.updateFileHeaderState(header, false);
5244
+ }
5245
+ }
5246
+ } else {
5247
+ this.viewedFiles.delete(key);
5248
+ // Auto-expand when unchecking viewed (match GitHub behavior)
5249
+ if (wrapper && wrapper.classList.contains('collapsed')) {
5250
+ wrapper.classList.remove('collapsed');
5251
+ this.collapsedFiles.delete(key);
5252
+ if (header) {
5253
+ window.DiffRenderer.updateFileHeaderState(header, true);
5254
+ }
5255
+ }
5256
+ }
5257
+
5258
+ // Context entries only get their own sidebar row when the file is not in
5259
+ // the diff; scope to context items so a same-path diff row is untouched.
5260
+ this.updateFileItemViewedState(filePath, isViewed, { contextItem: true });
5261
+
5262
+ this.saveViewedState();
5263
+ }
5264
+
4183
5265
  /**
4184
5266
  * Build the eye-slash icon wrapper element used to mark a sidebar
4185
5267
  * file row as viewed. Shared by the initial render and in-place updates
@@ -4201,12 +5283,16 @@ class PRManager {
4201
5283
  * without re-rendering the whole file list.
4202
5284
  * @param {string} filePath - Path of the file
4203
5285
  * @param {boolean} isViewed - Whether the file is now viewed
5286
+ * @param {Object} [options]
5287
+ * @param {boolean} [options.contextItem=false] - Match the context-entry
5288
+ * sidebar row instead of the diff row (they can share a file path)
4204
5289
  */
4205
- updateFileItemViewedState(filePath, isViewed) {
5290
+ updateFileItemViewedState(filePath, isViewed, { contextItem = false } = {}) {
4206
5291
  const items = document.querySelectorAll('.file-item');
4207
5292
  let item = null;
4208
5293
  for (const candidate of items) {
4209
- if (candidate.dataset.path === filePath) {
5294
+ if (candidate.dataset.path === filePath &&
5295
+ candidate.classList.contains('context-file-item') === contextItem) {
4210
5296
  item = candidate;
4211
5297
  break;
4212
5298
  }
@@ -4718,6 +5804,31 @@ class PRManager {
4718
5804
  await this.toggleGeneratedFile(file);
4719
5805
  }
4720
5806
 
5807
+ await this._materializeDeferredDiff(file);
5808
+
5809
+ // For @pierre/diffs rendered files, use context ranges to reveal collapsed lines
5810
+ if (this.pierreBridge && this.pierreBridge.files.has(file)) {
5811
+ await this._ensurePierreContentUpgrade(file);
5812
+ let rangeStart = lineStart;
5813
+ let rangeEnd = lineEnd;
5814
+
5815
+ // addContextRanges expects NEW-file coordinates.
5816
+ // LEFT-side suggestions use OLD-file numbers — convert first.
5817
+ if (side === 'LEFT') {
5818
+ const converted = this.pierreBridge.convertOldToNew(file, lineStart, lineEnd);
5819
+ if (!converted) return false;
5820
+ rangeStart = converted.startLine;
5821
+ rangeEnd = converted.endLine;
5822
+ }
5823
+
5824
+ const padding = 3;
5825
+ const range = {
5826
+ startLine: Math.max(1, rangeStart - padding),
5827
+ endLine: rangeEnd + padding,
5828
+ };
5829
+ return this.pierreBridge.addContextRanges(file, [range]);
5830
+ }
5831
+
4721
5832
  // Find the gap section containing the target lines using the shared module
4722
5833
  // Pass the side parameter so findMatchingGap uses the correct coordinate system:
4723
5834
  // - 'RIGHT' = NEW coordinates (modified file, most common for AI suggestions)
@@ -4794,8 +5905,54 @@ class PRManager {
4794
5905
  async ensureLinesVisible(items) {
4795
5906
  for (const item of items) {
4796
5907
  const { file, line_start, line_end, side } = item;
5908
+ if (!file || !line_start) continue;
4797
5909
  const resolvedSide = (side || 'right').toUpperCase();
4798
5910
 
5911
+ await this._materializeDeferredDiff(file);
5912
+
5913
+ // Materialize the lazy body BEFORE branching on the rendering engine. A
5914
+ // Pierre file whose body hasn't rendered yet is NOT in pierreBridge.files,
5915
+ // so it would wrongly fall through to the legacy <tr> path below (which
5916
+ // scans zero rows for a Pierre file); and an unrendered legacy body has no
5917
+ // rows either. Rendering here lands the file in pierreBridge.files so the
5918
+ // Pierre branch is taken correctly.
5919
+ await this.ensureFileBodyRendered(file);
5920
+
5921
+ // @pierre/diffs files: use context ranges to reveal collapsed lines
5922
+ if (this.pierreBridge && this.pierreBridge.files.has(file)) {
5923
+ // Check the WHOLE range, not just line_start. Callers pass multi-line
5924
+ // ranges (comments, suggestions, chat citations); if line_start is on
5925
+ // screen but line_end is still inside a collapsed gap, we must still
5926
+ // expand. Preserve the skip-when-fully-visible optimization: only expand
5927
+ // when at least one endpoint is hidden.
5928
+ const endLine = line_end || line_start;
5929
+ const startVisible = this.pierreBridge.isLineVisible(file, line_start, resolvedSide);
5930
+ const endVisible = this.pierreBridge.isLineVisible(file, endLine, resolvedSide);
5931
+ if (!startVisible || !endVisible) {
5932
+ await this._ensurePierreContentUpgrade(file);
5933
+ let rangeStart = line_start;
5934
+ let rangeEnd = line_end || line_start;
5935
+
5936
+ // addContextRanges expects NEW-file coordinates.
5937
+ // LEFT-side items use OLD-file numbers — convert first.
5938
+ if (resolvedSide === 'LEFT') {
5939
+ const converted = this.pierreBridge.convertOldToNew(file, rangeStart, rangeEnd);
5940
+ if (converted) {
5941
+ rangeStart = converted.startLine;
5942
+ rangeEnd = converted.endLine;
5943
+ } else {
5944
+ continue;
5945
+ }
5946
+ }
5947
+
5948
+ this.pierreBridge.addContextRanges(file, [{
5949
+ startLine: rangeStart,
5950
+ endLine: rangeEnd,
5951
+ }]);
5952
+ }
5953
+ continue;
5954
+ }
5955
+
4799
5956
  const fileElement = this.findFileElement(file);
4800
5957
  if (!fileElement) continue;
4801
5958
 
@@ -4862,9 +6019,102 @@ class PRManager {
4862
6019
  * Comment form methods - delegate to CommentManager
4863
6020
  */
4864
6021
  showCommentForm(targetRow, lineNumber, fileName, diffPosition, endLineNumber, side = 'RIGHT') {
6022
+ // Use PierreBridge annotation for files rendered by @pierre/diffs
6023
+ if (this.pierreBridge && this.pierreBridge.files.has(fileName)) {
6024
+ const formId = `form-${fileName}-${lineNumber}-${side}`;
6025
+ this.pierreBridge.addAnnotation(fileName, {
6026
+ lineNumber: endLineNumber || lineNumber,
6027
+ side: side,
6028
+ type: 'comment-form',
6029
+ id: formId,
6030
+ data: {
6031
+ lineStart: lineNumber,
6032
+ lineEnd: endLineNumber || lineNumber,
6033
+ fileName: fileName,
6034
+ diffPosition: diffPosition,
6035
+ side: side,
6036
+ showSuggestionBtn: true,
6037
+ },
6038
+ });
6039
+ return;
6040
+ }
6041
+ // Fallback: old table-based comment form (context files)
4865
6042
  this.commentManager.showCommentForm(targetRow, lineNumber, fileName, diffPosition, endLineNumber, side);
4866
6043
  }
4867
6044
 
6045
+ /**
6046
+ * Handle comment form submission from PierreBridge annotation.
6047
+ * Saves the comment via API, removes the form annotation, and reloads comments.
6048
+ * @param {string} fileName - File the comment belongs to
6049
+ * @param {string} annotationId - PierreBridge annotation ID for the form
6050
+ * @param {Object} data - Form data (lineStart, lineEnd, fileName, diffPosition, side)
6051
+ * @param {string} body - Comment body text
6052
+ */
6053
+ async _handleCommentFormSubmit(fileName, annotationId, data, body) {
6054
+ if (!body || !body.trim()) return;
6055
+
6056
+ // Custom submit flow (e.g. edit-and-adopt suggestion): let the caller
6057
+ // decide how to save and how to re-render the result. The handler owns
6058
+ // removing the form annotation.
6059
+ if (typeof data.customSubmit === 'function') {
6060
+ try {
6061
+ await data.customSubmit(body.trim(), fileName, annotationId);
6062
+ } catch (error) {
6063
+ console.error('Error running custom comment form submit:', error);
6064
+ alert(`Failed to save: ${error.message}`);
6065
+ }
6066
+ return;
6067
+ }
6068
+
6069
+ try {
6070
+ const commentData = {
6071
+ file: data.fileName,
6072
+ line_start: data.lineStart,
6073
+ line_end: data.lineEnd,
6074
+ body: body.trim(),
6075
+ side: data.side || 'RIGHT',
6076
+ diff_position: data.diffPosition,
6077
+ // Anchor to the PR head commit so repositioning works if the PR is
6078
+ // updated later. Parity with CommentManager.saveComment.
6079
+ commit_sha: this.currentPR?.head_sha,
6080
+ };
6081
+
6082
+ const response = await fetch(`/api/reviews/${this.currentPR.id}/comments`, {
6083
+ method: 'POST',
6084
+ headers: {
6085
+ 'Content-Type': 'application/json',
6086
+ 'X-Client-Id': this._clientId,
6087
+ },
6088
+ body: JSON.stringify(commentData),
6089
+ });
6090
+
6091
+ if (response.ok) {
6092
+ const result = await response.json().catch(() => ({}));
6093
+ // Remove form annotation
6094
+ this.pierreBridge.removeAnnotation(fileName, annotationId);
6095
+ // Reload comments to show the new one
6096
+ const includeDismissed = window.aiPanel?.showDismissedComments || false;
6097
+ await this.loadUserComments(includeDismissed);
6098
+
6099
+ // Legacy-path side-effects: clear the dragged range, auto-expand in
6100
+ // minimize mode, and notify the AI chat context. Parity with
6101
+ // CommentManager.saveComment.
6102
+ this.lineTracker?.clearRangeSelection();
6103
+ if (result.commentId != null && this.commentMinimizer) {
6104
+ const newRow = document.querySelector(
6105
+ `[data-comment-id="${result.commentId}"]`
6106
+ );
6107
+ if (newRow) this.commentMinimizer.expandForElement(newRow);
6108
+ }
6109
+ window.chatPanel?.queueUserActionHint(
6110
+ `[User Action: created comment on ${data.fileName} lines ${data.lineStart}-${data.lineEnd}]`
6111
+ );
6112
+ }
6113
+ } catch (error) {
6114
+ console.error('Error saving comment:', error);
6115
+ }
6116
+ }
6117
+
4868
6118
  hideCommentForm() {
4869
6119
  this.commentManager.hideCommentForm();
4870
6120
  }
@@ -5322,38 +6572,74 @@ class PRManager {
5322
6572
  // Clear existing comment rows before re-rendering
5323
6573
  document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)').forEach(row => row.remove());
5324
6574
 
5325
- // Before rendering, ensure all comment target lines are visible
5326
- // (expand hidden hunks so the line rows exist in the DOM)
5327
- const lineItems = lineLevelComments.map(c => ({
5328
- file: c.file,
5329
- line_start: c.line_start,
5330
- line_end: c.line_start,
5331
- side: c.side || 'RIGHT'
5332
- }));
5333
- await this.ensureLinesVisible(lineItems);
5334
-
5335
- // Display line-level comments inline with diff (only active comments reach here)
5336
- lineLevelComments.forEach(comment => {
5337
- const fileElement = this.findFileElement(comment.file);
5338
- if (!fileElement) return;
6575
+ // Clear existing PierreBridge comment annotations
6576
+ if (this.pierreBridge) {
6577
+ for (const [file] of this.pierreBridge.files) {
6578
+ this.pierreBridge.removeAnnotationsByType(file, 'comment');
6579
+ }
6580
+ }
5339
6581
 
5340
- // Use the comment's side to determine which coordinate system to search in
5341
- // LEFT side = OLD coordinates (deleted lines or context lines in OLD coords)
5342
- // RIGHT side = NEW coordinates (added lines or context lines in NEW coords)
5343
- const side = comment.side || 'RIGHT';
6582
+ // Ensure every comment's target line is reachable in the DOM before
6583
+ // rendering. `ensureLinesVisible` handles both engines — for Pierre
6584
+ // files it expands collapsed gaps via `addContextRanges` so the
6585
+ // annotation row exists; for legacy files it expands hidden hunks.
6586
+ // Without this, comments on lines outside the default hunks render
6587
+ // nowhere on reload and "jump to comment" silently fails.
6588
+ if (lineLevelComments.length > 0) {
6589
+ await this.ensureLinesVisible(lineLevelComments.map(c => ({
6590
+ file: c.file,
6591
+ line_start: c.line_start,
6592
+ line_end: c.line_end || c.line_start,
6593
+ side: c.side || 'RIGHT',
6594
+ })));
6595
+ }
6596
+
6597
+ // Partition line-level comments by rendering engine
6598
+ const pierreComments = [];
6599
+ const legacyComments = [];
6600
+ lineLevelComments.forEach(comment => {
6601
+ if (this.pierreBridge && this.pierreBridge.files.has(comment.file)) {
6602
+ pierreComments.push(comment);
6603
+ } else {
6604
+ legacyComments.push(comment);
6605
+ }
6606
+ });
5344
6607
 
5345
- const lineRows = fileElement.querySelectorAll('tr');
5346
- for (const row of lineRows) {
5347
- // Pass side to getLineNumber() to get the correct coordinate system
5348
- // This allows context lines (which have BOTH old and new line numbers) to be found
5349
- // when the comment was placed on a LEFT-side line (old coordinate)
5350
- const lineNum = this.getLineNumber(row, side);
5351
- if (lineNum === comment.line_start) {
5352
- this.displayUserComment(comment, row);
5353
- break;
5354
- }
6608
+ // Display comments via PierreBridge annotations. Group by file so each
6609
+ // file rerenders ONCE for its whole set of comments, not once per comment.
6610
+ const commentAnnotationsByFile = new Map();
6611
+ pierreComments.forEach(comment => {
6612
+ if (!commentAnnotationsByFile.has(comment.file)) {
6613
+ commentAnnotationsByFile.set(comment.file, []);
5355
6614
  }
6615
+ commentAnnotationsByFile.get(comment.file).push({
6616
+ lineNumber: comment.line_start,
6617
+ side: comment.side || 'RIGHT',
6618
+ type: 'comment',
6619
+ id: `comment-${comment.id}`,
6620
+ data: comment,
6621
+ });
5356
6622
  });
6623
+ for (const [file, annotations] of commentAnnotationsByFile) {
6624
+ this.pierreBridge.addAnnotations(file, annotations);
6625
+ }
6626
+
6627
+ if (legacyComments.length > 0) {
6628
+ legacyComments.forEach(comment => {
6629
+ const fileElement = this.findFileElement(comment.file);
6630
+ if (!fileElement) return;
6631
+
6632
+ const side = comment.side || 'RIGHT';
6633
+ const lineRows = fileElement.querySelectorAll('tr');
6634
+ for (const row of lineRows) {
6635
+ const lineNum = this.getLineNumber(row, side);
6636
+ if (lineNum === comment.line_start) {
6637
+ this.displayUserComment(comment, row);
6638
+ break;
6639
+ }
6640
+ }
6641
+ });
6642
+ }
5357
6643
 
5358
6644
  // Load file-level comments into their zones (only active comments reach here)
5359
6645
  if (this.fileCommentManager && fileLevelComments.length > 0) {
@@ -5480,18 +6766,23 @@ class PRManager {
5480
6766
 
5481
6767
  /**
5482
6768
  * Collapse a suggestion div in the UI after adoption.
5483
- * Handles adding collapsed class, updating text to 'Suggestion adopted',
6769
+ * Handles adding collapsed class, setting the 'Adopted' state tooltip,
5484
6770
  * updating the restore button, and setting hiddenForAdoption flag.
5485
- * @param {HTMLElement} suggestionRow - The suggestion row element
6771
+ *
6772
+ * With legacy rendering, `suggestionRow` is the `<tr>` containing the
6773
+ * suggestion. With @pierre/diffs there is no `<tr>`, so callers pass null
6774
+ * and this method falls back to a document-wide lookup by id.
6775
+ *
6776
+ * @param {HTMLElement|null} suggestionRow - The suggestion row element (legacy only)
5486
6777
  * @param {number|string} suggestionId - Suggestion ID
5487
6778
  */
5488
6779
  collapseSuggestionForAdoption(suggestionRow, suggestionId) {
5489
- if (!suggestionRow) return;
5490
- const targetDiv = suggestionRow.querySelector(`[data-suggestion-id="${suggestionId}"]`);
6780
+ const targetDiv = suggestionRow
6781
+ ? suggestionRow.querySelector(`[data-suggestion-id="${suggestionId}"]`)
6782
+ : document.querySelector(`[data-suggestion-id="${suggestionId}"]`);
5491
6783
  if (!targetDiv) return;
5492
6784
  targetDiv.classList.add('collapsed');
5493
- const collapsedContent = targetDiv.querySelector('.collapsed-text');
5494
- if (collapsedContent) collapsedContent.textContent = 'Suggestion adopted';
6785
+ window.SuggestionUI?.setCollapsedStateTooltip?.(targetDiv, 'Adopted');
5495
6786
  const restoreButton = targetDiv.querySelector('.btn-restore');
5496
6787
  if (restoreButton) {
5497
6788
  restoreButton.title = 'Show suggestion';
@@ -5501,16 +6792,54 @@ class PRManager {
5501
6792
  targetDiv.dataset.hiddenForAdoption = 'true';
5502
6793
  }
5503
6794
 
6795
+ /**
6796
+ * Render an adopted user comment in the appropriate rendering engine.
6797
+ *
6798
+ * For files rendered by @pierre/diffs, `suggestionRow` is null (suggestions
6799
+ * are annotations, not table rows). Add the comment as a Pierre annotation
6800
+ * so it slots into the shadow DOM alongside the collapsed suggestion.
6801
+ *
6802
+ * For legacy (table-based) rendering, delegate to the existing
6803
+ * `displayUserComment(comment, suggestionRow)` which inserts a `<tr>`.
6804
+ *
6805
+ * @param {Object} comment - The newly-adopted comment
6806
+ * @param {HTMLElement|null} suggestionRow - Legacy table row, or null for Pierre
6807
+ * @private
6808
+ */
6809
+ async _renderAdoptedUserComment(comment, suggestionRow) {
6810
+ if (this.pierreBridge && comment.file && this.pierreBridge.files.has(comment.file)) {
6811
+ // Reveal the target line if it sits inside a collapsed gap — otherwise
6812
+ // the annotation has no DOM row to attach to and never renders.
6813
+ await this.ensureLinesVisible([{
6814
+ file: comment.file,
6815
+ line_start: comment.line_start,
6816
+ line_end: comment.line_end || comment.line_start,
6817
+ side: comment.side || 'RIGHT',
6818
+ }]);
6819
+ this.pierreBridge.addAnnotation(comment.file, {
6820
+ lineNumber: comment.line_start,
6821
+ side: comment.side || 'RIGHT',
6822
+ type: 'comment',
6823
+ id: `comment-${comment.id}`,
6824
+ data: comment,
6825
+ });
6826
+ return;
6827
+ }
6828
+ // Legacy path: displayUserComment inserts a <tr> after suggestionRow
6829
+ this.displayUserComment(comment, suggestionRow);
6830
+ }
6831
+
5504
6832
  /**
5505
6833
  * Build a user comment object from adoption/edit response data.
5506
6834
  * Single source of truth for comment shape — used by both adopt-as-is
5507
6835
  * and edit-then-adopt flows.
5508
6836
  */
5509
- _buildCommentObject({ userCommentId, formattedBody, fileName, lineNumber, suggestionType, suggestionTitle, suggestionId, diffPosition, side }) {
6837
+ _buildCommentObject({ userCommentId, formattedBody, fileName, lineNumber, lineEnd, suggestionType, suggestionTitle, suggestionId, diffPosition, side }) {
5510
6838
  return {
5511
6839
  id: userCommentId,
5512
6840
  file: fileName,
5513
6841
  line_start: parseInt(lineNumber),
6842
+ line_end: lineEnd ? parseInt(lineEnd) : null,
5514
6843
  body: formattedBody,
5515
6844
  type: suggestionType,
5516
6845
  title: suggestionTitle,
@@ -5529,7 +6858,7 @@ class PRManager {
5529
6858
  */
5530
6859
  async _adoptAndBuildComment(suggestionId, suggestionDiv) {
5531
6860
  const { suggestionText, suggestionType, suggestionTitle } = this.extractSuggestionData(suggestionDiv);
5532
- const { suggestionRow, lineNumber, fileName, diffPosition, side, isFileLevel } = this.getFileAndLineInfo(suggestionDiv);
6861
+ const { suggestionRow, lineNumber, lineEnd, fileName, diffPosition, side, isFileLevel } = this.getFileAndLineInfo(suggestionDiv);
5533
6862
 
5534
6863
  // File-level suggestions are handled by FileCommentManager; signal the caller
5535
6864
  if (isFileLevel) {
@@ -5554,7 +6883,7 @@ class PRManager {
5554
6883
  const newComment = this._buildCommentObject({
5555
6884
  userCommentId: adoptResult.userCommentId,
5556
6885
  formattedBody: adoptResult.formattedBody,
5557
- fileName, lineNumber, suggestionType, suggestionTitle,
6886
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
5558
6887
  suggestionId, diffPosition, side
5559
6888
  });
5560
6889
 
@@ -5631,6 +6960,58 @@ class PRManager {
5631
6960
  side
5632
6961
  };
5633
6962
 
6963
+ // Pierre-rendered files: suggestions live as annotations (no <tr>),
6964
+ // so `displaySuggestionEditForm` — which inserts a table row after
6965
+ // `suggestionRow` — cannot run. Open the edit form as a comment-form
6966
+ // annotation on the same line, pre-filled with the suggestion body,
6967
+ // and wire a custom submit that runs the adopt-edited flow.
6968
+ if (this.pierreBridge && this.pierreBridge.files.has(fileName)) {
6969
+ const formId = `edit-suggestion-${suggestionId}`;
6970
+ const onAdoptEdited = async (editedText, _fileName, annotationId) => {
6971
+ const reviewId = this.currentPR?.id;
6972
+ const editResponse = await fetch(`/api/reviews/${reviewId}/suggestions/${suggestionId}/edit`, {
6973
+ method: 'POST',
6974
+ headers: { 'Content-Type': 'application/json' },
6975
+ body: JSON.stringify({ action: 'adopt_edited', editedText })
6976
+ });
6977
+ if (!editResponse.ok) throw new Error('Failed to adopt suggestion with edits');
6978
+ const editResult = await editResponse.json();
6979
+
6980
+ // Collapse the suggestion annotation and render the new comment.
6981
+ this.collapseSuggestionForAdoption(null, suggestionId);
6982
+ const newComment = this._buildCommentObject({
6983
+ userCommentId: editResult.userCommentId,
6984
+ formattedBody: editResult.formattedBody,
6985
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
6986
+ suggestionId, diffPosition, side
6987
+ });
6988
+
6989
+ // Remove the edit form annotation and add the comment annotation.
6990
+ this.pierreBridge.removeAnnotation(fileName, annotationId);
6991
+ await this._renderAdoptedUserComment(newComment, null);
6992
+ this._notifyAdoption(suggestionId, newComment);
6993
+ };
6994
+
6995
+ this.pierreBridge.addAnnotation(fileName, {
6996
+ lineNumber: lineEnd || lineNumber,
6997
+ side: side || 'RIGHT',
6998
+ type: 'comment-form',
6999
+ id: formId,
7000
+ data: {
7001
+ headerTitle: 'Edit suggestion',
7002
+ lineStart: lineNumber,
7003
+ lineEnd: lineEnd || lineNumber,
7004
+ fileName: fileName,
7005
+ diffPosition: diffPosition,
7006
+ side: side || 'RIGHT',
7007
+ showSuggestionBtn: true,
7008
+ initialValue: formattedBody || suggestionText,
7009
+ customSubmit: onAdoptEdited,
7010
+ },
7011
+ });
7012
+ return;
7013
+ }
7014
+
5634
7015
  this.commentManager.displaySuggestionEditForm(
5635
7016
  suggestion,
5636
7017
  suggestionRow,
@@ -5653,10 +7034,10 @@ class PRManager {
5653
7034
  const newComment = this._buildCommentObject({
5654
7035
  userCommentId: editResult.userCommentId,
5655
7036
  formattedBody: editResult.formattedBody,
5656
- fileName, lineNumber, suggestionType, suggestionTitle,
7037
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
5657
7038
  suggestionId, diffPosition, side
5658
7039
  });
5659
- this.displayUserComment(newComment, suggestionRow);
7040
+ await this._renderAdoptedUserComment(newComment, suggestionRow);
5660
7041
  this._notifyAdoption(suggestionId, newComment);
5661
7042
  window.chatPanel?.queueUserActionHint(`[User Action: adopted suggestion ${suggestionId}]`);
5662
7043
  } catch (error) {
@@ -5702,7 +7083,7 @@ class PRManager {
5702
7083
  return;
5703
7084
  }
5704
7085
 
5705
- this.displayUserComment(result.newComment, result.suggestionRow);
7086
+ await this._renderAdoptedUserComment(result.newComment, result.suggestionRow);
5706
7087
  this._notifyAdoption(suggestionId, result.newComment);
5707
7088
  window.chatPanel?.queueUserActionHint(`[User Action: adopted suggestion ${suggestionId}]`);
5708
7089
  } catch (error) {
@@ -5723,8 +7104,11 @@ class PRManager {
5723
7104
  // If this suggestion was adopted, only toggle visibility - don't change status
5724
7105
  // The adoption still exists (there's a user comment linked to this suggestion)
5725
7106
  if (suggestionDiv?.dataset?.hiddenForAdoption === 'true') {
5726
- // suggestionDiv is guaranteed to exist since we just queried for it
7107
+ // suggestionDiv is guaranteed to exist since we just queried for it.
7108
+ // The suggestion stays adopted here; we only re-hide it, so the
7109
+ // collapsed-bar tooltip keeps reading 'Adopted'.
5727
7110
  suggestionDiv.classList.add('collapsed');
7111
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, 'Adopted');
5728
7112
 
5729
7113
  const button = suggestionDiv.querySelector('.btn-restore');
5730
7114
  if (button) {
@@ -5745,6 +7129,7 @@ class PRManager {
5745
7129
 
5746
7130
  if (suggestionDiv) {
5747
7131
  suggestionDiv.classList.add('collapsed');
7132
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, 'Dismissed');
5748
7133
  const restoreButton = suggestionDiv.querySelector('.btn-restore');
5749
7134
  if (restoreButton) {
5750
7135
  restoreButton.title = 'Show suggestion';
@@ -5790,11 +7175,13 @@ class PRManager {
5790
7175
 
5791
7176
  // Find the button within this specific suggestion div, not the first one in the row
5792
7177
  const button = suggestionDiv.querySelector('.btn-restore');
7178
+ const isNowCollapsed = suggestionDiv.classList.contains('collapsed');
5793
7179
  if (button) {
5794
- const isNowCollapsed = suggestionDiv.classList.contains('collapsed');
5795
7180
  button.title = isNowCollapsed ? 'Show suggestion' : 'Hide suggestion';
5796
7181
  button.querySelector('.btn-text').textContent = isNowCollapsed ? 'Show' : 'Hide';
5797
7182
  }
7183
+ // Still adopted; keep the 'Adopted' tooltip only while re-hidden.
7184
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, isNowCollapsed ? 'Adopted' : '');
5798
7185
  return;
5799
7186
  }
5800
7187
 
@@ -5808,6 +7195,12 @@ class PRManager {
5808
7195
 
5809
7196
  if (suggestionDiv) {
5810
7197
  suggestionDiv.classList.remove('collapsed');
7198
+ // Restored to active — clear the collapsed-bar state tooltip.
7199
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, '');
7200
+ // Strip stale dismissal-reason markup (note + popover attr/brain button)
7201
+ // baked in while dismissed; same-tab broadcasts are suppressed so no
7202
+ // refetch rescues this card.
7203
+ window.SuggestionUI?.clearDismissalReasonUI?.(suggestionDiv);
5811
7204
  }
5812
7205
 
5813
7206
  if (this.suggestionNavigator?.suggestions) {
@@ -6367,7 +7760,10 @@ class PRManager {
6367
7760
 
6368
7761
  if (file.generated) item.classList.add('generated');
6369
7762
  if (file.contextFile) item.classList.add('context-file-item');
6370
- if (this.viewedFiles && this.viewedFiles.has(file.fullPath)) {
7763
+ // Context entries track viewed state under a context-scoped key so they
7764
+ // stay independent of a diff entry for the same file.
7765
+ const viewedKey = file.contextFile ? this._contextStateKey(file.fullPath) : file.fullPath;
7766
+ if (this.viewedFiles && this.viewedFiles.has(viewedKey)) {
6371
7767
  item.classList.add('viewed');
6372
7768
  const viewedIcon = this._createViewedIcon();
6373
7769
  item.insertBefore(viewedIcon, item.firstChild);
@@ -6492,6 +7888,15 @@ class PRManager {
6492
7888
  // later still renders on demand via toggleFileCollapse.
6493
7889
  if (!fileWrapper.classList.contains('collapsed')) {
6494
7890
  await this.ensureFileBodyRendered(filePath);
7891
+ // Only now can this file be moved to the front of the Pierre
7892
+ // content-upgrade queue: rendering its body is what enqueues it
7893
+ // (_renderPierreFileBodyNow → _enqueuePierreContentUpgrade), so
7894
+ // state.pending contains it and the reorder actually takes effect.
7895
+ // Hoisting this before the render would be a silent no-op — findIndex
7896
+ // misses the not-yet-enqueued file and the later render appends it to
7897
+ // the queue tail. Collapsed files stay hidden and never upgrade, so
7898
+ // they intentionally get no priority hint.
7899
+ this._prioritizePierreContentUpgrade(filePath);
6495
7900
  }
6496
7901
  // Stable variant: lazy bodies between here and the target render as
6497
7902
  // the smooth scroll passes them, shifting layout mid-flight. The
@@ -6517,27 +7922,19 @@ class PRManager {
6517
7922
  * Theme methods
6518
7923
  */
6519
7924
  initTheme() {
6520
- document.documentElement.setAttribute('data-theme', this.currentTheme);
6521
- this.updateThemeIcon();
6522
- }
6523
-
6524
- toggleTheme() {
6525
- this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
6526
- localStorage.setItem('theme', this.currentTheme);
6527
- document.documentElement.setAttribute('data-theme', this.currentTheme);
6528
- this.updateThemeIcon();
6529
- }
6530
-
6531
- updateThemeIcon() {
6532
- const themeButton = document.getElementById('theme-toggle');
6533
- if (themeButton) {
6534
- // Sun icon for light mode (with hollow center), moon icon for dark mode
6535
- const icon = this.currentTheme === 'light' ?
6536
- `<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0-1.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5Zm0-10.5a.75.75 0 0 1 .75.75v1.5a.75.75 0 0 1-1.5 0V.75A.75.75 0 0 1 8 0Zm0 13a.75.75 0 0 1 .75.75v1.5a.75.75 0 0 1-1.5 0v-1.5A.75.75 0 0 1 8 13ZM2.343 2.343a.75.75 0 0 1 1.061 0l1.06 1.061a.75.75 0 0 1-1.06 1.06l-1.06-1.06a.75.75 0 0 1 0-1.06Zm9.193 9.193a.75.75 0 0 1 1.06 0l1.061 1.06a.75.75 0 0 1-1.06 1.061l-1.061-1.06a.75.75 0 0 1 0-1.061ZM16 8a.75.75 0 0 1-.75.75h-1.5a.75.75 0 0 1 0-1.5h1.5A.75.75 0 0 1 16 8ZM3 8a.75.75 0 0 1-.75.75H.75a.75.75 0 0 1 0-1.5h1.5A.75.75 0 0 1 3 8Zm10.657-5.657a.75.75 0 0 1 0 1.061l-1.061 1.06a.75.75 0 1 1-1.06-1.06l1.06-1.06a.75.75 0 0 1 1.06 0Zm-9.193 9.193a.75.75 0 0 1 0 1.06l-1.06 1.061a.75.75 0 0 1-1.061-1.06l1.06-1.061a.75.75 0 0 1 1.061 0Z"/></svg>` :
6537
- `<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M9.598 1.591a.749.749 0 0 1 .785-.175 7.001 7.001 0 1 1-8.967 8.967.75.75 0 0 1 .961-.96 5.5 5.5 0 0 0 7.046-7.046.75.75 0 0 1 .175-.786Z"/></svg>`;
6538
- themeButton.innerHTML = icon;
6539
- themeButton.title = `Switch to ${this.currentTheme === 'light' ? 'dark' : 'light'} mode`;
6540
- }
7925
+ // Shared helper (js/theme.js) owns preference storage, the
7926
+ // light → dark → system toggle cycle, the button icon, and the live
7927
+ // OS-change listener. We keep this.currentTheme as the *resolved* theme so
7928
+ // the diff renderer (@pierre/diffs) always receives a concrete
7929
+ // 'light'|'dark', never the 'system' preference.
7930
+ this._themeDispose = window.PairReviewTheme.setup({
7931
+ onChange: (resolved) => {
7932
+ this.currentTheme = resolved;
7933
+ if (this.pierreBridge) {
7934
+ this.pierreBridge.setTheme(resolved);
7935
+ }
7936
+ },
7937
+ });
6541
7938
  }
6542
7939
 
6543
7940
  savePanelStates() {
@@ -6605,9 +8002,16 @@ class PRManager {
6605
8002
 
6606
8003
  const btnText = btn.querySelector('.btn-text');
6607
8004
  if (btnText) {
8005
+ // Insert the spinner before the label (guard against a double-call
8006
+ // stacking two spinners), then switch the label.
8007
+ if (!btn.querySelector('.btn-spinner')) {
8008
+ const spinner = document.createElement('span');
8009
+ spinner.className = 'btn-spinner';
8010
+ btn.insertBefore(spinner, btnText);
8011
+ }
6608
8012
  btnText.textContent = 'Analyzing...';
6609
8013
  } else {
6610
- btn.innerHTML = '<span class="analyzing-icon">✨</span> Analyzing...';
8014
+ btn.innerHTML = '<span class="btn-spinner"></span> Analyzing...';
6611
8015
  }
6612
8016
  }
6613
8017
 
@@ -6627,6 +8031,8 @@ class PRManager {
6627
8031
 
6628
8032
  const btnText = btn.querySelector('.btn-text');
6629
8033
  if (btnText) {
8034
+ const spinner = btn.querySelector('.btn-spinner');
8035
+ if (spinner) spinner.remove();
6630
8036
  btnText.textContent = 'Complete';
6631
8037
  } else {
6632
8038
  btn.innerHTML = '✓ Analysis Complete';
@@ -6656,6 +8062,8 @@ class PRManager {
6656
8062
 
6657
8063
  const btnText = btn.querySelector('.btn-text');
6658
8064
  if (btnText) {
8065
+ const spinner = btn.querySelector('.btn-spinner');
8066
+ if (spinner) spinner.remove();
6659
8067
  btnText.textContent = 'Analyze';
6660
8068
  } else {
6661
8069
  btn.innerHTML = 'Analyze with AI';
@@ -7343,6 +8751,10 @@ class PRManager {
7343
8751
  const reviewId = this.currentPR?.id;
7344
8752
  if (!reviewId) return;
7345
8753
 
8754
+ // Capture before anything reassigns this.contextFiles — needed to scrub
8755
+ // context-scoped state for rows deleted remotely (peer tab / WebSocket).
8756
+ const previousFiles = this.contextFiles || [];
8757
+
7346
8758
  try {
7347
8759
  const response = await fetch(`/api/reviews/${reviewId}/context-files`);
7348
8760
  if (!response.ok) return;
@@ -7381,9 +8793,18 @@ class PRManager {
7381
8793
  }
7382
8794
  }
7383
8795
 
7384
- // Add only new context files
8796
+ // Add only new context files. "Diff wins": a stored context row whose
8797
+ // file has since entered the diff (Local-mode scope change, new commits,
8798
+ // PR refresh) is suppressed at the view layer — never rendered as a
8799
+ // duplicate wrapper, never deleted from the DB. renderDiff is a full
8800
+ // clear-and-rebuild that resets contextFiles and re-runs this method,
8801
+ // so a file leaving the diff self-heals back to a context wrapper.
8802
+ // Mirrors the add-time guards (ensureContextFile, the POST route) and
8803
+ // the sidebar merge (mergeFileListWithContext).
8804
+ const diffPaths = new Set((this.diffFiles || []).map(f => f.file));
7385
8805
  let newFilesRendered = false;
7386
8806
  for (const cf of newFiles) {
8807
+ if (diffPaths.has(cf.file)) continue;
7387
8808
  if (!oldIds.has(cf.id)) {
7388
8809
  await this.renderContextFile(cf);
7389
8810
  newFilesRendered = true;
@@ -7392,6 +8813,13 @@ class PRManager {
7392
8813
 
7393
8814
  this.contextFiles = newFiles;
7394
8815
 
8816
+ // Scrub context-scoped viewed/collapsed keys for paths whose entries all
8817
+ // disappeared in this refresh. Without this, a delete arriving via the
8818
+ // WebSocket path leaves orphaned `context:` keys on peer tabs: re-adding
8819
+ // the file renders it pre-viewed/pre-collapsed, and a later
8820
+ // saveViewedState() writes the orphan back into shared storage.
8821
+ this._scrubRemovedContextState(previousFiles);
8822
+
7395
8823
  // Rebuild sidebar with context files interleaved in natural path order
7396
8824
  this.rebuildFileListWithContext();
7397
8825
 
@@ -7444,31 +8872,6 @@ class PRManager {
7444
8872
  }
7445
8873
  tbody.dataset.lineStart = effectiveStart;
7446
8874
 
7447
- // Chunk header row with range label and per-chunk dismiss button
7448
- const headerRow = document.createElement('tr');
7449
- headerRow.className = 'context-chunk-header';
7450
- const lineNumTd = document.createElement('td');
7451
- lineNumTd.className = 'd2h-code-linenumber';
7452
- headerRow.appendChild(lineNumTd);
7453
- const contentTd = document.createElement('td');
7454
- contentTd.className = 'd2h-code-side-line';
7455
- contentTd.colSpan = 3;
7456
- const rangeLabel = document.createElement('span');
7457
- rangeLabel.className = 'context-range-label';
7458
- rangeLabel.textContent = `Lines ${effectiveStart}\u2013${clampedEnd}`;
7459
- contentTd.appendChild(rangeLabel);
7460
- const chunkDismiss = document.createElement('button');
7461
- chunkDismiss.className = 'context-chunk-dismiss';
7462
- chunkDismiss.title = 'Remove this range';
7463
- chunkDismiss.innerHTML = '\u00d7';
7464
- chunkDismiss.addEventListener('click', (e) => {
7465
- e.stopPropagation();
7466
- this.removeContextFile(contextFile.id);
7467
- });
7468
- contentTd.appendChild(chunkDismiss);
7469
- headerRow.appendChild(contentTd);
7470
- tbody.appendChild(headerRow);
7471
-
7472
8875
  // Add expand-up gap row if there are lines above the context range
7473
8876
  if (effectiveStart > 1) {
7474
8877
  const gapAboveSize = effectiveStart - 1;
@@ -7618,7 +9021,7 @@ class PRManager {
7618
9021
  chevronBtn.innerHTML = window.DiffRenderer.CHEVRON_DOWN_ICON;
7619
9022
  chevronBtn.addEventListener('click', (e) => {
7620
9023
  e.stopPropagation();
7621
- this.toggleFileCollapse(contextFile.file);
9024
+ this.toggleContextFileCollapse(contextFile.file);
7622
9025
  });
7623
9026
  header.appendChild(chevronBtn);
7624
9027
 
@@ -7640,10 +9043,10 @@ class PRManager {
7640
9043
  const viewedCheckbox = document.createElement('input');
7641
9044
  viewedCheckbox.type = 'checkbox';
7642
9045
  viewedCheckbox.className = 'file-viewed-checkbox';
7643
- viewedCheckbox.checked = this.viewedFiles.has(contextFile.file);
9046
+ viewedCheckbox.checked = this.viewedFiles.has(this._contextStateKey(contextFile.file));
7644
9047
  viewedCheckbox.addEventListener('change', (e) => {
7645
9048
  e.stopPropagation();
7646
- this.toggleFileViewed(contextFile.file, viewedCheckbox.checked);
9049
+ this.toggleContextFileViewed(contextFile.file, viewedCheckbox.checked);
7647
9050
  });
7648
9051
  viewedLabel.appendChild(viewedCheckbox);
7649
9052
  viewedLabel.appendChild(document.createTextNode('Viewed'));
@@ -7722,7 +9125,7 @@ class PRManager {
7722
9125
  e.target.closest('.context-file-dismiss')) {
7723
9126
  return;
7724
9127
  }
7725
- this.toggleFileCollapse(contextFile.file);
9128
+ this.toggleContextFileCollapse(contextFile.file);
7726
9129
  });
7727
9130
 
7728
9131
  wrapper.appendChild(header);
@@ -7743,6 +9146,14 @@ class PRManager {
7743
9146
  fileBody.appendChild(table);
7744
9147
  wrapper.appendChild(fileBody);
7745
9148
 
9149
+ // Apply context-scoped collapse/viewed state (independent of any diff
9150
+ // entry for the same file) — mirrors renderFileDiff's initial state.
9151
+ const contextKey = this._contextStateKey(contextFile.file);
9152
+ if (this.viewedFiles.has(contextKey) || this.collapsedFiles.has(contextKey)) {
9153
+ wrapper.classList.add('collapsed');
9154
+ window.DiffRenderer.updateFileHeaderState(header, false);
9155
+ }
9156
+
7746
9157
  // Insert in sorted path order among existing file wrappers
7747
9158
  const allWrappers = [...diffContainer.querySelectorAll('.d2h-file-wrapper')];
7748
9159
  const insertBefore = allWrappers.find(w => w.dataset.fileName > contextFile.file);
@@ -7753,6 +9164,38 @@ class PRManager {
7753
9164
  }
7754
9165
  }
7755
9166
 
9167
+ /**
9168
+ * Scrub context-scoped viewed/collapsed keys for context entries that no
9169
+ * longer have any row for their path in the current this.contextFiles.
9170
+ * Persists via saveViewedState() only when a viewed key was actually
9171
+ * removed, so WebSocket-driven refreshes don't POST on every event.
9172
+ * Idempotent: re-running with the same input is a no-op.
9173
+ *
9174
+ * Note: the "diff wins" guard in loadContextFiles only suppresses rendering;
9175
+ * suppressed rows remain in this.contextFiles, so they are correctly treated
9176
+ * as still present here and never scrubbed.
9177
+ *
9178
+ * @param {Array<{file: string}>} previousContextFiles - Context rows that
9179
+ * existed before the refresh/delete (candidates for scrubbing)
9180
+ */
9181
+ _scrubRemovedContextState(previousContextFiles) {
9182
+ if (!previousContextFiles || previousContextFiles.length === 0) return;
9183
+
9184
+ const remainingPaths = new Set((this.contextFiles || []).map(cf => cf.file));
9185
+ let viewedRemoved = false;
9186
+ for (const prev of previousContextFiles) {
9187
+ if (!prev || remainingPaths.has(prev.file)) continue;
9188
+ const key = this._contextStateKey(prev.file);
9189
+ this.collapsedFiles?.delete(key);
9190
+ if (this.viewedFiles?.delete(key)) {
9191
+ viewedRemoved = true;
9192
+ }
9193
+ }
9194
+ if (viewedRemoved) {
9195
+ this.saveViewedState();
9196
+ }
9197
+ }
9198
+
7756
9199
  /**
7757
9200
  * Remove a context file by ID.
7758
9201
  * @param {number} contextFileId
@@ -7761,6 +9204,12 @@ class PRManager {
7761
9204
  const reviewId = this.currentPR?.id;
7762
9205
  if (!reviewId) return;
7763
9206
 
9207
+ // Capture the row before loadContextFiles refreshes this.contextFiles —
9208
+ // afterwards the deleted ID is gone and the file path with it.
9209
+ const removed = (this.contextFiles || []).find(
9210
+ cf => String(cf.id) === String(contextFileId)
9211
+ );
9212
+
7764
9213
  try {
7765
9214
  const resp = await fetch(`/api/reviews/${reviewId}/context-files/${contextFileId}`, {
7766
9215
  method: 'DELETE',
@@ -7772,6 +9221,13 @@ class PRManager {
7772
9221
  }
7773
9222
  // Refresh immediately — WebSocket self-echo is suppressed by the client ID filter
7774
9223
  await this.loadContextFiles();
9224
+
9225
+ // Defense-in-depth: loadContextFiles already scrubs based on its own
9226
+ // previous-files snapshot, but scrub the captured row explicitly too —
9227
+ // the helper's remaining-paths check makes double-scrubbing harmless.
9228
+ if (removed) {
9229
+ this._scrubRemovedContextState([removed]);
9230
+ }
7775
9231
  } catch (error) {
7776
9232
  console.error('Error removing context file:', error);
7777
9233
  }