-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1753 lines (1552 loc) · 53.2 KB
/
Copy pathbackground.js
File metadata and controls
1753 lines (1552 loc) · 53.2 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
// 本文件维护 ImgPrompt 扩展后台服务。
// 本次修改把“禧哈哈灵感集”的本地保存、云端上传和分组同步放到后台执行,避免内容脚本直接承载后端请求逻辑。
// 具体修改点:新增 xihaha 消息处理、Cloudflare Worker 上传、chrome.storage.local 本地灵感库保存,并把生成图片 data URL 传回结果面板。
//
// 2026-07-13 健壮性修复(问题 4/5/6/8/11):
// - 问题4:saveToHistory 超出上限时改为循环删除所有超额记录,并在同一事务内 await 完成,修复历史记录无法真正裁剪到 50 条的问题。
// - 问题5:compressImageBlob 对 PNG/WebP/GIF 等可能带透明通道的图片改用 PNG 输出,避免透明背景被填成黑底影响模型分析。
// - 问题6:新增 fetchWithTimeout,为正式生成的模型请求(OpenAI 兼容 / Anthropic)加入自动超时(默认 120s),避免接口卡死时进度条永久停留。
// - 问题8:settings:updated 消息处理改为同步回包并对 sendResponse 做保护,避免 message port closed 告警。
// - 问题11:将 Supabase URL/Key 抽到 config.js 统一维护,background 不再内联硬编码,减少多处重复。
// 问题3(遥测默认关闭):trackAnalyticsEvent 原判断为 `analyticsConfig !== false`,因存储键从未被写入,
// 默认 undefined 被判定为开启,且 options 无可见开关,导致 PostHog 遥测默认常开。现改为必须显式
// 为 true 才发送(opt-in),默认即关闭,避免把访问页面 URL 默认上报到第三方。
importScripts("config.js");
const CONFIG = globalThis.ImgPromptConfig || {};
const DEFAULT_SETTINGS = CONFIG.DEFAULT_SETTINGS;
const UI_STRINGS = CONFIG.UI_STRINGS;
const POSTHOG_PROJECT_KEY = CONFIG.POSTHOG_PROJECT_KEY;
const POSTHOG_HOST = CONFIG.POSTHOG_HOST;
const ERROR_CODES = CONFIG.ERROR_CODES;
const ERROR_MESSAGES = CONFIG.ERROR_MESSAGES;
const ANALYTICS_CONFIG_KEY = CONFIG.ANALYTICS_CONFIG_KEY;
const XIHAHA_WORKER_ENDPOINT = CONFIG.XIHAHA_WORKER_ENDPOINT;
const XIHAHA_CATEGORIES_ENDPOINT = CONFIG.XIHAHA_CATEGORIES_ENDPOINT;
const XIHAHA_LOCAL_LIBRARY_KEY = CONFIG.XIHAHA_LOCAL_LIBRARY_KEY || "xihaha_local_inspirations";
// 问题11:Supabase 连接信息统一从 config.js 读取,避免在 background 内联硬编码导致多处维护。
const SUPABASE_URL = CONFIG.SUPABASE_URL || "https://mxcsnyobeboahlctkssq.supabase.co";
const SUPABASE_PUBLISHABLE_KEY =
CONFIG.SUPABASE_PUBLISHABLE_KEY || "sb_publishable_i4hxK3VR6QYRuSlCiBszoA_G_Ew-2qc";
const MENU_ID = "image-prompt-inspector.generate";
const CLIENT_ID_KEY = "clientId";
const MAX_HISTORY_ITEMS = 50;
// 问题6:正式生成的模型请求超时时间(毫秒)。视觉模型响应较慢,给到 120s;超时后自动中止并按超时错误处理。
const MODEL_REQUEST_TIMEOUT_MS = 120000;
// IndexedDB configuration
const DB_NAME = "ImgPromptDB";
const DB_VERSION = 1;
const HISTORY_STORE = "history";
let dbInstance = null;
const activeRequests = new Map();
// Initialize IndexedDB when service worker starts
initIndexedDB().catch((error) => {
console.error("[ImgPrompt] Failed to initialize IndexedDB on startup:", error);
});
chrome.runtime.onInstalled.addListener(async (details) => {
const clientId = await ensureClientId();
chrome.contextMenus.create({
id: MENU_ID,
title: "ImgPrompt",
contexts: ["image"],
});
if (chrome.sidePanel?.setPanelBehavior) {
await chrome.sidePanel.setPanelBehavior({
openPanelOnActionClick: true,
});
}
const current = await chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS));
const nextValues = {};
for (const [key, value] of Object.entries(DEFAULT_SETTINGS)) {
if (current[key] === undefined) {
nextValues[key] = value;
}
}
if (Object.keys(nextValues).length) {
await chrome.storage.local.set(nextValues);
}
// Initialize IndexedDB for history
try {
await initIndexedDB();
} catch (error) {
console.error("[ImgPrompt] Failed to initialize IndexedDB:", error);
}
const installReason = details?.reason || "unknown";
if (installReason === "install") {
void safeTrackAnalyticsEvent("extension_installed", {
clientId,
installReason,
});
} else if (installReason === "update") {
void safeTrackAnalyticsEvent("extension_updated", {
clientId,
installReason,
previousVersion: details?.previousVersion || "",
});
}
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId !== MENU_ID || !tab?.id) {
return;
}
const requestId = crypto.randomUUID();
await sendTabMessage(tab.id, {
type: "prompt:start-analysis",
requestId,
srcUrl: info.srcUrl || "",
pageUrl: info.pageUrl || "",
trigger: "context_menu",
});
});
chrome.commands.onCommand.addListener(async (command) => {
if (command !== "capture_screenshot") return;
const settings = await loadSettings();
if (settings.snippingShortcutEnabled === false) return;
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id) return;
try {
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: "png" });
await sendTabMessage(tab.id, {
type: "prompt:start-snipping",
dataUrl,
});
} catch (err) {
console.error("Failed to capture screenshot:", err);
}
});
// 记录最近一次激活的“普通网页”标签页 id,供设置页“抓取当前页面”使用。
// 否则当设置页本身处于激活态时,会把设置页当成抓取目标(无图片/无内容脚本)。
let lastWebTabId = null;
if (chrome.tabs?.onActivated) {
chrome.tabs.onActivated.addListener(async ({ tabId }) => {
try {
const tab = await chrome.tabs.get(tabId);
const url = tab?.url || "";
if (/^https?:\/\//i.test(url)) {
lastWebTabId = tabId;
}
} catch {
/* 忽略无权限或临时标签 */
}
});
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "analytics:track") {
safeTrackAnalyticsEvent(message.event, {
...(message.properties || {}),
...buildAnalyticsContext(message.properties?.pageUrl || sender.tab?.url || ""),
})
.then((sent) => sendResponse({ ok: true, sent }))
.catch((error) => {
sendResponse({
ok: false,
error: error instanceof Error ? error.message : String(error),
});
});
return true;
}
if (message?.type === "prompt:open-options") {
openSidePanelForSender(sender)
.then(() => sendResponse({ ok: true }))
.catch((error) => {
sendResponse({
ok: false,
error: error instanceof Error ? error.message : String(error),
});
});
return true;
}
// 中转:侧边栏历史记录 → 网页 content script 面板
if (message?.type === "prompt:relay-history-item") {
(async () => {
try {
const targetTabId = await findBestWebTabId();
if (!targetTabId) {
sendResponse({ ok: false, error: "当前窗口无可用网页标签(请先打开一个普通网页)" });
return;
}
// 逐标签尝试,直到有 content script 成功接收
const webTabIds = (await chrome.tabs.query({ currentWindow: true }))
.filter(
(t) =>
t.id && /^https?:\/\//i.test(t.url || "") && !t.url.startsWith("chrome-extension://"),
)
.map((t) => t.id);
// 把最佳标签排到最前
const ordered = [targetTabId, ...webTabIds.filter((id) => id !== targetTabId)];
let lastErr = null;
for (const tabId of ordered) {
try {
await chrome.tabs.sendMessage(tabId, {
type: "prompt:load-history-item",
data: message.data,
});
sendResponse({ ok: true });
return;
} catch (e) {
lastErr = e;
}
}
sendResponse({
ok: false,
error:
lastErr instanceof Error ? lastErr.message : "所有网页标签均无响应(可能未加载完成)",
});
} catch (err) {
sendResponse({
ok: false,
error: err instanceof Error ? err.message : String(err),
});
}
})();
return true;
}
if (message?.type === "prompt:cancel-generation") {
const controller = activeRequests.get(message.requestId);
if (controller) {
controller.abort();
activeRequests.delete(message.requestId);
sendResponse({ ok: true, canceled: true });
return false;
}
sendResponse({ ok: true, canceled: false });
return false;
}
if (message?.type === "settings:updated") {
// 问题8:这是一个“通知型”消息,无需等待转发结果即可回包。
// 先同步回包(避免消息端口在异步 tabs.query 期间关闭产生 message port closed 告警),
// 再 fire-and-forget 地把更新转发给所有标签页的内容脚本。
try {
sendResponse({ ok: true });
} catch (error) {
// 端口可能已被发送方关闭(发送方使用 fire-and-forget),忽略即可。
}
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
if (tab.id) {
chrome.tabs.sendMessage(tab.id, { type: "settings:updated" }).catch(() => {
// Ignore errors for tabs where content script is not injected or responsive
});
}
});
});
return false;
}
if (message?.type === "history:get") {
getHistory()
.then((history) => sendResponse({ ok: true, history }))
.catch((error) => sendResponse({ ok: false, error: String(error) }));
return true;
}
if (message?.type === "history:delete") {
deleteHistoryItem(message.id)
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: String(error) }));
return true;
}
if (message?.type === "history:clear") {
clearHistory()
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: String(error) }));
return true;
}
if (message?.type === "api:test-connection") {
testApiConnection(message.settings)
.then((result) => sendResponse(result))
.catch((error) => sendResponse({ success: false, error: error.message }));
return true;
}
if (message?.type === "xihaha:get-categories") {
getXihahaCategories()
.then((categories) => sendResponse({ ok: true, categories }))
.catch((error) =>
sendResponse({ ok: false, error: error instanceof Error ? error.message : String(error) }),
);
return true;
}
if (message?.type === "xihaha:collect-page-images") {
collectActiveTabImages()
.then((result) =>
sendResponse({
ok: true,
images: result.images,
prompt: result.prompt,
title: result.title,
pageUrl: result.pageUrl,
}),
)
.catch((error) =>
sendResponse({ ok: false, error: error instanceof Error ? error.message : String(error) }),
);
return true;
}
if (message?.type === "xihaha:save-local") {
saveXihahaLocalInspiration(message.payload || {})
.then((item) => sendResponse({ ok: true, item }))
.catch((error) =>
sendResponse({ ok: false, error: error instanceof Error ? error.message : String(error) }),
);
return true;
}
if (message?.type === "xihaha:upload-cloud") {
uploadXihahaCloudInspiration(message.payload || {})
.then((result) => sendResponse({ ok: true, result }))
.catch((error) =>
sendResponse({ ok: false, error: error instanceof Error ? error.message : String(error) }),
);
return true;
}
if (message?.type !== "prompt:begin-generation") {
return false;
}
processGeneration(message, sender)
.then(() => sendResponse({ ok: true }))
.catch((error) => {
sendResponse({
ok: false,
error: error instanceof Error ? error.message : String(error),
});
});
return true;
});
async function openSidePanelForSender(sender) {
if (!chrome.sidePanel?.open) {
throw new Error("当前浏览器不支持侧边栏 API。");
}
if (sender.tab?.windowId) {
await chrome.sidePanel.open({
windowId: sender.tab.windowId,
});
return;
}
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
if (!activeTab?.windowId) {
throw new Error("未找到可用窗口来打开侧边栏。");
}
await chrome.sidePanel.open({
windowId: activeTab.windowId,
});
}
// 找到最适合承载 ImgPrompt 内容面板的网页标签页:
// 优先 lastWebTabId(最近激活的普通网页)→ 其次当前窗口中激活的网页 → 再退化为任意普通网页
async function findBestWebTabId() {
const isWebUrl = (url) =>
!!url && /^https?:\/\//i.test(url) && !url.startsWith("chrome-extension://");
const tabs = await chrome.tabs.query({ currentWindow: true });
const webTabs = tabs.filter((t) => t.id && isWebUrl(t.url));
if (!webTabs.length) return null;
// 1. lastWebTabId 优先
if (lastWebTabId) {
const matched = webTabs.find((t) => t.id === lastWebTabId);
if (matched) return matched.id;
}
// 2. 当前激活的网页标签
const activeWeb = webTabs.find((t) => t.active);
if (activeWeb) return activeWeb.id;
// 3. 退化:第一个可用网页
return webTabs[0].id;
}
function normalizeXihahaPayload(payload = {}) {
const title = String(payload.title || "").trim();
const category = String(payload.category || "未分组").trim() || "未分组";
const prompt = String(payload.prompt || "").trim();
const imageDataUrl = String(payload.imageDataUrl || "").trim();
const imageUrl = String(payload.imageUrl || "").trim();
if (!title) {
throw new Error("缺少标题。");
}
if (!prompt) {
throw new Error("缺少提示词内容。");
}
if (!imageDataUrl && !imageUrl) {
throw new Error("缺少图片内容或图片链接。");
}
return {
title,
category,
prompt,
imageDataUrl,
imageUrl,
pageTitle: String(payload.pageTitle || "").trim(),
pageUrl: String(payload.pageUrl || "").trim(),
};
}
async function saveXihahaLocalInspiration(payload) {
const normalized = normalizeXihahaPayload(payload);
const stored = await chrome.storage.local.get({ [XIHAHA_LOCAL_LIBRARY_KEY]: [] });
const currentItems = Array.isArray(stored[XIHAHA_LOCAL_LIBRARY_KEY])
? stored[XIHAHA_LOCAL_LIBRARY_KEY]
: [];
const item = {
id: crypto.randomUUID(),
createdAt: Date.now(),
source: "img2prompt",
...normalized,
};
await chrome.storage.local.set({
[XIHAHA_LOCAL_LIBRARY_KEY]: [item, ...currentItems].slice(0, 500),
});
// 同时尽力推送到桌面端「我的灵感」本地收藏:桌面端需运行且桥接服务在监听 127.0.0.1:18765
pushToDesktopLocalBridge(normalized);
return item;
}
// 浏览器扩展 → 桌面端本地收藏 的桥接推送(best-effort,桌面端未运行时静默忽略)
const XIHAHA_DESKTOP_BRIDGE_URL = "http://127.0.0.1:18765/api/xihaha/local-inspiration";
async function pushToDesktopLocalBridge(normalized) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4000);
const response = await fetch(XIHAHA_DESKTOP_BRIDGE_URL, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({
title: normalized.title,
prompt: normalized.prompt,
group: normalized.category,
imageUrl: normalized.imageUrl,
imageDataUrl: normalized.imageDataUrl || undefined,
sourceUrl: normalized.pageUrl || normalized.pageTitle || "",
tags: normalized.category && normalized.category !== "未分组" ? [normalized.category] : [],
}),
signal: controller.signal,
});
clearTimeout(timeout);
if (!response.ok) {
console.warn("[ImgPrompt] 桌面端桥接返回非成功状态:", response.status);
}
} catch (error) {
// 桌面端未启动 / 端口未监听 / 被拦截:忽略,保存本地已成功写入扩展本地库
console.warn(
"[ImgPrompt] 推送桌面端本地收藏失败(桌面端可能未运行):",
error?.message || error,
);
}
}
async function uploadXihahaCloudInspiration(payload) {
const normalized = normalizeXihahaPayload(payload);
const adminPassword = String(payload.adminPassword || "").trim();
if (!adminPassword) {
throw new Error("请先在禧哈哈灵感集设置里填写管理员密码。");
}
if (!XIHAHA_WORKER_ENDPOINT) {
throw new Error("缺少云端上传接口配置。");
}
const response = await fetch(XIHAHA_WORKER_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
adminPassword,
...normalized,
}),
});
let data = null;
try {
data = await response.json();
} catch (error) {
data = null;
}
if (!response.ok || data?.ok === false) {
throw new Error(data?.error || `云端上传失败:HTTP ${response.status}`);
}
return data || { ok: true };
}
async function getXihahaCategories() {
// 策略1:优先从 Cloudflare Worker 获取分组
if (XIHAHA_CATEGORIES_ENDPOINT) {
try {
const response = await fetch(XIHAHA_CATEGORIES_ENDPOINT, {
method: "GET",
headers: { Accept: "application/json" },
});
if (response.ok) {
const data = await response.json();
const cats = extractCategories(data);
if (cats.length > 0) return cats;
}
} catch (e) {
console.warn("[ImgPrompt] Worker categories 端点不可达,改用 Supabase 直连:", e.message);
}
}
// 策略2:Worker 不可达或返回空时,直连 Supabase REST API 兜底
// 问题11:使用 config.js 统一维护的 SUPABASE_URL / SUPABASE_PUBLISHABLE_KEY,不再内联硬编码。
try {
const response = await fetch(
`${SUPABASE_URL}/rest/v1/inspirations?select=category&order=category.asc`,
{
method: "GET",
headers: {
apikey: SUPABASE_PUBLISHABLE_KEY,
authorization: `Bearer ${SUPABASE_PUBLISHABLE_KEY}`,
Accept: "application/json",
},
},
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const rows = await response.json();
const cats = [
...new Set(
rows
.map((row) => (typeof row.category === "string" ? row.category.trim() : ""))
.filter(Boolean),
),
];
return cats;
} catch (e) {
console.warn("[ImgPrompt] Supabase 分组直连也失败:", e.message);
return [];
}
}
function extractCategories(data) {
const rawCategories = Array.isArray(data)
? data
: Array.isArray(data?.categories)
? data.categories
: Array.isArray(data?.data)
? data.data
: [];
return rawCategories
.map((item) => {
if (typeof item === "string") return item;
return item?.name || item?.category || item?.title || "";
})
.map((category) => String(category || "").trim())
.filter(Boolean);
}
// 向当前激活标签页的内容脚本请求页面图片列表(供设置页"抓取当前页面"使用)
// 抓取当前页面的图片/提示词/标题/地址,完整透传给设置页。
// 优先抓取"最近激活的普通网页",避免设置页自身作为激活标签时抓不到任何内容。
// 若 lastWebTabId 无结果则遍历所有非扩展标签页尝试。
async function collectActiveTabImages() {
const empty = { images: [], prompt: "", title: "", pageUrl: "" };
// 收集候选标签页:当前活跃 + 最近访问的网页 + 所有其他网页标签
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
const allTabs = await chrome.tabs.query({ currentWindow: true });
const webTabs = allTabs.filter(
(t) => t.id && /^https?:\/\//i.test(t.url || "") && !t.url.startsWith("chrome-extension://"),
);
// 去重候选列表(保持顺序:active → lastWebTab → 其他网页)
const candidateIds = [];
if (activeTab?.id) candidateIds.push(activeTab.id);
if (lastWebTabId && lastWebTabId !== activeTab?.id) candidateIds.push(lastWebTabId);
for (const t of webTabs) {
if (!candidateIds.includes(t.id)) candidateIds.push(t.id);
}
// 记录最佳候选(有图片的那个)用于日志
let bestResult = null;
for (const tabId of candidateIds) {
try {
const response = await chrome.tabs.sendMessage(tabId, { type: "xihaha:collect-page-images" });
if (response?.ok) {
const images = Array.isArray(response.images) ? response.images : [];
const result = {
images,
prompt: String(response.prompt || ""),
title: String(response.title || ""),
pageUrl: String(response.pageUrl || ""),
};
// 有图片直接采用;无图片但有 prompt/title 也保留为备选
if (images.length > 0) return result;
if (!bestResult && (result.prompt || result.title)) bestResult = result;
}
} catch (e) {
// 该标签无内容脚本或不可达,继续下一个
console.warn(`[ImgPrompt] 标签 ${tabId} 抓取跳过:`, e?.message || e);
if (!bestResult) {
// 尝试动态注入内容脚本并重试
try {
await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ["config.js", "content.js"],
});
const retryResponse = await chrome.tabs.sendMessage(tabId, {
type: "xihaha:collect-page-images",
});
if (
retryResponse &&
retryResponse.ok &&
(retryResponse.images?.length > 0 || retryResponse.prompt || retryResponse.title)
) {
bestResult = retryResponse;
continue; // 成功获取,继续下一个
}
} catch (injectErr) {
// 注入失败,继续执行基础后备逻辑
console.warn(`[ImgPrompt] 标签 ${tabId} 注入回退失败:`, injectErr?.message || injectErr);
}
// 如果依然没有结果,获取起码的页面标题和URL
if (!bestResult) {
try {
const tab = await chrome.tabs.get(tabId);
if (tab && tab.title) {
bestResult = {
images: [],
prompt: "",
title: String(tab.title || ""),
pageUrl: String(tab.url || ""),
};
}
} catch (err) {
// 忽略
}
}
}
}
}
// 所有候选都没有图片但可能有文字内容
return bestResult || empty;
}
async function processGeneration(message, sender) {
const tabId = sender.tab?.id;
if (!tabId) {
throw new Error("Missing tab id.");
}
const { requestId, srcUrl, imageDataUrl, pageContext = {}, trigger = "unknown" } = message;
const controller = new AbortController();
activeRequests.set(requestId, controller);
const startedAt = Date.now();
const settings = await loadSettings();
const lang = settings.uiLanguage || "zh";
const dict = UI_STRINGS[lang] || UI_STRINGS.zh;
try {
await sendProgress(tabId, requestId, 8, dict.preparing, "config");
void safeTrackAnalyticsEvent("generation_started", {
requestId,
trigger,
model: settings.model,
...buildAnalyticsContext(pageContext.pageUrl || sender.tab?.url || ""),
});
validateSettings(settings, lang);
await sendProgress(tabId, requestId, 22, dict.fetchingImage, "image");
// Always fetch and compress in background (unified logic)
const imageInput = await fetchAndCompressImage(
imageDataUrl || srcUrl,
settings.maxImageEdge || 1024,
controller.signal,
);
if (!imageInput) {
throw new Error(dict.base64Failed);
}
await sendProgress(tabId, requestId, 48, dict.callingModel, "request");
const rawResult = await requestPromptFromModel({
settings,
imageInput,
pageContext,
signal: controller.signal,
});
await sendProgress(tabId, requestId, 88, dict.organizingPrompts, "parse");
const prompts = normalizePromptResult(rawResult, lang);
await sendTabMessage(tabId, {
type: "prompt:result",
requestId,
progress: 100,
prompts,
source: {
srcUrl,
imageDataUrl: imageInput,
},
});
void safeTrackAnalyticsEvent("generation_succeeded", {
requestId,
trigger,
model: settings.model,
durationMs: Date.now() - startedAt,
...buildAnalyticsContext(pageContext.pageUrl || sender.tab?.url || ""),
});
void saveToHistory({
prompts,
srcUrl,
imageDataUrl: imageInput,
pageUrl: pageContext.pageUrl || sender.tab?.url || "",
model: settings.model,
trigger,
}).then(() => {
// Notify options page to refresh history
chrome.runtime.sendMessage({ type: "history:updated" }).catch(() => {});
});
} catch (error) {
if (controller.signal.aborted) {
await sendTabMessage(tabId, {
type: "prompt:canceled",
requestId,
errorCode: ERROR_CODES.CANCELED,
});
void safeTrackAnalyticsEvent("generation_canceled", {
requestId,
trigger,
durationMs: Date.now() - startedAt,
...buildAnalyticsContext(pageContext.pageUrl || sender.tab?.url || ""),
});
return;
}
// Classify error
const errorCode = classifyError(error);
const userMessage = getUserErrorMessage(errorCode, lang);
await sendTabMessage(tabId, {
type: "prompt:error",
requestId,
errorCode,
message: userMessage,
});
void safeTrackAnalyticsEvent("generation_failed", {
requestId,
trigger,
model: (await loadSettings()).model,
durationMs: Date.now() - startedAt,
errorCode,
errorMessage:
error instanceof Error ? error.message.slice(0, 240) : String(error).slice(0, 240),
...buildAnalyticsContext(pageContext.pageUrl || sender.tab?.url || ""),
});
throw error;
} finally {
activeRequests.delete(requestId);
}
}
async function loadSettings() {
const stored = await chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS));
return {
...DEFAULT_SETTINGS,
...stored,
};
}
async function ensureClientId() {
const stored = await chrome.storage.local.get(CLIENT_ID_KEY);
if (stored[CLIENT_ID_KEY]) {
return stored[CLIENT_ID_KEY];
}
const clientId = crypto.randomUUID();
await chrome.storage.local.set({
[CLIENT_ID_KEY]: clientId,
});
return clientId;
}
function buildAnalyticsContext(rawUrl) {
if (!rawUrl) {
return {};
}
try {
const url = new URL(rawUrl);
return {
pageHost: url.host,
pageProtocol: url.protocol.replace(":", ""),
};
} catch (error) {
return {};
}
}
async function trackAnalyticsEvent(eventName, properties = {}) {
if (!eventName) {
return false;
}
// 问题3:遥测改为 opt-in——必须显式存储为 true 才发送,默认(undefined/任何非 true 值)一律关闭。
const analyticsConfig = await chrome.storage.local.get(ANALYTICS_CONFIG_KEY);
const analyticsEnabled = analyticsConfig[ANALYTICS_CONFIG_KEY] === true;
if (!analyticsEnabled) {
return false;
}
if (!POSTHOG_PROJECT_KEY || !POSTHOG_HOST) {
return false;
}
const clientId = properties.clientId || (await ensureClientId());
const captureUrl = `${String(POSTHOG_HOST).replace(/\/+$/, "")}/capture/`;
const response = await fetch(captureUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
api_key: POSTHOG_PROJECT_KEY,
event: eventName,
distinct_id: clientId,
timestamp: new Date().toISOString(),
properties: {
...properties,
distinct_id: clientId,
$lib: "imgprompt-extension",
$lib_version: chrome.runtime.getManifest().version,
extensionVersion: chrome.runtime.getManifest().version,
},
}),
});
if (!response.ok) {
throw new Error(`Analytics request failed (${response.status})`);
}
return true;
}
async function safeTrackAnalyticsEvent(eventName, properties = {}) {
try {
return await trackAnalyticsEvent(eventName, properties);
} catch (error) {
return false;
}
}
async function saveToHistory(record) {
try {
console.log("[ImgPrompt] Saving to history:", {
prompts: record.prompts?.zh?.substring(0, 50),
});
const db = await getDB();
const tx = db.transaction(HISTORY_STORE, "readwrite");
const store = tx.objectStore(HISTORY_STORE);
const item = {
id: crypto.randomUUID(),
timestamp: Date.now(),
...record,
};
await new Promise((resolve, reject) => {
const request = store.add(item);
request.onsuccess = () => {
console.log("[ImgPrompt] History item saved successfully");
resolve();
};
request.onerror = (event) => {
console.error("[ImgPrompt] Failed to save history item:", event.target.error);
reject(event.target.error);
};
});
// Check if we exceed max items and delete oldest if needed
const count = await new Promise((resolve, reject) => {
const request = store.count();
request.onsuccess = () => resolve(request.result);
request.onerror = reject;
});
// 问题4:超过上限时,循环删除所有超额的最旧记录,并在同一事务内 await 完成,
// 避免旧实现只删 1 条且 cursor.delete() 时机不稳导致历史缓慢超出上限。
if (count > MAX_HISTORY_ITEMS) {
const excess = count - MAX_HISTORY_ITEMS;
await new Promise((resolve, reject) => {
const index = store.index("timestamp");
// timestamp 升序(next)即从最旧开始
const cursorRequest = index.openCursor(null, "next");
let removed = 0;
cursorRequest.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && removed < excess) {
cursor.delete();
removed += 1;
cursor.continue();
} else {
resolve();
}
};
cursorRequest.onerror = (event) => reject(event.target.error);
});
}
return true;
} catch (error) {
console.error("[ImgPrompt] Failed to save history:", error);
return false;
}
}
async function getHistory() {
try {
const db = await getDB();
const tx = db.transaction(HISTORY_STORE, "readonly");
const store = tx.objectStore(HISTORY_STORE);
const index = store.index("timestamp");
return new Promise((resolve, reject) => {
const request = index.openCursor(null, "prev");
const results = [];
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && results.length < MAX_HISTORY_ITEMS) {
results.push(cursor.value);
cursor.continue();
} else {
console.log("[ImgPrompt] Retrieved history items:", results.length);
resolve(results);
}
};
request.onerror = (event) => {
console.error("[ImgPrompt] Failed to retrieve history:", event.target.error);
reject(event.target.error);
};
});
} catch (error) {
console.error("[ImgPrompt] Failed to get history:", error);
return [];
}
}
async function deleteHistoryItem(id) {
try {
const db = await getDB();
const tx = db.transaction(HISTORY_STORE, "readwrite");
const store = tx.objectStore(HISTORY_STORE);
await new Promise((resolve, reject) => {
const request = store.delete(id);
request.onsuccess = resolve;
request.onerror = reject;
});
return true;
} catch (error) {
console.error("[ImgPrompt] Failed to delete history item:", error);
return false;
}
}
async function clearHistory() {
try {
const db = await getDB();