-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
724 lines (663 loc) · 38.9 KB
/
Copy pathcontent.js
File metadata and controls
724 lines (663 loc) · 38.9 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
/* Chat Queue v1.5.0 – z.ai, Claude, ChatGPT, DeepSeek, Qwen, Gemini, AI Studio & Copilot */
const DEBUG = false;
const log = (...args) => DEBUG && console.log("[CQ]", ...args);
const storage = {
get(key, def){return new Promise(r=>chrome.storage.local.get([key],o=>r(o[key]??def)))},
set(key,val){return new Promise(r=>chrome.storage.local.set({[key]:val},r))}
};
const genState={v:false,set(x){this.v=!!x},is(){return this.v}};
const appState={
queue:[],
itemModes:[],
paused:false,
panelVisible:false,
processing:false,
lastSendAt:0,
userTyping:false,
sendInProgress:false,
userInput:"",
lastTypingTime:0,
typingTimeout:null,
editingIndex: -1,
editingText: "",
draggedIndex: null,
bulkTexts: [""],
lastCleared: null,
generatingStartedAt: null,
lastGenerationStoppedAt: null,
settleIntervalId: null,
settings: {
defaultVisible: false,
zaiEnabled: true,
chatgptEnabled: true,
claudeEnabled: true,
copilotEnabled: true,
deepseekEnabled: true,
qwenEnabled: true,
geminiEnabled: true,
aistudioEnabled: true,
settleMs: 10000,
hardTimeoutSec: 120
}
};
const _origGenSet = genState.set.bind(genState);
genState.set = function(x) {
const prev = this.v;
_origGenSet(x);
if (prev !== this.v) {
if (this.v) {
appState.generatingStartedAt = Date.now();
appState.lastGenerationStoppedAt = null;
cancelSettle();
} else {
appState.lastGenerationStoppedAt = Date.now();
appState.generatingStartedAt = null;
}
}
};
function showSettleOverlay(sec) {
let overlay = document.getElementById('cq-settle-overlay');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'cq-settle-overlay';
overlay.style.cssText = [
'position:fixed', 'bottom:24px', 'right:24px',
'background:#5865F2', 'color:#fff',
'font:600 14px system-ui,sans-serif', 'padding:8px 14px',
'border-radius:8px', 'z-index:2147483647',
'box-shadow:0 4px 12px rgba(0,0,0,0.4)',
'transition:background .15s ease,opacity .15s ease'
].join(';');
document.body.appendChild(overlay);
}
overlay.style.background = '#5865F2';
overlay.style.opacity = '1';
overlay.textContent = `Queue settling: ${sec}s — ESC to cancel`;
}
function cancelSettle() {
if (appState.settleIntervalId) { clearInterval(appState.settleIntervalId); appState.settleIntervalId = null; }
const overlay = document.getElementById('cq-settle-overlay');
if (overlay) overlay.remove();
}
function flashSettleCancelled() {
const overlay = document.getElementById('cq-settle-overlay');
if (!overlay) return;
overlay.textContent = '✕ cancelled';
overlay.style.background = '#e53e3e';
setTimeout(() => { if (overlay.parentNode) overlay.remove(); }, 400);
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && appState.settleIntervalId) {
e.preventDefault();
cancelSettle();
appState.lastGenerationStoppedAt = null;
flashSettleCancelled();
}
});
const delay=ms=>new Promise(r=>setTimeout(r,ms));
function getTabId() {
let tabId = sessionStorage.getItem('cq-tab-id');
if (!tabId) {
tabId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
sessionStorage.setItem('cq-tab-id', tabId);
}
return tabId;
}
const key=()=>`cq-queue-${location.hostname}-${getTabId()}`;
const pauseKey=()=>`cq-paused-${location.hostname}-${getTabId()}`;
const settingsKey=()=>`cq-settings`;
async function loadSettings(){
appState.settings = await storage.get(settingsKey(), {
defaultVisible: false,
zaiEnabled: true,
chatgptEnabled: true,
claudeEnabled: true,
copilotEnabled: true,
deepseekEnabled: true,
qwenEnabled: true,
geminiEnabled: true,
aistudioEnabled: true,
settleMs: 10000,
hardTimeoutSec: 120
});
appState.panelVisible = appState.settings.defaultVisible;
const panel = document.getElementById("cq-panel");
if (panel) {
panel.style.display = appState.panelVisible ? "block" : "none";
if (appState.panelVisible) { removeDock(); } else { showDock(); }
}
}
async function load(){
await loadSettings();
const raw = await storage.get(key(), { queue: [], modes: [] });
if (Array.isArray(raw)) {
appState.queue = raw;
appState.itemModes = raw.map(() => 'queue');
await save();
} else {
appState.queue = raw.queue || [];
appState.itemModes = raw.modes || [];
}
while (appState.itemModes.length < appState.queue.length) appState.itemModes.push('queue');
while (appState.queue.length < appState.itemModes.length) appState.itemModes.pop();
appState.paused=await storage.get(pauseKey(),false);
render();
updatePauseButton();
}
async function save(){await storage.set(key(), { queue: appState.queue, modes: appState.itemModes })}
async function savePause(){await storage.set(pauseKey(),appState.paused)}
function updatePauseButton(){
const pauseIcon = document.querySelector("#cq-pause-btn .cq-icon[alt='Pause']");
const playIcon = document.querySelector("#cq-pause-btn .cq-icon[alt='Play']");
if(pauseIcon && playIcon) {
if(appState.paused) { pauseIcon.style.display="none"; playIcon.style.display="block"; }
else { pauseIcon.style.display="block"; playIcon.style.display="none"; }
}
}
function toast(msg, duration = 2000){
let el=document.getElementById("cq-toast");
if(!el){el=document.createElement("div");el.id="cq-toast";document.body.appendChild(el)}
el.textContent=msg;el.classList.add("show");
setTimeout(()=>el.classList.remove("show"), duration);
}
function isEnabledForCurrentSite() {
const h = location.hostname;
if (h.includes("space.chatglm.site") || h.includes("z.ai")) return appState.settings.zaiEnabled;
if (h.includes("chat.openai.com") || h.includes("chatgpt.com")) return appState.settings.chatgptEnabled;
if (h.includes("claude.ai")) return appState.settings.claudeEnabled;
if (h.includes("copilot.microsoft.com")) return appState.settings.copilotEnabled;
if (h.includes("deepseek.com")) return appState.settings.deepseekEnabled;
if (h.includes("qwen.ai")) return appState.settings.qwenEnabled;
if (h.includes("gemini.google.com")) return appState.settings.geminiEnabled;
if (h.includes("aistudio.google.com")) return appState.settings.aistudioEnabled;
return false;
}
/* ========= Base Adapter ========= */
const baseAdapter = {
focus(el){
if(!el) return;
el.focus();
try{el.scrollIntoView({block:"nearest"})}catch{}
},
preserveUserInput() {
const currentText = this.getText().trim();
if(currentText.length > 0) { appState.userInput = currentText; return true; }
return false;
},
restoreUserInput() {
if(appState.userInput) {
setTimeout(() => {
this.setText(appState.userInput);
appState.userInput = "";
appState.userTyping = true;
toast("Input restored", 1500);
}, 100);
}
},
setText(txt){
const el=this.getComposer();
if(!el) return false;
this.focus(el);
if(el.tagName==="TEXTAREA"){
const lastValue = el.value;
el.value = txt;
const event = new Event('input', { bubbles: true });
const tracker = el._valueTracker;
if (tracker) tracker.setValue(lastValue);
el.dispatchEvent(event);
} else if(el.classList.contains('ProseMirror')) {
try {
const range = document.createRange();
range.selectNodeContents(el);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('delete');
document.execCommand('insertText', false, txt);
el.dispatchEvent(new InputEvent('input', { bubbles:true, cancelable:true, inputType:'insertText', data:txt }));
} catch (e) {
el.innerHTML = `<p>${txt}</p>`;
el.dispatchEvent(new InputEvent('input', { bubbles: true }));
}
} else if(el.classList.contains('ql-editor')) {
// Quill editor (Gemini)
try {
const container = el.closest('.ql-container');
if(container && container.__quill){
container.__quill.setText('');
container.__quill.insertText(0, txt);
} else {
el.innerHTML = '';
const success = document.execCommand('insertText', false, txt);
if(!success) el.innerHTML = `<p>${txt}</p>`;
}
} catch(e) {
el.innerHTML = `<p>${txt}</p>`;
}
el.dispatchEvent(new InputEvent('input', { bubbles:true, cancelable:true, inputType:'insertText', data:txt }));
el.dispatchEvent(new Event('input', { bubbles:true }));
el.dispatchEvent(new Event('change', { bubbles:true }));
el.dispatchEvent(new CompositionEvent('compositionstart', { bubbles:true }));
el.dispatchEvent(new CompositionEvent('compositionend', { bubbles:true, data:txt }));
} else {
try{ el.focus(); document.execCommand('selectAll', false, null); document.execCommand('insertText', false, txt); } catch {
el.textContent = txt;
}
el.dispatchEvent(new InputEvent("input", {bubbles:true, data:txt, inputType:"insertText"}));
}
return true;
},
getText(){
const el=this.getComposer();
if(!el) return "";
if(el.tagName==="TEXTAREA") return el.value || "";
if(el.classList.contains('ProseMirror')) {
const paragraphs = el.querySelectorAll('p');
if(paragraphs.length > 0) return Array.from(paragraphs).map(p => p.textContent||'').join('\n').trim();
return el.textContent || "";
}
if(el.classList.contains('ql-editor')) {
const paragraphs = el.querySelectorAll('p');
if(paragraphs.length > 0) return Array.from(paragraphs).map(p => p.textContent||'').join('\n').trim();
return el.textContent || "";
}
return el.textContent || "";
},
clear(){ this.setText(""); },
async send(text = null) {
if(appState.sendInProgress) return false;
appState.sendInProgress = true;
try {
if(text) {
if(!this.setText(text)){ appState.sendInProgress=false; return false; }
await delay(300);
let attempts=0;
while(attempts<10){
const sendBtn = document.querySelector('button[data-testid="send-button"], button[aria-label*="Send"], button#send-message-button');
if(sendBtn && !sendBtn.disabled) break;
await delay(100); attempts++;
}
}
const methods=[()=>this.clickSend(), ()=>this.sendViaKeyboard(), ()=>this.submitForm()];
for(const method of methods){
if(method()){ setTimeout(()=>appState.sendInProgress=false, 1000); return true; }
await delay(100);
}
appState.sendInProgress=false; return false;
} catch(e){ appState.sendInProgress=false; return false; }
},
sendViaKeyboard(){
const el=this.getComposer(); if(!el) return false;
this.focus(el);
el.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",bubbles:true,cancelable:true}));
return true;
},
submitForm(){
const form=document.querySelector('form[data-type="unified-composer"], form');
if(form){ try{ form.requestSubmit(); return true; } catch { try{ form.submit(); return true; } catch { return false; } } }
return false;
}
};
/* ========= Provider registry (providers/*.js) ========= */
const cqRuntime = { genState, log };
const cqProviders = window.createChatQueueProviders(baseAdapter, cqRuntime);
const { zai, chatgpt, claude, gemini, copilot, deepseek, qwen, aistudio } = cqProviders;
function adapter(){
const h=location.hostname;
if(h.includes("space.chatglm.site")||h.includes("z.ai")) return zai;
if(h.includes("chat.openai.com")||h.includes("chatgpt.com")) return chatgpt;
if(h.includes("claude.ai")) return claude;
if(h.includes("copilot.microsoft.com")) return copilot;
if(h.includes("chat.deepseek.com") || h.includes("deepseek.com")) return deepseek;
if(h.includes("qwen.ai")) return qwen;
if(h.includes("gemini.google.com")) return gemini;
if(h.includes("aistudio.google.com")) return aistudio;
return null;
}
/* ========= Settings Listener ========= */
function setupSettingsListener() {
chrome.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
if (msg?.type === "settings-changed") {
await loadSettings();
if (!isEnabledForCurrentSite()) {
const panel = document.getElementById("cq-panel"); if(panel) panel.style.display="none";
removeDock(); toast("Chat Queue disabled for this site");
sendResponse({ status: "disabled" }); return;
}
const panel = document.getElementById("cq-panel");
if (panel) {
panel.style.display = appState.panelVisible ? "block" : "none";
if(appState.panelVisible) removeDock(); else showDock();
}
sendResponse({ status: "updated" });
}
return true;
});
chrome.storage.onChanged.addListener(async (changes) => {
if (changes[settingsKey()]) {
await loadSettings();
if (!isEnabledForCurrentSite()) {
const panel = document.getElementById("cq-panel"); if(panel) panel.style.display="none";
removeDock();
}
}
});
}
/* ========= UI Building ========= */
function buildUI(){
if(document.getElementById("cq-panel")) return;
const panel=document.createElement("div");
panel.id="cq-panel";
panel.style.display = appState.panelVisible ? "block" : "none";
const header=document.createElement("div"); header.id="cq-header";
const left=document.createElement("div"); left.id="cq-left";
const count=document.createElement("span"); count.id="cq-count"; count.textContent="0";
left.append(count);
const actions=document.createElement("div"); actions.id="cq-actions";
const btnQueue=button("Queue","primary",async ()=>{
const ad=adapter(); if(!ad) return;
const t=(ad.getText()||"").trim(); if(!t){toast("Empty");return}
enqueue(t); ad.clear(); toast("Queued");
});
btnQueue.id="cq-queue-btn"; btnQueue.style.display="none";
const btnPause=document.createElement("button");
btnPause.className="cq-btn ghost cq-icon-btn"; btnPause.id="cq-pause-btn";
const pauseIcon=document.createElement("img");
pauseIcon.src=chrome.runtime.getURL("icons/pause.png"); pauseIcon.alt="Pause"; pauseIcon.className="cq-icon";
const playIcon=document.createElement("img");
playIcon.src=chrome.runtime.getURL("icons/play.png"); playIcon.alt="Play"; playIcon.className="cq-icon"; playIcon.style.display="none";
btnPause.append(pauseIcon, playIcon);
btnPause.addEventListener("click",async ()=>{
appState.paused=!appState.paused; await savePause();
if(appState.paused){pauseIcon.style.display="none";playIcon.style.display="block";}
else{pauseIcon.style.display="block";playIcon.style.display="none";}
toast(appState.paused?"Paused":"Resumed"); updateStatus();
});
const btnClear=button("Clear","ghost",async ()=>{
if(appState.lastCleared){
appState.queue=[...appState.lastCleared.queue]; appState.itemModes=[...appState.lastCleared.modes]; appState.bulkTexts=[...appState.lastCleared.bulkTexts]; appState.lastCleared=null;
await save(); render(); updateClearBtn(); toast("Restored");
} else {
const hasBulk=appState.bulkTexts.some(t=>t.trim().length>0);
if(appState.queue.length===0&&!hasBulk) return;
appState.lastCleared={queue:[...appState.queue],modes:[...appState.itemModes],bulkTexts:[...appState.bulkTexts]};
appState.queue=[]; appState.itemModes=[]; appState.bulkTexts=[""]; await save(); render();
panel.style.display="block"; appState.panelVisible=true; removeDock(); updateClearBtn(); toast("Cleared - tap Undo to restore");
}
});
btnClear.id="cq-clear-btn";
const btnHide=button("Hide","ghost",()=>{ panel.style.display="none"; appState.panelVisible=false; showDock(); });
actions.append(btnQueue,btnPause,btnClear,btnHide);
header.append(left,actions);
const status=document.createElement("div"); status.id="cq-status"; status.className="cq-status";
const body=document.createElement("div"); body.id="cq-body";
panel.append(header,status,body);
document.body.appendChild(panel);
updateStatus();
if(!appState.panelVisible) showDock();
}
function button(label,cls,onclick){
const b=document.createElement("button"); b.className=`cq-btn ${cls||""}`.trim();
b.textContent=label; b.addEventListener("click",onclick); return b;
}
function updateStatus() {
const status = document.getElementById("cq-status"); if(!status) return;
let text = "Ready"; let className = "cq-status";
if(appState.editingIndex===0&&appState.queue.length>0&&!genState.is()){ text="Waiting for edit to finish..."; className+=" waiting"; }
else if(appState.userTyping&&appState.queue.length>0){ text="Waiting for you to stop typing..."; className+=" waiting"; }
else if(genState.is()){ text="AI is responding..."; className+=" generating"; }
else if(appState.sendInProgress){ text="Sending..."; className+=" sending"; }
else if(appState.paused){ text="Queue paused"; className+=" paused"; }
else if(appState.queue.length>0){ text=`${appState.queue.length} item${appState.queue.length===1?'':'s'} queued`; }
status.textContent=text; status.className=className;
}
function updateClearBtn(){
const btn=document.getElementById("cq-clear-btn"); if(!btn) return;
if(appState.lastCleared){ btn.textContent="Undo"; btn.style.display=""; }
else { btn.textContent="Clear"; const hasBulk=appState.bulkTexts.some(t=>t.trim().length>0); btn.style.display=(appState.queue.length>0||hasBulk)?"":"none"; }
}
function updateQueueBtn(){
const btn=document.getElementById("cq-queue-btn"); if(!btn) return;
const ad=adapter(); if(!ad){btn.style.display="none";return}
btn.style.display=(ad.getText()||"").trim().length>0?"":"none";
}
function resetUndo(){ if(!appState.lastCleared) return; appState.lastCleared=null; updateClearBtn(); }
function showDock(){
removeDock();
const d=document.createElement("div"); d.id="cq-dock";
const queueCount=appState.queue.length;
d.title=queueCount>0?`Open Queue (${queueCount} item${queueCount===1?'':'s'})`:"Open Queue";
d.addEventListener("click",()=>{ d.remove(); const p=document.getElementById("cq-panel"); if(p){p.style.display="block";appState.panelVisible=true;} });
if(queueCount>0){ const badge=document.createElement("div"); badge.id="cq-dock-badge"; badge.textContent=queueCount>99?"99+":queueCount; d.appendChild(badge); }
document.body.appendChild(d);
}
function removeDock(){ const d=document.getElementById("cq-dock"); if(d) d.remove(); }
function ensureUIExists(){
let panel=document.getElementById("cq-panel");
if(!panel){
log("Chat Queue UI missing, rebuilding...");
buildUI(); render(); updateStatus();
const ad=adapter();
if(ad){ document.querySelectorAll('[data-cq-bound]').forEach(c=>c.removeAttribute('data-cq-bound')); setTimeout(()=>bindKeys(),100); }
toast("Chat Queue restored",1500); return;
}
if(!document.body.contains(panel)){
document.body.appendChild(panel);
panel.style.display=appState.panelVisible?"block":"none";
if(!appState.panelVisible) showDock();
}
if(!appState.panelVisible){ const dock=document.getElementById("cq-dock"); if(!dock) showDock(); }
}
function render(){
const body=document.getElementById("cq-body"); if(!body) return;
const count=document.getElementById("cq-count"); if(count) count.textContent=String(appState.queue.length);
updateStatus(); body.innerHTML="";
if(appState.queue.length===0){
const empty=document.createElement("div"); empty.className="cq-empty"; empty.textContent="Queue is empty"; body.appendChild(empty);
const hasBulkText=appState.bulkTexts.some(t=>t.trim().length>0);
if(!hasBulkText){ const panel=document.getElementById("cq-panel"); if(panel&&appState.panelVisible){panel.style.display="none";appState.panelVisible=false;showDock();} if(!appState.panelVisible) showDock(); }
} else { if(!appState.panelVisible) showDock(); }
appState.queue.forEach((text,idx)=>{
const row=document.createElement("div");
const isShort=text.length<=50&&!text.includes('\n');
row.className=isShort?"cq-item compact":"cq-item"; row.draggable=true; row.dataset.idx=idx;
row.addEventListener("dragstart",(e)=>{row.classList.add("dragging");e.dataTransfer.effectAllowed="move";e.dataTransfer.setData("text/plain",idx);appState.draggedIndex=idx;});
row.addEventListener("dragend",()=>{row.classList.remove("dragging");document.querySelectorAll(".cq-item.drag-over").forEach(el=>el.classList.remove("drag-over"));appState.draggedIndex=null;});
row.addEventListener("dragover",(e)=>{e.preventDefault();e.dataTransfer.dropEffect="move";const d=document.querySelector(".cq-item.dragging");if(d&&d!==row)row.classList.add("drag-over");});
row.addEventListener("dragleave",()=>{row.classList.remove("drag-over");});
row.addEventListener("drop",async(e)=>{e.preventDefault();row.classList.remove("drag-over");const fi=parseInt(e.dataTransfer.getData("text/plain"));if(fi!==idx&&!isNaN(fi)){const[item]=appState.queue.splice(fi,1);appState.itemModes.splice(fi,1);appState.queue.splice(idx,0,item);appState.itemModes.splice(idx,0,appState.itemModes[fi]||'queue');if(appState.editingIndex===fi)appState.editingIndex=idx;else if(fi<appState.editingIndex&&idx>=appState.editingIndex)appState.editingIndex--;else if(fi>appState.editingIndex&&idx<=appState.editingIndex)appState.editingIndex++;await save();render();}});
const t=document.createElement("div");
t.className=isShort?"cq-text single-line":"cq-text multi-line";
t.textContent=text.length>150?text.substring(0,150)+"...":text; t.title=text;
let nextBadge=null;
if(idx===0){ row.classList.add("cq-next"); nextBadge=document.createElement("span"); nextBadge.className="cq-next-badge"; nextBadge.textContent="NEXT"; }
const a=document.createElement("div"); a.className="cq-actions";
const arrows=document.createElement("div"); arrows.className="cq-arrows"; arrows.title="Drag to reorder, or click arrows";
const upHalf=document.createElement("div"); upHalf.className="cq-arrow-up"; upHalf.innerHTML="▲"; if(idx===0)upHalf.classList.add("disabled");
upHalf.addEventListener("click",async(e)=>{e.stopPropagation();if(idx===0)return;[appState.queue[idx-1],appState.queue[idx]]=[appState.queue[idx],appState.queue[idx-1]];[appState.itemModes[idx-1],appState.itemModes[idx]]=[appState.itemModes[idx],appState.itemModes[idx-1]];if(appState.editingIndex===idx)appState.editingIndex=idx-1;else if(appState.editingIndex===idx-1)appState.editingIndex=idx;await save();render();});
const downHalf=document.createElement("div"); downHalf.className="cq-arrow-down"; downHalf.innerHTML="▼"; if(idx===appState.queue.length-1)downHalf.classList.add("disabled");
downHalf.addEventListener("click",async(e)=>{e.stopPropagation();if(idx===appState.queue.length-1)return;[appState.queue[idx+1],appState.queue[idx]]=[appState.queue[idx],appState.queue[idx+1]];[appState.itemModes[idx+1],appState.itemModes[idx]]=[appState.itemModes[idx],appState.itemModes[idx+1]];if(appState.editingIndex===idx)appState.editingIndex=idx+1;else if(appState.editingIndex===idx+1)appState.editingIndex=idx;await save();render();});
arrows.append(upHalf,downHalf);
const startEdit=(initialText)=>{
appState.editingIndex=idx; appState.editingText=initialText||text; row.className="cq-item editing";
const ec=document.createElement("div"); ec.className="cq-edit-container";
const ta=document.createElement("textarea"); ta.className="cq-edit-input"; ta.value=appState.editingText;
ta.addEventListener("input",()=>{appState.editingText=ta.value;});
const ea=document.createElement("div"); ea.className="cq-edit-actions";
const saveBtn=button("Save","primary",async()=>{const nt=appState.editingText.trim();appState.editingIndex=-1;appState.editingText="";if(nt&&nt!==text){appState.queue[idx]=nt;await save();toast("Saved");}render();});
const cancelBtn=button("Cancel","ghost",()=>{appState.editingIndex=-1;appState.editingText="";render();});
ea.append(cancelBtn,saveBtn); ec.append(ta,ea); row.appendChild(ec); ta.focus(); ta.setSelectionRange(ta.value.length,ta.value.length);
};
if(appState.editingIndex===idx) setTimeout(()=>startEdit(appState.editingText),0);
const edit=button("Edit","ghost",()=>startEdit()); edit.title="Edit";
const modeBtn=document.createElement("button");
const currentMode = appState.itemModes[idx] || 'queue';
modeBtn.className = `cq-mode cq-mode-${currentMode}`;
modeBtn.textContent = currentMode === 'steer' ? '⚡' : '⊙';
modeBtn.title = currentMode === 'steer' ? 'steer — first opportunity (click to switch to queue)' : 'queue — wait for action to end (click to switch to steer)';
modeBtn.addEventListener('click',async(e)=>{
e.stopPropagation();
appState.itemModes[idx] = currentMode === 'queue' ? 'steer' : 'queue';
await save(); render();
});
const del=button("X","ghost",async()=>{if(appState.editingIndex===idx){appState.editingIndex=-1;appState.editingText="";}else if(appState.editingIndex>idx)appState.editingIndex--;appState.queue.splice(idx,1);appState.itemModes.splice(idx,1);await save();render();});
del.title="Remove";
a.append(arrows,modeBtn,edit,del);
if(nextBadge) row.append(nextBadge,t,a); else row.append(t,a);
body.appendChild(row);
});
// Bulk section
const bulkSection=document.createElement("div"); bulkSection.className="cq-bulk-section";
const rowsContainer=document.createElement("div"); rowsContainer.className="cq-bulk-rows";
if(!appState.bulkTexts||appState.bulkTexts.length===0) appState.bulkTexts=[""];
const bulkActions=document.createElement("div"); bulkActions.className="cq-bulk-actions"; bulkActions.style.display="none";
let addAllBtn=null,splitBtn=null,splitUndoBtn=null,preSplitTexts=null;
const updateAddAllVisibility=()=>{const f=appState.bulkTexts.filter(t=>t.trim().length>0).length;bulkActions.style.display=f>0?"flex":"none";if(addAllBtn)addAllBtn.textContent=f>1?"Add All to Queue":"Add to Queue";const hb=appState.bulkTexts.some(t=>t.includes("\n"));if(splitBtn)splitBtn.style.display=hb?"block":"none";if(splitUndoBtn&&preSplitTexts){if(JSON.stringify(appState.bulkTexts)!==JSON.stringify(preSplitTexts._after)){preSplitTexts=null;splitUndoBtn.style.display="none";}}};
const getRowIndex=(row)=>Array.from(rowsContainer.querySelectorAll(".cq-bulk-row")).indexOf(row);
const updatePlaceholders=()=>{rowsContainer.querySelectorAll(".cq-bulk-row").forEach((r,n)=>{const i=r.querySelector("textarea");if(i)i.placeholder=rowsContainer.querySelectorAll(".cq-bulk-row").length>1?`Prompt ${n+1}`:"Enter prompt";});};
const rebuildRows=()=>{rowsContainer.innerHTML="";appState.bulkTexts.forEach(t=>addRow(t));updatePlaceholders();updateAddAllVisibility();};
const addInsertBtn=(afterIdx)=>{const ins=document.createElement("div");ins.className="cq-bulk-insert";const btn=document.createElement("button");btn.className="cq-bulk-insert-btn";btn.textContent="\u25C2";btn.title="Insert prompt here";btn.addEventListener("click",()=>{const allIns=rowsContainer.querySelectorAll(".cq-bulk-insert");const pos=Array.from(allIns).indexOf(ins)+1;appState.bulkTexts.splice(pos,0,"");rebuildRows();const rows=rowsContainer.querySelectorAll(".cq-bulk-row");const ni=rows[pos]?.querySelector("textarea");if(ni)ni.focus();});ins.appendChild(btn);rowsContainer.appendChild(ins);};
const addRow=(value="")=>{
const rowCount=rowsContainer.querySelectorAll(".cq-bulk-row").length;
if(rowCount>0)addInsertBtn(rowCount-1);
const row=document.createElement("div");row.className="cq-bulk-row";
const input=document.createElement("textarea");input.className="cq-bulk-field";input.rows=1;input.placeholder=rowCount>0?`Prompt ${rowCount+1}`:"Enter prompt";input.value=value;
const autoResize=()=>{input.style.height="auto";input.style.height=input.scrollHeight+"px";};setTimeout(autoResize,0);
const removeBtn=document.createElement("button");removeBtn.className="cq-btn ghost cq-bulk-remove";removeBtn.textContent="\u2715";
removeBtn.addEventListener("click",()=>{const i=getRowIndex(row);const rows=rowsContainer.querySelectorAll(".cq-bulk-row");if(rows.length>1){appState.bulkTexts.splice(i,1);rebuildRows();}else{input.value="";appState.bulkTexts[0]="";autoResize();updateAddAllVisibility();}});
input.addEventListener("input",()=>{autoResize();const i=getRowIndex(row);appState.bulkTexts[i]=input.value;const rows=rowsContainer.querySelectorAll(".cq-bulk-row");if(i===rows.length-1&&input.value.trim().length>0){appState.bulkTexts.push("");addRow("");updatePlaceholders();const bodyEl=document.getElementById("cq-body");if(bodyEl)bodyEl.scrollTop=bodyEl.scrollHeight;}updateAddAllVisibility();if(input.value.trim().length>0)resetUndo();});
row.append(input,removeBtn);rowsContainer.appendChild(row);return input;
};
appState.bulkTexts.forEach(t=>addRow(t));
addAllBtn=button("Add to Queue","primary",async()=>{const prompts=appState.bulkTexts.map(t=>t.trim()).filter(t=>t.length>0);if(prompts.length===0){toast("Nothing to add");return;}for(const p of prompts){appState.queue.push(p);appState.itemModes.push('queue');}await save();appState.bulkTexts=[""];resetUndo();render();toast(`Added ${prompts.length} prompt${prompts.length===1?"":"s"}`);});
splitBtn=button("Split by Lines","ghost",()=>{const before=[...appState.bulkTexts];const newTexts=[];for(const t of appState.bulkTexts)t.split("\n").map(l=>l.trim()).filter(l=>l.length>0).forEach(l=>newTexts.push(l));if(newTexts.length===0)return;newTexts.push("");appState.bulkTexts=newTexts;preSplitTexts={before:before,_after:[...newTexts]};rebuildRows();if(splitUndoBtn)splitUndoBtn.style.display="block";});splitBtn.style.display="none";
splitUndoBtn=button("Undo Split","ghost",()=>{if(!preSplitTexts)return;appState.bulkTexts=[...preSplitTexts.before];preSplitTexts=null;splitUndoBtn.style.display="none";rebuildRows();});splitUndoBtn.style.display="none";
bulkActions.append(splitUndoBtn,splitBtn,addAllBtn);updateAddAllVisibility();
bulkSection.append(rowsContainer,bulkActions);body.appendChild(bulkSection);
}
function enqueue(text,front=false){
if(!text||!text.trim()) return; const trimmed=text.trim();
if(appState.queue.includes(trimmed)){toast("Already queued");return;}
if(front){
appState.queue.unshift(trimmed);
appState.itemModes.unshift('queue');
} else {
appState.queue.push(trimmed);
appState.itemModes.push('queue');
}
resetUndo();save().then(render);
if(!appState.panelVisible){const panel=document.getElementById("cq-panel");if(panel){panel.style.display="block";appState.panelVisible=true;removeDock();}}
}
/* ========= Navigation Detection ========= */
function setupNavigationWatcher(){
let lastUrl=location.href;
const checkForNavigation=()=>{if(location.href!==lastUrl){log("Navigation detected...");lastUrl=location.href;setTimeout(()=>ensureUIExists(),1000);}};
setInterval(checkForNavigation,1000);
window.addEventListener('popstate',()=>setTimeout(()=>ensureUIExists(),1000));
const oPS=history.pushState;const oRS=history.replaceState;
history.pushState=function(...args){oPS.apply(this,args);setTimeout(()=>ensureUIExists(),1000);};
history.replaceState=function(...args){oRS.apply(this,args);setTimeout(()=>ensureUIExists(),1000);};
}
/* ========= Send Next ========= */
async function maybeSendNext(force=false){
const ad=adapter(); if(!ad) return;
if(appState.paused) return; if(!force&&Date.now()-appState.lastSendAt<1200) return;
if(appState.queue.length===0) return; if(appState.sendInProgress) return;
if(appState.editingIndex===0){updateStatus();return;}
if(appState.userTyping&&!force){updateStatus();setTimeout(()=>maybeSendNext(false),1000);return;}
const peekMode = appState.itemModes[0] || 'queue';
const settleMs = appState.settings.settleMs ?? 10000;
const hardTimeoutMs = (appState.settings.hardTimeoutSec ?? 120) * 1000;
if (genState.is()) {
const elapsed = appState.generatingStartedAt ? Date.now() - appState.generatingStartedAt : 0;
if (elapsed > hardTimeoutMs) {
log(`Hard timeout ${hardTimeoutMs}ms — forcing send`);
cancelSettle();
} else {
return;
}
} else if (!force && peekMode === 'queue') {
if (!appState.lastGenerationStoppedAt) {
appState.lastGenerationStoppedAt = Date.now();
}
const remaining = settleMs - (Date.now() - appState.lastGenerationStoppedAt);
if (remaining > 0) {
showSettleOverlay(Math.ceil(remaining / 1000));
if (!appState.settleIntervalId) {
appState.settleIntervalId = setInterval(() => {
if (!appState.lastGenerationStoppedAt || genState.is()) { cancelSettle(); return; }
const r = settleMs - (Date.now() - appState.lastGenerationStoppedAt);
if (r <= 0) { cancelSettle(); return; }
const o = document.getElementById('cq-settle-overlay');
if (o) o.textContent = `Queue settling: ${Math.ceil(r/1000)}s — ESC to cancel`;
}, 250);
}
return;
}
cancelSettle();
} else {
cancelSettle();
}
const next=appState.queue.shift();
appState.itemModes.shift();
if(appState.editingIndex>0) appState.editingIndex--;
appState.lastGenerationStoppedAt = null;
await save(); render();
const hadUserInput=ad.preserveUserInput();
let sent=false; let attempts=0; const maxAttempts=3;
while(attempts<maxAttempts&&!sent){attempts++;log(`${ad.name}: Send attempt ${attempts}/${maxAttempts}`);if(await ad.send(next)){sent=true;toast("Sent");break;}if(attempts<maxAttempts)await delay(500);}
if(sent){appState.lastSendAt=Date.now();appState.userTyping=false;setTimeout(()=>{if(hadUserInput)ad.restoreUserInput();},1000);}
else{log(`${ad.name}: Failed to send after ${maxAttempts} attempts`);toast("Failed to send - re-queued");appState.queue.unshift(next);appState.itemModes.unshift(peekMode);await save();render();if(hadUserInput)ad.restoreUserInput();}
}
/* ========= Typing & Key Bindings ========= */
function bindKeys(){
const ad=adapter(); if(!ad) return;
chrome.runtime.onMessage.addListener((msg,sender,sendResponse)=>{
if(!isEnabledForCurrentSite()){sendResponse({status:"disabled"});return true;}
if(msg?.type==="cq-toggle"){const p=document.getElementById("cq-panel");if(!p){sendResponse({status:"panel_not_found"});return true;}if(!appState.panelVisible){p.style.display="block";appState.panelVisible=true;removeDock();}else{p.style.display="none";appState.panelVisible=false;showDock();}sendResponse({status:"toggled",visible:appState.panelVisible});return true;}
if(msg?.type==="cq-clear-queue"){appState.lastCleared={queue:[...appState.queue],modes:[...appState.itemModes],bulkTexts:[...appState.bulkTexts]};appState.queue=[];appState.itemModes=[];appState.bulkTexts=[""];save().then(()=>{render();updateClearBtn();toast("Queue cleared");sendResponse({status:"cleared"});});return true;}
return true;
});
const trackTyping=()=>{
const cmp=ad.getComposer(); if(!cmp) return; if(cmp.dataset.cqBound==="1") return; cmp.dataset.cqBound="1";
const handleInput=()=>{if(ad.programmaticInput)return;appState.userTyping=true;appState.lastTypingTime=Date.now();if(appState.typingTimeout)clearTimeout(appState.typingTimeout);appState.typingTimeout=setTimeout(()=>{appState.userTyping=false;updateStatus();},2000);updateStatus();};
cmp.addEventListener("input",handleInput); cmp.addEventListener("keydown",handleInput); cmp.addEventListener("paste",handleInput);
cmp.addEventListener("keydown",(e)=>{
if(e.key!=="Enter")return; if(ad.programmaticInput) return;
if(genState.is()&&!e.shiftKey&&!e.ctrlKey&&!e.altKey){
const t=(ad.getText()||"").trim(); if(!t) return;
e.preventDefault(); e.stopPropagation();
enqueue(t); ad.clear(); toast("Queued (Enter during generation)");
appState.userTyping=false; updateStatus();
}
},true);
};
trackTyping();
const mo=new MutationObserver(trackTyping);
mo.observe(document.documentElement,{childList:true,subtree:true});
}
function startLoop(){
if(appState.processing) return; appState.processing=true;
setInterval(async()=>{
const ad=adapter(); if(!ad) return;
if(!isEnabledForCurrentSite()) return;
ensureUIExists(); updateStatus(); updateQueueBtn(); updateClearBtn();
if(!appState.paused&&appState.queue.length>0&&!appState.sendInProgress) await maybeSendNext(false);
},500);
}
/* ========= Boot ========= */
(async function(){
const ad=adapter(); if(!ad) return;
await loadSettings();
if(!isEnabledForCurrentSite()){ log("Chat Queue disabled for this site"); return; }
log(`Chat Queue v1.5.0 initializing for ${ad.name}`);
buildUI(); await load();
setupSettingsListener(); setupNavigationWatcher();
ad.watch(); bindKeys(); startLoop();
window.chatQueueDebug={
forceReset:()=>{genState.set(false);appState.userTyping=false;appState.sendInProgress=false;appState.lastGenerationStoppedAt=null;cancelSettle();updateStatus();log("State reset");},
getState:()=>({generating:genState.is(),userTyping:appState.userTyping,sendInProgress:appState.sendInProgress,paused:appState.paused,queueLength:appState.queue.length,site:ad.name,settling:!!appState.settleIntervalId,firstItemMode:appState.itemModes[0]||'queue'}),
clearQueue:async()=>{appState.queue=[];appState.itemModes=[];await save();render();}
};
setTimeout(()=>{render();updateStatus();},1000);
})();