-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
4086 lines (3811 loc) · 163 KB
/
Copy pathcontent.js
File metadata and controls
4086 lines (3811 loc) · 163 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
(function () {
const FRAME_ID = "shiki-docs-skin-frame";
const STYLE_ID = "shiki-docs-skin-style";
const HOST_SOURCE = "shiki-host";
const SKIN_SOURCE = "shiki-docs-skin";
const STORAGE_KEY = "shikiDocsSkinEnabled";
const PROFILE_KEY = "shikiProfileImage";
const RICH_KEY = "shikiRichFormatting";
const IMAGE_CONTROL_KEY = "shikiImageControl";
const CAPABILITIES_KEY = "shikiDetectedCapabilities";
const NATIVE_CONTROL_MASK_CLASS = "shiki-native-control-suppressed";
const SYNC_INTERVAL_MS = 1500;
const CAPABILITY_REFRESH_MS = 5 * 60 * 1000;
const ROUTE_WATCH_MS = 1500;
const SKIN_ORIGIN = new URL(chrome.runtime.getURL("index.html")).origin;
const ADAPTERS = globalThis.ShikiProviderAdapters || null;
const EXTENSION_VERSION = chrome.runtime.getManifest().version;
const CAPABILITY_SCHEMA_VERSION = ADAPTERS?.CAPABILITY_SCHEMA_VERSION || 1;
// Capability snapshots are per-browser-session performance hints, so they
// live in chrome.storage.session when available (cleared when Chrome exits;
// the background script grants content scripts access). storage.local is the
// fallback for older Chrome builds only.
const capabilityStorage = chrome.storage.session || chrome.storage.local;
// Routes on supported hosts where Shiki must not inject or scan: sign-in,
// consent, onboarding, legal, checkout, and share-view pages. The chat app
// itself stays fully supported.
const BLOCKED_ROUTE_PATTERN = /^\/(?:login|log-in|signin|sign-in|signup|sign-up|register|auth(?:orize)?|oauth|sso|magic-link|onboarding|welcome|consent|terms|tos|privacy|legal|policies|pricing|plans|upgrade|billing|checkout|payment|subscribe|careers|blog|press|about|help|support|docs|status)(?:\/|$)/i;
function isSupportedRoute(pathname = location.pathname) {
return !BLOCKED_ROUTE_PATTERN.test(String(pathname || "/"));
}
// Coarse route family used to key/invalidate capability caches: the first
// path segment groups "/", "/c/…", "/chat/…", "/search/…" style app areas.
function routeFamily(pathname = location.pathname) {
const segment = String(pathname || "/").split("/").filter(Boolean)[0] || "root";
return segment.toLowerCase();
}
// Development diagnostics for the capability cache (surfaced in the popup's
// diagnostics section; in-memory only, never persisted).
const cacheStats = { hits: 0, misses: 0, invalidations: 0, lastScanDurationMs: 0 };
// The content script now runs at document_end (not document_idle) so the
// workspace appears as soon as the DOM exists. Provider apps hydrate their
// controls afterwards, so early scans that find no trigger retry with
// backoff instead of caching a false "unavailable" for the whole TTL.
const PAGE_START = Date.now();
let earlyScanRetries = 0;
let routeHydrationStartedAt = PAGE_START;
const PROVIDERS = {
"chatgpt.com": {
name: "ChatGPT",
defaultModel: { id: "gpt-5.6-sol", label: "GPT-5.6 Sol" },
conversationPatterns: ["/c/"],
conversationSelectors: ['a[href*="/c/"]']
},
"chat.openai.com": {
name: "ChatGPT",
defaultModel: { id: "gpt-5.6-sol", label: "GPT-5.6 Sol" },
conversationPatterns: ["/c/"],
conversationSelectors: ['a[href*="/c/"]']
},
"claude.ai": {
name: "Claude",
defaultModel: { id: "sonnet-5", label: "Sonnet 5" },
conversationPatterns: ["/chat/"],
conversationSelectors: ['a[href*="/chat/"]']
},
"gemini.google.com": {
name: "Gemini",
defaultModel: { id: "gemini-3.1-flash-lite", label: "Gemini 3.1 Flash-Lite" },
conversationPatterns: ["/app/"],
conversationSelectors: ['a[href*="/app/"]']
},
"grok.com": {
name: "Grok",
defaultModel: { id: "grok", label: "Grok" },
conversationPatterns: ["/c/", "/chat/"],
conversationSelectors: ['a[href*="/c/"]', 'a[href*="/chat/"]']
},
"chat.deepseek.com": {
name: "DeepSeek",
defaultModel: { id: "deepseek", label: "DeepSeek" },
conversationPatterns: ["/a/chat/s/", "/chat/s/"],
conversationSelectors: ['a[href*="/a/chat/s/"]', 'a[href*="/chat/s/"]']
},
"copilot.microsoft.com": {
name: "Copilot",
defaultModel: { id: "copilot", label: "Copilot" },
conversationPatterns: ["/chats/", "/chat/"],
conversationSelectors: ['a[href*="/chats/"]', 'a[href*="/chat/"]']
},
"www.perplexity.ai": {
name: "Perplexity",
defaultModel: { id: "best", label: "Best" },
conversationPatterns: ["/search/", "/page/"],
conversationSelectors: ['a[href*="/search/"]', 'a[href*="/page/"]']
},
"www.meta.ai": {
name: "Meta AI",
defaultModel: { id: "muse-spark", label: "Muse Spark" },
conversationPatterns: ["/c/", "/chat/"],
conversationSelectors: ['a[href*="/c/"]', 'a[href*="/chat/"]']
},
"meta.ai": {
name: "Meta AI",
defaultModel: { id: "muse-spark", label: "Muse Spark" },
conversationPatterns: ["/c/", "/chat/"],
conversationSelectors: ['a[href*="/c/"]', 'a[href*="/chat/"]']
},
"character.ai": {
name: "Character.AI",
defaultModel: { id: "character", label: "Character" },
conversationPatterns: ["/chat/"],
conversationSelectors: ['a[href*="/chat/"]']
},
"poe.com": {
name: "Poe",
defaultModel: { id: "assistant", label: "Assistant" },
conversationPatterns: ["/chat/"],
conversationSelectors: ['a[href*="/chat/"]']
},
"pi.ai": {
name: "Pi",
defaultModel: { id: "pi", label: "Pi" },
conversationPatterns: ["/talk/", "/chat/"],
conversationSelectors: ['a[href*="/talk/"]', 'a[href*="/chat/"]']
},
"hey.pi.ai": {
name: "Pi",
defaultModel: { id: "pi", label: "Pi" },
conversationPatterns: ["/talk/", "/chat/"],
conversationSelectors: ['a[href*="/talk/"]', 'a[href*="/chat/"]']
},
"chat.mistral.ai": {
name: "Vibe",
defaultModel: { id: "vibe", label: "Vibe" },
conversationPatterns: ["/chat/"],
conversationSelectors: ['a[href*="/chat/"]']
},
"chat.qwen.ai": {
name: "Qwen",
defaultModel: { id: "qwen3.7-plus", label: "Qwen3.7-Plus" },
conversationPatterns: ["/c/", "/chat/"],
conversationSelectors: ['a[href*="/c/"]', 'a[href*="/chat/"]']
},
"www.kimi.com": {
name: "Kimi",
defaultModel: { id: "kimi-k2.6", label: "K2.6" },
conversationPatterns: ["/chat/", "/c/"],
conversationSelectors: ['a[href*="/chat/"]', 'a[href*="/c/"]']
}
};
let frame = null;
let enabled = true;
let voicePassthrough = false;
let syncTimer = 0;
let profileImage = "";
// When on, assistant turns are reverse-engineered from the host's rendered
// markdown into a structured AST (see extractBlocks) so the skin can show
// headings/lists/code/etc. Toggled from the popup; persisted in storage.
let richFormatting = true;
let imageControl = "composer";
let historyLoading = false;
let historyHasMore = true;
// Sidebar (conversation list) lazy loading, mirrored to the skin.
let conversationsLoading = false;
let conversationsHasMore = true;
let detectedCapabilities = null;
let capabilityScanPromise = null;
let lastCapabilityScan = 0;
let capabilityErrorRetries = 0;
let lastFrameRemountAt = 0;
let frameRemountWindowStart = 0;
let frameRemountCount = 0;
let frameKeeperObserver = null;
let lastPostedState = null;
let nativeControlMaskDepth = 0;
// Cache of converted image sources (blob:/tainted -> data: URL). The cache is
// bounded because data URLs are base64-expanded strings and can otherwise pin a
// lot of tab memory in image-heavy chats.
const IMAGE_CACHE_MAX_ENTRIES = 24;
const IMAGE_CACHE_MAX_BYTES = 24 * 1024 * 1024;
const IMAGE_CACHE_MAX_ITEM_BYTES = 4 * 1024 * 1024;
const IMAGE_CONVERT_MAX_SOURCE_BYTES = 8 * 1024 * 1024;
const IMAGE_CONVERT_MAX_EDGE = 1600;
const IMAGE_CONVERT_MAX_PIXELS = 2560000;
const IMAGE_CONVERT_MAX_IN_FLIGHT = 6;
const IMAGE_CONVERT_TIMEOUT_MS = 10000;
const IMAGE_CONVERT_JPEG_QUALITY = 0.86;
const IMAGE_CACHE_MAX_DROPPED_SOURCES = 100;
const imageDataCache = new Map();
const imageDataCacheBytes = new Map();
const droppedImageSources = new Set();
const imageConverting = new Set();
let imageDataCacheTotalBytes = 0;
let imageCacheGeneration = 0;
// `imageCacheVersion` bumps when a conversion lands so memoized message blocks
// re-walk and pick it up.
let imageCacheVersion = 0;
function provider() {
const local = PROVIDERS[location.hostname] || {
name: "AI",
defaultModel: { id: "gpt-5.5", label: "GPT-5.5" },
conversationPatterns: [],
conversationSelectors: ["a[href]"]
};
const shared = ADAPTERS?.PROVIDERS?.[local.name];
return shared?.defaultModel ? { ...local, defaultModel: shared.defaultModel } : local;
}
function cleanText(value) {
return String(value || "")
.replace(/\s+/g, " ")
.replace(/\b(new chat|delete|archive|share|more|options)\b/gi, "")
.trim();
}
// Menu navigation words are meaningful capability evidence (notably Claude's
// "More models"). Keep them intact while normalizing only whitespace.
function surfaceOptionText(value) {
return String(value || "").replace(/\s+/g, " ").trim();
}
function absoluteHref(href) {
try {
return new URL(href, location.origin).href;
} catch {
return "";
}
}
// Stable conversation identity: canonical path with query/hash stripped, and
// provider-specific slug normalization (Perplexity retitles its slugs, which
// used to create one duplicate "Perplexity" row per title change).
function normalizeId(href, index) {
const url = absoluteHref(href);
if (!url) return `conversation-${index + 1}`;
if (ADAPTERS?.canonicalConversationId) {
return ADAPTERS.canonicalConversationId(provider().name, url) || `conversation-${index + 1}`;
}
return new URL(url).pathname || `conversation-${index + 1}`;
}
function titleFromDocument() {
const rawTitle = document.title
.replace(/\s*[-|]\s*(ChatGPT|Claude|Gemini|Grok|DeepSeek|Copilot|Perplexity|Meta AI|Character\.AI|Poe|Pi|Vibe|Mistral|Qwen|Kimi).*$/i, "")
.replace(/^ChatGPT\s*[-|]\s*/i, "");
return cleanText(rawTitle) || "Conversation Name";
}
function isConversationHref(href, config) {
const normalized = absoluteHref(href);
if (!normalized) return false;
return config.conversationPatterns.some((pattern) => normalized.includes(pattern));
}
function extractConversations() {
const config = provider();
const seen = new Set();
const anchors = config.conversationSelectors.flatMap((selector) => Array.from(document.querySelectorAll(selector)));
const conversations = [];
anchors.forEach((anchor, index) => {
const href = absoluteHref(anchor.getAttribute("href"));
if (!href || !isConversationHref(href, config)) return;
// De-duplicate by canonical conversation id, not raw href: the same
// thread can be linked with different query strings, hashes, or retitled
// slugs (Perplexity), which previously produced duplicate rows.
const id = normalizeId(href, index);
if (seen.has(id)) return;
const title = cleanText(anchor.textContent) || titleFromDocument();
if (!title || title.length < 2) return;
seen.add(id);
conversations.push({
id,
href,
title,
label: title
});
});
if (!conversations.length) {
conversations.push({
id: normalizeId(location.href, 0) || "current",
href: location.href,
title: titleFromDocument(),
label: "Tab 1"
});
}
// Surface everything the host currently has in its DOM (it lazy-loads its own
// sidebar, so this is however many it has rendered). The skin's list scrolls,
// so we don't need to keep them all on screen at once.
return conversations.slice(0, 200);
}
function extractActiveConversation(conversations) {
const exact = conversations.find((conversation) => conversation.href === location.href);
if (exact) return exact;
// Match by canonical id so query strings and retitled slugs still resolve
// to the already-listed row instead of a phantom duplicate.
const currentId = normalizeId(location.href, 0);
const idMatch = conversations.find((conversation) => conversation.id === currentId);
if (idMatch) return idMatch;
const currentPath = location.pathname;
const pathMatch = conversations.find((conversation) => {
try {
return new URL(conversation.href).pathname === currentPath;
} catch {
return false;
}
});
return pathMatch || conversations[0];
}
function modelSelectors() {
const host = location.hostname;
if (host.includes("chatgpt") || host.includes("openai")) {
// ChatGPT folds the model picker into the composer's effort pill: opening it
// shows the reasoning levels plus a current-model row that expands the model
// list. The pill carries no testid/aria-label, but its class is stable. Older
// top-bar switcher selectors are kept as fallbacks.
return ['button.__composer-pill', '[data-testid="model-switcher-dropdown-button"]', '[data-testid*="model-switcher" i]'];
}
if (host.includes("claude")) {
return ['[data-testid="model-selector-dropdown"]', 'button[aria-haspopup="listbox"]', 'button[aria-label*="model" i]'];
}
if (host.includes("gemini")) {
// Gemini's "mode picker" button (Material) is the trigger; its visible pill
// only shows an abbreviated name ("Flash-Lite"). The aria-label-based
// selectors target the real button; the pill div is a last-resort fallback.
return ['button[aria-label*="mode picker" i]', 'button[aria-label*="currently" i]', '.logo-pill-label-container'];
}
if (host.includes("grok")) {
return [
'button[aria-label*="model" i]:not([aria-label*="voice" i])',
'button[aria-label*="mode" i]:not([aria-label*="voice" i])',
'button[data-testid*="model" i]',
'button[data-testid*="mode" i]:not([data-testid*="voice" i])'
];
}
if (host.includes("deepseek")) {
return [
'button[aria-label*="model" i]:not([aria-label*="deepthink" i]):not([aria-label*="thinking" i])',
'button[aria-label*="mode" i]:not([aria-label*="deepthink" i]):not([aria-label*="thinking" i])',
'button[data-testid*="model" i]',
'button[data-testid*="mode" i]:not([data-testid*="deepthink" i]):not([data-testid*="thinking" i])',
'[class*="model" i] button',
'[class*="mode" i] button:not([aria-label*="deepthink" i]):not([aria-label*="thinking" i])'
];
}
if (host.includes("perplexity")) {
return [
'button[aria-label*="model" i]:not([aria-label*="voice" i])',
'button[aria-label*="mode" i]:not([aria-label*="voice" i])',
'button[data-testid*="model" i]',
'button[data-testid*="mode" i]:not([data-testid*="voice" i])'
];
}
if (host.includes("poe")) {
return ['button[aria-label*="bot" i]', 'button[aria-label*="model" i]', 'button[data-testid*="bot" i]', 'button[data-testid*="model" i]'];
}
if (host.includes("character")) {
return ['button[aria-label*="chat style" i]', 'button[aria-label*="model" i]', 'button[data-testid*="chat-style" i]', 'button[data-testid*="model" i]', '[class*="chat-style" i] button'];
}
if (host.includes("kimi")) {
// Kimi's model chip is a plain Vue div (no ARIA, no testid); the
// semantic class name is the only stable hook (verified 2026-07-18,
// shows e.g. "K2.6").
return [
'[role="button"][aria-label*="model" i]:not([aria-label*="voice" i])',
'button[aria-label*="model" i]:not([aria-label*="voice" i])',
'button[data-testid*="model" i]',
'.current-model',
'.chat-editor-action'
];
}
if (host.includes("mistral")) {
// Vibe's current Fast/Think/Research trigger has no aria-label or model/
// mode class. Its composer-row ancestor is the stable discriminator from
// settings and voice menus elsewhere on the page.
return [
'[class*="chat-input-row"] button[aria-haspopup="menu"]:not([aria-label*="voice" i])',
'button[aria-label*="mode" i]:not([aria-label*="voice" i]):not([aria-label*="live" i])',
'button[data-testid*="mode" i]:not([data-testid*="voice" i])'
];
}
if (host.includes("copilot") || host.includes("meta.ai") || host.includes("qwen")) {
// Voice/live controls also carry "mode" in their labels ("Voice Mode" on
// Vibe); they must never be treated as the model/mode picker. Custom
// comboboxes are often DIVs with button/combobox roles (Qwen's "Select
// Model" is one), so role-based selectors come before tag-based ones.
return [
'[role="button"][aria-label*="model" i]:not([aria-label*="voice" i])',
'[role="combobox"][aria-label*="model" i]',
'[aria-haspopup="listbox"][aria-label*="model" i]:not([aria-label*="voice" i])',
'button[aria-label*="model" i]:not([aria-label*="voice" i])',
'button[aria-label*="mode" i]:not([aria-label*="voice" i]):not([aria-label*="live" i])',
'button[data-testid*="model" i]',
'button[data-testid*="mode" i]:not([data-testid*="voice" i])',
'[class*="model" i] button:not([aria-label*="voice" i])',
'[class*="mode" i] button:not([aria-label*="voice" i])'
];
}
// Pi is a single-assistant experience without a consumer model picker.
return [];
}
// Providers with reasoning/mode choices generally expose them from the same
// picker as the model. The provider-specific navigation in switchEffort opens the right
// nested row before selecting a leaf, avoiding the old broad "thinking" click
// that could flip a toggle instead of selecting an effort.
function effortSelectors() {
const host = location.hostname;
if (host.includes("qwen")) {
// "Select Mode" opens Qwen's tools menu. The reasoning effort is a
// separate Ant combobox whose visible label contains the active value.
return ['.qwen-select-thinking-label', 'input[role="combobox"][aria-label="Thinking"]'];
}
if (host.includes("perplexity")) {
// Search workflows live in a second composer menu, separate from Model.
return ['button[aria-haspopup="menu"][aria-pressed]'];
}
return modelSelectors();
}
function inlinePrimaryControl() {
if (!location.hostname.includes("deepseek")) return null;
return Array.from(document.querySelectorAll('[role="radio"][data-model-type], [role="radio"][aria-checked]'))
.find((el) => isElementVisible(el)) || null;
}
function voiceSelectors() {
const host = location.hostname;
if (host.includes("chatgpt") || host.includes("openai")) {
return ['button[data-testid*="voice" i]', 'button[aria-label*="voice mode" i]', 'button[aria-label*="voice" i]'];
}
if (host.includes("claude")) {
return ['button[data-testid*="voice" i]', 'button[aria-label*="voice" i]', 'button[aria-label*="microphone" i]'];
}
if (host.includes("gemini")) {
return ['button[aria-label*="Gemini Live" i]', 'button[aria-label*="Live" i]', 'button[aria-label*="microphone" i]', 'button[aria-label*="voice" i]'];
}
if (host.includes("grok")) {
return ['button[data-testid*="voice" i]', 'button[aria-label*="voice" i]', 'button[aria-label*="talk" i]'];
}
if (host.includes("deepseek")) return [];
if (host.includes("meta.ai")) {
return ['button[aria-label*="voice" i]', 'button[aria-label*="talk" i]', 'button[data-testid*="voice" i]'];
}
if (host.includes("character")) {
return ['button[aria-label*="call" i]', 'button[aria-label*="voice" i]', 'button[data-testid*="call" i]'];
}
if (host === "pi.ai" || host === "hey.pi.ai") {
return ['button[aria-label*="voice" i]', 'button[aria-label*="talk" i]', 'button[aria-label*="microphone" i]'];
}
if (host.includes("copilot") || host.includes("poe") || host.includes("mistral") || host.includes("qwen") || host.includes("kimi")) {
return ['button[aria-label*="voice" i]', 'button[aria-label*="microphone" i]', 'button[data-testid*="voice" i]'];
}
return [];
}
function findVoiceControl() {
return voiceSelectors().map(safeQuery).find((el) => isElementVisible(el)) || null;
}
function extractModel() {
const config = provider();
const host = location.hostname;
// ChatGPT no longer shows the model name in a top-bar switcher: the composer
// pill shows the effort ("Instant") plus a model badge ("5.4") ONLY when a
// non-default model is picked. So read the badge; its absence means the default
// model. This is the only reliable closed-menu read for ChatGPT. Bare numbers
// must contain a dot ("5.4", "5.10") so counters/short digits in the pill
// can't false-positive; o-series and gpt-prefixed badges are matched whole.
if (host.includes("chatgpt") || host.includes("openai")) {
const pill = document.querySelector("button.__composer-pill");
if (pill) {
const badge = Array.from(pill.querySelectorAll("span"))
.map((s) => cleanText(s.textContent || "").trim())
.find((t) => /^(o\d+|\d+\.\d+(?:\s+(?:Sol|Terra|Luna))?|gpt[-\s]?\d[\w.]*(?:\s+(?:Sol|Terra|Luna))?)$/i.test(t));
if (badge) {
let label;
if (/^o\d+$/i.test(badge)) label = badge.toLowerCase();
else if (/^gpt/i.test(badge)) label = "GPT-" + badge.replace(/^gpt[-\s]?/i, "");
else label = "GPT-" + badge;
if (ADAPTERS?.resolveModelAlias) label = ADAPTERS.resolveModelAlias("ChatGPT", label);
return { id: label.toLowerCase().replace(/[^a-z0-9.]+/g, "-"), label };
}
return config.defaultModel;
}
}
// Gemini's collapsed pill shows an ABBREVIATED mode ("Flash-Lite"/"Flash"/
// "Pro") with no version, which the version-requiring regex can't match. The
// mode-picker button's aria-label ("…currently Flash") is the reliable source.
// If the label ever carries a versioned name (e.g. "currently 3.5 Flash"), use
// it directly; otherwise map the short name back to the full model label.
// NOTE: keep this map in step with the Gemini entries in skin.js
// PROVIDER_MODELS when Google renames or reversions models.
if (host.includes("gemini")) {
const btn = document.querySelector('button[aria-label*="mode picker" i]')
|| document.querySelector('button[aria-label*="currently" i]');
const m = btn && (btn.getAttribute("aria-label") || "").match(/currently\s+(.+)$/i);
if (m) {
const short = m[1].trim();
// Gemini's collapsed control omits version numbers. The July 2026
// consumer menu identifies the generic "Flash" row as Gemini 3.5 Flash.
const map = { "flash-lite": "Gemini 3.1 Flash-Lite", "flash": "Gemini 3.5 Flash", "pro": "Gemini 3.1 Pro" };
const label = /\d/.test(short) ? short : (map[short.toLowerCase()] || short);
return { id: label.toLowerCase().replace(/[^a-z0-9.]+/g, "-"), label };
}
}
// Recognise current provider model names: GPT-x / o-series / Instant x.x
// (ChatGPT), Fable/Opus/Sonnet/Haiku x.x (Claude), "x.x Flash-Lite/Flash/
// Pro" (Gemini), and third-party names on Perplexity. Mode names (Grok
// Fast/Auto/Expert/Heavy, DeepSeek Instant/Expert/Vision, Vibe Fast/Think/
// Research) are deliberately NOT model names and are read separately.
const modelPattern = /\b(GPT[-\s]?[\w.]+(?:\s+(?:Sol|Terra|Luna))?|Instant\s+\d(?:\.\d)+|o\d(?:[-\s]?\w+)?|Fable\s+[\w.]+|Opus\s+[\w.]+|Sonnet\s+[\w.]+|Haiku\s+[\w.]+|(?:Gemini\s+)?\d(?:\.\d)*\s+Flash(?:[-\s]Lite)?|(?:Gemini\s+)?\d(?:\.\d)*\s+Pro|Grok\s+\d(?:\.\d)*|DeepSeek[-\s]?V?\d(?:\.\d)*|Sonar(?:\s+\d(?:\.\d)*)?|GLM\s+\d(?:\.\d)*|Nemotron\s+\d(?:\s+Ultra)?|Muse\s+Spark|Dynamic|PipSqueak|Prime|Braniac|Brainiac|Flash|Goro|Pawly|Qwen\d(?:\.\d)*(?:[-\s](?:Max|Plus|Flash|Omni|Coder|VL|Preview|\d+B|A\d+B|\d{4}))*|(?:Kimi\s+)?K\d(?:\.\d)*(?:\s+Swarm)?)\b/i;
// Read only from the host's model-switcher control, not arbitrary page text.
for (const selector of modelSelectors()) {
const el = document.querySelector(selector);
const text = el && cleanText(el.innerText || el.textContent || "").slice(0, 80);
const match = text && text.match(modelPattern);
if (match) {
let label = cleanText(match[1]).replace(/\s+/g, " ");
if (/^Brainiac$/i.test(label)) label = "Braniac";
const accepted = ADAPTERS?.sanitizeModelLabels
? ADAPTERS.sanitizeModelLabels(config.name, [label])[0]
: label;
if (accepted) return { id: accepted.toLowerCase().replace(/[^a-z0-9.]+/g, "-"), label: accepted };
}
}
return config.defaultModel;
}
// Read reasoning/mode only from the closed provider picker. This avoids the
// old full-page text scan, which confused ordinary conversation words such as
// "high quality" for an active effort level. Operating modes (Grok, DeepSeek,
// Vibe, Copilot) are recognized separately from reasoning levels but share
// the same collapsed control.
function extractEffort() {
if (!ADAPTERS) return null;
const texts = [];
[...modelSelectors(), ...effortSelectors()].forEach((selector) => {
const el = safeQuery(selector);
if (!el || !isElementVisible(el)) return;
const text = cleanText(`${el.getAttribute("aria-label") || ""} ${el.textContent || ""}`).slice(0, 180);
if (text) texts.push(text);
});
if (location.hostname.includes("deepseek")) {
document.querySelectorAll('[role="radio"][aria-checked="true"]').forEach((el) => {
const text = cleanText(el.textContent || "").slice(0, 80);
if (text) texts.unshift(text);
});
}
const providerName = provider().name;
const efforts = ADAPTERS.recognizeEfforts(providerName, texts);
if (efforts.length) return { label: efforts[0], level: normOption(efforts[0]) };
const modes = ADAPTERS.recognizeModes ? ADAPTERS.recognizeModes(providerName, texts) : [];
return modes.length ? { label: modes[0], level: normOption(modes[0]), kind: "mode" } : null;
}
// While the model is replying, each host swaps its send button for a "stop"
// control. That's the most reliable cross-provider "is generating" signal, so
// we surface it to the skin to drive the thinking animation. Specific selectors
// first, then a guarded generic fallback for when a provider's DOM shifts.
function generatingSelectors() {
const host = location.hostname;
if (host.includes("chatgpt") || host.includes("openai")) {
return ['button[data-testid="stop-button"]', 'button[aria-label="Stop streaming"]', 'button[aria-label*="stop" i]'];
}
if (host.includes("claude")) {
return ['button[aria-label="Stop response"]', 'button[data-testid="stop-button"]', 'button[aria-label*="stop" i]'];
}
if (host.includes("gemini")) {
return ['button[aria-label*="stop" i]', 'button.stop', 'button.send-button.stop'];
}
if (host.includes("grok")) {
return ['button[aria-label*="stop" i]', 'button[data-testid*="stop" i]'];
}
if (host.includes("deepseek")) {
return ['button[aria-label*="stop" i]', 'button[data-testid*="stop" i]', 'button[class*="stop" i]'];
}
if (host.includes("copilot") || host.includes("perplexity") || host.includes("meta.ai")
|| host.includes("character") || host.includes("poe") || host === "pi.ai" || host === "hey.pi.ai"
|| host.includes("mistral") || host.includes("qwen") || host.includes("kimi")) {
return ['button[aria-label*="stop" i]', 'button[data-testid*="stop" i]', 'button[class*="stop" i]'];
}
return ['button[aria-label*="stop" i]'];
}
function isElementVisible(el) {
if (!el || el.disabled || el.getAttribute("aria-disabled") === "true") return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function detectGenerating() {
for (const selector of generatingSelectors()) {
if (isElementVisible(safeQuery(selector))) return true;
}
return false;
}
function messageNodeSelectors() {
const host = location.hostname;
if (host.includes("chatgpt") || host.includes("openai")) {
return ["[data-message-author-role]"];
}
if (host.includes("claude")) {
return ['[data-testid="user-message"]', '[data-testid="assistant-message"]', ".font-claude-message"];
}
if (host.includes("gemini")) {
return ["user-query", "model-response"];
}
if (host.includes("grok")) {
return ['[data-message-author-role]', '[data-testid*="user-message" i]', '[data-testid*="assistant-message" i]'];
}
if (host.includes("deepseek")) {
return ['[data-message-author-role]', '[data-role="user"]', '[data-role="assistant"]', '[data-testid*="user-message" i]', '[data-testid*="assistant-message" i]'];
}
if (host.includes("perplexity")) {
// Perplexity renders question/answer pairs, not chat-role nodes. The
// generic role selectors matched nothing here, which left existing
// threads as a blank document in Shiki.
return [
'[data-testid="user-query"]',
'div[class*="group/query"]',
'h1[class*="query" i]',
'div[id^="markdown-content-"]',
'[data-testid="answer"]',
'[data-message-author-role]'
];
}
if (host.includes("copilot") || host.includes("meta.ai")
|| host.includes("character") || host.includes("poe") || host === "pi.ai" || host === "hey.pi.ai"
|| host.includes("mistral") || host.includes("qwen") || host.includes("kimi")) {
return ['[data-message-author-role]', '[data-role="user"]', '[data-role="assistant"]', '[data-testid*="user-message" i]', '[data-testid*="assistant-message" i]'];
}
return [];
}
function messageNodes() {
let nodes = [];
const seen = new Set();
messageNodeSelectors().forEach((selector) => {
try {
Array.from(document.querySelectorAll(selector)).forEach((node) => {
if (!seen.has(node)) {
seen.add(node);
nodes.push(node);
}
});
} catch {
/* ignore selector drift */
}
});
if (!nodes.length) {
nodes = Array.from(document.querySelectorAll(
'[data-message-author-role], [data-testid="user-message"], [data-testid="assistant-message"], user-query, model-response'
));
}
return nodes;
}
function closestMessageNode(value) {
const selectors = messageNodeSelectors();
if (!selectors.length || !value) return null;
const selector = selectors.join(", ");
let node = value.nodeType === 1 ? value : value.parentElement;
while (node && node.nodeType === 1) {
try {
if (node.matches(selector)) return node;
} catch {
return null;
}
node = node.parentElement;
}
return null;
}
function markMessageDirtyForNode(value) {
const node = closestMessageNode(value);
if (node) dirtyMessageNodes.add(node);
else forceFullMessageScan = true;
}
function detectAuthor(node, index) {
const role = (node.getAttribute && (
node.getAttribute("data-message-author-role")
|| node.getAttribute("data-role")
|| node.getAttribute("data-author")
)) || "";
if (/user|human/i.test(role)) return "user";
if (/assistant|bot|model|ai/i.test(role)) return "assistant";
const tag = (node.tagName || "").toLowerCase();
if (tag === "user-query") return "user";
if (tag === "model-response") return "assistant";
const hint = (node.getAttribute && (
`${node.getAttribute("data-testid") || ""} ${node.getAttribute("id") || ""} ${node.getAttribute("class") || ""}`
)) || "";
if (/(^|[^a-z])(user|human|query|question)([^a-z]|$)/i.test(hint)) return "user";
if (/assistant|model|response|answer|markdown-content|claude|gemini|bot/i.test(hint)) return "assistant";
// Fallback: turns alternate, conventionally starting with the user.
return index % 2 === 0 ? "user" : "assistant";
}
// ---- Reverse-engineer the host's rendered markdown -------------------------
// ChatGPT/Claude/Gemini render the model's markdown into semantic HTML
// (h1-6, p, ul/ol/li, pre/code, strong/em, a, blockquote, table, hr). We walk
// that DOM back into a tiny, safe block/inline AST so the skin can re-render it
// as a formatted document. The skin only ever receives this structured data and
// builds DOM from it via textContent — raw host HTML is never forwarded.
const BLOCK_CAP = 600; // max blocks per message (defensive)
const RUN_CAP = 6000; // max inline runs per block (defensive)
const MESSAGE_SCAN_TAIL_COUNT = 8;
const MESSAGE_FULL_RECONCILE_MS = 15000;
let blockCache = new WeakMap(); // node -> { len, blocks }; skips re-walking unchanged turns
let messageCache = new WeakMap(); // node -> { author, richFormatting, message }
let dirtyMessageNodes = new WeakSet();
let forceFullMessageScan = true;
let lastFullMessageScan = 0;
let lastStateConversationKey = "";
// Search inside shadow roots (Gemini and other web components often hide the
// rendered markdown there; a flat querySelector misses it).
function queryInTree(root, selector) {
if (!root || !root.querySelector) return null;
try {
const direct = root.querySelector(selector);
if (direct) return direct;
} catch {
return null;
}
const elements = root.querySelectorAll ? root.querySelectorAll("*") : [];
for (const el of elements) {
if (el.shadowRoot) {
const found = queryInTree(el.shadowRoot, selector);
if (found) return found;
}
}
return null;
}
// The element holding the rendered answer, skipping surrounding host chrome.
// Ordered most-specific → generic; matches ChatGPT's .markdown.prose, Claude's
// message body, and Gemini's model-response content.
const CONTENT_ROOT_SELECTORS = [
"[data-message-content]",
".markdown.prose",
".markdown",
".prose",
"[class*='markdown']",
".font-claude-message",
"message-content",
".model-response-text",
".response-content",
"article"
];
function contentRoot(node) {
for (const selector of CONTENT_ROOT_SELECTORS) {
const found = queryInTree(node, selector);
if (found) return found;
}
return node;
}
// Cheap structural signature so we re-parse when the host adds headings/lists/
// code blocks during streaming even if total text length is unchanged.
function structureFingerprint(node) {
const root = contentRoot(node);
const tags = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "UL", "OL", "PRE", "BLOCKQUOTE", "TABLE", "HR", "CODE", "IMG"];
let sig = "";
tags.forEach((tag) => {
try {
sig += `${tag[0]}${root.querySelectorAll(tag).length},`;
} catch {
sig += "0,";
}
});
// Bump when an out-of-band image conversion lands so memoized blocks re-walk.
return `${sig}v${imageCacheVersion}`;
}
function isSkippable(el) {
const tag = el.tagName;
if (tag === "SVG" || tag === "BUTTON" || tag === "STYLE" || tag === "SCRIPT" || tag === "NOSCRIPT") return true;
if (el.getAttribute("aria-hidden") === "true") return true;
const testId = el.getAttribute("data-testid") || "";
if (/copy|feedback|regenerate|thumb|message-actions|conversation-actions|toolbar|edit-message|branch/i.test(testId)) return true;
const aria = el.getAttribute("aria-label") || "";
if (/copy|regenerate|good response|bad response|edit message|read aloud/i.test(aria)) return true;
const role = el.getAttribute("role") || "";
if (role === "toolbar" || role === "menu") return true;
return false;
}
// ---- Images ---------------------------------------------------------------
const MIN_CONTENT_IMAGE = 48; // px; below this an <img> is treated as an icon/avatar
// Is this <img> worth surfacing — a real content/generated image, not an icon,
// avatar, or tiny inline glyph?
function isContentImage(img) {
if (!img || img.tagName !== "IMG") return false;
const src = img.getAttribute("src") || img.currentSrc || "";
if (!src) return false;
if (/^data:image\/svg/i.test(src)) return false; // inline SVGs are almost always icons
// Citation/source logos are wrapped in an <a href> to the source. They're never
// real content (and the host renders them as tiny favicons), so drop them.
if (img.closest("a[href]")) return false;
const w = img.naturalWidth || img.width || parseInt(img.getAttribute("width") || "0", 10) || 0;
const h = img.naturalHeight || img.height || parseInt(img.getAttribute("height") || "0", 10) || 0;
if (w && h && w < MIN_CONTENT_IMAGE && h < MIN_CONTENT_IMAGE) return false;
// Some source logos have a large natural size but the host displays them tiny
// (e.g. a 128px publisher logo shown at 12px beside a citation). Trust the
// on-page render size so they aren't surfaced as full-width content images.
const rect = img.getBoundingClientRect();
if (rect.width && rect.height && rect.width < MIN_CONTENT_IMAGE && rect.height < MIN_CONTENT_IMAGE) return false;
if (img.closest('button, [data-testid*="avatar" i], [class*="avatar" i]')) return false;
return true;
}
function dataUrlBytes(dataUrl) {
return String(dataUrl || "").length;
}
function trimImageDataCache() {
let evicted = false;
while (imageDataCache.size > IMAGE_CACHE_MAX_ENTRIES || imageDataCacheTotalBytes > IMAGE_CACHE_MAX_BYTES) {
const oldest = imageDataCache.keys().next().value;
if (!oldest) break;
imageDataCache.delete(oldest);
imageDataCacheTotalBytes -= imageDataCacheBytes.get(oldest) || 0;
imageDataCacheBytes.delete(oldest);
droppedImageSources.add(oldest);
while (droppedImageSources.size > IMAGE_CACHE_MAX_DROPPED_SOURCES) {
droppedImageSources.delete(droppedImageSources.keys().next().value);
}
evicted = true;
}
if (imageDataCacheTotalBytes < 0) imageDataCacheTotalBytes = 0;
if (evicted) clearMessageExtractionCache();
}
function cacheImageDataUrl(src, dataUrl) {
if (!src || !/^data:image\//i.test(dataUrl)) return false;
const bytes = dataUrlBytes(dataUrl);
if (!bytes || bytes > IMAGE_CACHE_MAX_ITEM_BYTES) return false;
droppedImageSources.delete(src);
if (imageDataCache.has(src)) {
imageDataCacheTotalBytes -= imageDataCacheBytes.get(src) || 0;
imageDataCache.delete(src);
imageDataCacheBytes.delete(src);
}
imageDataCache.set(src, dataUrl);
imageDataCacheBytes.set(src, bytes);
imageDataCacheTotalBytes += bytes;
trimImageDataCache();
return imageDataCache.has(src);
}
function getCachedImageDataUrl(src) {
if (!imageDataCache.has(src)) return "";
const dataUrl = imageDataCache.get(src);
const bytes = imageDataCacheBytes.get(src) || dataUrlBytes(dataUrl);
imageDataCache.delete(src);
imageDataCacheBytes.delete(src);
imageDataCache.set(src, dataUrl);
imageDataCacheBytes.set(src, bytes);
return dataUrl;
}
function clearImageDataCache() {
imageDataCache.clear();
imageDataCacheBytes.clear();
droppedImageSources.clear();
imageConverting.clear();
imageDataCacheTotalBytes = 0;
imageCacheGeneration += 1;
imageCacheVersion += 1;
}
function scaledImageDimensions(width, height) {
if (!width || !height) return { width: 0, height: 0 };
const edgeScale = Math.min(1, IMAGE_CONVERT_MAX_EDGE / Math.max(width, height));
const pixelScale = Math.min(1, Math.sqrt(IMAGE_CONVERT_MAX_PIXELS / (width * height)));
const scale = Math.min(edgeScale, pixelScale);
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale))
};
}
// Resolve an <img> to a source the skin's CSP can render (data:/https:). blob:
// and CORS-tainted images are converted to a data: URL out of band (see
// convertImageToDataUrl); until that lands we return "" so they're skipped.
function resolveImageSrc(img, raw) {
const src = String(raw || "").trim();
if (!src) return "";
if (/^data:image\//i.test(src)) return dataUrlBytes(src) <= IMAGE_CACHE_MAX_ITEM_BYTES ? src : "";
if (droppedImageSources.has(src)) return "";
const cached = getCachedImageDataUrl(src);
if (cached) return cached;
if (/^https:\/\//i.test(src)) return src; // CSP allows https images directly
if (/^blob:/i.test(src)) {
convertImageToDataUrl(img, src);
return "";
}
return ""; // http:, relative, etc. — not rendered
}
// Best-effort: turn a blob:/tainted image into a data: URL. Tries a same-origin
// canvas first, then fetch(); caches the result and re-syncs so the skin shows it.
function convertImageToDataUrl(img, src) {
if (imageConverting.has(src) || imageDataCache.has(src) || imageConverting.size >= IMAGE_CONVERT_MAX_IN_FLIGHT) return;
imageConverting.add(src);
const generation = imageCacheGeneration;
const done = (dataUrl) => {
imageConverting.delete(src);
if (generation !== imageCacheGeneration) return;
if (dataUrl && cacheImageDataUrl(src, dataUrl)) {
markMessageDirtyForNode(img);
imageCacheVersion += 1;
postState();
}
};
try {
const w = img.naturalWidth, h = img.naturalHeight;
if (w && h) {
const size = scaledImageDimensions(w, h);
const canvas = document.createElement("canvas");
canvas.width = size.width;
canvas.height = size.height;
const context = canvas.getContext("2d");
if (!context) throw new Error("canvas-context-unavailable");
context.drawImage(img, 0, 0, size.width, size.height);
const url = canvas.toDataURL("image/jpeg", IMAGE_CONVERT_JPEG_QUALITY);
if (url && url.length > 64) { done(url); return; }
}
} catch {
/* tainted canvas — fall through to fetch */
}
try {
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), IMAGE_CONVERT_TIMEOUT_MS);
fetch(src, { signal: controller.signal })
.then((response) => {
const type = response.headers.get("content-type") || "";
const length = Number(response.headers.get("content-length") || "0");
if (!response.ok) throw new Error("image-fetch-failed");
if (type && !/^image\//i.test(type)) throw new Error("not-image");
if (length > IMAGE_CONVERT_MAX_SOURCE_BYTES) throw new Error("image-too-large");
return response.blob();
})
.then((blob) => {
if (!blob || !blob.type || !/^image\//i.test(blob.type) || blob.size > IMAGE_CONVERT_MAX_SOURCE_BYTES) {
done("");
return;
}
const reader = new FileReader();
reader.onload = () => done(String(reader.result || ""));
reader.onerror = () => done("");
reader.readAsDataURL(blob);
})
.catch(() => done(""))
.finally(() => window.clearTimeout(timeout));
} catch {
done("");
}
}
// Content images within a message (generated images, user-uploaded photos),
// de-duplicated and resolved to renderable sources.
function collectMessageImages(node, author) {
const root = author === "assistant" ? contentRoot(node) : node;
let imgs = [];