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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) 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 +666 -394
  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/external-comment-manager.js +414 -48
  27. package/public/js/modules/file-comment-manager.js +28 -21
  28. package/public/js/modules/hunk-summary-renderer.js +155 -29
  29. package/public/js/modules/pierre-bridge.js +2513 -0
  30. package/public/js/modules/pierre-context.js +345 -0
  31. package/public/js/modules/suggestion-manager.js +176 -20
  32. package/public/js/modules/tour-renderer.js +400 -184
  33. package/public/js/pr.js +1434 -150
  34. package/public/js/repo-settings.js +60 -284
  35. package/public/js/settings.js +1086 -0
  36. package/public/js/theme-bootstrap.js +40 -0
  37. package/public/js/theme.js +247 -0
  38. package/public/js/utils/provider-model.js +3 -3
  39. package/public/js/utils/suggestion-ui.js +157 -8
  40. package/public/local.html +20 -31
  41. package/public/pr.html +14 -23
  42. package/public/repo-settings.html +24 -14
  43. package/public/settings.html +138 -0
  44. package/public/setup.html +8 -13
  45. package/src/chat/api-reference.js +9 -5
  46. package/src/chat/prompt-builder.js +8 -1
  47. package/src/config.js +15 -6
  48. package/src/database.js +307 -14
  49. package/src/external/github-adapter.js +39 -5
  50. package/src/headless/delegate.js +682 -0
  51. package/src/local-review.js +10 -10
  52. package/src/local-scope.js +9 -0
  53. package/src/main.js +276 -157
  54. package/src/mcp-stdio.js +24 -1
  55. package/src/review-config.js +93 -25
  56. package/src/routes/chat.js +2 -2
  57. package/src/routes/config.js +12 -10
  58. package/src/routes/external-comments.js +5 -1
  59. package/src/routes/local.js +2 -4
  60. package/src/routes/mcp.js +18 -13
  61. package/src/routes/reviews.js +223 -4
  62. package/src/routes/settings.js +252 -0
  63. package/src/routes/setup.js +80 -1
  64. package/src/routes/shared.js +31 -29
  65. package/src/routes/snippets.js +154 -0
  66. package/src/routes/stack-analysis.js +17 -14
  67. package/src/server.js +86 -18
  68. package/src/settings/global-settings-service.js +472 -0
  69. package/src/settings/registry.js +624 -0
  70. 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);
4155
+ }
4156
+ table.appendChild(tbody);
4157
+
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;
3426
4267
  }
3427
4268
 
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(() => {});
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
 
@@ -4718,6 +5708,31 @@ class PRManager {
4718
5708
  await this.toggleGeneratedFile(file);
4719
5709
  }
4720
5710
 
5711
+ await this._materializeDeferredDiff(file);
5712
+
5713
+ // For @pierre/diffs rendered files, use context ranges to reveal collapsed lines
5714
+ if (this.pierreBridge && this.pierreBridge.files.has(file)) {
5715
+ await this._ensurePierreContentUpgrade(file);
5716
+ let rangeStart = lineStart;
5717
+ let rangeEnd = lineEnd;
5718
+
5719
+ // addContextRanges expects NEW-file coordinates.
5720
+ // LEFT-side suggestions use OLD-file numbers — convert first.
5721
+ if (side === 'LEFT') {
5722
+ const converted = this.pierreBridge.convertOldToNew(file, lineStart, lineEnd);
5723
+ if (!converted) return false;
5724
+ rangeStart = converted.startLine;
5725
+ rangeEnd = converted.endLine;
5726
+ }
5727
+
5728
+ const padding = 3;
5729
+ const range = {
5730
+ startLine: Math.max(1, rangeStart - padding),
5731
+ endLine: rangeEnd + padding,
5732
+ };
5733
+ return this.pierreBridge.addContextRanges(file, [range]);
5734
+ }
5735
+
4721
5736
  // Find the gap section containing the target lines using the shared module
4722
5737
  // Pass the side parameter so findMatchingGap uses the correct coordinate system:
4723
5738
  // - 'RIGHT' = NEW coordinates (modified file, most common for AI suggestions)
@@ -4794,8 +5809,54 @@ class PRManager {
4794
5809
  async ensureLinesVisible(items) {
4795
5810
  for (const item of items) {
4796
5811
  const { file, line_start, line_end, side } = item;
5812
+ if (!file || !line_start) continue;
4797
5813
  const resolvedSide = (side || 'right').toUpperCase();
4798
5814
 
5815
+ await this._materializeDeferredDiff(file);
5816
+
5817
+ // Materialize the lazy body BEFORE branching on the rendering engine. A
5818
+ // Pierre file whose body hasn't rendered yet is NOT in pierreBridge.files,
5819
+ // so it would wrongly fall through to the legacy <tr> path below (which
5820
+ // scans zero rows for a Pierre file); and an unrendered legacy body has no
5821
+ // rows either. Rendering here lands the file in pierreBridge.files so the
5822
+ // Pierre branch is taken correctly.
5823
+ await this.ensureFileBodyRendered(file);
5824
+
5825
+ // @pierre/diffs files: use context ranges to reveal collapsed lines
5826
+ if (this.pierreBridge && this.pierreBridge.files.has(file)) {
5827
+ // Check the WHOLE range, not just line_start. Callers pass multi-line
5828
+ // ranges (comments, suggestions, chat citations); if line_start is on
5829
+ // screen but line_end is still inside a collapsed gap, we must still
5830
+ // expand. Preserve the skip-when-fully-visible optimization: only expand
5831
+ // when at least one endpoint is hidden.
5832
+ const endLine = line_end || line_start;
5833
+ const startVisible = this.pierreBridge.isLineVisible(file, line_start, resolvedSide);
5834
+ const endVisible = this.pierreBridge.isLineVisible(file, endLine, resolvedSide);
5835
+ if (!startVisible || !endVisible) {
5836
+ await this._ensurePierreContentUpgrade(file);
5837
+ let rangeStart = line_start;
5838
+ let rangeEnd = line_end || line_start;
5839
+
5840
+ // addContextRanges expects NEW-file coordinates.
5841
+ // LEFT-side items use OLD-file numbers — convert first.
5842
+ if (resolvedSide === 'LEFT') {
5843
+ const converted = this.pierreBridge.convertOldToNew(file, rangeStart, rangeEnd);
5844
+ if (converted) {
5845
+ rangeStart = converted.startLine;
5846
+ rangeEnd = converted.endLine;
5847
+ } else {
5848
+ continue;
5849
+ }
5850
+ }
5851
+
5852
+ this.pierreBridge.addContextRanges(file, [{
5853
+ startLine: rangeStart,
5854
+ endLine: rangeEnd,
5855
+ }]);
5856
+ }
5857
+ continue;
5858
+ }
5859
+
4799
5860
  const fileElement = this.findFileElement(file);
4800
5861
  if (!fileElement) continue;
4801
5862
 
@@ -4862,9 +5923,102 @@ class PRManager {
4862
5923
  * Comment form methods - delegate to CommentManager
4863
5924
  */
4864
5925
  showCommentForm(targetRow, lineNumber, fileName, diffPosition, endLineNumber, side = 'RIGHT') {
5926
+ // Use PierreBridge annotation for files rendered by @pierre/diffs
5927
+ if (this.pierreBridge && this.pierreBridge.files.has(fileName)) {
5928
+ const formId = `form-${fileName}-${lineNumber}-${side}`;
5929
+ this.pierreBridge.addAnnotation(fileName, {
5930
+ lineNumber: endLineNumber || lineNumber,
5931
+ side: side,
5932
+ type: 'comment-form',
5933
+ id: formId,
5934
+ data: {
5935
+ lineStart: lineNumber,
5936
+ lineEnd: endLineNumber || lineNumber,
5937
+ fileName: fileName,
5938
+ diffPosition: diffPosition,
5939
+ side: side,
5940
+ showSuggestionBtn: true,
5941
+ },
5942
+ });
5943
+ return;
5944
+ }
5945
+ // Fallback: old table-based comment form (context files)
4865
5946
  this.commentManager.showCommentForm(targetRow, lineNumber, fileName, diffPosition, endLineNumber, side);
4866
5947
  }
4867
5948
 
5949
+ /**
5950
+ * Handle comment form submission from PierreBridge annotation.
5951
+ * Saves the comment via API, removes the form annotation, and reloads comments.
5952
+ * @param {string} fileName - File the comment belongs to
5953
+ * @param {string} annotationId - PierreBridge annotation ID for the form
5954
+ * @param {Object} data - Form data (lineStart, lineEnd, fileName, diffPosition, side)
5955
+ * @param {string} body - Comment body text
5956
+ */
5957
+ async _handleCommentFormSubmit(fileName, annotationId, data, body) {
5958
+ if (!body || !body.trim()) return;
5959
+
5960
+ // Custom submit flow (e.g. edit-and-adopt suggestion): let the caller
5961
+ // decide how to save and how to re-render the result. The handler owns
5962
+ // removing the form annotation.
5963
+ if (typeof data.customSubmit === 'function') {
5964
+ try {
5965
+ await data.customSubmit(body.trim(), fileName, annotationId);
5966
+ } catch (error) {
5967
+ console.error('Error running custom comment form submit:', error);
5968
+ alert(`Failed to save: ${error.message}`);
5969
+ }
5970
+ return;
5971
+ }
5972
+
5973
+ try {
5974
+ const commentData = {
5975
+ file: data.fileName,
5976
+ line_start: data.lineStart,
5977
+ line_end: data.lineEnd,
5978
+ body: body.trim(),
5979
+ side: data.side || 'RIGHT',
5980
+ diff_position: data.diffPosition,
5981
+ // Anchor to the PR head commit so repositioning works if the PR is
5982
+ // updated later. Parity with CommentManager.saveComment.
5983
+ commit_sha: this.currentPR?.head_sha,
5984
+ };
5985
+
5986
+ const response = await fetch(`/api/reviews/${this.currentPR.id}/comments`, {
5987
+ method: 'POST',
5988
+ headers: {
5989
+ 'Content-Type': 'application/json',
5990
+ 'X-Client-Id': this._clientId,
5991
+ },
5992
+ body: JSON.stringify(commentData),
5993
+ });
5994
+
5995
+ if (response.ok) {
5996
+ const result = await response.json().catch(() => ({}));
5997
+ // Remove form annotation
5998
+ this.pierreBridge.removeAnnotation(fileName, annotationId);
5999
+ // Reload comments to show the new one
6000
+ const includeDismissed = window.aiPanel?.showDismissedComments || false;
6001
+ await this.loadUserComments(includeDismissed);
6002
+
6003
+ // Legacy-path side-effects: clear the dragged range, auto-expand in
6004
+ // minimize mode, and notify the AI chat context. Parity with
6005
+ // CommentManager.saveComment.
6006
+ this.lineTracker?.clearRangeSelection();
6007
+ if (result.commentId != null && this.commentMinimizer) {
6008
+ const newRow = document.querySelector(
6009
+ `[data-comment-id="${result.commentId}"]`
6010
+ );
6011
+ if (newRow) this.commentMinimizer.expandForElement(newRow);
6012
+ }
6013
+ window.chatPanel?.queueUserActionHint(
6014
+ `[User Action: created comment on ${data.fileName} lines ${data.lineStart}-${data.lineEnd}]`
6015
+ );
6016
+ }
6017
+ } catch (error) {
6018
+ console.error('Error saving comment:', error);
6019
+ }
6020
+ }
6021
+
4868
6022
  hideCommentForm() {
4869
6023
  this.commentManager.hideCommentForm();
4870
6024
  }
@@ -5322,38 +6476,74 @@ class PRManager {
5322
6476
  // Clear existing comment rows before re-rendering
5323
6477
  document.querySelectorAll('.user-comment-row:not(.suggestion-edit-pending)').forEach(row => row.remove());
5324
6478
 
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;
6479
+ // Clear existing PierreBridge comment annotations
6480
+ if (this.pierreBridge) {
6481
+ for (const [file] of this.pierreBridge.files) {
6482
+ this.pierreBridge.removeAnnotationsByType(file, 'comment');
6483
+ }
6484
+ }
5339
6485
 
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';
6486
+ // Ensure every comment's target line is reachable in the DOM before
6487
+ // rendering. `ensureLinesVisible` handles both engines — for Pierre
6488
+ // files it expands collapsed gaps via `addContextRanges` so the
6489
+ // annotation row exists; for legacy files it expands hidden hunks.
6490
+ // Without this, comments on lines outside the default hunks render
6491
+ // nowhere on reload and "jump to comment" silently fails.
6492
+ if (lineLevelComments.length > 0) {
6493
+ await this.ensureLinesVisible(lineLevelComments.map(c => ({
6494
+ file: c.file,
6495
+ line_start: c.line_start,
6496
+ line_end: c.line_end || c.line_start,
6497
+ side: c.side || 'RIGHT',
6498
+ })));
6499
+ }
6500
+
6501
+ // Partition line-level comments by rendering engine
6502
+ const pierreComments = [];
6503
+ const legacyComments = [];
6504
+ lineLevelComments.forEach(comment => {
6505
+ if (this.pierreBridge && this.pierreBridge.files.has(comment.file)) {
6506
+ pierreComments.push(comment);
6507
+ } else {
6508
+ legacyComments.push(comment);
6509
+ }
6510
+ });
5344
6511
 
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
- }
6512
+ // Display comments via PierreBridge annotations. Group by file so each
6513
+ // file rerenders ONCE for its whole set of comments, not once per comment.
6514
+ const commentAnnotationsByFile = new Map();
6515
+ pierreComments.forEach(comment => {
6516
+ if (!commentAnnotationsByFile.has(comment.file)) {
6517
+ commentAnnotationsByFile.set(comment.file, []);
5355
6518
  }
6519
+ commentAnnotationsByFile.get(comment.file).push({
6520
+ lineNumber: comment.line_start,
6521
+ side: comment.side || 'RIGHT',
6522
+ type: 'comment',
6523
+ id: `comment-${comment.id}`,
6524
+ data: comment,
6525
+ });
5356
6526
  });
6527
+ for (const [file, annotations] of commentAnnotationsByFile) {
6528
+ this.pierreBridge.addAnnotations(file, annotations);
6529
+ }
6530
+
6531
+ if (legacyComments.length > 0) {
6532
+ legacyComments.forEach(comment => {
6533
+ const fileElement = this.findFileElement(comment.file);
6534
+ if (!fileElement) return;
6535
+
6536
+ const side = comment.side || 'RIGHT';
6537
+ const lineRows = fileElement.querySelectorAll('tr');
6538
+ for (const row of lineRows) {
6539
+ const lineNum = this.getLineNumber(row, side);
6540
+ if (lineNum === comment.line_start) {
6541
+ this.displayUserComment(comment, row);
6542
+ break;
6543
+ }
6544
+ }
6545
+ });
6546
+ }
5357
6547
 
5358
6548
  // Load file-level comments into their zones (only active comments reach here)
5359
6549
  if (this.fileCommentManager && fileLevelComments.length > 0) {
@@ -5480,18 +6670,23 @@ class PRManager {
5480
6670
 
5481
6671
  /**
5482
6672
  * Collapse a suggestion div in the UI after adoption.
5483
- * Handles adding collapsed class, updating text to 'Suggestion adopted',
6673
+ * Handles adding collapsed class, setting the 'Adopted' state tooltip,
5484
6674
  * updating the restore button, and setting hiddenForAdoption flag.
5485
- * @param {HTMLElement} suggestionRow - The suggestion row element
6675
+ *
6676
+ * With legacy rendering, `suggestionRow` is the `<tr>` containing the
6677
+ * suggestion. With @pierre/diffs there is no `<tr>`, so callers pass null
6678
+ * and this method falls back to a document-wide lookup by id.
6679
+ *
6680
+ * @param {HTMLElement|null} suggestionRow - The suggestion row element (legacy only)
5486
6681
  * @param {number|string} suggestionId - Suggestion ID
5487
6682
  */
5488
6683
  collapseSuggestionForAdoption(suggestionRow, suggestionId) {
5489
- if (!suggestionRow) return;
5490
- const targetDiv = suggestionRow.querySelector(`[data-suggestion-id="${suggestionId}"]`);
6684
+ const targetDiv = suggestionRow
6685
+ ? suggestionRow.querySelector(`[data-suggestion-id="${suggestionId}"]`)
6686
+ : document.querySelector(`[data-suggestion-id="${suggestionId}"]`);
5491
6687
  if (!targetDiv) return;
5492
6688
  targetDiv.classList.add('collapsed');
5493
- const collapsedContent = targetDiv.querySelector('.collapsed-text');
5494
- if (collapsedContent) collapsedContent.textContent = 'Suggestion adopted';
6689
+ window.SuggestionUI?.setCollapsedStateTooltip?.(targetDiv, 'Adopted');
5495
6690
  const restoreButton = targetDiv.querySelector('.btn-restore');
5496
6691
  if (restoreButton) {
5497
6692
  restoreButton.title = 'Show suggestion';
@@ -5501,16 +6696,54 @@ class PRManager {
5501
6696
  targetDiv.dataset.hiddenForAdoption = 'true';
5502
6697
  }
5503
6698
 
6699
+ /**
6700
+ * Render an adopted user comment in the appropriate rendering engine.
6701
+ *
6702
+ * For files rendered by @pierre/diffs, `suggestionRow` is null (suggestions
6703
+ * are annotations, not table rows). Add the comment as a Pierre annotation
6704
+ * so it slots into the shadow DOM alongside the collapsed suggestion.
6705
+ *
6706
+ * For legacy (table-based) rendering, delegate to the existing
6707
+ * `displayUserComment(comment, suggestionRow)` which inserts a `<tr>`.
6708
+ *
6709
+ * @param {Object} comment - The newly-adopted comment
6710
+ * @param {HTMLElement|null} suggestionRow - Legacy table row, or null for Pierre
6711
+ * @private
6712
+ */
6713
+ async _renderAdoptedUserComment(comment, suggestionRow) {
6714
+ if (this.pierreBridge && comment.file && this.pierreBridge.files.has(comment.file)) {
6715
+ // Reveal the target line if it sits inside a collapsed gap — otherwise
6716
+ // the annotation has no DOM row to attach to and never renders.
6717
+ await this.ensureLinesVisible([{
6718
+ file: comment.file,
6719
+ line_start: comment.line_start,
6720
+ line_end: comment.line_end || comment.line_start,
6721
+ side: comment.side || 'RIGHT',
6722
+ }]);
6723
+ this.pierreBridge.addAnnotation(comment.file, {
6724
+ lineNumber: comment.line_start,
6725
+ side: comment.side || 'RIGHT',
6726
+ type: 'comment',
6727
+ id: `comment-${comment.id}`,
6728
+ data: comment,
6729
+ });
6730
+ return;
6731
+ }
6732
+ // Legacy path: displayUserComment inserts a <tr> after suggestionRow
6733
+ this.displayUserComment(comment, suggestionRow);
6734
+ }
6735
+
5504
6736
  /**
5505
6737
  * Build a user comment object from adoption/edit response data.
5506
6738
  * Single source of truth for comment shape — used by both adopt-as-is
5507
6739
  * and edit-then-adopt flows.
5508
6740
  */
5509
- _buildCommentObject({ userCommentId, formattedBody, fileName, lineNumber, suggestionType, suggestionTitle, suggestionId, diffPosition, side }) {
6741
+ _buildCommentObject({ userCommentId, formattedBody, fileName, lineNumber, lineEnd, suggestionType, suggestionTitle, suggestionId, diffPosition, side }) {
5510
6742
  return {
5511
6743
  id: userCommentId,
5512
6744
  file: fileName,
5513
6745
  line_start: parseInt(lineNumber),
6746
+ line_end: lineEnd ? parseInt(lineEnd) : null,
5514
6747
  body: formattedBody,
5515
6748
  type: suggestionType,
5516
6749
  title: suggestionTitle,
@@ -5529,7 +6762,7 @@ class PRManager {
5529
6762
  */
5530
6763
  async _adoptAndBuildComment(suggestionId, suggestionDiv) {
5531
6764
  const { suggestionText, suggestionType, suggestionTitle } = this.extractSuggestionData(suggestionDiv);
5532
- const { suggestionRow, lineNumber, fileName, diffPosition, side, isFileLevel } = this.getFileAndLineInfo(suggestionDiv);
6765
+ const { suggestionRow, lineNumber, lineEnd, fileName, diffPosition, side, isFileLevel } = this.getFileAndLineInfo(suggestionDiv);
5533
6766
 
5534
6767
  // File-level suggestions are handled by FileCommentManager; signal the caller
5535
6768
  if (isFileLevel) {
@@ -5554,7 +6787,7 @@ class PRManager {
5554
6787
  const newComment = this._buildCommentObject({
5555
6788
  userCommentId: adoptResult.userCommentId,
5556
6789
  formattedBody: adoptResult.formattedBody,
5557
- fileName, lineNumber, suggestionType, suggestionTitle,
6790
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
5558
6791
  suggestionId, diffPosition, side
5559
6792
  });
5560
6793
 
@@ -5631,6 +6864,58 @@ class PRManager {
5631
6864
  side
5632
6865
  };
5633
6866
 
6867
+ // Pierre-rendered files: suggestions live as annotations (no <tr>),
6868
+ // so `displaySuggestionEditForm` — which inserts a table row after
6869
+ // `suggestionRow` — cannot run. Open the edit form as a comment-form
6870
+ // annotation on the same line, pre-filled with the suggestion body,
6871
+ // and wire a custom submit that runs the adopt-edited flow.
6872
+ if (this.pierreBridge && this.pierreBridge.files.has(fileName)) {
6873
+ const formId = `edit-suggestion-${suggestionId}`;
6874
+ const onAdoptEdited = async (editedText, _fileName, annotationId) => {
6875
+ const reviewId = this.currentPR?.id;
6876
+ const editResponse = await fetch(`/api/reviews/${reviewId}/suggestions/${suggestionId}/edit`, {
6877
+ method: 'POST',
6878
+ headers: { 'Content-Type': 'application/json' },
6879
+ body: JSON.stringify({ action: 'adopt_edited', editedText })
6880
+ });
6881
+ if (!editResponse.ok) throw new Error('Failed to adopt suggestion with edits');
6882
+ const editResult = await editResponse.json();
6883
+
6884
+ // Collapse the suggestion annotation and render the new comment.
6885
+ this.collapseSuggestionForAdoption(null, suggestionId);
6886
+ const newComment = this._buildCommentObject({
6887
+ userCommentId: editResult.userCommentId,
6888
+ formattedBody: editResult.formattedBody,
6889
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
6890
+ suggestionId, diffPosition, side
6891
+ });
6892
+
6893
+ // Remove the edit form annotation and add the comment annotation.
6894
+ this.pierreBridge.removeAnnotation(fileName, annotationId);
6895
+ await this._renderAdoptedUserComment(newComment, null);
6896
+ this._notifyAdoption(suggestionId, newComment);
6897
+ };
6898
+
6899
+ this.pierreBridge.addAnnotation(fileName, {
6900
+ lineNumber: lineEnd || lineNumber,
6901
+ side: side || 'RIGHT',
6902
+ type: 'comment-form',
6903
+ id: formId,
6904
+ data: {
6905
+ headerTitle: 'Edit suggestion',
6906
+ lineStart: lineNumber,
6907
+ lineEnd: lineEnd || lineNumber,
6908
+ fileName: fileName,
6909
+ diffPosition: diffPosition,
6910
+ side: side || 'RIGHT',
6911
+ showSuggestionBtn: true,
6912
+ initialValue: formattedBody || suggestionText,
6913
+ customSubmit: onAdoptEdited,
6914
+ },
6915
+ });
6916
+ return;
6917
+ }
6918
+
5634
6919
  this.commentManager.displaySuggestionEditForm(
5635
6920
  suggestion,
5636
6921
  suggestionRow,
@@ -5653,10 +6938,10 @@ class PRManager {
5653
6938
  const newComment = this._buildCommentObject({
5654
6939
  userCommentId: editResult.userCommentId,
5655
6940
  formattedBody: editResult.formattedBody,
5656
- fileName, lineNumber, suggestionType, suggestionTitle,
6941
+ fileName, lineNumber, lineEnd, suggestionType, suggestionTitle,
5657
6942
  suggestionId, diffPosition, side
5658
6943
  });
5659
- this.displayUserComment(newComment, suggestionRow);
6944
+ await this._renderAdoptedUserComment(newComment, suggestionRow);
5660
6945
  this._notifyAdoption(suggestionId, newComment);
5661
6946
  window.chatPanel?.queueUserActionHint(`[User Action: adopted suggestion ${suggestionId}]`);
5662
6947
  } catch (error) {
@@ -5702,7 +6987,7 @@ class PRManager {
5702
6987
  return;
5703
6988
  }
5704
6989
 
5705
- this.displayUserComment(result.newComment, result.suggestionRow);
6990
+ await this._renderAdoptedUserComment(result.newComment, result.suggestionRow);
5706
6991
  this._notifyAdoption(suggestionId, result.newComment);
5707
6992
  window.chatPanel?.queueUserActionHint(`[User Action: adopted suggestion ${suggestionId}]`);
5708
6993
  } catch (error) {
@@ -5723,8 +7008,11 @@ class PRManager {
5723
7008
  // If this suggestion was adopted, only toggle visibility - don't change status
5724
7009
  // The adoption still exists (there's a user comment linked to this suggestion)
5725
7010
  if (suggestionDiv?.dataset?.hiddenForAdoption === 'true') {
5726
- // suggestionDiv is guaranteed to exist since we just queried for it
7011
+ // suggestionDiv is guaranteed to exist since we just queried for it.
7012
+ // The suggestion stays adopted here; we only re-hide it, so the
7013
+ // collapsed-bar tooltip keeps reading 'Adopted'.
5727
7014
  suggestionDiv.classList.add('collapsed');
7015
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, 'Adopted');
5728
7016
 
5729
7017
  const button = suggestionDiv.querySelector('.btn-restore');
5730
7018
  if (button) {
@@ -5745,6 +7033,7 @@ class PRManager {
5745
7033
 
5746
7034
  if (suggestionDiv) {
5747
7035
  suggestionDiv.classList.add('collapsed');
7036
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, 'Dismissed');
5748
7037
  const restoreButton = suggestionDiv.querySelector('.btn-restore');
5749
7038
  if (restoreButton) {
5750
7039
  restoreButton.title = 'Show suggestion';
@@ -5790,11 +7079,13 @@ class PRManager {
5790
7079
 
5791
7080
  // Find the button within this specific suggestion div, not the first one in the row
5792
7081
  const button = suggestionDiv.querySelector('.btn-restore');
7082
+ const isNowCollapsed = suggestionDiv.classList.contains('collapsed');
5793
7083
  if (button) {
5794
- const isNowCollapsed = suggestionDiv.classList.contains('collapsed');
5795
7084
  button.title = isNowCollapsed ? 'Show suggestion' : 'Hide suggestion';
5796
7085
  button.querySelector('.btn-text').textContent = isNowCollapsed ? 'Show' : 'Hide';
5797
7086
  }
7087
+ // Still adopted; keep the 'Adopted' tooltip only while re-hidden.
7088
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, isNowCollapsed ? 'Adopted' : '');
5798
7089
  return;
5799
7090
  }
5800
7091
 
@@ -5808,6 +7099,12 @@ class PRManager {
5808
7099
 
5809
7100
  if (suggestionDiv) {
5810
7101
  suggestionDiv.classList.remove('collapsed');
7102
+ // Restored to active — clear the collapsed-bar state tooltip.
7103
+ window.SuggestionUI?.setCollapsedStateTooltip?.(suggestionDiv, '');
7104
+ // Strip stale dismissal-reason markup (note + popover attr/brain button)
7105
+ // baked in while dismissed; same-tab broadcasts are suppressed so no
7106
+ // refetch rescues this card.
7107
+ window.SuggestionUI?.clearDismissalReasonUI?.(suggestionDiv);
5811
7108
  }
5812
7109
 
5813
7110
  if (this.suggestionNavigator?.suggestions) {
@@ -6492,6 +7789,15 @@ class PRManager {
6492
7789
  // later still renders on demand via toggleFileCollapse.
6493
7790
  if (!fileWrapper.classList.contains('collapsed')) {
6494
7791
  await this.ensureFileBodyRendered(filePath);
7792
+ // Only now can this file be moved to the front of the Pierre
7793
+ // content-upgrade queue: rendering its body is what enqueues it
7794
+ // (_renderPierreFileBodyNow → _enqueuePierreContentUpgrade), so
7795
+ // state.pending contains it and the reorder actually takes effect.
7796
+ // Hoisting this before the render would be a silent no-op — findIndex
7797
+ // misses the not-yet-enqueued file and the later render appends it to
7798
+ // the queue tail. Collapsed files stay hidden and never upgrade, so
7799
+ // they intentionally get no priority hint.
7800
+ this._prioritizePierreContentUpgrade(filePath);
6495
7801
  }
6496
7802
  // Stable variant: lazy bodies between here and the target render as
6497
7803
  // the smooth scroll passes them, shifting layout mid-flight. The
@@ -6517,27 +7823,19 @@ class PRManager {
6517
7823
  * Theme methods
6518
7824
  */
6519
7825
  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
- }
7826
+ // Shared helper (js/theme.js) owns preference storage, the
7827
+ // light → dark → system toggle cycle, the button icon, and the live
7828
+ // OS-change listener. We keep this.currentTheme as the *resolved* theme so
7829
+ // the diff renderer (@pierre/diffs) always receives a concrete
7830
+ // 'light'|'dark', never the 'system' preference.
7831
+ this._themeDispose = window.PairReviewTheme.setup({
7832
+ onChange: (resolved) => {
7833
+ this.currentTheme = resolved;
7834
+ if (this.pierreBridge) {
7835
+ this.pierreBridge.setTheme(resolved);
7836
+ }
7837
+ },
7838
+ });
6541
7839
  }
6542
7840
 
6543
7841
  savePanelStates() {
@@ -6605,9 +7903,16 @@ class PRManager {
6605
7903
 
6606
7904
  const btnText = btn.querySelector('.btn-text');
6607
7905
  if (btnText) {
7906
+ // Insert the spinner before the label (guard against a double-call
7907
+ // stacking two spinners), then switch the label.
7908
+ if (!btn.querySelector('.btn-spinner')) {
7909
+ const spinner = document.createElement('span');
7910
+ spinner.className = 'btn-spinner';
7911
+ btn.insertBefore(spinner, btnText);
7912
+ }
6608
7913
  btnText.textContent = 'Analyzing...';
6609
7914
  } else {
6610
- btn.innerHTML = '<span class="analyzing-icon">✨</span> Analyzing...';
7915
+ btn.innerHTML = '<span class="btn-spinner"></span> Analyzing...';
6611
7916
  }
6612
7917
  }
6613
7918
 
@@ -6627,6 +7932,8 @@ class PRManager {
6627
7932
 
6628
7933
  const btnText = btn.querySelector('.btn-text');
6629
7934
  if (btnText) {
7935
+ const spinner = btn.querySelector('.btn-spinner');
7936
+ if (spinner) spinner.remove();
6630
7937
  btnText.textContent = 'Complete';
6631
7938
  } else {
6632
7939
  btn.innerHTML = '✓ Analysis Complete';
@@ -6656,6 +7963,8 @@ class PRManager {
6656
7963
 
6657
7964
  const btnText = btn.querySelector('.btn-text');
6658
7965
  if (btnText) {
7966
+ const spinner = btn.querySelector('.btn-spinner');
7967
+ if (spinner) spinner.remove();
6659
7968
  btnText.textContent = 'Analyze';
6660
7969
  } else {
6661
7970
  btn.innerHTML = 'Analyze with AI';
@@ -7444,31 +8753,6 @@ class PRManager {
7444
8753
  }
7445
8754
  tbody.dataset.lineStart = effectiveStart;
7446
8755
 
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
8756
  // Add expand-up gap row if there are lines above the context range
7473
8757
  if (effectiveStart > 1) {
7474
8758
  const gapAboveSize = effectiveStart - 1;