-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
1689 lines (1511 loc) · 64.5 KB
/
Copy pathmain.js
File metadata and controls
1689 lines (1511 loc) · 64.5 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
(() => {
const $ = (sel, ctx = document) => ctx.querySelector(sel);
const $$ = (sel, ctx = document) => Array.from(ctx.querySelectorAll(sel));
function cleanText(value) {
return String(value || '')
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.replace(/`/g, '')
.trim();
}
function cleanURL(value) {
const raw = cleanText(value);
try {
return new URL(raw).origin;
} catch {
return raw.replace(/\s/g, '').replace(/\/+$/, '');
}
}
const _urlParams = new URLSearchParams(window.location.search);
const iframeState = {
token: cleanText(_urlParams.get('token')),
srcHost: cleanURL(_urlParams.get('src_host')),
userId: cleanText(_urlParams.get('user_id')),
isEmbedded: cleanText(_urlParams.get('ui_mode')) === 'embedded'
};
console.log('[生图调试] iframe参数:', {
hasToken: !!iframeState.token,
tokenLen: iframeState.token.length,
srcHost: iframeState.srcHost,
userId: iframeState.userId,
isEmbedded: iframeState.isEmbedded
});
(function initDarkMode() {
const root = document.documentElement;
function applyTheme(isDark) {
root.setAttribute('data-theme', isDark ? 'dark' : 'light');
console.log('[深色模式]', isDark ? '深色' : '浅色');
}
function getSystemDark() {
try {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch (e) {
return false;
}
}
function getParentDark() {
try {
if (window.parent && window.parent !== window) {
const parentDoc = window.parent.document;
const parentTheme = parentDoc.documentElement.getAttribute('data-theme');
if (parentTheme) return parentTheme === 'dark';
const parentCS = window.parent.getComputedStyle(parentDoc.documentElement);
if (parentCS.colorScheme && parentCS.colorScheme.includes('dark')) return true;
const parentBg = parentCS.backgroundColor;
if (parentBg) {
const match = parentBg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (match) {
const brightness = (parseInt(match[1]) * 299 + parseInt(match[2]) * 587 + parseInt(match[3]) * 114) / 1000;
return brightness < 128;
}
}
}
} catch (e) {
console.log('[深色模式] 无法访问父级窗口:', e.message);
}
return null;
}
let currentDark = false;
function syncTheme() {
const parentDark = getParentDark();
const isDark = parentDark !== null ? parentDark : getSystemDark();
if (isDark !== currentDark) {
currentDark = isDark;
applyTheme(isDark);
}
}
syncTheme();
try {
if (window.parent && window.parent !== window) {
const parentDoc = window.parent.document;
const observer = new MutationObserver(function() {
syncTheme();
});
observer.observe(parentDoc.documentElement, {
attributes: true,
attributeFilter: ['data-theme', 'class', 'style']
});
console.log('[深色模式] 已监听父级窗口变化');
}
} catch (e) {
console.log('[深色模式] 无法监听父级窗口:', e.message);
}
try {
if (window.matchMedia) {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handler = function() {
if (getParentDark() === null) {
syncTheme();
}
};
if (mediaQuery.addEventListener) {
mediaQuery.addEventListener('change', handler);
} else if (mediaQuery.addListener) {
mediaQuery.addListener(handler);
}
console.log('[深色模式] 已监听系统主题变化');
}
} catch (e) {
console.log('[深色模式] 无法监听系统主题:', e.message);
}
window.addEventListener('focus', syncTheme);
setInterval(syncTheme, 2000);
})();
async function callSub2API(path) {
if (!iframeState.token || !iframeState.srcHost) return null;
const url = new URL(path, iframeState.srcHost + '/').toString();
const resp = await fetch(url, {
headers: {
'Authorization': 'Bearer ' + iframeState.token,
'Accept': 'application/json'
},
mode: 'cors',
credentials: 'omit',
cache: 'no-store'
});
if (!resp.ok) {
const text = await resp.text();
throw new Error('API ' + resp.status + ': ' + text);
}
return resp.json();
}
function showToast(message, type = 'info') {
let container = $('#toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
const toast = document.createElement('div');
toast.className = 'toast toast-' + type;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(() => toast.classList.add('toast-visible'));
setTimeout(() => {
toast.classList.remove('toast-visible');
toast.addEventListener('transitionend', () => toast.remove(), { once: true });
setTimeout(() => toast.remove(), 400);
}, 3000);
}
function showConfirm(title, message) {
return new Promise(function(resolve) {
var overlay = document.createElement('div');
overlay.className = 'confirm-overlay';
overlay.innerHTML = '<div class="confirm-backdrop"></div><div class="confirm-dialog"><div class="confirm-icon"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/></svg></div><h3 class="confirm-title"></h3><p class="confirm-message"></p><div class="confirm-actions"><button type="button" class="confirm-btn confirm-btn-cancel">取消</button><button type="button" class="confirm-btn confirm-btn-confirm">确认清空</button></div></div>';
overlay.querySelector('.confirm-title').textContent = title;
overlay.querySelector('.confirm-message').textContent = message;
document.body.appendChild(overlay);
requestAnimationFrame(function() { overlay.classList.add('confirm-active'); });
function close(result) {
overlay.classList.remove('confirm-active');
setTimeout(function() { overlay.remove(); }, 250);
resolve(result);
}
overlay.querySelector('.confirm-backdrop').addEventListener('click', function() { close(false); });
overlay.querySelector('.confirm-btn-cancel').addEventListener('click', function() { close(false); });
overlay.querySelector('.confirm-btn-confirm').addEventListener('click', function() { close(true); });
document.addEventListener('keydown', function handler(e) {
if (e.key === 'Escape') {
document.removeEventListener('keydown', handler);
close(false);
}
});
});
}
(() => {
const modes = ['text', 'image', 'history'];
const tabs = $$('.image-tabs .image-tab[data-mode]');
const panels = $$('[data-panel]');
if (!tabs.length || !panels.length) return;
function setMode(mode, updateHash = false) {
const next = modes.includes(mode) ? mode : modes[0];
for (const tab of tabs) {
const active = tab.dataset.mode === next;
tab.classList.toggle('image-tab-active', active);
tab.setAttribute('aria-selected', active ? 'true' : 'false');
tab.tabIndex = active ? 0 : -1;
}
for (const panel of panels) {
const active = panel.dataset.panel === next;
panel.hidden = !active;
panel.setAttribute('aria-hidden', active ? 'false' : 'true');
}
if (updateHash) {
history.replaceState(null, '', '#' + next);
}
}
tabs.forEach(tab => {
tab.addEventListener('click', () => setMode(tab.dataset.mode, true));
});
const tabList = $('.image-tabs');
if (tabList) {
tabList.addEventListener('keydown', e => {
const current = tabs.findIndex(t => t.classList.contains('image-tab-active'));
let next = -1;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
e.preventDefault();
next = (current + 1) % tabs.length;
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
e.preventDefault();
next = (current - 1 + tabs.length) % tabs.length;
} else if (e.key === 'Home') {
e.preventDefault();
next = 0;
} else if (e.key === 'End') {
e.preventDefault();
next = tabs.length - 1;
}
if (next >= 0) {
tabs[next].focus();
setMode(tabs[next].dataset.mode, true);
}
});
}
const fromHash = location.hash.replace('#', '');
const initial = modes.includes(fromHash) ? fromHash : (tabs.find(t => t.classList.contains('image-tab-active'))?.dataset.mode || modes[0]);
setMode(initial, false);
})();
(() => {
const panels = $$('.advanced-panel');
if (!panels.length) return;
const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
const duration = 300;
function setExpanded(details, expanded) {
const summary = details.querySelector('summary');
if (summary) summary.setAttribute('aria-expanded', expanded ? 'true' : 'false');
}
function finishAnimation(body, callback) {
let done = false;
const cleanup = () => {
if (done) return;
done = true;
body.removeEventListener('transitionend', onEnd);
callback();
};
const onEnd = event => {
if (event.target === body && event.propertyName === 'height') cleanup();
};
body.addEventListener('transitionend', onEnd);
window.setTimeout(cleanup, duration + 60);
}
function openPanel(details, body) {
details.open = true;
setExpanded(details, true);
body.style.paddingBottom = '0px';
if (motionQuery.matches) {
body.style.height = 'auto';
body.style.opacity = '1';
body.style.paddingBottom = '';
return;
}
body.style.height = '0px';
body.style.opacity = '0';
body.style.transform = 'translateY(-6px)';
body.dataset.animating = 'true';
requestAnimationFrame(() => {
body.style.paddingBottom = '';
body.style.height = body.scrollHeight + 'px';
body.style.opacity = '1';
body.style.transform = 'translateY(0)';
});
finishAnimation(body, () => {
body.dataset.animating = 'false';
body.style.height = 'auto';
body.style.paddingBottom = '';
body.style.transform = '';
});
}
function closePanel(details, body) {
setExpanded(details, false);
body.style.paddingBottom = window.getComputedStyle(body).paddingBottom;
if (motionQuery.matches) {
body.style.height = '0px';
body.style.opacity = '0';
details.open = false;
body.style.paddingBottom = '';
return;
}
body.style.height = body.scrollHeight + 'px';
body.style.opacity = '1';
body.dataset.animating = 'true';
requestAnimationFrame(() => {
body.style.height = '0px';
body.style.opacity = '0';
body.style.paddingBottom = '0px';
body.style.transform = 'translateY(-6px)';
});
finishAnimation(body, () => {
body.dataset.animating = 'false';
details.open = false;
body.style.paddingBottom = '';
body.style.transform = '';
});
}
panels.forEach(details => {
const summary = details.querySelector('summary');
const body = details.querySelector('.advanced-body');
if (!summary || !body) return;
details.open = false;
body.style.height = '0px';
body.style.opacity = '0';
summary.setAttribute('aria-expanded', 'false');
summary.addEventListener('click', event => {
event.preventDefault();
if (body.dataset.animating === 'true') return;
if (details.open) {
closePanel(details, body);
} else {
openPanel(details, body);
}
});
});
})();
// ============================================================
// SizeIntent 尺寸意图自动降级模块
// ============================================================
const SIZE_MATRIX = {
'1:1': {
'1k': [1024, 1024],
'2k': [2048, 2048],
'4k': [4096, 4096]
},
'4:3': {
'1k': [1365, 1024],
'2k': [2730, 2048],
'4k': [5461, 4096]
},
'3:4': {
'1k': [1024, 1365],
'2k': [2048, 2730],
'4k': [4096, 5461]
},
'16:9': {
'1k': [1536, 864],
'2k': [2048, 1152],
'4k': [3840, 2160]
},
'9:16': {
'1k': [864, 1536],
'2k': [1152, 2048],
'4k': [2160, 3840]
}
};
const ASPECT_PROMPT_MAP = {
'1:1': 'square composition',
'4:3': 'landscape composition, 4:3 aspect ratio',
'3:4': 'portrait composition, 3:4 aspect ratio',
'16:9': 'cinematic wide composition, 16:9 aspect ratio',
'9:16': 'vertical mobile composition, 9:16 aspect ratio'
};
const RESOLUTION_PROMPT_MAP = {
'1k': 'high detail',
'2k': 'ultra detailed, high resolution',
'4k': 'extremely detailed, 4k quality, ultra high resolution'
};
function getGPTModelCapabilities(modelID) {
const normalized = String(modelID || '').toLowerCase();
if (normalized.startsWith('gpt-image') || normalized.startsWith('chatgpt-image')) {
return {
supportsSize: true,
supportedSizes: ['1024x1024', '1536x1024', '1024x1536'],
maxResolution: 1536
};
}
if (normalized.startsWith('dall-e-3')) {
return {
supportsSize: true,
supportedSizes: ['1024x1024', '1792x1024', '1024x1792'],
maxResolution: 1792
};
}
if (normalized.startsWith('dall-e-2')) {
return {
supportsSize: true,
supportedSizes: ['256x256', '512x512', '1024x1024'],
maxResolution: 1024
};
}
return {
supportsSize: true,
supportedSizes: ['1024x1024', '1536x1024', '1024x1536'],
maxResolution: 1536
};
}
function buildSizeIntent(ratio, resolutionTier) {
const isAutoRatio = (ratio === '自动生成');
const isAutoTier = (resolutionTier === 'auto');
if (isAutoRatio && isAutoTier) {
return {
aspect: 'auto',
resolution: 'auto',
width: null,
height: null,
size: 'auto',
aspectRatio: null,
promptEnhancement: ''
};
}
const aspectKey = isAutoRatio ? '1:1' : ratio.replace(/ 正方形| 横版| 竖版/g, '');
const resolutionKey = isAutoTier ? '1k' : resolutionTier.toLowerCase();
const sizeEntry = SIZE_MATRIX[aspectKey]?.[resolutionKey];
const width = sizeEntry ? sizeEntry[0] : 1024;
const height = sizeEntry ? sizeEntry[1] : 1024;
const aspectDesc = ASPECT_PROMPT_MAP[aspectKey] || '';
const resolutionDesc = RESOLUTION_PROMPT_MAP[resolutionKey] || '';
const promptEnhancement = [aspectDesc, resolutionDesc].filter(Boolean).join(', ');
return {
aspect: aspectKey,
resolution: resolutionKey,
width,
height,
size: `${width}x${height}`,
aspectRatio: `${width}:${height}`,
promptEnhancement
};
}
function applySizeIntentToTool(tool, sizeIntent, modelID) {
const capabilities = getGPTModelCapabilities(modelID);
console.log('[生图调试] ===== 尺寸应用 =====');
console.log('[生图调试] 模型ID:', modelID);
console.log('[生图调试] 模型能力:', JSON.stringify(capabilities, null, 2));
console.log('[生图调试] 期望尺寸:', sizeIntent.size);
if (sizeIntent.size === 'auto') {
tool.size = 'auto';
console.log('[生图调试] 结果: 自动模式,使用auto');
return tool;
}
if (capabilities.supportedSizes.includes(sizeIntent.size)) {
tool.size = sizeIntent.size;
console.log('[生图调试] 结果: 模型直接支持,使用', tool.size);
return tool;
}
console.log('[生图调试] 模型不直接支持', sizeIntent.size, ',开始降级...');
const scale = Math.min(
capabilities.maxResolution / sizeIntent.width,
capabilities.maxResolution / sizeIntent.height,
1
);
const scaledWidth = Math.floor(sizeIntent.width * scale);
const scaledHeight = Math.floor(sizeIntent.height * scale);
const roundTo64 = (n) => Math.round(n / 64) * 64;
tool.size = `${roundTo64(scaledWidth)}x${roundTo64(scaledHeight)}`;
console.log('[生图调试] 缩放比例:', scale.toFixed(4));
console.log('[生图调试] 缩放后:', scaledWidth + 'x' + scaledHeight);
console.log('[生图调试] 对齐64后:', tool.size);
console.log('[生图调试] 最终降级: ' + sizeIntent.size + ' -> ' + tool.size + ' (模型最大' + capabilities.maxResolution + ')');
return tool;
}
function enhancePromptWithSizeIntent(prompt, sizeIntent) {
if (!sizeIntent.promptEnhancement) return prompt;
const lowerPrompt = prompt.toLowerCase();
const skipKeywords = ['aspect ratio', 'resolution', 'composition', 'detail', '4k', '2k', '1k'];
const hasExistingSizeHint = skipKeywords.some(kw => lowerPrompt.includes(kw));
if (hasExistingSizeHint) return prompt;
return `${prompt}, ${sizeIntent.promptEnhancement}`;
}
console.log('[生图调试] SizeIntent模块已加载');
const SELECT_OPTIONS = {
'api-key': [
{ value: 'pool-gpt', label: '对接中转 · GPT【主推号池】' },
{ value: 'pool-claude', label: '对接中转 · Claude【备用号池】' },
{ value: 'direct-gpt4o', label: '直连官方 · GPT-4o' }
],
'model': [
{ value: 'gpt-image-2', label: 'gpt-image-2' },
{ value: 'gpt-image-1.5', label: 'gpt-image-1.5' },
{ value: 'gpt-image-1', label: 'gpt-image-1' }
],
'quality': [
{ value: 'auto', label: '自动' },
{ value: 'low', label: '低' },
{ value: 'medium', label: '中' },
{ value: 'high', label: '高' }
],
'background': [
{ value: 'auto', label: '自动' },
{ value: 'transparent', label: '透明' },
{ value: 'opaque', label: '不透明' }
],
'format': [
{ value: 'png', label: 'PNG' },
{ value: 'webp', label: 'WebP' },
{ value: 'jpeg', label: 'JPEG' }
]
};
(() => {
let openDropdown = null;
function closeDropdown() {
if (openDropdown) {
openDropdown.classList.remove('select-open');
const menu = openDropdown.querySelector('.select-menu');
if (menu) menu.remove();
openDropdown = null;
}
}
document.addEventListener('click', e => {
if (openDropdown && !openDropdown.contains(e.target)) {
closeDropdown();
}
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape') closeDropdown();
});
function createSelect(field, optionsKey) {
const trigger = field.querySelector('.select-trigger');
if (!trigger) return;
const wrapper = trigger.closest('.relative') || trigger.parentElement;
const options = SELECT_OPTIONS[optionsKey] || [];
let currentValue = options[0]?.value || '';
trigger.addEventListener('click', e => {
e.stopPropagation();
if (openDropdown === wrapper) {
closeDropdown();
return;
}
closeDropdown();
const menu = document.createElement('div');
menu.className = 'select-menu';
options.forEach(opt => {
const item = document.createElement('button');
item.type = 'button';
item.className = 'select-option' + (opt.value === currentValue ? ' select-option-active' : '');
item.textContent = opt.label;
item.addEventListener('click', ev => {
ev.stopPropagation();
currentValue = opt.value;
trigger.querySelector('.select-value').textContent = opt.label;
closeDropdown();
updateCost();
});
menu.appendChild(item);
});
wrapper.classList.add('select-open');
wrapper.appendChild(menu);
openDropdown = wrapper;
const firstItem = menu.querySelector('.select-option');
if (firstItem) firstItem.focus();
});
trigger.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
trigger.click();
}
});
}
function initPanelSelects(panel) {
if (!panel) return;
const fields = $$('.image-field', panel);
fields.forEach(field => {
const trigger = field.querySelector('.select-trigger');
if (!trigger) return;
const label = field.querySelector('.input-label');
if (!label) return;
const labelText = label.textContent.trim();
let key = '';
if (labelText.includes('API') || labelText.includes('密钥')) key = 'api-key';
else if (labelText.includes('模型')) key = 'model';
else if (labelText.includes('质量')) key = 'quality';
else if (labelText.includes('背景')) key = 'background';
else if (labelText.includes('输出格式')) key = 'format';
if (key) createSelect(field, key);
});
}
async function fetchAndPopulateApiKeys() {
if (!iframeState.isEmbedded || !iframeState.token) return;
try {
const resp = await callSub2API('/api/v1/keys').catch(() => null);
const items = resp?.data?.items || resp?.data || [];
if (!Array.isArray(items) || items.length === 0) return;
const apiKeys = items.map(item => ({
value: cleanText(item.key),
label: cleanText(item.name || item.key || '未命名密钥')
}));
console.log('[生图调试] 获取到API密钥数量:', apiKeys.length, apiKeys.map(k => ({ label: k.label, valueLen: k.value.length })));
if (apiKeys.length > 0) {
SELECT_OPTIONS['api-key'] = apiKeys;
}
$$('.select-trigger').forEach(trigger => {
const field = trigger.closest('.image-field');
if (!field) return;
const label = field.querySelector('.input-label');
if (!label) return;
if (label.textContent.trim().includes('API') || label.textContent.trim().includes('密钥')) {
trigger.querySelector('.select-value').textContent = SELECT_OPTIONS['api-key'][0]?.label || '';
}
});
} catch (e) {
// fallback to hardcoded options
}
}
(async () => {
await fetchAndPopulateApiKeys();
initPanelSelects($('#panel-text'));
initPanelSelects($('#panel-image'));
})();
})();
(() => {
$$('.field-ratio').forEach(field => {
const cards = $$('.ratio-card', field);
const tierBtns = $$('.tier-btn', field);
const display = $('.image-active-value', field);
cards.forEach(card => {
card.addEventListener('click', () => {
cards.forEach(c => c.classList.remove('ratio-card-active'));
card.classList.add('ratio-card-active');
const ratio = card.querySelector('.ratio-label')?.textContent || '';
if (display) display.textContent = ratio;
updateCost();
});
});
tierBtns.forEach(btn => {
btn.addEventListener('click', () => {
tierBtns.forEach(b => b.classList.remove('tier-btn-active'));
btn.classList.add('tier-btn-active');
updateCost();
});
});
});
})();
(() => {
$$('.image-range').forEach(range => {
const field = range.closest('.field-prompt');
if (!field) return;
const display = $('.image-active-value', field);
if (display) {
const update = () => {
display.textContent = range.value;
updateCost();
};
range.addEventListener('input', update);
update();
}
});
$$('textarea.input, textarea.prompt-textarea').forEach(textarea => {
const field = textarea.closest('.image-field');
if (!field) return;
const counter = $('.char-count', field);
if (counter) {
const update = () => {
counter.textContent = textarea.value.length + ' 字符';
};
textarea.addEventListener('input', update);
update();
}
});
})();
(() => {
$$('.prompt-chip').forEach(chip => {
chip.addEventListener('click', () => {
const field = chip.closest('.image-field');
if (!field) return;
const textarea = $('textarea.input, textarea.prompt-textarea', field);
if (textarea) {
textarea.value = chip.textContent;
textarea.dispatchEvent(new Event('input'));
textarea.focus();
}
});
});
})();
(() => {
const panel = $('#panel-image');
if (!panel) return;
const fileInput = $('input[type="file"]', panel);
const uploadLabel = $('.reference-upload', panel);
const listContainer = $('.mock-reference-list', panel);
const countDisplay = $('.image-muted', panel);
if (!fileInput || !listContainer) return;
let files = [];
function updateCount() {
if (countDisplay) countDisplay.textContent = files.length + ' / 4';
if (uploadLabel) uploadLabel.style.display = files.length >= 4 ? 'none' : '';
}
function renderList() {
listContainer.innerHTML = '';
files.forEach((f, i) => {
const item = document.createElement('div');
item.className = 'reference-item';
if (f.dataUrl) {
const img = document.createElement('img');
img.src = f.dataUrl;
img.alt = f.name;
img.className = 'reference-thumb';
item.appendChild(img);
}
const nameSpan = document.createElement('span');
nameSpan.className = 'reference-name';
nameSpan.textContent = f.name;
nameSpan.title = f.name;
item.appendChild(nameSpan);
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'reference-remove';
removeBtn.innerHTML = '×';
removeBtn.title = '移除';
removeBtn.addEventListener('click', () => {
files.splice(i, 1);
renderList();
updateCount();
});
item.appendChild(removeBtn);
listContainer.appendChild(item);
});
updateCost();
}
fileInput.addEventListener('change', () => {
const newFiles = Array.from(fileInput.files);
const remaining = 4 - files.length;
if (remaining <= 0) {
showToast('最多上传 4 张参考图', 'warning');
fileInput.value = '';
return;
}
const toAdd = newFiles.slice(0, remaining);
if (newFiles.length > remaining) {
showToast('已达上限,仅添加前 ' + remaining + ' 张', 'warning');
}
let loaded = 0;
toAdd.forEach(file => {
if (file.size > 20 * 1024 * 1024) {
showToast(file.name + ' 超过 20MB 限制', 'error');
loaded++;
return;
}
const reader = new FileReader();
reader.onload = () => {
files.push({ name: file.name, dataUrl: reader.result });
loaded++;
if (loaded === toAdd.length) renderList();
};
reader.onerror = () => {
loaded++;
showToast(file.name + ' 读取失败', 'error');
if (loaded === toAdd.length) renderList();
};
reader.readAsDataURL(file);
});
fileInput.value = '';
});
if (uploadLabel) {
uploadLabel.addEventListener('dragover', e => {
e.preventDefault();
uploadLabel.classList.add('reference-upload-hover');
});
uploadLabel.addEventListener('dragleave', () => {
uploadLabel.classList.remove('reference-upload-hover');
});
uploadLabel.addEventListener('drop', e => {
e.preventDefault();
uploadLabel.classList.remove('reference-upload-hover');
const dt = e.dataTransfer;
if (dt.files.length) {
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event('change'));
}
});
}
panel._getFiles = () => files;
updateCount();
})();
function updateCost() {
const PRICE_PER_IMAGE = 0.06;
$$('.mode-panel').forEach(panel => {
const costEl = $('.cost-value', panel);
if (!costEl) return;
let count = 1;
const range = $('.image-range', panel);
if (range) count = parseInt(range.value) || 1;
const total = (PRICE_PER_IMAGE * count).toFixed(2);
costEl.textContent = '$' + total;
});
}
updateCost();
// 最大重试次数:请求失败时最多重试3次
const MAX_ATTEMPTS = 3;
// 重试等待间隔:两次重试之间暂停15秒(单位:毫秒)
const RETRY_BACKOFF_MS = 15000;
// 最大并发数:同时生成的图片数量上限,避免并发过高导致接口限流
const MAX_CONCURRENT = 10;
function isRetryableError(err) {
const msg = (err.message || '').toLowerCase();
if (msg.includes('service temporarily unavailable')) return true;
if (msg.includes('524') || msg.includes('504') || msg.includes('gateway time-out')) return true;
if (msg.includes('origin_gateway_timeout')) return true;
if (msg.includes('api_error') || msg.includes('server_error')) return true;
if (/http 50[234]/.test(msg) || /http 524/.test(msg)) return true;
return false;
}
function getErrorHint(err) {
const msg = (err.message || '').toLowerCase();
if (msg.includes('moderation_blocked') || msg.includes('content_policy_violation'))
return '上游内容审核拦截,提示词可能包含违规内容';
if (msg.includes('rate_limit_exceeded'))
return '上游限速,请稍后再试';
if (msg.includes('insufficient_quota') || msg.includes('billing_hard_limit_reached'))
return '上游账户额度不足,请更换 API 密钥';
if (msg.includes('model_not_found'))
return '上游找不到指定模型,请检查模型配置';
if (msg.includes('service temporarily unavailable'))
return '服务暂时不可用,已自动重试';
if (msg.includes('524') || msg.includes('504') || msg.includes('gateway time-out'))
return '上游网关超时,生成可能仍在进行';
return '';
}
function walkForImageCall(value) {
if (!value) return null;
if (Array.isArray(value)) {
for (const child of value) {
const found = walkForImageCall(child);
if (found) return found;
}
return null;
}
if (typeof value === 'object') {
if (value.type === 'image_generation_call' && value.result) return value;
for (const child of Object.values(value)) {
const found = walkForImageCall(child);
if (found) return found;
}
}
return null;
}
function extractImageResult(raw) {
let partialB64 = '';
let partialPrompt = '';
for (const line of raw.split(/\r?\n/)) {
if (!line.startsWith('data: ')) continue;
const payload = line.slice(6).trim();
if (!payload || payload === '[DONE]') continue;
let event;
try { event = JSON.parse(payload); } catch { continue; }
if (event.type === 'response.image_generation_call.partial_image' && event.partial_image_b64) {
partialB64 = event.partial_image_b64;
partialPrompt = event.revised_prompt || partialPrompt;
continue;
}
if (event.type === 'response.output_item.done' && event.item?.type === 'image_generation_call') {
if (event.item.result) {
return { imageB64: event.item.result, revisedPrompt: event.item.revised_prompt || '' };
}
if (partialB64) {
return { imageB64: partialB64, revisedPrompt: partialPrompt };
}
}
}
try {
const parsed = JSON.parse(raw);
const found = walkForImageCall(parsed);
if (found?.result) {
return { imageB64: found.result, revisedPrompt: found.revised_prompt || '' };
}
} catch {}
if (partialB64) {
return { imageB64: partialB64, revisedPrompt: partialPrompt };
}
return null;
}
async function requestResponsesAPI(baseURL, apiKey, requestBody, onProgress) {
let lastError;
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
const fullURL = baseURL + '/v1/responses';
const maskedKey = apiKey ? (apiKey.slice(0, 8) + '****' + apiKey.slice(-4)) : 'null';
console.groupCollapsed('[生图调试] 第 ' + attempt + ' 次请求');
console.log('请求地址:', fullURL);
console.log('API Key:', maskedKey);
console.log('请求体:', JSON.stringify(requestBody, null, 2));
console.groupEnd();
if (attempt > 1 && onProgress) {
onProgress('第 ' + attempt + ' 次重试中...');
}
const response = await fetch(fullURL, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json',
'Accept': 'text/event-stream, application/json'
},
body: JSON.stringify(requestBody)
});
console.log('[生图调试] 响应状态:', response.status, response.statusText);
if (!response.ok) {
const errText = await response.text();
console.error('[生图调试] 错误响应原文:', errText);
let msg = 'HTTP ' + response.status;
try {