-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcontent.js
More file actions
1993 lines (1758 loc) · 78.3 KB
/
content.js
File metadata and controls
1993 lines (1758 loc) · 78.3 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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// content.js
// Detects GitLab MR and Azure DevOps PR pages, fetches code changes, injects UI, and displays integrated code review
// Debug toggle: set to false to disable console logs in production
// Check if DEBUG already exists to avoid conflicts
if (typeof DEBUG === 'undefined') {
var DEBUG = false;
}
// Timing constants (in milliseconds)
const TIMEOUT_AUTO_REVIEW_DELAY = 500;
const MAX_PATCH_SIZE_FALLBACK = 50_000;
/** Set to false to restore automatic review on PR load (and autoReviewDecisionMaker for those runs). */
const TEMP_FORCE_MANUAL_REVIEW_ONLY = true;
// Logger functions - loaded dynamically to avoid module import issues in content scripts
// Provide fallback functions immediately, then upgrade when logger loads
// Check if variables already exist to avoid redeclaration errors
if (typeof dbgLog === 'undefined') {
var dbgLog = (...args) => { if (DEBUG) console.log('[ThinkReview Extension]', ...args); };
}
if (typeof dbgWarn === 'undefined') {
var dbgWarn = (...args) => { if (DEBUG) console.warn('[ThinkReview Extension]', ...args); };
}
if (typeof dbgError === 'undefined') {
var dbgError = (...args) => { if (DEBUG) console.error('[ThinkReview Extension]', ...args); };
}
// Initialize logger functions with dynamic import
(async () => {
try {
// Use chrome.runtime.getURL for content scripts (same pattern as other dynamic imports)
const loggerModule = await import(chrome.runtime.getURL('utils/logger.js'));
// Upgrade to use the real logger functions
dbgLog = loggerModule.dbgLog;
dbgWarn = loggerModule.dbgWarn;
dbgError = loggerModule.dbgError;
dbgLog('Logger module loaded successfully');
} catch (error) {
// Keep using fallback functions if logger fails to load
dbgWarn('Failed to load logger module, using console fallback:', error);
}
})();
// Configuration constants
// Note: Daily review limit is now handled server-side via Firebase Remote Config
// Delay initial log until logger is loaded
setTimeout(() => {
dbgLog('Content script loaded on:', window.location.href);
}, 100);
// Track if a review request is in progress to prevent duplicates
let isReviewInProgress = false;
// When the user requests a manual review while another run is in flight (e.g. auto-review
// still fetching patch or running the auto decision maker), remember it and run after the
// current invocation finishes so REVIEW_PATCH_CODE / reviewPatchCode_1_1 is not dropped.
let pendingManualReview = null;
// Track current PR ID for detecting navigation to new PRs
let currentPRId = null;
// State for the button-injection retry observer — grouped to reduce namespace pollution.
const retryState = {
observer: null, // MutationObserver instance
timeoutId: null, // 10 s hard-stop timer
debounceTimerId: null, // debounce timer inside the observer callback
isInjecting: false, // prevents concurrent injectButtons() calls in the observer
};
/** Disconnect the retry observer and clear all associated timers in one call. */
function _teardownRetryObserver() {
clearTimeout(retryState.timeoutId);
retryState.timeoutId = null;
clearTimeout(retryState.debounceTimerId);
retryState.debounceTimerId = null;
if (retryState.observer) {
retryState.observer.disconnect();
retryState.observer = null;
}
}
// Listen for Ollama metadata bar actions (switch to cloud, change model)
document.addEventListener('thinkreview-switch-to-cloud', async () => {
await chrome.storage.local.set({ aiProvider: 'cloud' });
if (typeof fetchAndDisplayCodeReview === 'function') {
fetchAndDisplayCodeReview(true, false);
}
});
document.addEventListener('thinkreview-ollama-model-changed', async (e) => {
const model = e.detail?.model;
if (!model) return;
const { ollamaConfig } = await chrome.storage.local.get(['ollamaConfig']);
const config = ollamaConfig || { url: 'http://localhost:11434', model: '' };
await chrome.storage.local.set({ ollamaConfig: { ...config, model } });
if (typeof fetchAndDisplayCodeReview === 'function') {
fetchAndDisplayCodeReview(true, false);
}
});
// Import platform detection services
let platformDetector = null;
// Import Azure DevOps token error module
let azureDevOpsTokenError = null;
// Initialize platform detection
async function initializePlatformDetection() {
try {
// Dynamically import platform detector
const platformModule = await import(chrome.runtime.getURL('services/platform-detector.js'));
platformDetector = platformModule.platformDetector;
platformDetector.init();
// Load custom Azure DevOps domains so on-prem URLs are detected
const storage = await chrome.storage.local.get(['azureDevOpsDomains', 'bitbucketDataCenterDomains']);
platformDetector.setAzureDevOpsCustomDomains(storage.azureDevOpsDomains || []);
// Load custom Bitbucket Data Center domains
platformDetector.setBitbucketCustomDomains(storage.bitbucketDataCenterDomains || []);
// Dynamically import Azure DevOps API module for error handling
const apiModule = await import(chrome.runtime.getURL('services/azure-devops-api.js'));
// Run server version detection only for on-prem/custom domains (skip dev.azure.com and visualstudio.com)
const hostname = window.location.hostname || '';
const isAzureCloud = hostname.includes('dev.azure.com') || hostname.includes('visualstudio.com');
if (
!isAzureCloud &&
platformDetector.isAzureDevOpsSite() &&
typeof apiModule.detectAndCacheServerVersion === 'function'
) {
const pathParts = window.location.pathname.split('/').filter(Boolean);
const collection = pathParts.length > 0 ? pathParts[0] : '';
const origin = window.location.origin;
apiModule.detectAndCacheServerVersion(origin, collection)
.then((result) => {
if (!result || result.fromCache !== false) return;
// Send to cloud via background script (avoids content script fetch to external API / CSP)
chrome.runtime.sendMessage({
type: 'LOG_AZURE_DEVOPS_VERSION',
origin,
version: result.version,
collection,
azureOnPremiseApiVersion: result.azureOnPremiseApiVersion ?? null,
azureOnPremiseVersion: result.azureOnPremiseVersion ?? null
}, (response) => {
if (chrome.runtime.lastError) dbgWarn('Azure DevOps version cloud log failed (non-critical):', chrome.runtime.lastError);
});
})
.catch((err) => {
dbgWarn('Azure DevOps server version detection failed (non-critical):', err);
});
}
// Dynamically import Azure DevOps token error module
const tokenErrorModule = await import(chrome.runtime.getURL('components/azure-devops-token-error.js'));
azureDevOpsTokenError = tokenErrorModule;
dbgLog('Platform detection initialized');
} catch (error) {
dbgWarn('Error initializing platform detection:', error);
}
}
// Debug information about the page
if (DEBUG) {
const pageInfo = {
url: window.location.href,
pathname: window.location.pathname,
host: window.location.host,
protocol: window.location.protocol,
hasMergeRequestsInPath: window.location.pathname.includes('/merge_requests/'),
hasPullRequestsInPath: window.location.pathname.includes('/pullrequest/'),
documentTitle: document.title,
relevantElements: {
mergeRequest: !!document.querySelector('.merge-request'),
mergeRequestDetails: !!document.querySelector('.merge-request-details'),
diffFilesHolder: !!document.querySelector('.diff-files-holder'),
diffs: !!document.querySelector('.diffs'),
mrStateWidget: !!document.querySelector('.mr-state-widget'),
prHeader: !!document.querySelector('[data-testid="pull-request-header"]'),
prTitle: !!document.querySelector('[data-testid="pull-request-title"]')
}
};
dbgLog('Page information:', pageInfo);
}
// The integrated review component functions (createIntegratedReviewPanel, displayIntegratedReview, showIntegratedReviewError)
// are loaded from integrated-review.js which is included in the manifest.json
// Note: CloudService is imported dynamically when needed
// Cloud function URL for code review
const CLOUD_FUNCTIONS_BASE_URL = 'https://us-central1-thinkgpt.cloudfunctions.net';
const REVIEW_CODE_URL = `${CLOUD_FUNCTIONS_BASE_URL}/reviewPatchCode`;
/**
* Check if the current page is a supported platform (GitLab MR, GitHub PR, or Azure DevOps PR)
* @returns {boolean} True if the current page is supported
*/
function isSupportedPage() {
if (!platformDetector) {
// Fallback to GitLab detection if platform detector not initialized
return isGitLabMRPage();
}
return platformDetector.isCurrentPageSupported();
}
/**
* Check if we should show the ThinkReview trigger button
* For Azure DevOps and GitHub, always show the button (since they're SPAs)
* For GitLab, only show on MR pages
* @returns {boolean} True if button should be shown
*/
function shouldShowButton() {
if (!platformDetector) {
return isGitLabMRPage();
}
// Always show button on Azure DevOps sites (SPA)
if (platformDetector.isAzureDevOpsSite()) {
return true;
}
// Always show button on GitHub sites (SPA)
if (platformDetector.isGitHubSite()) {
return true;
}
// Always show button on Bitbucket sites (SPA; content script only runs when user allowed Bitbucket)
if (platformDetector.isBitbucketSite()) {
return true;
}
// For other platforms, only show on supported pages
return platformDetector.isCurrentPageSupported();
}
/**
* Get the current platform
* @returns {string|null} Current platform ('gitlab' or 'azure-devops')
*/
function getCurrentPlatform() {
if (!platformDetector) {
return isGitLabMRPage() ? 'gitlab' : null;
}
return platformDetector.getCurrentPlatform();
}
/**
* Check if the current page is a GitLab merge request page (legacy function)
* @returns {boolean} True if the current page is a GitLab MR page
*/
function isGitLabMRPage() {
return /\/merge_requests\//.test(window.location.pathname);
}
/**
* Get patch URL for GitLab or GitHub (legacy function)
* @returns {string} Patch URL
*/
function getPatchUrl() {
// GitHub: normalize to canonical PR diff URL so suffix views like /files or /commits still work
if (platformDetector && platformDetector.isOnGitHubPRPage()) {
const githubDiffUrl = platformDetector.getGitHubPRDiffUrl && platformDetector.getGitHubPRDiffUrl();
if (githubDiffUrl) {
return githubDiffUrl;
}
// Fallback: legacy behavior for safety
let legacyUrl = window.location.href.replace(/[#?].*$/, '');
if (!legacyUrl.endsWith('.diff')) {
legacyUrl += '.diff';
}
return legacyUrl;
}
// Bitbucket: API 2.0 patch endpoint (cookie auth from content script)
if (platformDetector && platformDetector.isOnBitbucketPRPage()) {
const bitbucketPatchUrl = platformDetector.getBitbucketPatchApiUrl && platformDetector.getBitbucketPatchApiUrl();
if (bitbucketPatchUrl) {
return bitbucketPatchUrl;
}
}
// GitLab and others: keep existing .patch behavior
let url = window.location.href.replace(/[#?].*$/, '');
const extension = '.patch';
if (!url.endsWith(extension)) {
url += extension;
}
return url;
}
/**
* Extract GitHub pull request ID from URL
* @returns {string|null} Pull request ID
*/
function getGitHubPRId() {
const pathname = window.location.pathname;
const match = pathname.match(/\/pull\/(\d+)/);
return match ? match[1] : null;
}
/**
* Reads layout settings from chrome.storage.local, merged with defaults.
* @returns {Promise<Object>}
*/
async function getLayoutSettings() {
try {
const result = await chrome.storage.local.get(['reviewLayoutSettings']);
const raw = {
triggerMode: 'sidebar-tab',
buttonPosition: 'bottom-right',
panelMode: 'docked',
sidebarSide: 'right',
...(result.reviewLayoutSettings || {}),
};
const pos = raw.buttonPosition;
if (pos === 'top-right') raw.buttonPosition = 'bottom-right';
else if (pos === 'top-left') raw.buttonPosition = 'bottom-left';
return raw;
} catch (e) {
dbgWarn('Failed to load layout settings:', e);
return { triggerMode: 'sidebar-tab', buttonPosition: 'bottom-right', panelMode: 'docked', sidebarSide: 'right' };
}
}
/**
* Applies or removes the docked-sidebar body margin when the panel is expanded/collapsed.
* @param {boolean} isExpanded - True when panel is being shown, false when minimized
* @param {string} panelMode - 'overlay' | 'docked'
* @param {string} sidebarSide - 'right' | 'left'
*/
function applyDockedBodyMargin(isExpanded, panelMode, sidebarSide) {
if (panelMode !== 'docked') {
document.body.classList.remove('thinkreview-body-docked-right', 'thinkreview-body-docked-left');
return;
}
const bodyClass = sidebarSide === 'left' ? 'thinkreview-body-docked-left' : 'thinkreview-body-docked-right';
const otherClass = sidebarSide === 'left' ? 'thinkreview-body-docked-right' : 'thinkreview-body-docked-left';
if (isExpanded) {
document.body.classList.add(bodyClass);
document.body.classList.remove(otherClass);
} else {
document.body.classList.remove('thinkreview-body-docked-right', 'thinkreview-body-docked-left');
}
}
const areButtonsInjected = () =>
!!(document.getElementById('code-review-btns') || document.getElementById('thinkreview-sidebar-tab'));
async function injectButtons() {
if (areButtonsInjected()) {
dbgLog('Buttons already injected');
return;
}
dbgLog('Injecting trigger UI');
try {
const settings = await getLayoutSettings();
const { injectTrigger } = await import(chrome.runtime.getURL('components/layout-trigger.js'));
injectTrigger(settings, toggleReviewPanel);
dbgLog('Trigger injected via layout-trigger.js, mode:', settings.triggerMode);
} catch (error) {
dbgError('Failed to load layout-trigger.js, falling back to inline button:', error);
_injectFallbackButton();
}
}
// Fallback button used if layout-trigger.js fails to load
function _injectFallbackButton() {
if (document.getElementById('code-review-btns')) return;
const container = document.createElement('div');
container.id = 'code-review-btns';
container.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:9999;display:flex;flex-direction:column;gap:8px;';
const reviewBtn = document.createElement('button');
reviewBtn.id = 'code-review-btn';
reviewBtn.style.cssText = 'padding:8px 12px;background:#6b4fbb;color:white;border:none;border-radius:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;';
reviewBtn.innerHTML = '<span style="margin-right:5px;">ThinkReview</span><span style="font-size:10px;">▼</span>';
reviewBtn.onclick = (e) => { e.preventDefault(); e.stopPropagation(); toggleReviewPanel(); };
container.appendChild(reviewBtn);
document.body.appendChild(container);
}
/**
* Checks if the current page is a GitLab merge request page
* Simplified: If content script loaded, Chrome already validated the domain
* @returns {boolean} True if the current page is a GitLab MR page
*/
function isGitLabMRPage() {
// If content script is running, we're already on a registered GitLab domain
// Chrome filtered via registration pattern in background.js
// Just verify URL path indicates an MR page
const pathname = window.location.pathname;
const isMRPathPattern = pathname.includes('/merge_requests/') ||
pathname.includes('/-/merge_requests/') ||
pathname.includes('/merge_requests');
dbgLog('Page detection:', {
isMRPathPattern,
pathname: pathname
});
return isMRPathPattern;
}
/**
* Extracts the merge request ID from the URL
* @returns {string} The merge request ID
*/
function getMergeRequestId() {
const pathParts = window.location.pathname.split('/');
const mrIndex = pathParts.indexOf('merge_requests');
if (mrIndex !== -1 && mrIndex + 1 < pathParts.length) {
return pathParts[mrIndex + 1];
}
// Fallback: try to extract from the URL
const matches = window.location.pathname.match(/\/merge_requests\/(\d+)/);
return matches && matches[1] ? matches[1] : null;
}
/**
* Extracts the merge request subject/title from the page
* @returns {string} The merge request subject
*/
function getMergeRequestSubject() {
// Try to get the title from the page header
const titleElement = document.querySelector('.detail-page-header-title');
if (titleElement) {
return titleElement.textContent.trim();
}
// Alternative: try the merge request title element
const mrTitleElement = document.querySelector('.merge-request-title');
if (mrTitleElement) {
return mrTitleElement.textContent.trim();
}
// Another alternative: try the page title
const pageTitle = document.title;
if (pageTitle) {
// Remove the project name and GitLab suffix if present
return pageTitle.split('·')[0].trim();
}
return 'Unknown MR';
}
/**
* Get the current PR/MR ID
* @returns {string|null} Current PR/MR ID
*/
function getCurrentPRId() {
if (!platformDetector) {
return null;
}
if (platformDetector.isOnGitLabMRPage()) {
return getMergeRequestId();
} else if (platformDetector.isOnGitHubPRPage()) {
return getGitHubPRId();
} else if (platformDetector.isOnAzureDevOpsPRPage()) {
const prInfo = platformDetector.detectPlatform().pageInfo;
return prInfo?.prId || null;
} else if (platformDetector.isOnBitbucketPRPage()) {
const prInfo = platformDetector.detectPlatform().pageInfo;
return prInfo?.prId || null;
}
return null;
}
/**
* Check if we've navigated to a new PR and trigger review if needed.
* Clears panel state only when the URL identifies a different PR than currentPRId
* (not when navigating to non-PR pages).
*/
async function checkAndTriggerReviewForNewPR() {
// Only check if we're on a supported page (PR page)
if (!isSupportedPage()) {
// Not on a PR page: do not clear the integrated panel or reset currentPRId.
// Keeping currentPRId lets us detect a switch to a *different* PR after browsing
// elsewhere (clear + optional auto-run only runs in that branch below).
// Hide score popup when navigating to a non-PR page
try {
const scorePopupModule = await import(chrome.runtime.getURL('components/popup-modules/score-popup.js'));
scorePopupModule.hideScorePopup();
} catch (error) {
// Silently fail if module not available
}
// Clear completion effects (shake + bubble)
try {
const effectsModule = await import(chrome.runtime.getURL('components/popup-modules/completion-effects.js'));
effectsModule.clearTriggerShake();
} catch (error) {
// Silently fail if module not available
}
try {
const bubbleModule = await import(chrome.runtime.getURL('components/popup-modules/completion-message-bubble.js'));
bubbleModule.hideBubble();
} catch (error) {
// Silently fail if module not available
}
return;
}
const panel = document.getElementById('gitlab-mr-integrated-review');
// If panel doesn't exist yet, create it (this handles SPA navigation to PR pages)
if (!panel) {
// Await the panel creation to ensure it completes before returning
await injectIntegratedReviewPanel();
return;
}
const newPRId = getCurrentPRId();
// Check if we've navigated to a different PR
if (newPRId && newPRId !== currentPRId) {
dbgLog('Detected new PR page:', {
oldId: currentPRId,
newId: newPRId
});
// Clear patch content and conversation history from previous PR to free up memory
if (typeof window.clearPatchContentAndHistory === 'function') {
window.clearPatchContentAndHistory();
}
// Update tracked PR ID
currentPRId = newPRId;
// Ensure panel is minimized
if (!panel.classList.contains('thinkreview-panel-minimized-to-button')) {
panel.classList.add('thinkreview-panel-minimized-to-button');
const reviewBtn = document.getElementById('code-review-btn');
if (reviewBtn) {
const arrowSpan = reviewBtn.querySelector('span:last-child');
if (arrowSpan) {
arrowSpan.textContent = '▲';
}
}
}
isReviewInProgress = false;
pendingManualReview = null;
// Trigger new review only if auto-start is enabled
const autoStart = await getAutoStartReview();
if (autoStart && isSupportedPage()) {
setTimeout(() => fetchAndDisplayCodeReview(false, true), TIMEOUT_AUTO_REVIEW_DELAY);
}
} else if (currentPRId === null && newPRId) {
// First time detecting a PR - just track it
currentPRId = newPRId;
}
}
/**
* Gets whether to start the review automatically when opening a PR page (from extension options).
* @returns {Promise<boolean>}
*/
function getAutoStartReview() {
return new Promise((resolve) => {
chrome.storage.local.get(['autoStartReview'], (result) => {
if (TEMP_FORCE_MANUAL_REVIEW_ONLY) {
if (result.autoStartReview === true) {
dbgLog('TEMP_FORCE_MANUAL_REVIEW_ONLY: ignoring autoStartReview storage (manual reviews only)');
}
resolve(false);
return;
}
// Respect the "Start review automatically" option for all providers (default off when unset)
resolve(result.autoStartReview === true);
});
});
}
/**
* Injects the integrated review panel into the GitLab MR page.
* @param {Object} [opts] - Options
* @param {boolean} [opts.triggerReview] - If true, trigger the review after creating the panel (e.g. user clicked the ThinkReview button). If false/undefined, trigger only when autoStartReview option is enabled.
*/
async function injectIntegratedReviewPanel(opts = {}) {
const panel = document.getElementById('gitlab-mr-integrated-review');
// Check if the panel already exists
if (panel) {
dbgLog('Integrated review panel already exists');
// Check if we've navigated to a new PR
checkAndTriggerReviewForNewPR();
return;
}
// Check if we're on a supported page first
if (!isSupportedPage()) {
dbgLog('Not on a supported page, skipping panel injection');
return;
}
dbgLog('Creating integrated review panel');
// Create the review panel with the patch URL
const patchUrl = getPatchUrl();
await createIntegratedReviewPanel(patchUrl);
dbgLog('Integrated review panel created');
// Track current PR ID (before review fetch so SPA state stays consistent)
currentPRId = getCurrentPRId();
// If the user explicitly triggered this (button click), expand the panel and start review in parallel
if (opts.triggerReview === true) {
const fetchPromise = fetchAndDisplayCodeReview(false, false);
const createdPanel = document.getElementById('gitlab-mr-integrated-review');
if (createdPanel) {
createdPanel.classList.remove('thinkreview-panel-minimized-to-button');
const expandSettings = await getLayoutSettings();
if (expandSettings.panelMode === 'docked') {
createdPanel.classList.add('thinkreview-panel-docked');
if (expandSettings.sidebarSide === 'left') createdPanel.classList.add('thinkreview-panel-docked-left');
} else if (expandSettings.sidebarSide === 'left') {
// In overlay mode, still apply the sidebar side for positioning alignment
createdPanel.classList.add('thinkreview-panel-overlay-left');
} else {
createdPanel.classList.remove('thinkreview-panel-overlay-left');
}
applyDockedBodyMargin(true, expandSettings.panelMode, expandSettings.sidebarSide);
}
try {
await fetchPromise;
} catch (e) {
dbgWarn('Review fetch failed:', e?.message || e);
}
} else if (await getAutoStartReview()) {
fetchAndDisplayCodeReview(false, true);
}
}
/**
* Check if the user is logged in
* @returns {Promise<boolean>} True if the user is logged in
*/
function isUserLoggedIn() {
return new Promise((resolve) => {
chrome.storage.local.get(['user', 'userData', 'authSource'], (result) => {
// Check both user and userData fields for backward compatibility
// userData is the new field used by the updated authentication flow
// Supports both extension OAuth and webapp Firebase auth
if (result.userData) {
dbgLog('User logged in via:', result.authSource || 'extension');
resolve(true);
} else if (result.user) {
try {
// Try to parse the user data to ensure it's valid
const userData = JSON.parse(result.user);
resolve(!!userData && !!userData.email);
} catch (e) {
resolve(false);
}
} else {
resolve(false);
}
});
});
}
/**
* Shows a login prompt in the review panel
*/
function showLoginPrompt() {
// Stop the enhanced loader if it's running
if (typeof stopEnhancedLoader === 'function') {
stopEnhancedLoader();
}
const reviewLoading = document.getElementById('review-loading');
const reviewContent = document.getElementById('review-content');
const reviewError = document.getElementById('review-error');
// Hide all sections
if (reviewLoading) reviewLoading.classList.add('gl-hidden');
if (reviewContent) reviewContent.classList.add('gl-hidden');
if (reviewError) reviewError.classList.add('gl-hidden');
// Create login prompt if it doesn't exist (replace legacy Google-only prompt)
let loginPrompt = document.getElementById('review-login-prompt');
if (loginPrompt && loginPrompt.dataset.signinFlow !== 'portal-v2') {
loginPrompt.remove();
loginPrompt = null;
}
if (!loginPrompt) {
loginPrompt = document.createElement('div');
loginPrompt.id = 'review-login-prompt';
loginPrompt.dataset.signinFlow = 'portal-v2';
loginPrompt.className = 'gl-p-5 gl-text-center';
// Create the login message
const messageContainer = document.createElement('div');
messageContainer.className = 'gl-mb-5';
// Add user icon
const userIcon = document.createElement('div');
userIcon.className = 'thinkreview-login-icon';
userIcon.innerHTML = `
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM12 5C13.66 5 15 6.34 15 8C15 9.66 13.66 11 12 11C10.34 11 9 9.66 9 8C9 6.34 10.34 5 12 5ZM12 19.2C9.5 19.2 7.29 17.92 6 15.98C6.03 13.99 10 12.9 12 12.9C13.99 12.9 17.97 13.99 18 15.98C16.71 17.92 14.5 19.2 12 19.2Z" fill="#6b4fbb"/>
</svg>
`;
messageContainer.appendChild(userIcon);
// Add heading
const heading = document.createElement('h3');
heading.className = 'thinkreview-login-heading';
heading.textContent = 'Sign in to start generating reviews';
messageContainer.appendChild(heading);
const portalSignInUrl = 'https://portal.thinkreview.dev/signin-extension';
const description = document.createElement('p');
description.className = 'thinkreview-login-description';
description.innerHTML =
`Click the button below or open <a href="${portalSignInUrl}" target="_blank" rel="noopener noreferrer">${portalSignInUrl}</a>.`;
messageContainer.appendChild(description);
loginPrompt.appendChild(messageContainer);
// Create sign-in button container
const signInContainer = document.createElement('div');
signInContainer.id = 'gitlab-mr-signin-container';
signInContainer.className = 'thinkreview-signin-container';
const signInButton = document.createElement('button');
signInButton.type = 'button';
signInButton.className = 'thinkreview-signin-button';
signInButton.textContent = 'Signup / Sign in';
signInButton.addEventListener('click', () => {
dbgLog('Requesting background to open portal sign-in page');
signInButton.disabled = true;
const prevLabel = signInButton.textContent;
signInButton.textContent = 'Opening…';
chrome.runtime.sendMessage({ type: 'OPEN_SIGNIN_PORTAL' }, (response) => {
if (chrome.runtime.lastError) {
dbgWarn('Error opening portal sign-in:', chrome.runtime.lastError);
signInButton.disabled = false;
signInButton.textContent = prevLabel;
return;
}
if (!response || !response.success) {
dbgWarn('Portal sign-in open failed:', response && response.error);
signInButton.disabled = false;
signInButton.textContent = prevLabel;
return;
}
signInButton.textContent = prevLabel;
signInButton.disabled = false;
});
});
signInContainer.appendChild(signInButton);
const refreshHint = document.createElement('p');
refreshHint.className = 'thinkreview-login-description thinkreview-login-refresh-hint';
refreshHint.textContent = 'After signing in, refresh this page, then click the ThinkReview button.';
signInContainer.appendChild(refreshHint);
loginPrompt.appendChild(signInContainer);
// Add the login prompt to the panel
const cardBody = document.querySelector('#gitlab-mr-integrated-review .thinkreview-card-body');
if (cardBody) {
cardBody.appendChild(loginPrompt);
}
}
// Show the login prompt
loginPrompt.classList.remove('gl-hidden');
}
/**
* Shows an upgrade message in the integrated review panel
* @param {number} reviewCount - The number of reviews used today
* @param {number} dailyLimit - The daily review limit (optional, defaults to 3)
* @param {Object|null} limitOverride - Optional override for the limit title/body (e.g. for PR size errors).
* If provided, { title: string, body: string } will be used instead of the remote config / fallback values.
*/
async function showUpgradeMessage(reviewCount, dailyLimit = 3, limitOverride = null) {
// Stop the enhanced loader if it's running
if (typeof stopEnhancedLoader === 'function') {
stopEnhancedLoader();
}
const reviewLoading = document.getElementById('review-loading');
const reviewContent = document.getElementById('review-content');
const reviewError = document.getElementById('review-error');
const loginPrompt = document.getElementById('review-login-prompt');
// Hide loading indicator
if (reviewLoading) reviewLoading.classList.add('gl-hidden');
// Show content area
if (reviewContent) reviewContent.classList.remove('gl-hidden');
// Hide error area
if (reviewError) reviewError.classList.add('gl-hidden');
// Hide login prompt
if (loginPrompt) loginPrompt.classList.add('gl-hidden');
if (!reviewContent) return;
// Hide all existing review UI (tabs, sections, chat input) so only the
// upgrade message is visible and nothing remains interactive.
const tabsWrapper = reviewContent.querySelector('.thinkreview-tabs-wrapper');
const chatInputContainer = document.getElementById('chat-input-container');
if (tabsWrapper) tabsWrapper.classList.add('gl-hidden');
if (chatInputContainer) chatInputContainer.classList.add('gl-hidden');
// Remove a previously injected upgrade wrapper if the function is called again
const existingWrapper = document.getElementById('upgrade-message-wrapper');
if (existingWrapper) existingWrapper.remove();
// Create a dedicated full-panel upgrade container
const upgradeWrapper = document.createElement('div');
upgradeWrapper.id = 'upgrade-message-wrapper';
// Load subscription section styles
if (!document.getElementById('subscription-styles')) {
const linkEl = document.createElement('link');
linkEl.id = 'subscription-styles';
linkEl.rel = 'stylesheet';
linkEl.href = chrome.runtime.getURL('components/subscription-section.css');
document.head.appendChild(linkEl);
}
// Load and initialize upgrade tip banner module
const tipBannerModule = await import(chrome.runtime.getURL('components/helpful-tip-banner.js'));
tipBannerModule.injectStyles();
// Load subscription section HTML via background (avoids page CSP blocking fetch to chrome-extension://)
chrome.runtime.sendMessage(
{ type: 'GET_EXTENSION_RESOURCE', path: 'components/subscription-section.html' },
async (response) => {
if (chrome.runtime.lastError || !response?.success) {
dbgWarn('Error loading subscription section:', response?.error || chrome.runtime.lastError?.message);
return;
}
const fallbackConfig = {
prompt: {
limitTitle: 'Daily Review Limit Reached',
limitBody: "You've used {reviewCount} of {dailyLimit} free reviews today. Your limit resets daily - come back tomorrow for more reviews, or unlock unlimited reviews by upgrading now.",
title: 'Upgrade to one of our premium plans',
description: 'Get unlimited reviews, review larger PRs, choose your AI model, customize review rules, and more'
},
promotionalMessage: '',
plans: [
{
name: 'Lite',
interval: 'monthly',
price: 10,
period: 'month',
currency: 'USD',
ctaText: 'Choose Lite',
features: ['15 reviews per day', 'Bigger PR analysis', 'Lite flagship models'],
checkoutUrl: 'https://portal.thinkreview.dev/subscription',
hasDiscount: false
},
{
name: 'Professional',
interval: 'monthly',
price: 15,
period: 'month',
currency: 'USD',
ctaText: 'Choose Professional',
features: ['25 reviews per day', 'Premium AI models', 'Priority support'],
checkoutUrl: 'https://portal.thinkreview.dev/subscription',
hasDiscount: false
}
]
};
let upgradeConfig = fallbackConfig;
try {
const cloudModule = await import(chrome.runtime.getURL('services/cloud-service.js'));
const storageData = await new Promise((resolve) => {
chrome.storage.local.get(['userData', 'user'], resolve);
});
let email = storageData?.userData?.email || null;
if (!email && storageData?.user) {
try {
const parsedUser = JSON.parse(storageData.user);
email = parsedUser?.email || null;
} catch (parseError) {
dbgWarn('Failed to parse user data for upgrade config:', parseError);
}
}
if (email) {
const remoteConfig = await cloudModule.CloudService.getUpgradePromptConfig(email);
if (remoteConfig && Array.isArray(remoteConfig.plans) && remoteConfig.plans.length > 0) {
upgradeConfig = {
...fallbackConfig,
...remoteConfig,
prompt: {
...fallbackConfig.prompt,
...(remoteConfig.prompt || {})
}
};
}
}
} catch (configError) {
dbgWarn('Error fetching upgrade prompt config, using fallback:', configError);
}
const safeBody = limitOverride
? String(limitOverride.body)
: String(upgradeConfig.prompt.limitBody || fallbackConfig.prompt.limitBody)
.replace('{reviewCount}', String(reviewCount))
.replace('{dailyLimit}', String(dailyLimit));
const safeLimitTitle = limitOverride
? String(limitOverride.title)
: String(upgradeConfig.prompt.limitTitle || fallbackConfig.prompt.limitTitle);
const html = response.content;
upgradeWrapper.innerHTML = `
${tipBannerModule.getHTML()}
<div class="gl-alert gl-alert-warning">
<div class="gl-alert-content">
<div class="gl-alert-title" id="upgrade-limit-title"></div>
<div class="gl-mb-3" id="upgrade-limit-body"></div>
</div>
</div>
${html}
`;
const limitTitleEl = upgradeWrapper.querySelector('#upgrade-limit-title');
const limitBodyEl = upgradeWrapper.querySelector('#upgrade-limit-body');
if (limitTitleEl) limitTitleEl.textContent = safeLimitTitle;
if (limitBodyEl) limitBodyEl.textContent = safeBody;
const titleEl = upgradeWrapper.querySelector('#subscription-title');
const descriptionEl = upgradeWrapper.querySelector('#subscription-description');
if (titleEl) titleEl.textContent = upgradeConfig.prompt.title || fallbackConfig.prompt.title;
if (descriptionEl) descriptionEl.textContent = upgradeConfig.prompt.description || fallbackConfig.prompt.description;
const promotionEl = upgradeWrapper.querySelector('#subscription-promotion');
const promoText =
typeof upgradeConfig.promotionalMessage === 'string' ? upgradeConfig.promotionalMessage.trim() : '';
if (promotionEl) {
if (promoText) {
promotionEl.textContent = promoText;
promotionEl.classList.remove('gl-hidden');
} else {
promotionEl.textContent = '';
promotionEl.classList.add('gl-hidden');
}
}
const plans = Array.isArray(upgradeConfig.plans) ? upgradeConfig.plans.slice(0, 2) : fallbackConfig.plans;
const cards = upgradeWrapper.querySelectorAll('.subscription-plan-card');
cards.forEach((card, idx) => {
const plan = plans[idx];
if (!plan) {
card.classList.add('gl-hidden');
return;
}
const nameEl = card.querySelector('.plan-name');
const priceEl = card.querySelector('.plan-price');
const billedEl = card.querySelector('.plan-billed');
const taglineEl = card.querySelector('.plan-tagline');
const offerEl = card.querySelector('.plan-offer');
const featuresEl = card.querySelector('.plan-features');
const ctaBtn = card.querySelector('.upgrade-btn');
const period = plan.period || 'month';
const isAnnualInterval = String(plan.interval || '').toLowerCase() === 'annual';
const currency = plan.currency || 'USD';
const price = Number.isFinite(Number(plan.price)) ? Number(plan.price) : null;
const discountPercent = Number(plan.discountPercent || 0);
const showDiscountedPrice =
plan.hasDiscount &&
discountPercent > 0 &&
discountPercent < 100 &&
price !== null &&
price > 0;
if (nameEl) nameEl.textContent = plan.name || `Plan ${idx + 1}`;
if (priceEl) {