-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaiChatHelper.js
More file actions
1237 lines (1076 loc) · 39.2 KB
/
aiChatHelper.js
File metadata and controls
1237 lines (1076 loc) · 39.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
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
// AI Chat Helper - Injects Copus taste profile button into AI chatboxes
// Only activates when user is logged into Copus extension
const AI_PLATFORMS = {
chatgpt: {
hostnames: ['chat.openai.com', 'chatgpt.com'],
textareaSelector: '#prompt-textarea',
anchorButtonSelector: 'button[data-testid="send-button"], button[aria-label="Send prompt"], button[aria-label*="Send"]',
anchorPosition: 'right',
proximityFallback: false,
},
claude: {
hostnames: ['claude.ai'],
textareaSelector: 'div.ProseMirror[contenteditable="true"]',
anchorButtonSelector: 'button[aria-label="Send Message"], button[aria-label*="Send"], button[data-testid="send-button"]',
anchorPosition: 'right',
proximityFallback: false,
},
perplexity: {
hostnames: ['perplexity.ai', 'www.perplexity.ai'],
textareaSelector: 'textarea[placeholder*="Ask"], textarea, div[contenteditable="true"], div[role="textbox"]',
anchorButtonSelector: 'button[aria-label="Submit"], button[aria-label="Send"], form button[type="submit"]',
anchorPosition: 'right',
},
deepseek: {
hostnames: ['chat.deepseek.com'],
textareaSelector: 'textarea#chat-input, textarea',
anchorButtonSelector: 'button[aria-label*="send" i], div[id*="input" i] button:last-of-type, div[class*="input" i] button:last-of-type',
anchorPosition: 'right',
},
gemini: {
hostnames: ['gemini.google.com'],
textareaSelector: 'rich-textarea .ql-editor, div[contenteditable="true"]',
anchorButtonSelector: 'button[aria-label*="Send" i], .send-button',
anchorPosition: 'right',
},
grok: {
hostnames: ['grok.com'],
textareaSelector: 'div[contenteditable="true"], textarea[aria-label="Ask Grok anything"], textarea[placeholder="Ask anything"]',
anchorButtonSelector: 'button[aria-label="Submit"], button[aria-label="Send message"], button[data-testid="send-button"]',
anchorPosition: 'right',
},
mistral: {
hostnames: ['chat.mistral.ai'],
textareaSelector: 'div.ProseMirror[contenteditable="true"], textarea[placeholder="Ask Le Chat anything"], textarea',
anchorButtonSelector: 'button[type="submit"], button.bg-state-primary',
anchorPosition: 'right',
},
huggingchat: {
hostnames: ['huggingface.co'],
textareaSelector: 'textarea',
anchorButtonSelector: 'button[type="submit"][aria-label="Send message"], button[type="submit"]',
anchorPosition: 'right',
}
};
const COPUS_BUTTON_ID = 'copus-taste-profile-btn';
const COPUS_BUTTON_STYLES_ID = 'copus-taste-profile-styles';
const COPUS_MENU_ID = 'copus-taste-profile-menu';
const COPUS_RESTORE_PILL_ID = 'copus-restore-pill';
const MIN_CURATIONS_THRESHOLD = 10;
let currentPlatform = null;
let userNamespace = null; // Cached namespace
let userUuid = null; // Cached user uuid for private taste URL
let userCurationCount = null; // Cached curation count from taste profile
let injectionAttempts = 0;
const MAX_INJECTION_ATTEMPTS = 30; // 15 seconds with 500ms intervals
let hiddenForSession = false; // Hide until page refresh
let isHiding = false; // Flag to prevent race conditions during hide
let isInjecting = false; // Flag to prevent concurrent injections
// Check if button is hidden for current site
async function isHiddenForSite() {
return new Promise((resolve) => {
try {
const hostname = window.location.hostname;
chrome.storage.local.get(['copus_hidden_sites'], (result) => {
if (chrome.runtime.lastError) {
resolve(false);
return;
}
const hiddenSites = result.copus_hidden_sites || [];
resolve(hiddenSites.includes(hostname));
});
} catch (e) {
resolve(false);
}
});
}
// Hide button for current site (persistent)
async function hideForSite() {
isHiding = true; // Prevent mutation observer from re-injecting
const hostname = window.location.hostname;
try {
chrome.storage.local.get(['copus_hidden_sites'], (result) => {
const hiddenSites = result.copus_hidden_sites || [];
if (!hiddenSites.includes(hostname)) {
hiddenSites.push(hostname);
chrome.storage.local.set({ copus_hidden_sites: hiddenSites });
}
});
} catch (e) {
console.warn('[Copus AI Helper] Could not save hidden site:', e);
}
removeButton();
showRestorePill();
// Keep isHiding true - site is persistently hidden
}
// Show button for current site (remove from hidden list)
async function showForSite() {
isHiding = false;
const hostname = window.location.hostname;
try {
chrome.storage.local.get(['copus_hidden_sites'], (result) => {
const hiddenSites = result.copus_hidden_sites || [];
const index = hiddenSites.indexOf(hostname);
if (index > -1) {
hiddenSites.splice(index, 1);
chrome.storage.local.set({ copus_hidden_sites: hiddenSites });
}
});
} catch (e) {
console.warn('[Copus AI Helper] Could not update hidden sites:', e);
}
hiddenForSession = false;
hideRestorePill();
injectionAttempts = 0;
injectButton();
}
// Hide button for this session only
function hideForSession() {
isHiding = true; // Prevent mutation observer from re-injecting
hiddenForSession = true;
removeButton();
showRestorePill();
}
// Remove button and menu from DOM
function removeButton() {
const button = document.getElementById(COPUS_BUTTON_ID);
const tooltip = document.getElementById(COPUS_BUTTON_ID + '-tooltip');
const menu = document.getElementById(COPUS_MENU_ID);
if (button) button.remove();
if (tooltip) tooltip.remove();
if (menu) menu.remove();
}
// Create and show the restore pill
let pillFadeTimeout = null;
let pillHideTimeout = null;
function showRestorePill() {
// Remove existing pill if any
const existingPill = document.getElementById(COPUS_RESTORE_PILL_ID);
if (existingPill) existingPill.remove();
const pill = document.createElement('div');
pill.id = COPUS_RESTORE_PILL_ID;
// Taste profile icon - full size
const iconUrl = chrome.runtime.getURL('taste-icon.png');
pill.innerHTML = `<div style="width: 28px; height: 28px; border-radius: 50%; overflow: hidden;">
<img src="${iconUrl}" style="width: 100%; height: 100%; object-fit: cover;" />
</div>`;
// Click to restore button
pill.addEventListener('click', async () => {
hideRestorePill();
hiddenForSession = false;
await showForSite();
});
// Hover resets fade timers
pill.addEventListener('mouseenter', () => {
if (pillFadeTimeout) clearTimeout(pillFadeTimeout);
if (pillHideTimeout) clearTimeout(pillHideTimeout);
pill.classList.remove('copus-pill-fading', 'copus-pill-hidden');
});
pill.addEventListener('mouseleave', () => {
startPillFade(pill);
});
document.body.appendChild(pill);
// Start fade after 5 seconds
startPillFade(pill);
}
function startPillFade(pill) {
// Clear existing timers
if (pillFadeTimeout) clearTimeout(pillFadeTimeout);
if (pillHideTimeout) clearTimeout(pillHideTimeout);
// Fade to subtle after 4 seconds
pillFadeTimeout = setTimeout(() => {
pill.classList.add('copus-pill-fading');
}, 4000);
// Hide completely after 8 seconds
pillHideTimeout = setTimeout(() => {
pill.classList.add('copus-pill-hidden');
}, 8000);
}
function hideRestorePill() {
const pill = document.getElementById(COPUS_RESTORE_PILL_ID);
if (pill) pill.remove();
if (pillFadeTimeout) clearTimeout(pillFadeTimeout);
if (pillHideTimeout) clearTimeout(pillHideTimeout);
}
// Re-show pill when page regains focus (if button is hidden)
function setupPillFocusListener() {
window.addEventListener('focus', async () => {
// Only show pill if button is actually hidden
const button = document.getElementById(COPUS_BUTTON_ID);
if (button) return; // Button exists, no need for pill
const siteHidden = await isHiddenForSite();
if (hiddenForSession || siteHidden) {
const existingPill = document.getElementById(COPUS_RESTORE_PILL_ID);
if (existingPill) {
// Reset fade state
existingPill.classList.remove('copus-pill-fading', 'copus-pill-hidden');
startPillFade(existingPill);
} else {
showRestorePill();
}
}
});
}
// Detect which AI platform we're on
function detectPlatform() {
const hostname = window.location.hostname;
for (const [name, config] of Object.entries(AI_PLATFORMS)) {
if (config.hostnames.some(h => hostname.includes(h))) {
return { name, config };
}
}
return null;
}
// Get the logged-in user's namespace and uuid from extension storage
async function getUserNamespace() {
return new Promise((resolve) => {
try {
chrome.storage.local.get(['copus_token', 'copus_user'], (result) => {
if (chrome.runtime.lastError) {
console.warn('[Copus AI Helper] Storage error:', chrome.runtime.lastError);
resolve(null);
return;
}
// Must have both token and user to be considered logged in
if (result.copus_token && result.copus_user && result.copus_user.namespace) {
// Also cache uuid if available in stored user data
if (result.copus_user.uuid) {
userUuid = result.copus_user.uuid;
}
resolve(result.copus_user.namespace);
} else {
resolve(null);
}
});
} catch (e) {
console.warn('[Copus AI Helper] Failed to access storage:', e);
resolve(null);
}
});
}
// Validate the token and fetch public article count + uuid from user info API
// Returns { valid: boolean, publicArticleCount: number | null, uuid: string | null }
async function validateToken(namespace) {
return new Promise((resolve) => {
try {
chrome.storage.local.get(['copus_token'], async (result) => {
if (chrome.runtime.lastError || !result.copus_token) {
resolve({ valid: false, publicArticleCount: null, uuid: null });
return;
}
try {
const response = await fetch(`https://api-prod.copus.network/client/userHome/userInfo?namespace=${encodeURIComponent(namespace)}`, {
headers: { 'Authorization': `Bearer ${result.copus_token}` }
});
if (response.ok) {
const data = await response.json();
const count = data?.data?.statistics?.publicArticleCount ?? null;
const uuid = data?.data?.uuid ?? null;
// Persist uuid in copus_user storage for future use
if (uuid) {
chrome.storage.local.get(['copus_user'], (r) => {
if (r.copus_user && !r.copus_user.uuid) {
chrome.storage.local.set({ copus_user: { ...r.copus_user, uuid } });
}
});
}
resolve({ valid: true, publicArticleCount: count, uuid });
} else if (response.status === 401 || response.status === 403) {
resolve({ valid: false, publicArticleCount: null, uuid: null });
} else {
console.warn('[Copus AI Helper] Token check got status', response.status, '— assuming valid');
resolve({ valid: true, publicArticleCount: null, uuid: null });
}
} catch (e) {
console.warn('[Copus AI Helper] Token validation error:', e, '— assuming valid');
resolve({ valid: true, publicArticleCount: null, uuid: null });
}
});
} catch (e) {
resolve({ valid: true, publicArticleCount: null, uuid: null }); // Can't check — don't block
}
});
}
// Check if user is logged into Copus
async function isUserLoggedIn() {
return new Promise((resolve) => {
// Timeout after 3 seconds to prevent hanging
const timeout = setTimeout(() => {
console.warn('[Copus AI Helper] Storage check timed out');
resolve(false);
}, 3000);
try {
chrome.storage.local.get(['copus_token', 'copus_user'], (result) => {
clearTimeout(timeout);
if (chrome.runtime.lastError) {
console.warn('[Copus AI Helper] Storage error:', chrome.runtime.lastError);
resolve(false);
return;
}
resolve(!!result.copus_token);
});
} catch (e) {
clearTimeout(timeout);
console.warn('[Copus AI Helper] Failed to access storage:', e);
resolve(false);
}
});
}
// Find the chatbox element
function findChatbox() {
const selectors = currentPlatform.config.textareaSelector.split(', ');
for (const selector of selectors) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (isElementVisible(element)) {
return element;
}
}
}
return null;
}
// Find the anchor button (send button for all platforms)
// First tries platform-specific selectors, then falls back to proximity-based search
function findAnchorButton(chatbox) {
const chatboxRect = chatbox ? chatbox.getBoundingClientRect() : null;
// Try platform-specific selectors
const useProximityCheck = currentPlatform.config.proximityFallback !== false;
const selectors = currentPlatform.config.anchorButtonSelector.split(', ');
for (const selector of selectors) {
try {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (!isElementVisible(element)) continue;
// For platforms with unreliable selectors, validate proximity to chatbox
if (useProximityCheck && chatboxRect) {
const rect = element.getBoundingClientRect();
const vertDist = Math.abs(rect.bottom - chatboxRect.bottom);
if (vertDist > 150) continue;
}
return element;
}
} catch (e) {
continue;
}
}
// Fallback: find the nearest small button to the right of the chatbox
// Only for platforms without reliable selectors
if (chatboxRect && currentPlatform.config.proximityFallback !== false) {
return findNearbyButton(chatboxRect);
}
return null;
}
// Proximity-based fallback: find a likely send/submit button near the chatbox
function findNearbyButton(chatboxRect) {
// Search all buttons on the page
const buttons = document.querySelectorAll('button');
let bestButton = null;
let bestScore = Infinity;
for (const btn of buttons) {
if (btn.id === COPUS_BUTTON_ID) continue;
if (!isElementVisible(btn)) continue;
const rect = btn.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) continue;
// Must be a small-ish button (icon button, not a large text button)
if (rect.width > 70 || rect.height > 70) continue;
// Must be to the right half of the chatbox area
if (rect.left < chatboxRect.left + chatboxRect.width * 0.5) continue;
// Must be vertically close to the chatbox bottom (within 120px)
const vertDist = Math.abs(rect.bottom - chatboxRect.bottom);
if (vertDist > 120) continue;
// Score: prefer buttons closest to the bottom-right of the chatbox
const horizDist = Math.abs(rect.right - chatboxRect.right);
const score = horizDist + vertDist * 2;
if (score < bestScore) {
bestScore = score;
bestButton = btn;
}
}
return bestButton;
}
// Check if element is visible
function isElementVisible(element) {
if (!element) return false;
const rect = element.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = window.getComputedStyle(element);
return style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0';
}
// Inject the Copus button styles
function injectStyles() {
if (document.getElementById(COPUS_BUTTON_STYLES_ID)) return;
const style = document.createElement('style');
style.id = COPUS_BUTTON_STYLES_ID;
style.textContent = `
#${COPUS_BUTTON_ID} {
position: fixed !important;
z-index: 2147483647 !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
width: 32px !important;
height: 32px !important;
border-radius: 50% !important;
background: transparent !important;
border: 1px solid #F23A00 !important;
cursor: pointer !important;
box-shadow: none !important;
transition: all 0.2s ease !important;
padding: 0 !important;
margin: 0 !important;
outline: none !important;
overflow: hidden !important;
}
#${COPUS_BUTTON_ID}:hover {
transform: scale(1.1) !important;
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.2) !important;
}
#${COPUS_BUTTON_ID}:active {
transform: scale(0.95) !important;
}
#${COPUS_BUTTON_ID} svg {
width: 32px !important;
height: 32px !important;
pointer-events: none !important;
}
#${COPUS_BUTTON_ID}-tooltip {
position: fixed !important;
z-index: 2147483647 !important;
background: #333 !important;
color: white !important;
padding: 8px 12px !important;
border-radius: 8px !important;
font-size: 13px !important;
font-weight: 500 !important;
white-space: nowrap !important;
pointer-events: none !important;
opacity: 0 !important;
transition: opacity 0.2s ease !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important;
}
#${COPUS_BUTTON_ID}-tooltip.visible {
opacity: 1 !important;
}
#${COPUS_BUTTON_ID}.copus-not-logged-in {
opacity: 0.5 !important;
filter: grayscale(100%) !important;
}
#${COPUS_BUTTON_ID}.copus-not-logged-in:hover {
opacity: 0.8 !important;
filter: grayscale(0%) !important;
}
#${COPUS_BUTTON_ID}.copus-insufficient-curations {
opacity: 0.6 !important;
filter: none !important;
}
#${COPUS_BUTTON_ID}.copus-insufficient-curations:hover {
opacity: 1 !important;
filter: none !important;
}
@keyframes copusSuccessPulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
#${COPUS_BUTTON_ID}.copus-success {
animation: copusSuccessPulse 0.3s ease !important;
}
/* Hide/Show Menu */
#${COPUS_MENU_ID} {
position: fixed !important;
z-index: 2147483647 !important;
background: white !important;
border-radius: 8px !important;
box-shadow: 0 4px 20px rgba(0,0,0,0.15) !important;
padding: 4px 0 !important;
min-width: 180px !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
display: none;
}
#${COPUS_MENU_ID}.visible {
display: block !important;
}
#${COPUS_MENU_ID} .copus-menu-item {
display: flex !important;
align-items: center !important;
padding: 10px 14px !important;
cursor: pointer !important;
font-size: 13px !important;
color: #333 !important;
transition: background 0.15s ease !important;
border: none !important;
background: none !important;
width: 100% !important;
text-align: left !important;
}
#${COPUS_MENU_ID} .copus-menu-item:hover {
background: #f5f5f5 !important;
}
#${COPUS_MENU_ID} .copus-menu-item svg {
margin-right: 10px !important;
flex-shrink: 0 !important;
}
#${COPUS_MENU_ID} .copus-menu-divider {
height: 1px !important;
background: #eee !important;
margin: 4px 0 !important;
}
#${COPUS_MENU_ID} .copus-menu-header {
padding: 8px 14px !important;
font-size: 11px !important;
color: #888 !important;
text-transform: uppercase !important;
letter-spacing: 0.5px !important;
}
/* Restore Pill - shows when button is hidden */
#${COPUS_RESTORE_PILL_ID} {
position: fixed !important;
z-index: 2147483647 !important;
bottom: 20px !important;
right: 20px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
width: 28px !important;
height: 28px !important;
padding: 0 !important;
background: transparent !important;
border: none !important;
border-radius: 50% !important;
cursor: pointer !important;
box-shadow: 0 2px 6px rgba(0,0,0,0.15) !important;
transition: all 0.3s ease !important;
opacity: 0.4 !important;
overflow: hidden !important;
}
#${COPUS_RESTORE_PILL_ID}:hover {
opacity: 1 !important;
transform: scale(1.15) !important;
box-shadow: 0 3px 10px rgba(0,0,0,0.2) !important;
}
#${COPUS_RESTORE_PILL_ID} svg {
width: 28px !important;
height: 28px !important;
}
#${COPUS_RESTORE_PILL_ID}.copus-pill-fading {
opacity: 0.3 !important;
}
#${COPUS_RESTORE_PILL_ID}.copus-pill-hidden {
opacity: 0 !important;
pointer-events: none !important;
}
`;
document.head.appendChild(style);
}
// Create the hide/show menu
function createMenu() {
const menu = document.createElement('div');
menu.id = COPUS_MENU_ID;
menu.innerHTML = `
<div class="copus-menu-header">TASTE GRAPH</div>
<button class="copus-menu-item" data-action="hide-session">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
<line x1="1" y1="1" x2="23" y2="23"/>
</svg>
Hide for this session
</button>
<button class="copus-menu-item" data-action="hide-site">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
</svg>
Hide on this site
</button>
<div class="copus-menu-divider"></div>
<button class="copus-menu-item" data-action="open-copus">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f23a00" stroke-width="2">
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
<polyline points="15 3 21 3 21 9"/>
<line x1="10" y1="14" x2="21" y2="3"/>
</svg>
Open Copus
</button>
`;
// Handle menu item clicks
menu.addEventListener('click', (e) => {
const item = e.target.closest('.copus-menu-item');
if (!item) return;
const action = item.dataset.action;
menu.classList.remove('visible');
switch (action) {
case 'hide-session':
hideForSession();
break;
case 'hide-site':
hideForSite();
break;
case 'open-copus':
window.open('https://copus.network', '_blank');
break;
}
});
// Close menu when clicking outside
document.addEventListener('click', (e) => {
if (!menu.contains(e.target) && e.target.id !== COPUS_BUTTON_ID) {
menu.classList.remove('visible');
}
});
return menu;
}
// Position the menu near the button
function positionMenu(menu, button) {
const btnRect = button.getBoundingClientRect();
const menuWidth = 180;
const menuHeight = 140; // Approximate menu height
// Position above the button, with bottom-left corner near button
let left = btnRect.left;
let top = btnRect.top - menuHeight - 8;
// If menu would go off-screen left, align to button's right edge
if (left + menuWidth > window.innerWidth - 10) {
left = btnRect.right - menuWidth;
}
if (left < 10) left = 10;
// If not enough space above, show below
if (top < 10) {
top = btnRect.bottom + 8;
}
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
menu.style.transform = 'none';
}
// Create the Copus button
function createButton(isLoggedIn, curationCount) {
const hasSufficientCurations = curationCount === -1 || curationCount >= MIN_CURATIONS_THRESHOLD;
const button = document.createElement('button');
button.id = COPUS_BUTTON_ID;
button.type = 'button';
button.setAttribute('aria-label', 'Add Copus taste profile');
if (!isLoggedIn) {
button.classList.add('copus-not-logged-in');
} else if (!hasSufficientCurations) {
button.classList.add('copus-insufficient-curations');
}
// Taste profile icon - full size
const iconUrl = chrome.runtime.getURL('taste-icon.png');
button.innerHTML = `<img src="${iconUrl}" style="width: 22px; height: 22px; object-fit: contain; margin-top: 3px;" />`;
// Create tooltip
const tooltip = document.createElement('div');
tooltip.id = COPUS_BUTTON_ID + '-tooltip';
if (!isLoggedIn) {
tooltip.textContent = 'Log in to activate your taste profile';
} else if (!hasSufficientCurations) {
tooltip.textContent = 'Curate or collect 10 public pieces to unlock your taste profile';
} else {
tooltip.textContent = 'Add my taste profile';
}
// Create menu
const menu = createMenu();
return { button, tooltip, menu };
}
// Get text content from chatbox (handles both textarea and contenteditable)
function getChatboxText(chatbox) {
if (chatbox.tagName === 'TEXTAREA' || chatbox.tagName === 'INPUT') {
return chatbox.value;
}
// For contenteditable divs (like Claude.ai uses ProseMirror)
return chatbox.innerText || chatbox.textContent || '';
}
// Set text content in chatbox (handles both textarea and contenteditable)
function setChatboxText(chatbox, text) {
if (chatbox.tagName === 'TEXTAREA' || chatbox.tagName === 'INPUT') {
// For textareas
chatbox.focus();
chatbox.value = text;
chatbox.dispatchEvent(new Event('input', { bubbles: true }));
chatbox.dispatchEvent(new Event('change', { bubbles: true }));
} else {
// For contenteditable divs (ProseMirror, Lexical, Quill, etc.)
chatbox.focus();
// Select all existing content
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(chatbox);
selection.removeAllRanges();
selection.addRange(range);
// Try execCommand first — works with most editors
const inserted = document.execCommand('insertText', false, text);
if (!inserted) {
// Fallback: simulate paste event
const dt = new DataTransfer();
dt.setData('text/plain', text);
const pasteEvent = new ClipboardEvent('paste', {
bubbles: true,
cancelable: true,
clipboardData: dt
});
chatbox.dispatchEvent(pasteEvent);
}
}
}
// Handle button click - insert taste profile instruction
async function handleButtonClick(chatbox) {
const button = document.getElementById(COPUS_BUTTON_ID);
// Block if user hasn't curated enough
if (userNamespace && userCurationCount !== null && userCurationCount !== -1 && userCurationCount < MIN_CURATIONS_THRESHOLD) {
window.open(`https://copus.network/u/${userNamespace}`, '_blank');
return;
}
// Use cached namespace if available
if (userNamespace) {
insertTasteInstruction(chatbox, userNamespace, button);
return;
}
// No cached namespace, try to fetch from extension storage
try {
const namespace = await getUserNamespace();
if (namespace) {
userNamespace = namespace; // Cache it
insertTasteInstruction(chatbox, namespace, button);
return;
}
} catch (e) {
console.warn('[Copus AI Helper] Extension storage failed:', e);
// Extension context invalidated and no cached namespace
alert('Extension connection lost. Please refresh the page.');
return;
}
// Only redirect to login if storage worked but returned no namespace
window.open('https://copus.network/login', '_blank');
}
// Append text to a contenteditable editor by moving cursor to end and inserting
function appendToContentEditable(chatbox, text) {
chatbox.focus();
// Move cursor to the very end
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(chatbox);
range.collapse(false); // collapse to end
selection.removeAllRanges();
selection.addRange(range);
// Try execCommand first — works with most editors (Quill, ProseMirror, etc.)
const inserted = document.execCommand('insertText', false, text);
if (!inserted) {
// Fallback: simulate paste event (works with Lexical, Slate, etc.)
const dt = new DataTransfer();
dt.setData('text/plain', text);
const pasteEvent = new ClipboardEvent('paste', {
bubbles: true,
cancelable: true,
clipboardData: dt
});
chatbox.dispatchEvent(pasteEvent);
}
}
// Insert the taste profile instruction into the chatbox
function insertTasteInstruction(chatbox, namespace, button) {
// Always use private URL with key param — works regardless of public/private setting
const tasteUrl = userUuid
? `https://copus.network/api/taste/${namespace}.json?key=${userUuid}`
: `https://copus.network/api/taste/${namespace}.json`;
// Taste profile instruction — uses natural language to avoid content policy triggers
const tasteInstruction = `Please reference my taste profile at ${tasteUrl} to personalize your response. Use the curations, curation notes, and patterns in that data to understand my interests, and explain how your suggestions connect to my taste profile.`;
const currentText = getChatboxText(chatbox).trim();
const isContentEditable = chatbox.tagName !== 'TEXTAREA' && chatbox.tagName !== 'INPUT';
if (isContentEditable) {
// For rich text editors (Lexical, ProseMirror, etc.) — use paste simulation
const textToInsert = currentText ? `\n\n${tasteInstruction}` : `${tasteInstruction} `;
appendToContentEditable(chatbox, textToInsert);
} else {
// For textareas — use value setter
let newText;
if (currentText) {
newText = `${currentText}\n\n${tasteInstruction}`;
} else {
newText = tasteInstruction + ' ';
}
setChatboxText(chatbox, newText);
}
// Visual feedback
if (button) {
button.classList.add('copus-success');
setTimeout(() => {
button.classList.remove('copus-success');
}, 400);
}
}
// Find the input container (the rounded frame that contains textarea and buttons)
function findInputContainer(chatbox) {
let element = chatbox;
// Walk up to find a container with border-radius (the rounded frame)
for (let i = 0; i < 8 && element; i++) {
element = element.parentElement;
if (!element) break;
const style = window.getComputedStyle(element);
const borderRadius = parseFloat(style.borderRadius) || 0;
const rect = element.getBoundingClientRect();
// Look for a reasonably sized container with border-radius
if (borderRadius >= 10 && rect.width > 200 && rect.height > 40 && rect.height < 400) {
return element;
}
}
return null;
}
// Position the button outside the bottom-right corner of the input area
function positionButton(button, tooltip, chatbox) {
const buttonSize = 32;
const gap = 10;
// Find the input container (rounded frame) or fall back to chatbox
const container = findInputContainer(chatbox);
const rect = container ? container.getBoundingClientRect() : chatbox.getBoundingClientRect();
// Position outside the bottom-right corner of the container
let left = rect.right + gap;
let top = rect.bottom - buttonSize;
// Show button and position it
button.style.display = 'flex';
// Ensure button stays in viewport
left = Math.max(10, Math.min(left, window.innerWidth - buttonSize - 10));
top = Math.max(10, Math.min(top, window.innerHeight - buttonSize - 10));
button.style.left = `${left}px`;
button.style.top = `${top}px`;
// Position tooltip above button
tooltip.style.left = `${left + buttonSize / 2}px`;
tooltip.style.top = `${top - 10}px`;
tooltip.style.transform = 'translate(-50%, -100%)';
}
// Inject the button into the page
async function injectButton() {
// Prevent concurrent injections (race between setTimeout and MutationObserver)
if (isInjecting) return;
isInjecting = true;
try {
// Check if hidden for this session
if (hiddenForSession) {
return;
}
// Check if hidden for this site
const hiddenForSite = await isHiddenForSite();
if (hiddenForSite) {
return;
}
// Check if button already exists and is valid
const existingButton = document.getElementById(COPUS_BUTTON_ID);
const existingTooltip = document.getElementById(COPUS_BUTTON_ID + '-tooltip');
const existingMenu = document.getElementById(COPUS_MENU_ID);
const chatbox = findChatbox();
// If button exists and chatbox exists, just update position
if (existingButton && existingTooltip && chatbox) {
positionButton(existingButton, existingTooltip, chatbox);
return;
}
// Remove stale elements if chatbox changed
if (existingButton) existingButton.remove();
if (existingTooltip) existingTooltip.remove();
if (existingMenu) existingMenu.remove();
if (!chatbox) {
injectionAttempts++;
if (injectionAttempts < MAX_INJECTION_ATTEMPTS) {
setTimeout(() => injectButton(), 500);
} else {
}
return;
}
// Inject styles first (don't wait for storage)