-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuserscript.js
More file actions
1147 lines (1073 loc) · 44.7 KB
/
userscript.js
File metadata and controls
1147 lines (1073 loc) · 44.7 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
// ==UserScript==
// @name IXL Auto Answer (OpenAI API Required)
// @namespace http://tampermonkey.net/
// @version 9.6
// @license GPL-3.0
// @description Sends HTML and canvas data to AI models for math problem-solving with enhanced accuracy, configurable API base, improved GUI with progress bar, auto-answer functionality, token usage display, rollback and detailed DOM change logging. Smart Compression + New 2026 Models.
// @match https://*.ixl.com/*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @require https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js
// @require https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
// @downloadURL https://update.greasyfork.org/scripts/517259/IXL%20Auto%20Answer%20%28OpenAI%20API%20Required%29.user.js
// @updateURL https://update.greasyfork.org/scripts/517259/IXL%20Auto%20Answer%20%28OpenAI%20API%20Required%29.meta.js
// ==/UserScript==
(function() {
'use strict';
// ensure MathJax loaded
if (!window.MathJax) {
const mjs = document.createElement('script');
mjs.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
document.head.appendChild(mjs);
}
// Detect if running under Tampermonkey
if (typeof GM_info !== 'undefined' && GM_info.scriptHandler) {
const handler = GM_info.scriptHandler.toLowerCase();
if (handler !== 'tampermonkey') {
alert('This script is designed for Tampermonkey. You are using ' + GM_info.scriptHandler + '. Redirecting to Tampermonkey.');
window.open('https://www.tampermonkey.net/', '_blank');
}
}
// (1) MIGRATION/CONFIG STORAGE
let oldStore1 = localStorage.getItem("gpt4o-modelConfigs");
let oldStore2 = localStorage.getItem("ixlAutoAnswerConfigs");
let newStore = localStorage.getItem("myNewIxLStorage");
if (!newStore) {
if (oldStore1) {
localStorage.setItem("myNewIxLStorage", oldStore1);
localStorage.removeItem("gpt4o-modelConfigs");
} else if (oldStore2) {
localStorage.setItem("myNewIxLStorage", oldStore2);
localStorage.removeItem("ixlAutoAnswerConfigs");
}
}
let modelConfigs = JSON.parse(localStorage.getItem("myNewIxLStorage") || "{}");
if (!modelConfigs["gpt-5.2"]) {
modelConfigs["gpt-5.2"] = {
apiKey: "",
apiBase: "https://api.openai.com/v1/chat/completions",
discovered: false,
modelList: []
};
}
let config = {
selectedModel: "gpt-5.2",
language: localStorage.getItem("myIxLLang") || "en",
mode: "displayOnly", // can be "autoFill" or "displayOnly"
autoSubmit: false,
totalTokens: 0,
lastState: null
};
function saveConfig() {
localStorage.setItem("myNewIxLStorage", JSON.stringify(modelConfigs));
localStorage.setItem("myIxLLang", config.language);
}
// (2) MULTI-LANG TEXT
const langText = {
en: {
panelTitle: "IXL Auto Answer (OpenAI API Required)",
modeLabel: "Mode",
modeAuto: "Auto Fill (Unstable)",
modeDisp: "Display Answer Only",
startButton: "Start Answering",
rollbackButton: "Rollback",
configAssistant: "Config Assistant",
shortAI: "Ask AI",
closeButton: "Close",
logsButton: "Logs",
logsHide: "Hide Logs",
tokensLabel: "Tokens: ",
statusIdle: "Status: Idle",
statusWaiting: "Waiting for GPT...",
statusDone: "Done.",
requestError: "Request error: ",
finalAnswerTitle: "Final Answer",
stepsTitle: "Solution Steps",
missingAnswerTag: "Missing <answer> tag",
modelSelectLabel: "Model",
modelDescLabel: "Model Description",
customModelPlaceholder: "Custom model name",
languageLabel: "Language",
autoSubmitLabel: "Auto Submit",
rentKeyButton: "Rent Key (Support Me!)",
settingsKeyButton: "Toggle Settings",
apiKeyLabel: "API Key",
saveButton: "Save",
testKeyButton: "Test Key",
testKeyMsg: "Testing key...",
keyOK: "API key valid.",
keyBad: "API key invalid (missing 'test success').",
placeKey: "Enter your API key",
placeBase: "Enter your API base URL",
apiBaseLabel: "API Base",
refreshModels: "Refresh Models",
getKeyLinkLabel: "Get API Key",
disclaimAutoFill: "Warning: Auto Fill is unstable. Use carefully."
},
zh: {
panelTitle: "IXL自动解题 (OpenAI)",
modeLabel: "模式",
modeAuto: "自动填入(不稳定)",
modeDisp: "仅展示答案",
startButton: "开始答题",
rollbackButton: "撤回",
configAssistant: "配置助手",
shortAI: "询问AI",
closeButton: "关闭",
logsButton: "日志",
logsHide: "隐藏日志",
tokensLabel: "用量: ",
statusIdle: "状态:空闲",
statusWaiting: "等待GPT...",
statusDone: "完成。",
requestError: "请求错误:",
finalAnswerTitle: "最终答案",
stepsTitle: "解题过程",
missingAnswerTag: "缺少<answer>标签",
modelSelectLabel: "模型",
modelDescLabel: "模型介绍",
customModelPlaceholder: "自定义模型名称",
languageLabel: "语言",
autoSubmitLabel: "自动提交",
rentKeyButton: "租用Key (支持我!)",
settingsKeyButton: "開啟“設定”",
apiKeyLabel: "API密钥",
saveButton: "保存",
testKeyButton: "测试密钥",
testKeyMsg: "正在测试...",
keyOK: "API密钥有效。",
keyBad: "API密钥无效(缺'test success')",
placeKey: "输入API密钥",
placeBase: "输入API基础地址",
apiBaseLabel: "API基础地址",
refreshModels: "刷新模型列表",
getKeyLinkLabel: "获取API Key",
disclaimAutoFill: "警告:自动填入模式可能不稳定,请慎用。"
}
};
// (3) MODEL DESCRIPTIONS
const modelDescDB = {
"gpt-5.2": "OpenAI flagship (2026). High-density, ultra-efficient reasoning.",
"gpt-5-mini": "Cost-effective GPT-5 variant. Fast and highly intelligent.",
"o3": "OpenAI's advanced reasoning model with synthetic data generation capabilities.",
"o3-mini": "Lightweight reasoning model, cheaper and faster than o3.",
"gemini-3-pro": "Google's reasoning-first model, optimized for complex agentic workflows.",
"gemini-3-flash": "Frontier intelligence built for extreme speed and low latency.",
"gemini-2.5-pro": "Strong complex reasoning and coding capabilities.",
"gemini-2.5-flash": "Balanced intelligence and latency.",
"gemini-2.0-flash": "Reliable workhorse for multimodal tasks.",
"gpt-4.1": "Refined GPT-4 architecture, better than 4o.",
"gpt-4o": "Solves images, cost-effective standard.",
"gpt-4o-mini": "Text-only, cheaper fallback.",
"o1": "First gen reasoning model.",
"deepseek-reasoner": "DeepSeek R1/R2 series, excellent for math.",
"deepseek-chat": "DeepSeek V3 chat model, very cheap.",
"custom": "User-defined model",
};
// (4) BUILD UI
const panel = document.createElement("div");
panel.id = "ixl-auto-panel";
panel.innerHTML = `
<div class="ixl-header">
<span id="panel-title">${langText[config.language].panelTitle}</span>
<span id="token-count">${langText[config.language].tokensLabel}0</span>
<button id="btn-logs">${langText[config.language].logsButton}</button>
<button id="btn-close">${langText[config.language].closeButton}</button>
</div>
<div class="ixl-content">
<div class="row">
<label>${langText[config.language].modeLabel}:</label>
<select id="sel-mode" style="width:100%;">
<option value="autoFill">${langText[config.language].modeAuto}</option>
<option value="displayOnly">${langText[config.language].modeDisp}</option>
</select>
</div>
<div class="row" style="margin-top:8px; display:flex; gap:8px;">
<button id="btn-start" class="btn-accent" style="flex:1;">${langText[config.language].startButton}</button>
<button id="btn-rollback" class="btn-normal" style="flex:1;">${langText[config.language].rollbackButton}</button>
<button id="btn-config-assist" class="btn-mini" style="flex:0;">${langText[config.language].configAssistant}</button>
</div>
<div id="answer-box" style="display:none; border:1px solid #999; padding:6px; background:#fff; margin-top:6px;">
<h4 id="answer-title">${langText[config.language].finalAnswerTitle}</h4>
<div id="answer-content" style="font-size:15px; font-weight:bold; color:#080;"></div>
<hr/>
<h5 id="steps-title">${langText[config.language].stepsTitle}</h5>
<div id="steps-content" style="font-size:13px; color:#666;"></div>
</div>
<div id="progress-area" style="display:none; margin-top:8px;">
<progress id="progress-bar" max="100" value="0" style="width:100%;"></progress>
<span id="progress-label">${langText[config.language].statusWaiting}</span>
</div>
<p id="status-line" style="font-weight:bold; margin-top:6px;">${langText[config.language].statusIdle}</p>
<div id="log-area" style="display:none; max-height:120px; overflow-y:auto; background:#fff; border:1px solid #888; margin-top:6px; padding:4px; font-family:monospace;"></div>
<div class="row" style="margin-top:10px;">
<button id="btn-rent" class="btn-normal" style="margin-top:10px; width:100%; font-weight:bold;">
${langText[config.language].rentKeyButton}
</button>
<button id="btn-settings" class="btn-normal" style="margin-top:10px; width:100%; font-weight:bold;">
${langText[config.language].settingsKeyButton}
</button>
</div>
<div id="settings-area">
<label>${langText[config.language].modelSelectLabel}:</label>
<select id="sel-model" style="width:100%;"></select>
<p id="model-desc" style="font-size:12px; color:#666; margin:4px 0;"></p>
<div id="custom-model-area" style="display:none;">
<input type="text" id="custom-model-input" style="width:100%;" placeholder="${langText[config.language].customModelPlaceholder}" />
</div>
<div class="row" style="margin-top:8px;">
<label>${langText[config.language].languageLabel}:</label>
<select id="sel-lang" style="width:100%;">
<option value="en">English</option>
<option value="zh">中文</option>
</select>
</div>
<div id="auto-submit-row" style="margin-top:8px;">
<label style="display:block;">${langText[config.language].autoSubmitLabel}:</label>
<input type="checkbox" id="chk-auto-submit"/>
</div>
<div class="row" style="margin-top:10px;">
<label>${langText[config.language].apiKeyLabel}:</label>
<div style="display:flex; gap:4px; margin-top:4px;">
<input type="password" id="txt-apikey" style="flex:1;" placeholder="${langText[config.language].placeKey}"/>
<button id="btn-save-key">${langText[config.language].saveButton}</button>
<button id="btn-test-key">${langText[config.language].testKeyButton}</button>
</div>
</div>
<div class="row" style="margin-top:8px;">
<label>${langText[config.language].apiBaseLabel}:</label>
<div style="display:flex; gap:4px; margin-top:4px;">
<input type="text" id="txt-apibase" style="flex:1;" placeholder="${langText[config.language].placeBase}"/>
<button id="btn-save-base">${langText[config.language].saveButton}</button>
</div>
</div>
<label style="margin-top:6px; display:block;">${langText[config.language].getKeyLinkLabel}:</label>
<div style="display:flex; gap:4px; margin-top:4px;">
<a id="link-getkey" href="#" target="_blank" class="link-btn" style="flex:1;">Link</a>
<button id="btn-refresh" class="btn-normal" style="flex:1;">${langText[config.language].refreshModels}</button>
</div>
</div>
</div>
`;
document.body.appendChild(panel);
// (5) CSS
GM_addStyle(`
#ixl-auto-panel {
position: fixed;
top:20px;
right:20px;
width:460px;
height:max-content;
max-height:500px;
background:#fff;
border-radius:6px;
box-shadow:0 2px 10px rgba(0,0,0,0.3);
z-index:99999999;
font-size:14px;
font-family: "Segoe UI", Arial, sans-serif;
overflow-y:auto;
display:table;
}
#ixl-auto-panel {
display:table-row;
}
.ixl-header {
background:#4caf50;
color:#fff;
padding:6px;
display:flex;
align-items:center;
justify-content:flex-end;
gap:6px;
}
#panel-title {
font-weight:bold;
margin-right:auto;
}
#answer-box {
overflow:auto;
width:430px;
max-height:300px;
display:table;
}
#answer-box * {
display:table-row;
}
#settings-area {
display:none;
background:#fff;
border-radius:6px;
box-shadow:0 2px 10px rgba(0,0,0,0.3);
}
.ixl-content {
padding:10px;
height:max-content;
}
.row { margin-top:6px; }
.btn-accent {
background:#f0ad4e; color:#fff; border:none; border-radius:4px; font-weight:bold;
}
.btn-accent:hover { background:#ec971f; }
.btn-normal {
background:#ddd; color:#333; border:none; border-radius:4px;
}
.btn-normal:hover {
background:#ccc;
}
.btn-mini {
background:#bbb; color:#333; border:none; border-radius:4px;
font-size:12px; padding:4px 6px;
}
.btn-mini:hover {
background:#aaa;
}
.link-btn {
background:#2f8ee0; color:#fff; border-radius:4px;
text-decoration:none; text-align:center; padding:6px;
}
.link-btn:hover { opacity:0.8; }
`);
// (6) REFS
const UI = {
panel,
logArea: document.getElementById("log-area"),
logsBtn: document.getElementById("btn-logs"),
closeBtn: document.getElementById("btn-close"),
tokenCount: document.getElementById("token-count"),
modeSelect: document.getElementById("sel-mode"),
startBtn: document.getElementById("btn-start"),
rollbackBtn: document.getElementById("btn-rollback"),
confAssistBtn: document.getElementById("btn-config-assist"),
answerBox: document.getElementById("answer-box"),
answerContent: document.getElementById("answer-content"),
stepsContent: document.getElementById("steps-content"),
progressArea: document.getElementById("progress-area"),
progressBar: document.getElementById("progress-bar"),
progressLabel: document.getElementById("progress-label"),
statusLine: document.getElementById("status-line"),
modelSelect: document.getElementById("sel-model"),
modelDesc: document.getElementById("model-desc"),
customModelArea: document.getElementById("custom-model-area"),
customModelInput: document.getElementById("custom-model-input"),
langSelect: document.getElementById("sel-lang"),
autoSubmitRow: document.getElementById("auto-submit-row"),
autoSubmitToggle: document.getElementById("chk-auto-submit"),
rentBtn: document.getElementById("btn-rent"),
settingsBtn: document.getElementById("btn-settings"),
settingsArea: document.getElementById("settings-area"),
txtApiKey: document.getElementById("txt-apikey"),
saveKeyBtn: document.getElementById("btn-save-key"),
testKeyBtn: document.getElementById("btn-test-key"),
txtApiBase: document.getElementById("txt-apibase"),
saveBaseBtn: document.getElementById("btn-save-base"),
linkGetKey: document.getElementById("link-getkey"),
refreshBtn: document.getElementById("btn-refresh")
};
// (7) UTILS
function logMsg(msg) {
const time = new Date().toLocaleString();
const div = document.createElement("div");
div.textContent = `[${time}] ${msg}`;
UI.logArea.appendChild(div);
console.log("[Log]", msg);
}
function logDump(label, val) {
let m = `[DUMP] ${label}: `;
try { m += JSON.stringify(val); } catch(e){ m += String(val); }
logMsg(m);
}
function updateLangText() {
UI.logsBtn.textContent = (UI.logArea.style.display==="none") ? langText[config.language].logsButton : langText[config.language].logsHide;
UI.closeBtn.textContent = langText[config.language].closeButton;
UI.tokenCount.textContent = langText[config.language].tokensLabel + config.totalTokens;
UI.statusLine.textContent = langText[config.language].statusIdle;
UI.progressLabel.textContent = langText[config.language].statusWaiting;
UI.modeSelect.options[0].text = langText[config.language].modeAuto;
UI.modeSelect.options[1].text = langText[config.language].modeDisp;
UI.startBtn.textContent = langText[config.language].startButton;
UI.rollbackBtn.textContent = langText[config.language].rollbackButton;
UI.confAssistBtn.textContent = langText[config.language].configAssistant;
document.getElementById("answer-title").textContent = langText[config.language].finalAnswerTitle;
document.getElementById("steps-title").textContent = langText[config.language].stepsTitle;
UI.txtApiKey.placeholder = langText[config.language].placeKey;
UI.saveKeyBtn.textContent = langText[config.language].saveButton;
UI.testKeyBtn.textContent = langText[config.language].testKeyButton;
UI.txtApiBase.placeholder = langText[config.language].placeBase;
UI.saveBaseBtn.textContent = langText[config.language].saveButton;
UI.linkGetKey.textContent = "Link";
UI.refreshBtn.textContent = langText[config.language].refreshModels;
UI.rentBtn.textContent = langText[config.language].rentKeyButton;
}
// (8) BUILD MODEL SELECT
function buildModelSelect() {
UI.modelSelect.innerHTML = "";
const ogPre = document.createElement("optgroup");
ogPre.label = "Predefined";
const builtins = [
"gpt-5.2", "gpt-5-mini", "o3", "o3-mini",
"gemini-3-pro", "gemini-3-flash", "gemini-2.5-pro", "gemini-2.5-flash",
"gpt-4.1", "gpt-4o", "gpt-4o-mini",
"deepseek-reasoner", "deepseek-chat"
];
for(const b of builtins){
const opt = document.createElement("option");
opt.value = b;
opt.textContent = b;
ogPre.appendChild(opt);
}
UI.modelSelect.appendChild(ogPre);
const discovered = Object.keys(modelConfigs).filter(k=>modelConfigs[k].discovered);
if(discovered.length>0){
const ogDisc = document.createElement("optgroup");
ogDisc.label = "Discovered";
discovered.forEach(m=>{
const opt = document.createElement("option");
opt.value = m;
opt.textContent = m;
ogDisc.appendChild(opt);
});
UI.modelSelect.appendChild(ogDisc);
}
const optCust = document.createElement("option");
optCust.value = "custom";
optCust.textContent = "custom";
UI.modelSelect.appendChild(optCust);
if(UI.modelSelect.querySelector(`option[value="${config.selectedModel}"]`)){
UI.modelSelect.value = config.selectedModel;
} else {
UI.modelSelect.value = "custom";
}
UI.modelDesc.textContent = modelDescDB[config.selectedModel] || "User-defined model";
UI.customModelArea.style.display = (config.selectedModel==="custom")?"block":"none";
}
// (9) EVENT BIND
UI.logsBtn.addEventListener("click",()=>{
if(UI.logArea.style.display==="none"){
UI.logArea.style.display="block";
UI.logsBtn.textContent=langText[config.language].logsHide;
} else {
UI.logArea.style.display="none";
UI.logsBtn.textContent=langText[config.language].logsButton;
}
});
UI.closeBtn.addEventListener("click",()=>{
panel.style.display="none";
logMsg("User closed panel");
});
UI.modeSelect.addEventListener("change",()=>{
config.mode = UI.modeSelect.value;
if(config.mode==="autoFill"){
UI.answerBox.style.display="none";
UI.autoSubmitRow.style.display="block";
alert(langText[config.language].disclaimAutoFill);
} else {
UI.answerBox.style.display="none";
UI.autoSubmitRow.style.display="none";
}
});
UI.startBtn.addEventListener("click",()=>{
startAnswer();
});
UI.rollbackBtn.addEventListener("click",()=>{
if(config.lastState){
const div = getQuestionDiv();
if(div){
div.innerHTML = config.lastState;
logMsg("Rolled back to previous question content");
}
} else {
logMsg("No stored state for rollback");
}
});
UI.confAssistBtn.addEventListener("click",()=>{
openConfigAssistant();
});
UI.autoSubmitToggle.addEventListener("change",()=>{
config.autoSubmit = UI.autoSubmitToggle.checked;
logDump("AutoSubmit?", config.autoSubmit);
});
UI.modelSelect.addEventListener("change",()=>{
config.selectedModel = UI.modelSelect.value;
if(!modelConfigs[config.selectedModel]){
modelConfigs[config.selectedModel] = {
apiKey:"",
apiBase:"https://api.openai.com/v1/chat/completions",
discovered:false,
modelList:[]
};
}
UI.customModelArea.style.display=(config.selectedModel==="custom")?"block":"none";
UI.modelDesc.textContent=modelDescDB[config.selectedModel]||"User-defined model";
UI.txtApiKey.value = modelConfigs[config.selectedModel].apiKey || "";
// SMART API BASE SWITCHING
let currentBase = modelConfigs[config.selectedModel].apiBase || "";
let modLow = config.selectedModel.toLowerCase();
if(modLow.includes("deepseek") && !currentBase.includes("deepseek")){
UI.txtApiBase.value="https://api.deepseek.com/v1/chat/completions";
modelConfigs[config.selectedModel].apiBase="https://api.deepseek.com/v1/chat/completions";
} else if(modLow.includes("gemini") && !currentBase.includes("googleapis") && !currentBase.includes("google")){
UI.txtApiBase.value="https://generativelanguage.googleapis.com/v1beta/openai/chat/completions";
modelConfigs[config.selectedModel].apiBase="https://generativelanguage.googleapis.com/v1beta/openai/chat/completions";
} else {
UI.txtApiBase.value = currentBase;
}
updateManageLink();
});
UI.customModelInput.addEventListener("change",()=>{
const name = UI.customModelInput.value.trim();
if(!name)return;
config.selectedModel=name;
if(!modelConfigs[name]){
modelConfigs[name]={
apiKey:"",
apiBase:"https://api.openai.com/v1/chat/completions",
discovered:false,
modelList:[]
};
}
buildModelSelect();
UI.modelSelect.value="custom";
UI.txtApiKey.value=modelConfigs[name].apiKey||"";
UI.txtApiBase.value=modelConfigs[name].apiBase||"";
updateManageLink();
});
UI.langSelect.addEventListener("change",()=>{
config.language=UI.langSelect.value;
saveConfig();
updateLangText();
});
UI.rentBtn.addEventListener("click",()=>{
openRentPopup();
});
UI.saveKeyBtn.addEventListener("click",()=>{
const k=UI.txtApiKey.value.trim();
modelConfigs[config.selectedModel].apiKey=k;
saveConfig();
logMsg("Saved new API key");
});
UI.testKeyBtn.addEventListener("click",()=>{
testApiKey();
});
UI.saveBaseBtn.addEventListener("click",()=>{
const nb=UI.txtApiBase.value.trim();
modelConfigs[config.selectedModel].apiBase=nb;
saveConfig();
logMsg("Saved new API Base");
});
UI.refreshBtn.addEventListener("click",()=>{
refreshModelList();
});
UI.settingsBtn.addEventListener("click",()=>{
logMsg("User toggled settings");
if(UI.settingsArea.style.display=="none") {
UI.settingsArea.style.display="block";
logMsg("Settings opened");
}
else {
UI.settingsArea.style.display="none";
logMsg("Settings closed");
}
});
// (10) MISC FUNCS
function updateManageLink(){
let mod = config.selectedModel.toLowerCase();
let link="#";
if(mod.includes("deepseek")){
link="https://platform.deepseek.com/api_keys";
} else if (mod.includes("gemini")) {
link="https://aistudio.google.com/app/apikey";
} else {
link="https://platform.openai.com/api-keys";
}
modelConfigs[config.selectedModel].manageUrl=link;
UI.linkGetKey.href=link;
saveConfig();
}
function openRentPopup(){
const overlay=document.createElement("div");
overlay.style.position="fixed";
overlay.style.top="0"; overlay.style.left="0";
overlay.style.width="100%"; overlay.style.height="100%";
overlay.style.backgroundColor="rgba(0,0,0,0.4)";
overlay.style.zIndex="999999999";
const box=document.createElement("div");
box.style.position="absolute";
box.style.top="50%"; box.style.left="50%";
box.style.transform="translate(-50%,-50%)";
box.style.width="300px";
box.style.backgroundColor="#fff";
box.style.borderRadius="6px";
box.style.padding="10px";
box.innerHTML=`
<h3 style="margin-top:0;">Rent Key</h3>
<p>Contact me to rent an API key:</p>
<ul>
<li>felixliujy@Gmail.com</li>
<li>admin@obanarchy.org</li>
</ul>
<p>Thanks for supporting!</p>
<button id="rent-close-btn">${langText[config.language].closeButton}</button>
`;
overlay.appendChild(box);
document.body.appendChild(overlay);
box.querySelector("#rent-close-btn").addEventListener("click",()=>{
document.body.removeChild(overlay);
});
}
function testApiKey(){
UI.statusLine.textContent=langText[config.language].testKeyMsg;
let conf = modelConfigs[config.selectedModel];
const payload={
model: config.selectedModel,
messages:[
{role:"system", content:"Test key."},
{role:"user", content:"Please ONLY respond with: test success"}
]
};
GM_xmlhttpRequest({
method:"POST",
url:conf.apiBase,
headers:{
"Content-Type":"application/json",
"Authorization":"Bearer "+conf.apiKey
},
data:JSON.stringify(payload),
onload:(resp)=>{
UI.statusLine.textContent=langText[config.language].statusIdle;
try{
const data=JSON.parse(resp.responseText);
const c = data.choices[0].message.content.toLowerCase();
if(c.includes("test success")) alert(langText[config.language].keyOK);
else alert(langText[config.language].keyBad);
} catch(e){
alert("Error parse test:"+e);
}
},
onerror:(err)=>{
UI.statusLine.textContent=langText[config.language].statusIdle;
alert("Test key error:"+JSON.stringify(err));
}
});
}
function refreshModelList(){
const c=modelConfigs[config.selectedModel];
if(!c)return;
const url=c.apiBase.replace("/chat/completions","/models");
logMsg("refreshing from: "+url);
GM_xmlhttpRequest({
method:"GET",
url,
headers:{
"Authorization":"Bearer "+c.apiKey
},
onload:(resp)=>{
try{
const d=JSON.parse(resp.responseText);
logDump("Model Refresh", d);
if(Array.isArray(d.data)){
const arr=d.data.map(x=>x.id);
c.modelList=arr;
for(let m of arr){
if(!modelConfigs[m]){
modelConfigs[m]={
apiKey:c.apiKey,
apiBase:c.apiBase,
discovered:true,
modelList:[]
};
}
}
saveConfig();
buildModelSelect();
alert("Found models: "+arr.join(", "));
}
}catch(e){
alert("Error parse model list:"+e);
}
},
onerror:(err)=>{
alert("Refresh error:"+JSON.stringify(err));
}
});
}
function openConfigAssistant(){
const overlay=document.createElement("div");
overlay.style.position="fixed";
overlay.style.top="0"; overlay.style.left="0";
overlay.style.width="100%"; overlay.style.height="100%";
overlay.style.backgroundColor="rgba(0,0,0,0.5)";
overlay.style.zIndex="999999999";
const box=document.createElement("div");
box.style.position="absolute";
box.style.top="50%"; box.style.left="50%";
box.style.transform="translate(-50%,-50%)";
box.style.width="320px";
box.style.backgroundColor="#fff";
box.style.borderRadius="6px";
box.style.padding="10px";
box.innerHTML=`
<h3 style="margin-top:0;">${langText[config.language].configAssistant}</h3>
<textarea id="assistant-inp" style="width:100%;height:80px;"></textarea>
<button id="assistant-ask" style="margin-top:6px;">${langText[config.language].shortAI}</button>
<button id="assistant-close" style="margin-top:6px;">${langText[config.language].closeButton}</button>
<div id="assistant-out" style="margin-top:6px; border:1px solid #ccc; background:#fafafa; padding:6px; white-space:pre-wrap;"></div>
`;
overlay.appendChild(box);
document.body.appendChild(overlay);
buildModelSelect();
const closeBtn=box.querySelector("#assistant-close");
const askBtn=box.querySelector("#assistant-ask");
const inp=box.querySelector("#assistant-inp");
const out=box.querySelector("#assistant-out");
closeBtn.addEventListener("click",()=>{
document.body.removeChild(overlay);
});
askBtn.addEventListener("click",()=>{
const q=inp.value.trim();
if(!q)return;
out.textContent="(waiting...)";
askAssistant(q,(resp)=>{
out.innerHTML=marked.parse(resp||"");
},(err)=>{
out.textContent="[Error] "+err;
});
});
}
function askAssistant(q,onSuccess,onError){
const c=modelConfigs[config.selectedModel]||{};
const pay={
model:config.selectedModel,
messages:[
{role:"system", content:"You are the config assistant. Provide helpful info for user to reconfigure."},
{role:"user", content:q}
]
};
GM_xmlhttpRequest({
method:"POST",
url:c.apiBase,
headers:{
"Content-Type":"application/json",
"Authorization":"Bearer "+c.apiKey
},
data:JSON.stringify(pay),
onload:(resp)=>{
try{
const d=JSON.parse(resp.responseText);
const ans=d.choices[0].message.content;
onSuccess(ans);
}catch(e){
onError("Parse error:"+e);
}
},
onerror:(err)=>{
onError(JSON.stringify(err));
}
});
}
// --- COMPRESSION FUNCTION ---
function compressIXLContent(sourceNode) {
if (!sourceNode) return "";
// 1. Clone to avoid damaging UI
const clone = sourceNode.cloneNode(true);
// 2. Junk Removal
const junkSelectors = [
'script', 'style', 'noscript', 'iframe',
'.scratchpad-bar',
'.practice-item-hidden',
'.box-header',
'.practice-audio-button',
'.audio_speaker',
'.audio_waves',
'.reference-view',
'.confetti-container',
'.cae-content',
'.yui3-widget-ft',
'button',
'input[type="hidden"]'
];
junkSelectors.forEach(sel => {
clone.querySelectorAll(sel).forEach(el => el.remove());
});
// 3. Semantic Extraction
const semanticElements = clone.querySelectorAll('[aria-label], img[alt], svg[aria-label]');
semanticElements.forEach(el => {
let label = el.getAttribute('aria-label') || el.getAttribute('alt');
if (label && label.trim().length > 0) {
// If it's a blank/input slot, identify it clearly
if(label.toLowerCase().includes('blank')) {
const textNode = document.createTextNode(` [Input_Slot: ${label.trim()}] `);
el.replaceWith(textNode);
} else {
const textNode = document.createTextNode(` [Shape: ${label.trim()}] `);
el.replaceWith(textNode);
}
}
});
// 4. Cleanup remaining SVGs
clone.querySelectorAll('svg').forEach(svg => svg.remove());
// 5. Attribute Cleanup
const walker = document.createTreeWalker(clone, NodeFilter.SHOW_ELEMENT);
let currentNode = walker.currentNode;
while (currentNode) {
while (currentNode.attributes.length > 0) {
currentNode.removeAttribute(currentNode.attributes[0].name);
}
currentNode = walker.nextNode();
}
// 6. Text Cleanup
let html = clone.innerHTML;
html = html.replace(/\s+/g, ' ').trim();
html = html.replace(/<([a-z]+)> <\/\1>/gi, '');
html = html.replace(//g, '');
return html;
}
// progress
let progressTimer=null;
function startProgress(){
UI.progressArea.style.display="block";
UI.progressBar.value=0;
progressTimer=setInterval(()=>{
if(UI.progressBar.value<90) UI.progressBar.value+=2;
},200);
}
function stopProgress(){
if(progressTimer) clearInterval(progressTimer);
UI.progressBar.value=100;
setTimeout(()=>{
UI.progressArea.style.display="none";
UI.progressBar.value=0;
},400);
}
// (11) MAIN LOGIC
function startAnswer(){
logMsg("User pressed StartAnswer");
const dv=getQuestionDiv();
if(!dv){
logMsg("No question region found!");
return;
}
config.lastState = dv.innerHTML;
// --- UPDATED LOGIC HERE ---
const minimalHTML = compressIXLContent(dv);
logMsg(`HTML Compressed: ${dv.innerHTML.length} -> ${minimalHTML.length} chars`);
let userPrompt="HTML:\n"+minimalHTML+"\n";
// --------------------------
const latexCap = captureLatex(dv);
if(latexCap) userPrompt+="LaTeX:\n"+latexCap+"\n";
else {
const c64=captureCanvas(dv);
if(c64) userPrompt+="Canvas image base64 attached.\n";
}
UI.answerBox.style.display="none";
let systemPrompt;
if(config.mode==="autoFill"){
systemPrompt = `
You are an IXL math solver with automation support.
Your task is to:
1. Solve the math problem (HTML/LaTeX/canvas if provided),
2. Output the solution using Markdown (LaTeX formulas in $...$),
3. Provide final answer inside <answer>...</answer>,
4. AND output a JavaScript snippet inside triple backticks to fill the answer automatically.
Important rules:
- DO NOT use LaTeX outside of Markdown or inside JavaScript.
- DO NOT include LaTeX in the <answer> tag if you plan to auto-fill it via JS.
- DO NOT output any math without $...$ wrapping.
- DO NOT use (-$...$), always write $-\\frac{3}{10}$ instead.
- Auto-fill code must be inside one single \`\`\`javascript code block.
Sample structure:
<answer>Final Answer (plain text if needed)</answer>
Then the steps in Markdown + code block at the end:
\`\`\`javascript
// JS to fill input field
document.querySelector("input").value = "-0.3";
\`\`\`
Avoid redundant explanations. Focus on clarity and automation.`;
} else {
systemPrompt = `
You are an IXL math solver.
Your task is to read the question (HTML and LaTeX/canvas if provided), analyze the math problem, and return a solution in Markdown format.
- All mathematical expressions must be properly formatted using LaTeX syntax and enclosed in inline math: $...$, or block math: $$...$$.
- Do NOT escape dollar signs. Output $...$ directly without backslashes.
- For example, output $-\\frac{3}{10}$, NOT -$\\frac{3}{10}$ or (-$\\frac{3}{10}$).
- Do not use backslashes outside math blocks.
- The final numeric or symbolic answer MUST appear inside an <answer>...</answer> tag.
- The answer tag must contain either plain text or LaTeX.
You may use Markdown to present solution steps (headers, lists, etc.).
Markdown output is required.`;
}
UI.statusLine.textContent=langText[config.language].statusWaiting;
startProgress();
let cConf = modelConfigs[config.selectedModel]||{};
const pay={
model:config.selectedModel,
messages:[
{role:"system", content:systemPrompt},
{role:"user", content:userPrompt}
]
};
GM_xmlhttpRequest({
method:"POST",
url:cConf.apiBase,
headers:{
"Content-Type":"application/json",
"Authorization":"Bearer "+cConf.apiKey
},
data:JSON.stringify(pay),
onload:(resp)=>{
stopProgress();
try{
const data=JSON.parse(resp.responseText);
logDump("GPT raw", data);
if(data.usage?.total_tokens){
config.totalTokens+=data.usage.total_tokens;
UI.tokenCount.textContent=langText[config.language].tokensLabel+config.totalTokens;
}
const fullOut=data.choices[0].message.content;
// parse <answer> part
const answerMatch=fullOut.match(/<answer>([\s\S]*?)<\/answer>/i);
let finalAnswer="";
let stepsText="";
if(answerMatch){
finalAnswer=answerMatch[1].trim();
stepsText=fullOut.replace(/<answer>[\s\S]*?<\/answer>/i,"").trim();
} else {
finalAnswer=langText[config.language].missingAnswerTag;
stepsText=fullOut;
}
// show container
UI.answerBox.style.display=(config.mode==="displayOnly")?"block":"none";