-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoderabbit-gerrit-plugin.js
More file actions
726 lines (631 loc) · 26.4 KB
/
Copy pathcoderabbit-gerrit-plugin.js
File metadata and controls
726 lines (631 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/**
* Gerrit UI Plugin: CodeRabbit Gerrit Plugin
* Replaces collapsed preview text for specific users (e.g., bots).
*/
(function() {
'use strict';
const CONFIG = {
debug: false,
enablePreviewReplacement: true,
enableChecksApi: true,
enableCopyPrompts: true,
checksPollingIntervalSeconds: 60,
botAccountName: 'CodeRabbitAI Bot',
targetUsers: [
{
name: 'CodeRabbitAI Bot',
phraseReplacements: [
{
phrase: 'This is an auto-generated comment: review in progress by coderabbit.ai',
replacementText: 'Processing new changes in this PR'
},
{
phrase: 'This is an auto-generated comment: release notes by coderabbit.ai',
replacementText: 'Summary by CodeRabbit'
},
{
phrase: 'walkthrough_start',
replacementText: 'Code Review'
},
{
phrase: 'This is an auto-generated comment by CodeRabbit for review status',
replacementText: 'Actionable comments'
},
{
phrase: 'This is an auto-generated comment: skip review by coderabbit.ai',
replacementText: 'Review Skipped'
},
{
phrase: 'This is an auto-generated reply by CodeRabbit',
replacementText: 'Reply by CodeRabbit'
}
]
}
]
};
const LOG_PREFIX = '[CodeRabbitGerritPlugin]';
function log(...args) {
if (CONFIG.debug) {
console.log(LOG_PREFIX, ...args);
}
}
Gerrit.install(plugin => {
log('CodeRabbit Gerrit Plugin initialized successfully');
// ── Checks API registration ──
let checksApi = null;
registerChecksProvider(plugin);
const cssRules = [
`.comment-header-replaced { display: inline-flex; align-items: center; gap: 4px; background-color: #e3f2fd; color: #1565c0; padding: 2px 8px; border-radius: 4px; font-weight: 500; }`
];
for (const rule of cssRules) {
try {
plugin.styleApi().insertCSSRule(rule);
} catch (e) {
console.error(LOG_PREFIX, 'Failed to inject CSS rule:', rule, e);
}
}
plugin.on('showchange', () => {
setTimeout(initCommentProcessing, 500);
});
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setTimeout(initCommentProcessing, 1000));
} else {
setTimeout(initCommentProcessing, 1000);
}
function initCommentProcessing() {
scanAllMessages();
setupMutationObserver();
}
let currentObserver = null;
function setupMutationObserver() {
if (currentObserver) {
currentObserver.disconnect();
}
const observer = new MutationObserver(
debounce((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE &&
(node.tagName === 'GR-MESSAGE' || node.querySelector?.('gr-message'))) {
scanAllMessages();
if (checksApi) {
log('New message detected, triggering checks refresh');
checksApi.announceUpdate();
}
return;
}
}
}
}, 300)
);
observer.observe(document.body, { childList: true, subtree: true });
currentObserver = observer;
}
function scanAllMessages() {
log('scanAllMessages: Starting scan...');
const messages = findAllElements('gr-message');
log(`scanAllMessages: Found ${messages.length} gr-message elements`);
messages.forEach((messageEl, index) => processMessage(messageEl, index));
log('scanAllMessages: Scan complete');
}
function findAllElements(selector) {
const results = [];
function searchInNode(node) {
if (node.querySelectorAll) {
results.push(...node.querySelectorAll(selector));
}
if (node.shadowRoot) {
searchInNode(node.shadowRoot);
}
const children = node.querySelectorAll ? node.querySelectorAll('*') : [];
children.forEach(child => {
if (child.shadowRoot) searchInNode(child.shadowRoot);
});
}
searchInNode(document.body);
return results;
}
function processMessage(messageEl, index) {
if (messageEl.dataset.headerReplacerProcessed === 'true') {
return;
}
const messageShadowRoot = messageEl.shadowRoot;
if (!messageShadowRoot) return;
const accountLabel = messageShadowRoot.querySelector('gr-account-label.authorLabel') ||
messageShadowRoot.querySelector('gr-account-label');
if (!accountLabel?.shadowRoot) return;
const nameSpan = accountLabel.shadowRoot.querySelector('span.name') ||
accountLabel.shadowRoot.querySelector('#hovercardTarget');
const authorName = nameSpan?.textContent?.trim();
if (!authorName) return;
messageEl.dataset.headerReplacerProcessed = 'true';
const matchedUser = findMatchingUser(authorName);
if (!matchedUser) return;
// Preview replacement (collapsed view)
if (CONFIG.enablePreviewReplacement) {
const previewElement = messageShadowRoot.querySelector('.message.hideOnOpen') ||
messageShadowRoot.querySelector('.hideOnOpen');
if (previewElement) {
const fullContent = getFullCommentContent(messageShadowRoot);
const replacementText = getReplacementTextForContent(matchedUser, fullContent);
if (replacementText !== null) {
log(`Message #${index}: "${authorName}" -> "${replacementText}"`);
replacePreviewText(previewElement, replacementText);
}
}
}
}
function findMatchingUser(authorName) {
if (!authorName) return null;
const normalizedAuthor = authorName.toLowerCase().trim();
for (const user of CONFIG.targetUsers) {
const normalizedTarget = user.name.toLowerCase().trim();
if (normalizedAuthor === normalizedTarget ||
normalizedAuthor.includes(normalizedTarget) ||
normalizedTarget.includes(normalizedAuthor)) {
return user;
}
}
return null;
}
function getFullCommentContent(messageShadowRoot) {
const formattedText = messageShadowRoot.querySelector('gr-formatted-text');
if (formattedText) {
const content = extractTextFromElement(formattedText);
if (content) return content;
}
const hideOnCollapsed = messageShadowRoot.querySelector('.message.hideOnCollapsed');
if (hideOnCollapsed) {
const content = extractTextFromElement(hideOnCollapsed);
if (content) return content;
}
const hideOnOpen = messageShadowRoot.querySelector('.message.hideOnOpen');
return hideOnOpen?.textContent?.trim() || '';
}
function extractTextFromElement(element) {
if (element.shadowRoot) {
const markedElement = element.shadowRoot.querySelector('marked-element');
if (markedElement) {
const slottedHtml = markedElement.querySelector('.markdown-html');
if (slottedHtml?.textContent?.trim()) return slottedHtml.textContent.trim();
if (markedElement.shadowRoot) {
const markdownHtml = markedElement.shadowRoot.querySelector('.markdown-html');
if (markdownHtml?.textContent?.trim()) return markdownHtml.textContent.trim();
}
if (markedElement.textContent?.trim()) return markedElement.textContent.trim();
}
if (element.shadowRoot.textContent?.trim()) return element.shadowRoot.textContent.trim();
}
return element.textContent?.trim() || '';
}
function getReplacementTextForContent(matchedUser, fullContent) {
const normalizedContent = fullContent.toLowerCase();
if (matchedUser.phraseReplacements?.length > 0) {
for (const phraseConfig of matchedUser.phraseReplacements) {
if (normalizedContent.includes(phraseConfig.phrase.toLowerCase())) {
return phraseConfig.replacementText;
}
}
}
return matchedUser.defaultReplacementText || matchedUser.replacementText || null;
}
function replacePreviewText(previewElement, replacementText) {
previewElement.dataset.originalText = previewElement.textContent?.trim();
previewElement.textContent = replacementText;
}
function debounce(fn, ms) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), ms);
};
}
// ── Checks API ──
function registerChecksProvider(plugin) {
if (!CONFIG.enableChecksApi) return;
if (!plugin.checks) {
log('Checks API not available in this Gerrit version');
return;
}
const provider = {
fetch: (changeData) => fetchCodeRabbitChecks(plugin, changeData),
};
checksApi = plugin.checks();
checksApi.register(provider, {
fetchPollingIntervalSeconds: CONFIG.checksPollingIntervalSeconds,
});
log('Checks API provider registered');
}
async function fetchCodeRabbitChecks(plugin, changeData) {
const { changeNumber, patchsetNumber } = changeData;
const restApi = plugin.restApi();
try {
const [messages, currentCommentsMap, allCommentsMap] = await Promise.all([
restApi.get(`/changes/${changeNumber}/messages`),
restApi.get(`/changes/${changeNumber}/revisions/${patchsetNumber}/comments`),
restApi.get(`/changes/${changeNumber}/comments`),
]);
const botMessages = filterBotMessages(messages, patchsetNumber);
// Also check for in-progress messages without a revision number (posted before patchset association)
const inProgressMessages = (messages || []).filter(
msg => isBotAuthor(msg.author) &&
(!msg._revision_number || msg._revision_number === patchsetNumber) &&
classifyMessage(msg.message) === 'IN_PROGRESS'
);
const allBotMessages = deduplicateMessages(botMessages, inProgressMessages);
const resolvedMap = buildThreadResolutionMap(allCommentsMap, patchsetNumber);
const currentBotComments = filterBotComments(currentCommentsMap, resolvedMap);
const unresolvedOlderComments = filterUnresolvedOlderBotComments(allCommentsMap, patchsetNumber, resolvedMap);
const botComments = deduplicateComments(currentBotComments, unresolvedOlderComments);
const run = buildCheckRun(allBotMessages, botComments, changeData);
const summaryMessage = buildSummaryMessage(botComments);
const topActions = buildTopLevelActions(botComments);
return {
responseCode: 'OK',
...(topActions.length > 0 ? { actions: topActions } : {}),
runs: [run],
...(summaryMessage ? { summaryMessage } : {}),
};
} catch (error) {
log('Checks fetch error:', error);
return {
responseCode: 'ERROR',
errorMessage: 'Failed to fetch CodeRabbit results: ' + error.message,
runs: [],
};
}
}
function isBotAuthor(author) {
if (!author?.name) return false;
const name = author.name.toLowerCase();
const target = CONFIG.botAccountName.toLowerCase();
return name.includes(target) || target.includes(name);
}
function filterBotMessages(messages, patchsetNumber) {
return (messages || []).filter(
msg => isBotAuthor(msg.author) && msg._revision_number === patchsetNumber
);
}
function buildThreadResolutionMap(commentsMap, asOfPatchset) {
// Build resolution state as of a specific patchset
const allComments = [];
for (const [filePath, comments] of Object.entries(commentsMap || {})) {
for (const comment of comments) {
allComments.push({ ...comment, path: filePath });
}
}
const byId = {};
for (const c of allComments) {
byId[c.id] = c;
}
function getRoot(comment) {
const visited = new Set();
let current = comment;
while (current.in_reply_to && byId[current.in_reply_to] && !visited.has(current.id)) {
visited.add(current.id);
current = byId[current.in_reply_to];
}
return current.id;
}
// Only consider comments up to the selected patchset
const relevantComments = allComments.filter(c => c.patch_set <= asOfPatchset);
// For each thread root, find the latest comment's unresolved state within the patchset range
const threadLatest = {};
for (const c of relevantComments) {
const rootId = getRoot(c);
const updated = c.updated || c.date || '';
if (!threadLatest[rootId] || updated > threadLatest[rootId].updated) {
threadLatest[rootId] = { updated, unresolved: c.unresolved };
}
}
// Map every comment ID to its thread's resolved state as of the selected patchset
const resolved = {};
for (const c of allComments) {
const rootId = getRoot(c);
resolved[c.id] = threadLatest[rootId]?.unresolved === false;
}
return resolved;
}
function filterBotComments(commentsMap, resolvedMap) {
const result = [];
for (const [filePath, comments] of Object.entries(commentsMap || {})) {
for (const comment of comments) {
if (isBotAuthor(comment.author) && !resolvedMap[comment.id]) {
result.push({ ...comment, path: filePath });
}
}
}
return result;
}
function filterUnresolvedOlderBotComments(commentsMap, currentPatchset, resolvedMap) {
const result = [];
for (const [filePath, comments] of Object.entries(commentsMap || {})) {
for (const comment of comments) {
if (isBotAuthor(comment.author) &&
!resolvedMap[comment.id] &&
comment.patch_set < currentPatchset) {
result.push({ ...comment, path: filePath });
}
}
}
return result;
}
function deduplicateMessages(primary, secondary) {
const seen = new Set(primary.map(m => m.id));
const unique = secondary.filter(m => !seen.has(m.id));
return [...primary, ...unique];
}
function deduplicateComments(current, older) {
const seen = new Set(current.map(c => c.id));
const unique = older.filter(c => !seen.has(c.id));
return [...current, ...unique];
}
function classifyMessage(messageText) {
const raw = (messageText || '').toLowerCase();
// Strip Gerrit's auto-prepended "Patch Set N:\n\n(N comments)\n\n" prefix
const text = raw.replace(/^patch set \d+:\s*(\(\d+ comments?\))?\s*/i, '').trim();
if (!text) return 'SKIP';
if (text.includes('review in progress')) return 'IN_PROGRESS';
if (text.includes('walkthrough_start')) return 'WALKTHROUGH';
if (text.includes('release notes')) return 'SUMMARY';
if (text.includes('review status')) return 'SKIP';
if (text.includes('actionable comments')) return 'SKIP';
if (text.includes('skip review')) return 'SKIPPED';
if (text.includes('auto-generated reply')) return 'SKIP';
if (text.includes('review approved')) return 'SKIP';
if (text.includes('review completed')) return 'SKIP';
if (text.match(/^code-review[+-]?\d*$/)) return 'SKIP';
if (text.match(/^verified[+-]?\d*$/)) return 'SKIP';
return 'OTHER';
}
function buildSummaryMessage(botComments) {
if (botComments.length === 0) {
return undefined;
}
const counts = { critical: 0, major: 0, minor: 0 };
for (const comment of botComments) {
const severity = classifyCommentSeverity(comment.message);
const name = severity.tag.name.toLowerCase();
if (name === 'critical') counts.critical++;
else if (name === 'major') counts.major++;
else counts.minor++;
}
const parts = [];
if (counts.critical > 0) parts.push(`🔴 ${counts.critical} critical`);
if (counts.major > 0) parts.push(`🟠 ${counts.major} major`);
if (counts.minor > 0) parts.push(`🟡 ${counts.minor} minor`);
return `**CodeRabbit** review complete — ${parts.join(', ')}.`;
}
function parseGerritDate(dateStr) {
if (!dateStr) return null;
// Gerrit dates are UTC but lack a timezone suffix, e.g. "2026-04-04 12:30:00.000000000"
const normalized = dateStr.trim().replace(' ', 'T').replace(/\.?\d{6,}$/, '') + 'Z';
const d = new Date(normalized);
return isNaN(d.getTime()) ? null : d;
}
function getRunTimestamps(botMessages, isRunning) {
const dates = botMessages
.map(msg => parseGerritDate(msg.date))
.filter(Boolean)
.sort((a, b) => a.getTime() - b.getTime());
if (dates.length === 0) return {};
const result = { startedTimestamp: dates[0] };
if (!isRunning) {
result.finishedTimestamp = dates[dates.length - 1];
}
return result;
}
function buildCheckRun(botMessages, botComments, changeData) {
const checkDescription = 'AI-powered code review by [CodeRabbit](https://coderabbit.ai). ' +
'Provides a walkthrough, summary, and inline comments with actionable suggestions.';
if (botMessages.length === 0 && botComments.length === 0) {
return {
checkName: 'CodeRabbit Review',
checkDescription,
status: 'RUNNABLE',
statusDescription: 'Waiting for CodeRabbit review',
isAiPowered: true,
results: [],
};
}
const results = [];
let hasInProgress = false;
for (const msg of botMessages) {
const type = classifyMessage(msg.message);
switch (type) {
case 'SKIP':
break;
case 'IN_PROGRESS':
hasInProgress = true;
break;
case 'WALKTHROUGH':
results.push({
category: 'SUCCESS',
summary: 'Code Review by CodeRabbit',
message: stripAutoGeneratedPrefix(msg.message),
tags: [{ name: 'WALKTHROUGH', color: 'purple' }],
});
break;
case 'SUMMARY':
results.push({
category: 'INFO',
summary: 'Summary by CodeRabbit',
message: stripAutoGeneratedPrefix(msg.message),
tags: [{ name: 'SUMMARY', color: 'cyan' }],
});
break;
case 'SKIPPED':
results.push({
category: 'INFO',
summary: 'Review Skipped',
message: stripAutoGeneratedPrefix(msg.message),
tags: [{ name: 'SKIPPED', color: 'gray' }],
});
break;
default:
results.push({
category: 'INFO',
summary: 'CodeRabbit Comment',
message: msg.message,
});
}
}
for (const comment of botComments) {
results.push(buildInlineResult(comment, changeData));
}
const isRunning = hasInProgress && results.length === 0;
const timestamps = getRunTimestamps(botMessages, isRunning);
const runActions = isRunning ? [] : buildTopLevelActions(botComments);
return {
checkName: 'CodeRabbit Review',
checkDescription,
status: isRunning ? 'RUNNING' : 'COMPLETED',
statusDescription: isRunning ? 'CodeRabbit review in progress' : 'Review complete',
isAiPowered: true,
results: results,
...(runActions.length > 0 ? { actions: runActions } : {}),
...timestamps,
};
}
function extractAllPrompts(botComments) {
const prompts = [];
for (const comment of botComments) {
const prompt = extractPromptFromComment(comment.message);
if (prompt) {
prompts.push(prompt);
}
}
return prompts;
}
function extractPromptFromComment(message) {
if (!message) return null;
// Pattern 1: HTML details block (platforms that support it)
const detailsMatch = message.match(
/<details>\s*<summary>🤖\s*Prompt for AI Agents<\/summary>\s*\n+\s*```[^\n]*\n([\s\S]*?)\n```\s*\n*\s*<\/details>/i
);
if (detailsMatch?.[1]) return detailsMatch[1].trim();
// Pattern 2: HTML comment markers (Gerrit and platforms without HTML details)
const commentMatch = message.match(
/<!--\s*details\s*-->\s*\n+\s*🤖\s*Prompt for AI Agents\s*\n+\s*```[^\n]*\n([\s\S]*?)\n```\s*\n+\s*<!--\s*\/details\s*-->/i
);
if (commentMatch?.[1]) return commentMatch[1].trim();
// Pattern 3: Plain markdown section (fallback)
const plainMatch = message.match(
/🤖\s*Prompt for AI Agents\s*\n+\s*```[^\n]*\n([\s\S]*?)\n```/i
);
if (plainMatch?.[1]) return plainMatch[1].trim();
return null;
}
function buildTopLevelActions(botComments) {
if (!CONFIG.enableCopyPrompts) return [];
const prompts = extractAllPrompts(botComments);
if (prompts.length === 0) return [];
return [{
name: 'Copy all Prompts',
tooltip: `Copy ${prompts.length} AI agent prompt${prompts.length === 1 ? '' : 's'} to clipboard`,
primary: true,
callback: (_change, _patchset, _attempt, _externalId, _checkName, _actionName) => {
const combined = prompts.join('\n\n---\n\n');
return navigator.clipboard.writeText(combined).then(() => {
log(`Copied ${prompts.length} prompts to clipboard`);
return { message: `Copied ${prompts.length} prompt${prompts.length === 1 ? '' : 's'} to clipboard`, shouldReload: false };
}).catch(err => {
log('Failed to copy prompts to clipboard:', err);
return { message: 'Failed to copy prompts to clipboard', shouldReload: false };
});
},
}];
}
function classifyCommentSeverity(message) {
// Only check the first line where CodeRabbit puts the severity indicator
// Format: "⚠️ Potential issue | 🔴 Critical" or "⚠️ Potential issue | 🟡 Minor"
const firstLine = (message || '').split('\n')[0].toLowerCase();
// Check explicit severity level first (after the pipe)
if (firstLine.includes('critical') || firstLine.includes('\ud83d\udd34')) {
return { category: 'ERROR', tag: { name: 'CRITICAL', color: 'pink' } };
}
if (firstLine.includes('minor') || firstLine.includes('suggestion') || firstLine.includes('nitpick') || firstLine.includes('\ud83d\udcdd') || firstLine.includes('\ud83d\udfe1')) {
return { category: 'INFO', tag: { name: 'MINOR', color: 'gray' } };
}
if (firstLine.includes('major') || firstLine.includes('\u26a0\ufe0f') || firstLine.includes('potential issue')) {
return { category: 'WARNING', tag: { name: 'MAJOR', color: 'yellow' } };
}
return { category: 'WARNING', tag: { name: 'COMMENT', color: 'yellow' } };
}
function extractHeaderFromComment(message) {
const lines = (message || '').split('\n');
// The first line is typically the severity indicator (e.g., "⚠️ Potential issue | 🟠 Major").
// Skip it and any blank lines to find the actual descriptive header.
const severityPattern = /^[\s]*(?:[_*]*)(\u26a0\ufe0f|\ud83d\udd34|\ud83d\udfe0|\ud83d\udfe1|\ud83d\udcdd).*\|/;
let startIdx = 0;
if (lines.length > 0 && severityPattern.test(lines[0])) {
startIdx = 1;
}
for (let i = startIdx; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (trimmed.length > 0) {
const header = trimmed.replace(/\*\*/g, '').substring(0, 120);
const body = lines.slice(i + 1).join('\n').trim();
return { header, body };
}
}
// Fallback to first line if no descriptive line found
const fallback = (lines[0] || '').trim().substring(0, 120);
return { header: fallback, body: '' };
}
function buildInlineResult(comment, changeData) {
const links = [];
const isRealFile = comment.path &&
!comment.path.startsWith('/PATCHSET_LEVEL') &&
!comment.path.startsWith('/COMMIT_MSG');
if (isRealFile && changeData) {
const { changeNumber, patchsetNumber, repo } = changeData;
const line = comment.range?.start_line || comment.line || '';
const lineAnchor = line ? `#${line}` : '';
const encodedRepo = String(repo).split('/').map(encodeURIComponent).join('/');
const encodedPath = String(comment.path).split('/').map(encodeURIComponent).join('/');
const url = `${window.location.origin}/c/${encodedRepo}/+/${changeNumber}/${patchsetNumber}/${encodedPath}${lineAnchor}`;
links.push({
url,
tooltip: `${comment.path}${line ? `:${line}` : ''}`,
primary: true,
icon: 'CODE',
});
}
const { header: firstLine, body: commentBody } = extractHeaderFromComment(comment.message);
const severity = classifyCommentSeverity(comment.message);
const actions = [];
const prompt = CONFIG.enableCopyPrompts ? extractPromptFromComment(comment.message) : null;
if (prompt) {
actions.push({
name: 'Copy Prompt',
tooltip: 'Copy AI agent prompt for this issue to clipboard',
callback: (_change, _patchset, _attempt, _externalId, _checkName, _actionName) => {
return navigator.clipboard.writeText(prompt).then(() => {
log('Copied prompt to clipboard');
return { message: 'Prompt copied to clipboard', shouldReload: false };
}).catch(err => {
log('Failed to copy prompt to clipboard:', err);
return { message: 'Failed to copy prompt to clipboard', shouldReload: false };
});
},
});
}
return {
category: severity.category,
summary: firstLine || 'Inline comment by CodeRabbit',
message: commentBody,
tags: [severity.tag],
...(links.length > 0 ? { links } : {}),
...(actions.length > 0 ? { actions } : {}),
};
}
function stripAutoGeneratedPrefix(message) {
return (message || '')
.replace(/^This is an auto-generated comment:?\s*/i, '')
.replace(/^This is an auto-generated reply by CodeRabbit\s*/i, '')
.replace(/by coderabbit\.ai\s*/i, '')
.trim();
}
});
})();