Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1180 lines (1094 loc) · 46.6 KB
/
Copy pathcontent.js
File metadata and controls
1180 lines (1094 loc) · 46.6 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
/*
* Protenix page automation.
*
* This content script deliberately uses visible labels, roles, and common
* component patterns instead of brittle generated class names. Submission
* state lives in chrome.storage.local so a Cloudflare navigation or ordinary
* page reload does not lose the queue. Cloudflare challenges are only detected
* and awaited; this script never clicks or solves them.
*/
(() => {
if (window.__pxAutomationInstalled) return;
window.__pxAutomationInstalled = true;
const STORAGE_KEY = 'pxAutomationState';
const ADD_PATH = '/model/prediction/add';
const HISTORY_PATH = '/model/prediction/history';
const FORM_WARMUP_MS = 1200;
const FORM_READY_TIMEOUT_MS = 30000;
const UI_RETRY_LIMIT = 4;
const normalize = (text = '') => String(text).replace(/\s+/g, ' ').trim().toLowerCase();
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let processing = false;
let downloading = false;
let stoppedLocally = false;
let retryingUi = false;
async function readState() {
const stored = await chrome.storage.local.get(STORAGE_KEY);
return stored[STORAGE_KEY] || null;
}
async function writeState(state) {
state.updatedAt = Date.now();
await chrome.storage.local.set({ [STORAGE_KEY]: state });
return state;
}
async function mutateState(mutator) {
const state = await readState();
if (!state) return null;
await mutator(state);
return writeState(state);
}
const overlay = (() => {
let panel;
let titleEl;
let logEl;
let countEl;
let barFill;
let stopButton;
let resumeButton;
let previousButton;
let nextButton;
let nextJobEl;
let contextName = '';
function build() {
if (panel && document.documentElement.contains(panel)) return;
panel = document.createElement('div');
panel.id = '__px_auto_panel';
Object.assign(panel.style, {
position: 'fixed', right: '16px', bottom: '16px', zIndex: '2147483647',
width: '340px', maxHeight: '62vh', display: 'flex', flexDirection: 'column',
background: '#111827', color: '#e8eef7', border: '1px solid #29364a',
borderRadius: '12px', overflow: 'hidden', boxShadow: '0 10px 34px rgba(0,0,0,.42)',
fontFamily: 'system-ui, -apple-system, Segoe UI, sans-serif', fontSize: '13px'
});
const header = document.createElement('div');
Object.assign(header.style, {
display: 'flex', alignItems: 'center', gap: '7px', padding: '10px 12px',
background: 'linear-gradient(135deg,#3168e0,#6658d3)', color: '#fff', fontWeight: '650'
});
titleEl = document.createElement('span');
titleEl.textContent = 'Protenix Automation';
Object.assign(titleEl.style, { flex: '1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
resumeButton = document.createElement('button');
resumeButton.textContent = 'Resume';
Object.assign(resumeButton.style, {
display: 'none', border: 'none', borderRadius: '6px', padding: '4px 8px',
cursor: 'pointer', background: 'rgba(255,255,255,.2)', color: '#fff', fontSize: '12px'
});
resumeButton.onclick = async () => {
await mutateState((state) => {
state.running = true;
state.paused = false;
state.note = 'Resuming the submission queue…';
});
stoppedLocally = false;
resumeButton.style.display = 'none';
runQueue();
};
stopButton = document.createElement('button');
stopButton.textContent = 'Stop';
Object.assign(stopButton.style, {
border: 'none', borderRadius: '6px', padding: '4px 8px', cursor: 'pointer',
background: 'rgba(255,255,255,.2)', color: '#fff', fontSize: '12px'
});
stopButton.onclick = async () => {
stoppedLocally = true;
const state = await mutateState((state) => {
state.running = false;
state.paused = true;
state.note = 'Queue stopped from the page panel.';
});
const current = state?.queue?.find((job) => job.id === state.currentId);
overlay.log(
current?.status === 'reviewing' && !current.serverRequestSentAt
? 'Stop requested before the final OK; no server request has been sent yet.'
: 'Stop requested. Any server request already sent cannot be undone.',
'warn'
);
overlay.setPaused(true);
};
const closeButton = document.createElement('button');
closeButton.textContent = '✕';
Object.assign(closeButton.style, {
border: 'none', background: 'transparent', color: '#fff', cursor: 'pointer',
fontSize: '14px', lineHeight: '1', padding: '2px'
});
closeButton.onclick = () => panel.remove();
header.append(titleEl, resumeButton, stopButton, closeButton);
const barWrap = document.createElement('div');
Object.assign(barWrap.style, { height: '4px', background: '#263247' });
barFill = document.createElement('div');
Object.assign(barFill.style, { height: '100%', width: '0%', background: '#42c786', transition: 'width .2s' });
barWrap.appendChild(barFill);
const queueNav = document.createElement('div');
Object.assign(queueNav.style, {
display: 'grid', gridTemplateColumns: 'auto 1fr auto', alignItems: 'center',
gap: '7px', padding: '7px 10px 0'
});
previousButton = document.createElement('button');
previousButton.textContent = '← Previous JSON';
nextButton = document.createElement('button');
nextButton.textContent = 'Next JSON →';
for (const button of [previousButton, nextButton]) {
Object.assign(button.style, {
border: '1px solid #3a4a63', borderRadius: '6px', padding: '4px 7px',
cursor: 'pointer', background: '#1d293b', color: '#dbe7f5', fontSize: '11px'
});
}
previousButton.title = 'Choose the previous pending JSON as the next job';
nextButton.title = 'Choose the next pending JSON as the next job';
previousButton.onclick = () => selectAdjacentPending(-1);
nextButton.onclick = () => selectAdjacentPending(1);
nextJobEl = document.createElement('span');
nextJobEl.textContent = 'Choose the next pending JSON';
Object.assign(nextJobEl.style, {
minWidth: '0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
textAlign: 'center', color: '#91a4bd', fontSize: '11px'
});
queueNav.append(previousButton, nextJobEl, nextButton);
countEl = document.createElement('div');
Object.assign(countEl.style, { padding: '7px 12px 0', color: '#a9bad0', fontSize: '12px' });
logEl = document.createElement('div');
Object.assign(logEl.style, {
padding: '7px 12px 12px', overflowY: 'auto', lineHeight: '1.48',
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: '12px'
});
panel.append(header, barWrap, queueNav, countEl, logEl);
(document.body || document.documentElement).appendChild(panel);
}
const colors = { info: '#d4dfec', ok: '#86e0ad', warn: '#f8cc68', err: '#f3a19b' };
return {
start(title, predictionName = '') {
build();
contextName = predictionName || '';
titleEl.textContent = title || 'Protenix Automation';
logEl.innerHTML = '';
barFill.style.background = '#42c786';
stopButton.style.display = '';
},
log(message, kind = 'info') {
build();
const line = document.createElement('div');
line.textContent = contextName && !String(message).includes(contextName)
? `[${contextName}] ${message}`
: message;
line.style.color = colors[kind] || colors.info;
logEl.appendChild(line);
logEl.scrollTop = logEl.scrollHeight;
},
count(text) {
build();
countEl.textContent = contextName ? `Prediction: ${contextName} · ${text}` : text;
},
nextJob(job, index, total) {
build();
nextJobEl.textContent = job ? `Next: ${job.name} (${index + 1}/${total})` : 'No pending JSON jobs';
previousButton.disabled = !job;
nextButton.disabled = !job;
previousButton.style.opacity = job ? '1' : '.45';
nextButton.style.opacity = job ? '1' : '.45';
},
progress(done, total) {
build();
const percent = total > 0 ? Math.round((done / total) * 100) : 0;
barFill.style.width = `${percent}%`;
},
setPaused(paused) {
build();
resumeButton.style.display = paused ? '' : 'none';
stopButton.style.display = paused ? 'none' : '';
if (paused) barFill.style.background = '#e3a931';
},
error(message) {
build();
barFill.style.background = '#e76057';
stopButton.style.display = 'none';
this.log(message, 'err');
},
done(message) {
build();
barFill.style.width = '100%';
stopButton.style.display = 'none';
resumeButton.style.display = 'none';
this.log(message, 'ok');
}
};
})();
function isVisible(element) {
if (!element || !element.isConnected) return false;
const style = getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
}
function fieldRoot(labelText) {
const target = normalize(labelText);
const labels = Array.from(document.querySelectorAll('label, .ant-form-item-label, [class*="label"], span, p'));
const label = labels.find((node) => isVisible(node) && normalize(node.textContent).replace(/[?:*]+$/g, '').trim() === target);
if (!label) return null;
return label.closest('.arco-form-item, .ant-form-item, .el-form-item, .form-item, [class*="formItem"], [class*="form-item"]')
|| label.parentElement?.parentElement || label.parentElement;
}
function dispatchControlEvents(element) {
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}
async function selectNative(select, desired) {
const options = Array.from(select.options);
const match = options.find((option) => option.value === desired || normalize(option.textContent) === normalize(desired));
if (!match) return false;
select.value = match.value;
dispatchControlEvents(select);
return true;
}
async function selectCustom(root, desired) {
const trigger = root?.querySelector('[role="combobox"], .ant-select-selector, .ant-select-selection-search, .el-select, [class*="select"]');
if (!trigger || !isVisible(trigger)) return false;
trigger.click();
await wait(250);
const target = normalize(desired);
const options = Array.from(document.querySelectorAll(
'[role="option"], .ant-select-item-option, .el-select-dropdown__item, [class*="select-option"], [class*="option"]'
)).filter(isVisible);
const option = options.find((item) => normalize(item.textContent) === target)
|| options.find((item) => normalize(item.textContent).includes(target));
if (!option) {
document.body.click();
return false;
}
option.click();
await wait(200);
return true;
}
async function selectArcoById(id, desired) {
const control = document.getElementById(id);
if (!control || !isVisible(control)) return false;
const current = control.querySelector('.arco-select-view-value')?.textContent || control.textContent;
if (normalize(current) === normalize(desired)) return true;
control.scrollIntoView({ block: 'center', behavior: 'auto' });
control.click();
const popupId = control.getAttribute('aria-controls');
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const popup = popupId ? document.getElementById(popupId) : document;
const options = Array.from((popup || document).querySelectorAll(
'[role="option"], .arco-select-option, li.arco-select-option'
)).filter(isVisible);
const target = normalize(desired);
const option = options.find((item) => normalize(item.getAttribute('title') || item.textContent) === target)
|| options.find((item) => normalize(item.textContent).includes(target));
if (option) {
(option.querySelector('.arco-select-option-content') || option).click();
await wait(250);
return normalize(control.querySelector('.arco-select-view-value')?.textContent || control.textContent).includes(target);
}
await wait(100);
}
document.body.click();
return false;
}
async function setModel(modelName) {
if (!modelName) return true;
if (await selectArcoById('model_name_input', modelName)) return true;
const root = fieldRoot('model') || document;
const selects = Array.from(root.querySelectorAll('select'));
for (const select of selects) {
if (await selectNative(select, modelName)) return true;
}
if (await selectCustom(root, modelName)) return true;
const anyNative = Array.from(document.querySelectorAll('select'));
for (const select of anyNative) {
if (Array.from(select.options).some((option) => option.value === modelName || normalize(option.textContent).includes(normalize(modelName)))) {
return selectNative(select, modelName);
}
}
return false;
}
async function setBooleanField(labelText, setting) {
if (!setting || setting === 'unchanged') return true;
const desired = setting === 'enable';
const root = fieldRoot(labelText) || fieldRoot(`use ${labelText}`);
if (!root) return false;
const radioInputs = Array.from(root.querySelectorAll('input[type="radio"]'));
const desiredRadio = radioInputs.find((input) => normalize(input.value) === String(desired));
if (desiredRadio) {
if (!desiredRadio.checked) (desiredRadio.closest('label') || desiredRadio).click();
await wait(150);
return desiredRadio.checked;
}
const desiredText = String(desired);
const arcoRadio = Array.from(root.querySelectorAll('.arco-radio-button, label')).find((node) =>
normalize(node.textContent) === desiredText
);
if (arcoRadio) {
arcoRadio.click();
await wait(150);
return true;
}
const checkbox = root.querySelector('input[type="checkbox"]');
if (checkbox) {
if (checkbox.checked !== desired) checkbox.click();
return true;
}
const switchElement = root.querySelector('[role="switch"], .ant-switch, .el-switch');
if (switchElement) {
const checked = switchElement.getAttribute('aria-checked') === 'true'
|| switchElement.classList.contains('ant-switch-checked')
|| switchElement.classList.contains('is-checked');
if (checked !== desired) switchElement.click();
return true;
}
const select = root.querySelector('select');
if (select) {
const preferred = desired ? ['yes', 'true', 'on', 'enable', 'enabled'] : ['no', 'false', 'off', 'disable', 'disabled'];
const option = Array.from(select.options).find((item) => preferred.includes(normalize(item.textContent)) || preferred.includes(normalize(item.value)));
if (!option) return false;
select.value = option.value;
dispatchControlEvents(select);
return true;
}
const choices = desired ? ['yes', 'enable', 'enabled', 'true', 'on'] : ['no', 'disable', 'disabled', 'false', 'off'];
for (const choice of choices) {
if (await selectCustom(root, choice)) return true;
}
return false;
}
async function selectJsonUploadMode(timeoutMs = FORM_READY_TIMEOUT_MS) {
const deadline = Date.now() + timeoutMs;
let sawUploadSection = false;
let selectedJson = false;
while (Date.now() < deadline) {
const root = fieldRoot('upload');
if (root) {
sawUploadSection = true;
const input = Array.from(root.querySelectorAll('input[type="radio"]')).find((radio) =>
normalize(radio.value) === 'json'
);
const option = input?.closest('label') || Array.from(root.querySelectorAll('.arco-radio-button, label, [role="radio"]')).find((node) =>
normalize(node.textContent) === 'json'
);
if (option && input && !input.checked) {
option.click();
selectedJson = true;
await wait(200);
continue;
}
if (option && !input && !selectedJson) {
option.click();
selectedJson = true;
await wait(200);
continue;
}
if (option && (input?.checked || selectedJson)) {
const fileInput = root.querySelector('input[type="file"]');
const uploadButton = Array.from(root.querySelectorAll('button')).find((button) =>
normalize(button.textContent) === 'click to upload'
);
if (fileInput && uploadButton) return { root, input: fileInput };
}
}
await wait(250);
}
throw new Error(sawUploadSection
? 'Protenix did not finish opening its JSON file-upload control.'
: `The Protenix Upload section did not appear within ${Math.round(timeoutMs / 1000)} seconds.`);
}
function findJsonInput() {
const root = fieldRoot('upload');
return root?.querySelector('input[type="file"]') || null;
}
function nameFieldValue() {
const input = document.getElementById('name_input') || fieldRoot('name')?.querySelector('input');
return String(input?.value || '').trim();
}
async function waitForJsonImport(job, timeoutMs = 12000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const messages = notificationTexts();
const failure = messages.find((message) =>
message.includes('please upload a valid json')
|| message.includes('sequences cannot contain ligand file')
);
if (failure) throw new Error(`Protenix rejected the JSON: ${failure}`);
if (nameFieldValue() === String(job.name).trim()) return true;
await wait(100);
}
throw new Error(`Protenix did not finish importing ${job.fileName}; the Name field never changed to “${job.name}”.`);
}
async function attachJson(job) {
let lastError;
for (let attempt = 1; attempt <= 3; attempt += 1) {
const { input } = await selectJsonUploadMode();
const file = new File([job.json], job.fileName || 'protenix_job.json', { type: 'application/json' });
const transfer = new DataTransfer();
transfer.items.add(file);
input.value = '';
input.files = transfer.files;
dispatchControlEvents(input);
try {
await waitForJsonImport(job);
return true;
} catch (error) {
if (String(error.message).includes('Protenix rejected the JSON')) throw error;
lastError = error;
if (attempt < 3) {
overlay.log(`JSON import was not ready; retrying (${attempt}/3)…`, 'warn');
await wait(attempt * 1000);
}
}
}
throw lastError || new Error(`Protenix did not finish importing ${job.fileName}.`);
}
async function waitForSubmitButton(timeoutMs = 15000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const submit = findSubmitButton();
if (submit) return submit;
await wait(250);
}
return null;
}
function visibleModalRoots() {
return Array.from(document.querySelectorAll(
'.arco-modal-wrapper .arco-modal, .arco-modal, [role="dialog"], [aria-modal="true"]'
)).filter(isVisible);
}
function submittedSuccessModal() {
return visibleModalRoots().find((root) => {
const title = root.querySelector('.arco-modal-title')?.textContent || '';
return normalize(title) === 'submitted successfully';
}) || null;
}
function taskConfirmationModal() {
return visibleModalRoots().find((root) => {
const title = root.querySelector('.arco-modal-title')?.textContent || '';
return normalize(title) === 'submit the task';
}) || null;
}
function modalOkButton(modal) {
return Array.from(modal?.querySelectorAll('.arco-modal-footer button, button') || []).find((button) =>
isVisible(button) && normalize(button.textContent) === 'ok'
) || null;
}
function buttonEnabled(button) {
return !!button
&& !button.disabled
&& button.getAttribute('aria-disabled') !== 'true'
&& !button.classList.contains('arco-btn-disabled');
}
async function consumeSubmittedSuccessModal() {
const modal = submittedSuccessModal();
if (!modal) return false;
const ok = modalOkButton(modal);
if (!buttonEnabled(ok)) return false;
ok.click();
await wait(250);
return true;
}
function findSubmitButton() {
const exactArco = Array.from(document.querySelectorAll('button.arco-btn-primary')).find((button) =>
isVisible(button)
&& !button.disabled
&& normalize(button.textContent) === 'submit'
);
if (exactArco) return exactArco;
const exact = ['submit', 'submit task', 'submit job', 'start prediction', 'run prediction', 'predict'];
const buttons = Array.from(document.querySelectorAll('button, input[type="submit"], [role="button"]')).filter(isVisible);
return buttons.find((button) => {
const text = normalize(button.textContent || button.value || button.getAttribute('aria-label'));
const disabled = button.disabled || button.getAttribute('aria-disabled') === 'true';
return !disabled && exact.includes(text);
}) || buttons.find((button) => {
const text = normalize(button.textContent || button.value || button.getAttribute('aria-label'));
const disabled = button.disabled || button.getAttribute('aria-disabled') === 'true';
return !disabled && /(^|\s)submit(\s|$)/.test(text);
}) || null;
}
function challengeVisible() {
const responseInputs = Array.from(document.querySelectorAll(
'input[name="cf-turnstile-response"], textarea[name="cf-turnstile-response"]'
));
const tokenReady = responseInputs.some((input) => String(input.value || '').trim().length > 20);
if (tokenReady) return false;
const visibleChallengeFrame = Array.from(document.querySelectorAll(
'iframe[src*="challenges.cloudflare.com"], iframe[title*="challenge" i]'
)).some(isVisible);
const visibleChallengeStage = Array.from(document.querySelectorAll(
'.cf-turnstile, .cf-challenge, #challenge-running, #challenge-stage'
)).some((element) => {
const frame = element.querySelector('iframe');
return isVisible(element) && ((frame && isVisible(frame)) || compactChallengeText(element));
});
if (visibleChallengeFrame || visibleChallengeStage) return true;
const title = normalize(document.title);
const visibleText = normalize(document.body?.innerText || '').slice(0, 6000);
const signals = [
'verify you are human',
'checking your browser',
'performing security verification',
'security check in progress',
'please wait while we verify',
'complete the human-machine detection'
];
return title === 'just a moment...' || signals.some((signal) => visibleText.includes(signal));
}
function compactChallengeText(element) {
const text = normalize(element?.textContent || '');
return /verify|checking|security|challenge/.test(text);
}
function notificationTexts() {
const selectors = [
'[role="alert"]', '[aria-live="assertive"]', '[aria-live="polite"]',
'.arco-message', '.arco-notification', '.arco-alert',
'.ant-message', '.ant-notification', '.ant-alert', '.el-message',
'.toast', '.Toastify', '[class*="snackbar"]', '[class*="notification"]'
].join(',');
return Array.from(document.querySelectorAll(selectors))
.filter(isVisible)
.map((node) => normalize(node.textContent))
.filter(Boolean);
}
function submissionOutcome(job) {
if (location.pathname === HISTORY_PATH) {
return { kind: 'success', message: 'Protenix opened prediction history after accepting the job.' };
}
const messages = notificationTexts();
const successWords = ['submitted successfully', 'successfully submitted', 'task submitted', 'job submitted', 'prediction submitted', 'added to queue', 'queued successfully'];
const fatalWords = ['quota', 'daily limit', 'submission limit', 'too many requests', 'maximum number'];
const failureWords = ['submission failed', 'failed to submit', 'invalid json', 'invalid input', 'upload failed', 'server error', 'try again'];
for (const message of messages) {
if (successWords.some((word) => message.includes(word))) return { kind: 'success', message };
if (fatalWords.some((word) => message.includes(word))) return { kind: 'fatal', message };
if (failureWords.some((word) => message.includes(word))) return { kind: 'failure', message };
}
const body = normalize(document.body?.innerText || '');
const jobName = normalize(job?.name || '');
if (jobName && body.includes(jobName)) {
const nearbyStatus = ['queued', 'pending', 'submitted', 'running'].some((word) => body.includes(word));
if (nearbyStatus && !findJsonInput()) return { kind: 'success', message: 'The submitted job appears on the resulting page.' };
}
return null;
}
function queueCounts(state) {
const total = state.queue.length;
const done = state.queue.filter((job) => ['submitted', 'skipped'].includes(job.status)).length;
const submitted = state.queue.filter((job) => job.status === 'submitted').length;
return { total, done, submitted };
}
function nextPendingSelection(state) {
const total = state?.queue?.length || 0;
if (!total) return null;
const cursor = Number.isInteger(state.queueCursor)
? ((state.queueCursor % total) + total) % total
: 0;
for (let offset = 0; offset < total; offset += 1) {
const index = (cursor + offset) % total;
const job = state.queue[index];
if (job.status === 'pending') return { job, index };
}
return null;
}
async function selectAdjacentPending(direction) {
const state = await readState();
const candidates = (state?.queue || [])
.map((job, index) => ({ job, index }))
.filter(({ job }) => job.status === 'pending');
if (!candidates.length) {
overlay.nextJob(null, 0, state?.queue?.length || 0);
overlay.log('There are no pending JSON jobs to select.', 'warn');
return;
}
const displayed = nextPendingSelection(state);
const cursor = displayed?.index ?? candidates[0].index;
let selected;
if (direction < 0) {
selected = [...candidates].reverse().find(({ index }) => index < cursor) || candidates[candidates.length - 1];
} else {
selected = candidates.find(({ index }) => index > cursor) || candidates[0];
}
await mutateState((draft) => {
draft.queueCursor = selected.index;
draft.note = `Selected next JSON: ${selected.job.name}.`;
});
overlay.nextJob(selected.job, selected.index, state.queue.length);
overlay.log(`Selected ${selected.job.name} as the next pending JSON.`, 'ok');
}
async function pauseWith(message, error = false) {
await mutateState((state) => {
state.running = false;
state.paused = true;
state.note = message;
});
if (error) overlay.error(message);
else overlay.log(message, 'warn');
overlay.setPaused(true);
}
async function finishCurrent(status, message) {
const state = await mutateState((draft) => {
const finishedIndex = draft.queue.findIndex((item) => item.id === draft.currentId);
const job = finishedIndex >= 0 ? draft.queue[finishedIndex] : null;
if (job) {
job.status = status;
job.completedAt = Date.now();
job.error = status === 'failed' ? message : '';
}
if (finishedIndex >= 0 && draft.queue.length) {
draft.queueCursor = (finishedIndex + 1) % draft.queue.length;
}
draft.currentId = null;
draft.note = message;
if (status === 'failed') {
draft.running = false;
draft.paused = true;
}
});
if (!state) return;
const counts = queueCounts(state);
const selection = nextPendingSelection(state);
overlay.nextJob(selection?.job || null, selection?.index || 0, state.queue.length);
overlay.count(`${counts.submitted} submitted · ${counts.total - counts.done} remaining`);
overlay.progress(counts.done, counts.total);
if (status === 'failed') {
overlay.error(message);
overlay.setPaused(true);
processing = false;
return;
}
overlay.log(message, status === 'submitted' ? 'ok' : 'warn');
processing = false;
if (!state.running || state.paused) return;
const pending = state.queue.some((job) => job.status === 'pending');
if (!pending) {
await mutateState((draft) => {
draft.running = false;
draft.paused = false;
draft.note = `Finished. Submitted ${draft.queue.filter((job) => job.status === 'submitted').length} job(s).`;
});
overlay.done(`Finished. Submitted ${state.queue.filter((job) => job.status === 'submitted').length} job(s).`);
return;
}
await wait(state.settings?.delayMs || 3000);
const submitUrl = state.submitUrl || `${location.origin}${ADD_PATH}`;
if (submitUrl) {
overlay.log('Returning to the submission form for the next job…');
location.assign(submitUrl);
} else {
runQueue();
}
}
async function monitorSubmission(job) {
let challengeWasSeen = !!job.challengeSeen;
let challengeLogged = false;
let confirmationLogged = false;
let confirmationClicked = !!job.serverRequestSentAt;
const startedAt = Date.now();
const state = await readState();
const timeoutMs = state?.settings?.outcomeTimeoutMs || 180000;
const startingUrl = job.submissionUrl || state?.submitUrl || location.href;
while (Date.now() - startedAt < timeoutMs) {
const latest = await readState();
if (!latest?.running || latest.paused || stoppedLocally) {
processing = false;
return;
}
if (await consumeSubmittedSuccessModal()) {
await finishCurrent('submitted', `${job.name}: Protenix reported “Submitted successfully”.`);
return;
}
const confirmation = taskConfirmationModal();
if (confirmation) {
if (!confirmationLogged) {
confirmationLogged = true;
overlay.log('“Submit the task” opened. Waiting for Protenix verification to enable OK…', 'warn');
}
const ok = modalOkButton(confirmation);
if (buttonEnabled(ok) && !confirmationClicked) {
confirmationClicked = true;
const sentAt = Date.now();
job.status = 'submitting';
job.serverRequestSentAt = sentAt;
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === draft.currentId);
if (current) {
current.status = 'submitting';
current.serverRequestSentAt = sentAt;
}
draft.note = `${job.name}: verification complete; confirming the server submission…`;
});
ok.click();
overlay.log('Verification complete. Pressed OK to send the server request.', 'ok');
await wait(500);
continue;
}
if (!buttonEnabled(ok)) {
if (!challengeLogged) {
challengeLogged = true;
overlay.log('Complete the Cloudflare check in the Protenix dialog if it asks you.', 'warn');
}
await wait(500);
continue;
}
}
if (challengeVisible()) {
challengeWasSeen = true;
if (!challengeLogged) {
challengeLogged = true;
overlay.log('Cloudflare verification detected. Waiting for it to finish; complete it yourself if prompted.', 'warn');
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === draft.currentId);
if (current) current.challengeSeen = true;
draft.note = 'Cloudflare verification detected. Complete it on the page if prompted; automation will continue afterward.';
});
}
await wait(750);
continue;
}
const outcome = submissionOutcome(job);
if (outcome?.kind === 'success') {
await finishCurrent('submitted', `${job.name}: submitted. ${outcome.message}`);
return;
}
if (outcome?.kind === 'failure' || outcome?.kind === 'fatal') {
await finishCurrent('failed', `${job.name}: ${outcome.message}`);
return;
}
const urlChanged = location.href !== startingUrl;
const pageReloaded = Number(job.pageTimeOrigin) && Number(job.pageTimeOrigin) !== Number(performance.timeOrigin);
if (job.status === 'reviewing' && !job.serverRequestSentAt && pageReloaded && Date.now() - startedAt > 2500) {
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === draft.currentId);
if (current) current.status = 'pending';
draft.currentId = null;
draft.note = `${job.name}: the pre-submit review dialog was lost during reload; safely retrying it.`;
});
overlay.log('The review dialog was lost before any server request was sent; safely retrying this JSON.', 'warn');
processing = false;
runQueue();
return;
}
if ((urlChanged || pageReloaded) && !findJsonInput() && Date.now() - startedAt > 2500) {
await finishCurrent('submitted', `${job.name}: submission completed after the server verification/navigation.`);
return;
}
if (challengeWasSeen && pageReloaded && Date.now() - startedAt > 5000) {
await finishCurrent('submitted', `${job.name}: Cloudflare verification completed and the submission page returned.`);
return;
}
await wait(500);
}
await pauseWith(
`${job.name}: the server outcome was not clear after ${Math.round(timeoutMs / 1000)} seconds. Check the page, then use “Mark submitted + next” or “Skip current” in the extension.`,
false
);
processing = false;
}
function isTransientUiError(error) {
const message = normalize(error?.message || error);
return [
'upload section did not appear',
'did not finish opening its json file-upload control',
'did not finish importing',
'name field never changed',
'submit button was not found or is still disabled',
'model option'
].some((fragment) => message.includes(fragment));
}
async function retryTransientUiFailure(job, error) {
const state = await readState();
const stored = state?.queue?.find((item) => item.id === job.id);
const retryCount = (stored?.uiRetryCount || 0) + 1;
if (!stored || stored.serverRequestSentAt || retryCount > UI_RETRY_LIMIT) return false;
retryingUi = true;
const retryDelayMs = Math.min(8000, 1500 * retryCount);
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === job.id);
if (current) {
current.status = 'pending';
current.error = '';
current.uiRetryCount = retryCount;
}
draft.currentId = null;
draft.running = true;
draft.paused = false;
draft.note = `${job.name}: the form was not ready; automatic retry ${retryCount}/${UI_RETRY_LIMIT} in ${Math.round(retryDelayMs / 1000)} seconds.`;
});
overlay.log(
`The Protenix form was not ready (${error.message}). Retrying automatically ${retryCount}/${UI_RETRY_LIMIT} in ${Math.round(retryDelayMs / 1000)} seconds…`,
'warn'
);
processing = false;
await wait(retryDelayMs);
const latest = await readState();
retryingUi = false;
if (!latest?.running || latest.paused || stoppedLocally) return true;
if (location.pathname !== ADD_PATH) {
location.assign(latest.submitUrl || `${location.origin}${ADD_PATH}`);
} else {
runQueue();
}
return true;
}
async function submitJob(state, job) {
overlay.start(`Submitting ${job.name}`, job.name);
const counts = queueCounts(state);
overlay.count(`${counts.submitted} submitted · ${state.queue.filter((item) => item.status === 'pending').length} pending`);
overlay.progress(counts.done, counts.total);
overlay.log(`Preparing ${job.fileName}…`);
try {
overlay.log(`Waiting ${FORM_WARMUP_MS / 1000} seconds for the Protenix form to settle…`);
await wait(FORM_WARMUP_MS);
if (challengeVisible()) {
await pauseWith('A Cloudflare verification is already open. Complete it on the page, then press Resume.', false);
processing = false;
return;
}
await attachJson(job);
overlay.log('Protenix parsed the JSON and populated the form.', 'ok');
if (state.settings?.modelName) {
const modelSet = await setModel(state.settings.modelName);
if (!modelSet) throw new Error(`Model option “${state.settings.modelName}” was not found.`);
overlay.log(`Model: ${state.settings.modelName}`, 'ok');
}
if (state.settings?.msa && state.settings.msa !== 'unchanged') {
const set = await setBooleanField('msa', state.settings.msa);
if (!set) overlay.log('MSA control was not found; the page setting was left unchanged.', 'warn');
}
if (state.settings?.template && state.settings.template !== 'unchanged') {
const set = await setBooleanField('template', state.settings.template);
if (!set) overlay.log('Template control was not found; the page setting was left unchanged.', 'warn');
}
const submit = await waitForSubmitButton();
if (!submit) throw new Error('The Submit button was not found or is still disabled.');
const pageTimeOrigin = performance.timeOrigin;
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === job.id);
if (current) {
current.status = 'reviewing';
current.attempts = (current.attempts || 0) + 1;
current.startedAt = Date.now();
current.submissionUrl = location.href;
current.pageTimeOrigin = pageTimeOrigin;
current.uiRetryCount = 0;
}
draft.currentId = job.id;
draft.note = `Submitting ${job.name}…`;
});
overlay.log('Pressing Submit to open Protenix’s review dialog…');
submit.click();
await wait(250);
const refreshed = await readState();
const storedJob = refreshed?.queue.find((item) => item.id === job.id) || { ...job, pageTimeOrigin, submissionUrl: location.href };
await monitorSubmission(storedJob);
} catch (error) {
if (isTransientUiError(error) && await retryTransientUiFailure(job, error)) return;
await mutateState((draft) => {
const current = draft.queue.find((item) => item.id === job.id);
if (current) {
current.status = 'failed';
current.error = error.message;
}
draft.currentId = null;
draft.running = false;
draft.paused = true;
draft.note = `${job.name}: ${error.message}`;
});
overlay.error(`${job.name}: ${error.message}`);
overlay.setPaused(true);
processing = false;
}
}
async function runQueue() {
if (processing || retryingUi) return;
processing = true;
stoppedLocally = false;
const state = await readState();
if (!state?.running || state.paused) { processing = false; return; }
if (state.currentId) {
const current = state.queue.find((job) => job.id === state.currentId);
if (current) {
overlay.start(`Waiting for ${current.name}`, current.name);
overlay.log(challengeVisible()
? 'Cloudflare verification detected. Complete it yourself if prompted.'
: 'A submission is already in progress; checking its result…', 'warn');
await monitorSubmission(current);
return;
}
await mutateState((draft) => { draft.currentId = null; });
}
const refreshed = await readState();
const selection = nextPendingSelection(refreshed);
if (!selection) {
const submitted = refreshed.queue.filter((job) => job.status === 'submitted').length;
await mutateState((draft) => {
draft.running = false;
draft.paused = false;
draft.note = `Finished. Submitted ${submitted} job(s).`;
});
overlay.start('Protenix queue complete');
overlay.done(`Finished. Submitted ${submitted} job(s).`);
processing = false;
return;