Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
945 lines (858 loc) · 33.2 KB
/
Copy pathcontent.js
File metadata and controls
945 lines (858 loc) · 33.2 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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
(async () => {
const [
{ el, showToast, iconGear, iconClose, tableFromQnA },
{ extractPRText },
{ reviewSchema, combinedSchema, structuredSchema, isReviewAnalysis, isReviewQnAList },
ai
] = await Promise.all([
import(chrome.runtime.getURL('utils/dom.js')),
import(chrome.runtime.getURL('utils/extractors.js')),
import(chrome.runtime.getURL('schemas.js')),
import(chrome.runtime.getURL('utils/ai.js'))
]);
const state = {
telemetry: {
totalChars: 0,
summary: { device: 0, hybrid: 0, lastMs: 0 },
review: { device: 0, hybrid: 0, lastMs: 0 },
translation: { device: 0, hybrid: 0 }
},
progress: { percent: 0, label: '' },
summarySource: null,
reviewSource: null,
translationSource: null,
hybridUsed: false,
lastSummaryMarkdown: '',
onboardingShown: false,
settings: null,
reviewQnA: [],
detectedLanguage: 'n/a',
structuredJson: null
};
const COMMON_LANGS = ['en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'zh', 'ja', 'ko', 'ar', 'hi'];
const selectors = {
root: null,
analyzeButton: null,
settingsButton: null,
closeButton: null,
toolbar: null,
status: null,
hybridBadge: null,
summaryArea: null,
summaryBody: null,
summaryProgress: null,
structuredArea: null,
structuredBody: null,
structuredTable: null,
structuredSource: null,
structuredCopy: null,
structuredInsert: null,
translationBadge: null,
translationTarget: null,
translationCustom: null,
translationButton: null,
translationOutput: null,
translationCopy: null,
translationInsert: null,
errorArea: null,
diagnosticsBody: null,
onboarding: null
};
let isMounted = false;
const SUMMARY_CONTEXT = [
'You are a staff-level reviewer summarizing this pull request for developers who are new to the repository.',
'Highlight the intent, the major code paths touched, potential risks, and what validation or follow-up is required.',
'Reference files or components when it adds clarity and keep the summary concise but information-dense.'
].join(' ');
mountPanel();
bindShortcuts();
await annotateAvailability();
await hydrateSettings();
// Warm the on-device model during page load so the first Analyze click does
// not pay the cold-start cost.
ai.warmUpModel?.();
function mountPanel() {
if (isMounted && selectors.root) {
selectors.root.classList.add('pp-open');
selectors.root.focus({ preventScroll: true });
return;
}
if (selectors.root?.isConnected) {
selectors.root.classList.add('pp-open');
isMounted = true;
return;
}
const panel = el(`
<aside id="pp-root" aria-live="polite" tabindex="-1">
<div id="pp-panel">
<div id="pp-header">
<div class="pp-header-left">
<div id="pp-title">PR-Pilot</div>
<span class="pp-badge" id="pp-status">idle</span>
<span class="pp-hybrid" id="pp-hybrid" hidden>AI ran in cloud (hybrid mode)</span>
</div>
<div id="prp-toolbar"></div>
</div>
<div id="pp-onboarding" class="pp-onboarding">
<strong>First run?</strong> Keep this tab focused while Chrome downloads the on-device models. Progress will appear here.
</div>
<div id="pp-body">
<div class="pp-error" id="pp-error" hidden></div>
<div class="pp-section">
<div class="pp-section-header">
<h3>Summary</h3>
<div class="pp-actions">
<button class="pp-link" id="pp-summary-copy">Copy</button>
</div>
</div>
<div id="pp-summary" class="pp-card pp-content">
<div id="pp-summary-progress" class="pp-progress" hidden>
<span class="pp-spinner"></span>
<span class="pp-progress-label">Preparing summarizer...</span>
</div>
<div id="pp-summary-body" class="pp-markdown pp-muted">
Click <span class="pp-kbd">Analyze PR</span> to generate a summary.
</div>
</div>
</div>
<div class="pp-section">
<div class="pp-section-header">
<h3>Structured analysis</h3>
<div class="pp-actions">
<span id="pp-structured-source" class="pp-source"></span>
<button class="pp-link" id="pp-structured-copy">Copy JSON</button>
<button class="pp-link" id="pp-structured-insert">Insert as PR comment</button>
</div>
</div>
<div id="pp-structured" class="pp-card pp-content">
<div id="prp-structured-body" class="pp-muted">Run Analyze PR to populate Q&A.</div>
<pre id="pp-structured-json" class="pp-json pp-muted">JSON with risks, tests, Q&A, release notes.</pre>
</div>
</div>
<div class="pp-section">
<div class="pp-section-header">
<h3>Translate & Language detect</h3>
</div>
<div class="pp-card pp-content prp-translate">
<div class="prp-translate-row">
<span class="prp-badge" id="prp-lang-detected">Detected: --</span>
<label class="sr-only" for="prp-lang-target">Target language</label>
<select id="prp-lang-target" class="prp-target-select"></select>
<input id="prp-lang-custom" class="prp-target-custom" type="text" placeholder="Custom code" hidden />
<button id="prp-translate" class="pp-btn">Translate summary</button>
</div>
<textarea id="prp-translate-output" class="pp-textarea" rows="6" placeholder="Translation will appear here"></textarea>
<div class="pp-row pp-actions">
<button id="prp-translate-copy" class="pp-link">Copy</button>
<button id="prp-translate-insert" class="pp-link">Insert into PR description</button>
</div>
</div>
</div>
<div class="pp-section">
<button id="pp-diagnostics-toggle" class="pp-link">Diagnostics</button>
<div id="pp-diagnostics" class="pp-card pp-content" hidden>
<dl id="pp-diagnostics-body" class="pp-diagnostics"></dl>
</div>
</div>
</div>
</div>
</aside>
`);
selectors.root = panel;
selectors.status = panel.querySelector('#pp-status');
selectors.hybridBadge = panel.querySelector('#pp-hybrid');
selectors.summaryArea = panel.querySelector('#pp-summary');
selectors.summaryBody = panel.querySelector('#pp-summary-body');
selectors.summaryProgress = panel.querySelector('#pp-summary-progress');
selectors.structuredArea = panel.querySelector('#pp-structured');
selectors.structuredTable = panel.querySelector('#prp-structured-body');
selectors.structuredBody = panel.querySelector('#pp-structured-json');
selectors.structuredSource = panel.querySelector('#pp-structured-source');
selectors.structuredCopy = panel.querySelector('#pp-structured-copy');
selectors.structuredInsert = panel.querySelector('#pp-structured-insert');
selectors.translationBadge = panel.querySelector('#prp-lang-detected');
selectors.translationTarget = panel.querySelector('#prp-lang-target');
selectors.translationCustom = panel.querySelector('#prp-lang-custom');
selectors.translationButton = panel.querySelector('#prp-translate');
selectors.translationOutput = panel.querySelector('#prp-translate-output');
selectors.translationCopy = panel.querySelector('#prp-translate-copy');
selectors.translationInsert = panel.querySelector('#prp-translate-insert');
selectors.errorArea = panel.querySelector('#pp-error');
selectors.diagnosticsBody = panel.querySelector('#pp-diagnostics-body');
selectors.onboarding = panel.querySelector('#pp-onboarding');
selectors.toolbar = renderToolbar(panel.querySelector('#prp-toolbar'));
document.body.appendChild(panel);
panel.querySelector('#pp-summary-copy').addEventListener('click', () => copyText(state.lastSummaryMarkdown));
selectors.structuredCopy.addEventListener('click', copyStructuredJSON);
selectors.structuredInsert.addEventListener('click', insertStructuredComment);
selectors.translationButton.addEventListener('click', translateSummary);
selectors.translationCopy.addEventListener('click', () => copyText(selectors.translationOutput?.value ?? ''));
selectors.translationInsert.addEventListener('click', insertTranslation);
selectors.translationTarget.addEventListener('change', handleTargetLanguageChange);
panel.querySelector('#pp-diagnostics-toggle').addEventListener('click', toggleDiagnostics);
createFab();
if (state.settings) {
populateTargetLanguages(state.settings.defaultTargetLanguage);
handleTargetLanguageChange();
}
isMounted = true;
panel.classList.add('pp-open');
panel.focus({ preventScroll: true });
}
function renderToolbar(slot) {
if (!slot) return null;
let toolbar = slot.querySelector('#prp-toolbar-bar');
if (!toolbar) {
toolbar = el(`
<div class="prp-toolbar" id="prp-toolbar-bar">
<button type="button" class="pp-btn primary" id="prp-analyze">Analyze PR</button>
<button type="button" class="pp-btn prp-icon-btn" id="prp-settings" aria-label="Open settings">${iconGear()}</button>
<button type="button" class="pp-btn prp-icon-btn" id="prp-close" aria-label="Close panel">${iconClose()}</button>
</div>
`);
slot.appendChild(toolbar);
}
selectors.analyzeButton = toolbar.querySelector('#prp-analyze');
selectors.settingsButton = toolbar.querySelector('#prp-settings');
selectors.closeButton = toolbar.querySelector('#prp-close');
if (selectors.analyzeButton) selectors.analyzeButton.onclick = analyzeCurrentPR;
if (selectors.settingsButton) selectors.settingsButton.onclick = openOptionsPage;
if (selectors.closeButton) selectors.closeButton.onclick = unmountPanel;
return toolbar;
}
// Ensure the options page opens even on older channels lacking openOptionsPage.
function openOptionsPage() {
const detailsUrl = `chrome://extensions/?id=${chrome.runtime.id}`;
try {
chrome.runtime.sendMessage({ type: 'open-extension-details' }, response => {
if (chrome.runtime.lastError || !response?.ok) {
openFallback();
}
});
} catch (err) {
openFallback();
}
function openFallback() {
if (chrome?.runtime?.openOptionsPage) {
try {
const maybePromise = chrome.runtime.openOptionsPage(() => {
if (chrome.runtime.lastError) {
window.open(chrome.runtime.getURL('options.html'), '_blank', 'noopener');
}
});
if (maybePromise && typeof maybePromise.catch === 'function') {
maybePromise.catch(() => window.open(chrome.runtime.getURL('options.html'), '_blank', 'noopener'));
}
} catch (err) {
window.open(chrome.runtime.getURL('options.html'), '_blank', 'noopener');
}
} else {
window.open(chrome.runtime.getURL('options.html'), '_blank', 'noopener');
}
}
}
function handleTargetLanguageChange() {
if (!selectors.translationTarget || !selectors.translationCustom) return;
const useCustom = selectors.translationTarget.value === 'other';
selectors.translationCustom.hidden = !useCustom;
if (!useCustom) {
selectors.translationCustom.value = '';
} else {
selectors.translationCustom.focus();
}
}
function populateTargetLanguages(preferred) {
if (!selectors.translationTarget || !selectors.translationCustom) return;
if (!selectors.translationTarget.options.length) {
COMMON_LANGS.forEach(code => {
const option = document.createElement('option');
option.value = code;
option.textContent = code;
selectors.translationTarget.appendChild(option);
});
const other = document.createElement('option');
other.value = 'other';
other.textContent = 'Other...';
selectors.translationTarget.appendChild(other);
}
if (preferred && COMMON_LANGS.includes(preferred)) {
selectors.translationTarget.value = preferred;
selectors.translationCustom.hidden = true;
selectors.translationCustom.value = '';
} else if (preferred) {
selectors.translationTarget.value = 'other';
selectors.translationCustom.hidden = false;
selectors.translationCustom.value = preferred;
} else {
selectors.translationTarget.value = COMMON_LANGS[0];
selectors.translationCustom.hidden = true;
selectors.translationCustom.value = '';
}
}
function getTargetLanguage() {
if (!selectors.translationTarget) {
return (
state.settings?.defaultTargetLanguage ||
navigator.language?.split('-')[0] ||
'en'
);
}
if (selectors.translationTarget.value === 'other') {
const custom = selectors.translationCustom?.value?.trim();
if (custom) return custom;
return (
state.settings?.defaultTargetLanguage ||
navigator.language?.split('-')[0] ||
'en'
);
}
return selectors.translationTarget.value;
}
async function hydrateSettings() {
try {
const settings = await ai.loadSettings();
state.settings = settings;
populateTargetLanguages(settings.defaultTargetLanguage);
handleTargetLanguageChange();
} catch (err) {
console.warn('Failed to load PR-Pilot settings', err);
state.settings = {
defaultTargetLanguage: COMMON_LANGS[0]
};
populateTargetLanguages(state.settings.defaultTargetLanguage);
handleTargetLanguageChange();
}
}
async function updateDetectedLanguage(summaryMarkdown) {
if (!selectors.translationBadge) return;
try {
const lang = summaryMarkdown ? await ai.detectLanguage(summaryMarkdown) : null;
state.detectedLanguage = lang || 'n/a';
selectors.translationBadge.textContent = `Detected: ${state.detectedLanguage}`;
} catch (err) {
console.warn('Language detection failed', err);
state.detectedLanguage = 'n/a';
selectors.translationBadge.textContent = 'Detected: n/a';
}
}
function unmountPanel() {
if (selectors.root?.parentElement) {
selectors.root.remove();
}
resetSelectors();
isMounted = false;
clearTransientState();
}
function resetSelectors() {
Object.keys(selectors).forEach(key => {
selectors[key] = null;
});
}
function clearTransientState() {
state.lastSummaryMarkdown = '';
state.reviewQnA = [];
state.summarySource = null;
state.reviewSource = null;
state.translationSource = null;
state.hybridUsed = false;
state.detectedLanguage = 'n/a';
state.structuredJson = null;
}
function createFab() {
if (document.getElementById('pp-floating')) return;
const fab = el(`<div id="pp-floating"><button class="pp-fab">PR-Pilot</button></div>`);
fab.querySelector('button').addEventListener('click', togglePanel);
document.body.appendChild(fab);
}
function togglePanel() {
if (!isMounted || !selectors.root) {
mountPanel();
return;
}
selectors.root.classList.toggle('pp-open');
if (selectors.root.classList.contains('pp-open')) {
selectors.root.focus({ preventScroll: true });
}
}
function bindShortcuts() {
window.addEventListener('keydown', evt => {
if ((evt.ctrlKey || evt.metaKey) && evt.shiftKey && evt.key.toLowerCase() === 'p') {
evt.preventDefault();
togglePanel();
}
});
if (chrome?.commands?.onCommand) {
chrome.commands.onCommand.addListener(command => {
if (command === 'analyze-pr') {
mountPanel();
if (selectors.root) {
selectors.root.classList.add('pp-open');
}
analyzeCurrentPR();
}
});
}
}
function setStatus(status) {
if (!selectors.status) return;
selectors.status.textContent = status;
}
function resetUI() {
selectors.errorArea.hidden = true;
selectors.errorArea.textContent = '';
selectors.summaryBody.classList.add('pp-muted');
selectors.summaryBody.innerHTML = 'Preparing...';
selectors.structuredBody.classList.add('pp-muted');
selectors.structuredBody.textContent = 'Working on structured analysis...';
if (selectors.structuredTable) {
selectors.structuredTable.classList.add('pp-muted');
selectors.structuredTable.textContent = 'Compiling reviewer Q&A...';
}
if (selectors.translationOutput) {
selectors.translationOutput.value = '';
}
if (selectors.translationBadge) {
selectors.translationBadge.textContent = 'Detected: --';
}
selectors.summaryProgress.hidden = false;
selectors.summaryProgress.querySelector('.pp-progress-label').textContent = 'Preparing summarizer...';
selectors.hybridBadge.hidden = true;
state.hybridUsed = false;
state.reviewQnA = [];
state.detectedLanguage = 'n/a';
}
function showError(message) {
selectors.errorArea.hidden = false;
selectors.errorArea.textContent = message;
setStatus('error');
}
function hideOnboarding() {
if (!state.onboardingShown) return;
selectors.onboarding.hidden = true;
}
async function analyzeCurrentPR() {
if (!navigator.userActivation.isActive) {
setStatus('needs-gesture');
showToast('Click Analyze with the page focused to unlock on-device AI.');
return;
}
state.onboardingShown = true;
selectors.onboarding.hidden = false;
resetUI();
setStatus('preparing');
let text = '';
try {
text = await extractPRText();
} catch (err) {
showError(`Failed to extract PR: ${err.message}`);
return;
}
if (!text || text.length < 100) {
showError('Not enough PR content found. Open Files changed or Commits tab and retry.');
return;
}
await runAnalyses(text);
}
async function runAnalyses(prText) {
// The summary only needs title/description/diff, so feed it a smaller slice
// for a faster prefill (quicker time-to-first-token). The heavier structured
// pass keeps the fuller context.
const SUMMARY_CHARS = 5_000;
const STRUCTURED_CHARS = 5_000;
const summaryInput = prText.length > SUMMARY_CHARS
? prText.slice(0, SUMMARY_CHARS) + '\n[...trimmed for summary]'
: prText;
const structuredInput = prText.length > STRUCTURED_CHARS
? prText.slice(0, STRUCTURED_CHARS) + '\n[...diff truncated for performance]'
: prText;
try {
setStatus('analyzing');
const analysisStart = performance.now();
selectors.summaryProgress.hidden = false;
selectors.summaryProgress.querySelector('.pp-progress-label').textContent = 'Summarizing...';
// Stream the summary so text appears within a second or two instead of
// blocking on the full structured JSON.
let summaryText = '';
const summaryResult = await ai.summarizeStreaming({
text: summaryInput,
context: SUMMARY_CONTEXT,
onChunk: (full) => {
summaryText = full;
selectors.summaryProgress.hidden = true;
selectors.summaryBody.classList.remove('pp-muted');
selectors.summaryBody.innerHTML = renderMarkdown(full);
}
});
summaryText = summaryResult.output || summaryText;
state.telemetry.summary.lastMs = performance.now() - analysisStart;
recordTelemetry('summary', summaryResult.source, prText.length);
state.lastSummaryMarkdown = summaryText;
selectors.summaryProgress.hidden = true;
selectors.summaryBody.classList.remove('pp-muted');
selectors.summaryBody.innerHTML = renderMarkdown(summaryText);
setHybrid(summaryResult.source === 'hybrid');
hideOnboarding();
updateDetectedLanguage(summaryText);
updateDiagnostics();
// Auto-run structured analysis. It is now a single fast call that also
// answers the reviewer questions, so we run it automatically once the
// summary is on screen instead of waiting for a button click.
await runStructured(structuredInput, prText.length);
} catch (err) {
console.error('PR-Pilot analysis failed', err);
showError(err.message);
}
}
function normalizeQna(list) {
if (!Array.isArray(list)) return [];
return list
.map(item => {
if (!item || typeof item !== 'object') return null;
const question = typeof item.question === 'string' ? item.question.trim() : '';
if (!question) return null;
const answer = typeof item.answer === 'string' && item.answer.trim()
? item.answer.trim()
: 'Unknown';
const confidence = typeof item.confidence === 'number' && isFinite(item.confidence)
? Math.min(1, Math.max(0, item.confidence))
: 1;
const entry = { question, answer, confidence };
if (Array.isArray(item.evidence_files)) {
const ev = item.evidence_files
.filter(s => typeof s === 'string' && s.trim())
.map(s => s.trim());
if (ev.length) entry.evidence_files = ev;
}
return entry;
})
.filter(Boolean)
.slice(0, 3);
}
async function runStructured(truncated, rawLength) {
try {
setStatus('analyzing');
const start = performance.now();
selectors.structuredBody.classList.add('pp-muted');
selectors.structuredBody.textContent = 'Working on structured analysis...';
selectors.structuredTable.classList.add('pp-muted');
selectors.structuredTable.textContent = 'Compiling reviewer questions...';
const combinedResult = await ai.combinedAnalysis({
text: truncated,
context: SUMMARY_CONTEXT,
schema: structuredSchema
});
state.telemetry.review.lastMs = performance.now() - start;
let structuredRaw;
try {
structuredRaw = JSON.parse(combinedResult.output);
} catch (err) {
showError('Analysis returned non-JSON payload. Try again.');
return;
}
const reviewQna = normalizeQna(structuredRaw?.review_qna);
const baseAnalysis = {
key_risks: ensureStringArray(structuredRaw?.key_risks),
tests_to_add: normalizeTests(structuredRaw?.tests_to_add),
release_notes: ensureStringArray(structuredRaw?.release_notes),
review_qna: reviewQna
};
const breaking = ensureStringArray(structuredRaw?.breaking_changes);
if (breaking.length) baseAnalysis.breaking_changes = breaking;
recordTelemetry('review', combinedResult.source === 'hybrid' ? 'hybrid' : 'on-device', rawLength);
selectors.structuredSource.textContent = combinedResult.source === 'hybrid' ? 'hybrid' : 'on-device';
setHybrid(combinedResult.source === 'hybrid');
const isValid = isReviewAnalysis(baseAnalysis);
state.structuredJson = isValid ? baseAnalysis : structuredRaw;
state.reviewQnA = reviewQna;
selectors.structuredBody.classList.remove('pp-muted');
selectors.structuredBody.textContent = JSON.stringify(state.structuredJson, null, 2);
// Q&A answers now arrive in the same structured call, so render directly
// instead of firing a second round of per-question prompts.
selectors.structuredTable.innerHTML = '';
if (reviewQna.length) {
selectors.structuredTable.classList.remove('pp-muted');
selectors.structuredTable.appendChild(tableFromQnA(reviewQna));
} else {
selectors.structuredTable.classList.add('pp-muted');
selectors.structuredTable.textContent = 'No reviewer questions generated.';
}
updateDiagnostics();
setStatus('done');
} catch (err) {
console.error('PR-Pilot structured analysis failed', err);
showError(err.message);
}
}
function setHybrid(isHybrid) {
state.hybridUsed = isHybrid;
if (selectors.hybridBadge) {
selectors.hybridBadge.hidden = !isHybrid;
}
}
function copyStructuredJSON() {
const source = state.structuredJson;
const text = source ? JSON.stringify(source, null, 2) : selectors.structuredBody?.textContent || '';
if (!text.trim()) {
showToast('Nothing to copy yet.');
return;
}
copyText(text);
}
async function translateSummary() {
const summary = state.lastSummaryMarkdown;
if (!summary) {
showToast('Run the summary first.');
return;
}
const target = getTargetLanguage();
if (selectors.translationButton) {
selectors.translationButton.disabled = true;
}
if (selectors.translationOutput) {
selectors.translationOutput.value = 'Translating...';
}
try {
let sourceLang = state.detectedLanguage;
if (!sourceLang || sourceLang === 'n/a') {
sourceLang = await ai.detectLanguage(summary);
}
const { output, source } = await ai.translateOnDevice({
text: summary,
targetLanguage: target,
sourceLanguage: sourceLang && sourceLang !== 'n/a' ? sourceLang : undefined
});
recordTelemetry('translation', source);
if (selectors.translationOutput) {
selectors.translationOutput.value = output;
}
if (selectors.translationBadge) {
selectors.translationBadge.textContent = `Detected: ${sourceLang || 'n/a'}`;
}
state.detectedLanguage = sourceLang || 'n/a';
setHybrid(source === 'hybrid');
updateDiagnostics();
} catch (err) {
if (selectors.translationOutput) {
selectors.translationOutput.value = `Translation failed: ${err.message}`;
}
} finally {
if (selectors.translationButton) {
selectors.translationButton.disabled = false;
}
}
}
function ensureStringArray(value) {
if (!Array.isArray(value)) return [];
return value
.map(item => (typeof item === 'string' ? item.trim() : ''))
.filter(Boolean);
}
function normalizeTests(value) {
if (!Array.isArray(value)) return [];
return value
.filter(
entry =>
entry &&
typeof entry === 'object' &&
typeof entry.file === 'string' &&
typeof entry.description === 'string'
)
.map(entry => {
const normalised = {
file: entry.file.trim(),
description: entry.description.trim()
};
if (typeof entry.test_stub === 'string' && entry.test_stub.trim()) {
normalised.test_stub = entry.test_stub.trim();
}
return normalised;
});
}
function copyText(text) {
if (!text) {
showToast('Nothing to copy yet.');
return;
}
navigator.clipboard.writeText(text).then(
() => showToast('Copied to clipboard.'),
err => showToast(`Copy failed: ${err.message}`)
);
}
function insertTranslation() {
const text = selectors.translationOutput?.value?.trim();
if (!text) {
showToast('Nothing to insert yet.');
return;
}
if (appendToTargetField(text)) {
showToast('Inserted translation into PR description.');
}
}
function insertStructuredComment() {
const analysis = state.structuredJson;
if (!analysis || typeof analysis !== 'object') {
showToast('Run Analyze PR first.');
return;
}
const lines = ['### PR-Pilot structured review'];
lines.push('', '**Key risks**');
lines.push(...formatList(analysis.key_risks));
lines.push('', '**Breaking changes**');
lines.push(...formatList(analysis.breaking_changes));
lines.push('', '**Tests to add**');
lines.push(...formatTests(analysis.tests_to_add));
lines.push('', '**Release notes**');
lines.push(...formatList(analysis.release_notes));
lines.push('', '**Reviewer Q&A**');
const qna = Array.isArray(analysis.review_qna) ? analysis.review_qna : [];
if (qna.length) {
lines.push('', '| Question | Answer | Confidence | Evidence |', '| --- | --- | --- | --- |');
qna.forEach(item => {
const evidence = Array.isArray(item.evidence_files) && item.evidence_files.length
? item.evidence_files.join('<br>')
: 'n/a';
lines.push(
`| ${escapeTableCell(item.question)} | ${escapeTableCell(item.answer)} | ${formatConfidence(item.confidence)} | ${escapeTableCell(evidence)} |`
);
});
} else {
lines.push('- None');
}
const payload = lines.join('\n');
if (appendToTargetField(payload)) {
showToast('Inserted structured analysis as PR comment.');
}
}
function appendToTargetField(text) {
const trimmed = text.trim();
if (!trimmed) return false;
const candidates = [
document.querySelector('textarea#pull_request_body'),
document.querySelector('.comment-form-textarea'),
document.querySelector('textarea#issue_comment_body')
];
const field = candidates.find(Boolean);
if (!field) {
showToast('Could not find PR description textarea.');
return false;
}
field.value = `${field.value}\n\n${trimmed}`.trim();
field.dispatchEvent(new Event('input', { bubbles: true }));
return true;
}
function formatList(items) {
const list = ensureStringArray(items);
if (!list.length) return ['- None'];
return list.map(item => `- ${item}`);
}
function formatTests(tests) {
const list = normalizeTests(tests);
if (!list.length) return ['- None'];
return list.map(item => {
const stub =
typeof item.test_stub === 'string' && item.test_stub.trim()
? `\n \`\`\`\n${item.test_stub.trim()}\n \`\`\``
: '';
return `- ${item.file}: ${item.description}${stub}`;
});
}
function escapeTableCell(value = '') {
return String(value).replace(/\|/g, '\\|').replace(/\r?\n/g, '<br>');
}
function formatConfidence(value) {
if (typeof value !== 'number' || Number.isNaN(value)) return 'n/a';
return `${Math.round(clampValue(value, 0, 1) * 100)}%`;
}
function clampValue(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function toggleDiagnostics() {
const container = document.getElementById('pp-diagnostics');
container.hidden = !container.hidden;
updateDiagnostics();
}
function updateDiagnostics() {
const diag = selectors.diagnosticsBody;
if (!diag || diag.parentElement.hidden) return;
diag.innerHTML = `
<dt>Total characters processed</dt><dd>${state.telemetry.totalChars}</dd>
<dt>Summary last run</dt><dd>${Math.round(state.telemetry.summary.lastMs)} ms (${state.summarySource || 'n/a'})</dd>
<dt>Structured analysis last run</dt><dd>${Math.round(state.telemetry.review.lastMs)} ms (${state.reviewSource || 'n/a'})</dd>
<dt>Runs (summary)</dt><dd>Device: ${state.telemetry.summary.device}, Hybrid: ${state.telemetry.summary.hybrid}</dd>
<dt>Runs (structured)</dt><dd>Device: ${state.telemetry.review.device}, Hybrid: ${state.telemetry.review.hybrid}</dd>
<dt>Runs (translation)</dt><dd>Device: ${state.telemetry.translation.device}, Hybrid: ${state.telemetry.translation.hybrid}</dd>
<dt>Detected language</dt><dd>${state.detectedLanguage}</dd>
`;
}
async function annotateAvailability() {
const summarizerAvail = await ai.availability('summarizer');
if (summarizerAvail === 'downloadable' || summarizerAvail === 'after-download') {
selectors.onboarding.hidden = false;
} else {
selectors.onboarding.hidden = true;
}
}
function renderMarkdown(markdown) {
const lines = markdown.split('\n');
const html = [];
let inList = false;
let inCode = false;
for (const line of lines) {
if (line.trim().startsWith('```')) {
if (inCode) {
html.push('</code></pre>');
inCode = false;
} else {
inCode = true;
html.push('<pre><code>');
}
continue;
}
if (inCode) {
html.push(escapeHtml(line));
continue;
}
if (/^\s*[-*+]\s+/.test(line)) {
if (!inList) {
html.push('<ul>');
inList = true;
}
const content = line.replace(/^\s*[-*+]\s+/, '');
html.push(`<li>${escapeHtml(content)}</li>`);
} else {
if (inList) {
html.push('</ul>');
inList = false;
}
if (line.trim() === '') {
html.push('<p></p>');
} else if (/^#{1,6}\s/.test(line)) {
const level = line.match(/^#+/)[0].length;
const content = line.replace(/^#{1,6}\s*/, '');
html.push(`<h${level}>${escapeHtml(content)}</h${level}>`);
} else {
html.push(`<p>${escapeHtml(line)}</p>`);
}
}
}
if (inList) html.push('</ul>');
if (inCode) html.push('</code></pre>');
return html.join('');
}
function escapeHtml(str = '') {
return str.replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch]));
}
function recordTelemetry(kind, source, chars = 0) {
state.telemetry.totalChars += chars;
if (kind === 'summary') {
state.telemetry.summary[source] += 1;
state.summarySource = source;
} else if (kind === 'review') {
state.telemetry.review[source] += 1;
state.reviewSource = source;
} else if (kind === 'translation') {
state.telemetry.translation[source] += 1;
state.translationSource = source;
}
}
})();