-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·3528 lines (3057 loc) · 157 KB
/
index.ts
File metadata and controls
executable file
·3528 lines (3057 loc) · 157 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
import 'webextension-polyfill';
console.log('[background] Initializing background imports...');
import { pluginChatApi } from './plugin-chat-api';
console.log('[background] Plugin chat API loaded');
import { hostApi } from './host-api';
console.log('[background] Host API loaded');
import { getAvailablePlugins } from './plugin-manager';
console.log('[background] Plugin manager loaded');
import { getPageKey } from '../../../packages/shared/lib/utils/helpers';
import { getApiKeyForModel, callAiModel } from './ai-api-client';
import { exampleThemeStorage, pluginSettingsStorage, getPluginSettings } from '@extension/storage';
import type { PluginSettings } from '@extension/storage';
import { ensureOffscreenDocument } from '../../../src/background/offscreen-manager';
import { APIKeyManager } from '../../../pages/options/src/utils/encryption';
console.log('[background] Storage modules loaded');
// Глобальный счетчик для генерации уникальных messageId
let messageIdCounter = 0;
// Интерфейсы для сообщений
interface ExtensionMessage {
type: string;
[key: string]: any;
}
/**
* Response for GET_ACTIVE_TAB_INFO and GET_ACTIVE_TAB_URL messages
* Contains information about the active tab including its URL and unique identifier
*/
interface ActiveTabInfo {
/** The URL of the active tab, or 'about:blank' if unavailable */
url: string;
/** The numeric ID of the active tab, or -1 if unavailable */
tabId: number;
/** Timestamp when the info was retrieved */
timestamp: number;
/** Error message if the tab info could not be retrieved */
error?: string;
}
console.log('[background] Starting Offscreen Document integration - REFACTORED BACKGROUND ARCHITECTURE');
// Функция для отправки обновлений чата плагина
const broadcastChatUpdate = (pluginId: string, pageKey: string) => {
chrome.runtime.sendMessage({
type: 'PLUGIN_CHAT_UPDATED',
pluginId,
pageKey,
});
};
// === OFFSCREEN API FEATURE DETECTION ===
// Enhanced production-ready feature detection функция для проверки доступности offscreen API
const offscreenSupported = (): boolean => {
try {
console.log('[background][OFFSCREEN DETECTION] ========== STARTING OFFSCREEN API FEATURE DETECTION ==========');
console.log('[background][OFFSCREEN DETECTION] Timestamp:', new Date().toISOString());
console.log('[background][OFFSCREEN DETECTION] Chrome User-Agent:', navigator.userAgent);
// Проверка 1: Глобальный объект chrome
const chromeExists = typeof chrome !== 'undefined';
console.log('[background][OFFSCREEN DETECTION] Chrome object exists:', chromeExists);
if (!chromeExists) {
console.warn('[background][OFFSCREEN DETECTION] ❌ FAIL: Chrome API unavailable - extension running in unsupported environment');
console.warn('[background][OFFSCREEN DETECTION] Current context:', {
globalThis: typeof globalThis,
window: typeof window,
self: typeof self,
process: typeof process
});
return false;
}
// Проверка 2: Offscreen API доступен
const offscreenExists = typeof chrome.offscreen !== 'undefined';
console.log('[background][OFFSCREEN DETECTION] chrome.offscreen property exists:', offscreenExists);
if (!offscreenExists) {
console.warn('[background][OFFSCREEN DETECTION] ❌ FAIL: chrome.offscreen is undefined - Chrome version < 109');
console.warn('[background][OFFSCREEN DETECTION] Available chrome API:', Object.keys(chrome).join(', '));
return false;
}
// Проверка 3: hasDocument method доступен
const hasDocumentExists = typeof chrome.offscreen.hasDocument === 'function';
console.log('[background][OFFSCREEN DETECTION] chrome.offscreen.hasDocument is function:', hasDocumentExists);
if (!hasDocumentExists) {
console.warn('[background][OFFSCREEN DETECTION] ❌ FAIL: chrome.offscreen.hasDocument is not a function');
console.warn('[background][OFFSCREEN DETECTION] chrome.offscreen properties:', Object.keys(chrome.offscreen).join(', '));
return false;
}
// Проверка 4: createDocument method доступен
const createDocumentExists = typeof chrome.offscreen.createDocument === 'function';
console.log('[background][OFFSCREEN DETECTION] chrome.offscreen.createDocument is function:', createDocumentExists);
if (!createDocumentExists) {
console.warn('[background][OFFSCREEN DETECTION] ❌ FAIL: chrome.offscreen.createDocument is not a function');
console.warn('[background][OFFSCREEN DETECTION] chrome.offscreen methods:', Object.getOwnPropertyNames(chrome.offscreen).join(', '));
return false;
}
// Проверка 5: Manifest permissions check (runtime validation)
const permissionsCheck = chrome.permissions ? typeof chrome.permissions.getAll === 'function' : true;
if (!permissionsCheck) {
console.warn('[background][OFFSCREEN DETECTION] ⚠️ WARNING: Cannot verify permissions at runtime');
}
console.log('[background][OFFSCREEN DETECTION] ✅ SUCCESS: All Offscreen API checks passed');
console.log('[background][OFFSCREEN DETECTION] ========== DETECTION COMPLETE ==========');
return true;
} catch (error) {
console.error('[background][OFFSCREEN DETECTION] ❌ CRITICAL ERROR during detection:', error);
console.error('[background][OFFSCREEN DETECTION] Error message:', (error as Error).message);
console.error('[background][OFFSCREEN DETECTION] Error stack:', (error as Error).stack);
console.error('[background][OFFSCREEN DETECTION] Chrome version from UA:', navigator.userAgent.match(/Chrome\/(\d+)/)?.[1] || 'Unknown');
// Additional diagnostic info
try {
console.error('[background][OFFSCREEN DETECTION] Chrome API dump (limited):');
if (typeof chrome !== 'undefined') {
console.error('- chrome.runtime available:', typeof chrome.runtime);
console.error('- chrome.permissions available:', typeof chrome.permissions);
if (chrome.offscreen) {
console.error('- chrome.offscreen keys:', Object.keys(chrome.offscreen));
}
}
} catch (dumpError) {
console.error('[background][OFFSCREEN DETECTION] Error creating diagnostic dump:', dumpError);
}
return false;
}
};
// Enhanced production-ready fallback обработчик для старых версий Chrome (< 109)
// === IMPROVED CHUNKING SYSTEM - ENHANCED VERSION ===
// Реализуем улучшенную систему chunking согласно Варианту B
// IMPROVED: Constants for enhanced chunking configuration
const CHUNK_SIZE = 256 * 1024; // 256KB - оптимальный размер для Chrome messaging
const MAX_CHUNKS = 50; // Максимум 50 чанков (12.5MB)
const CHUNK_DELAY = 10; // 10ms delay between chunks для стабильности
// IMPROVED: Enhanced function to create chunks from HTML data
function createChunks(html: string, chunkSize: number = CHUNK_SIZE): {
chunks: string[];
totalChunks: number;
totalSize: number;
chunkSize: number;
} {
const chunks: string[] = [];
const totalSize = html.length;
// Проверяем, не превышает ли общий размер лимиты
const maxTotalSize = chunkSize * MAX_CHUNKS;
if (totalSize > maxTotalSize) {
throw new Error(`HTML data too large: ${totalSize} chars exceeds maximum ${maxTotalSize} chars (${MAX_CHUNKS} chunks × ${chunkSize} chars)`);
}
// Разбиваем HTML на chunks
for (let i = 0; i < html.length; i += chunkSize) {
const chunk = html.slice(i, i + chunkSize);
chunks.push(chunk);
}
console.log(`[IMPROVED_CHUNKING] Created ${chunks.length} chunks from ${totalSize} chars (chunk size: ${chunkSize})`);
return {
chunks,
totalChunks: chunks.length,
totalSize,
chunkSize
};
}
// Функция для отправки HTML в одном сообщении (прямая передача)
const sendHtmlDirectly = async (
pluginId: string,
pageKey: string,
html: string,
requestId: string,
transferId: string,
pluginSettings: Record<string, any> = {}
): Promise<void> => {
console.log('[background][DIRECT_TRANSMISSION] Sending HTML directly to offscreen for transfer:', transferId);
console.log('[background][DIRECT_TRANSMISSION] HTML size:', html.length, 'chars');
console.log('[background][DIRECT_TRANSMISSION] Transmission mode: DIRECT');
try {
// Проверяем размер HTML для прямой передачи
if (html.length > CHUNK_SIZE * MAX_CHUNKS) {
console.warn('[background][DIRECT_TRANSMISSION] ⚠️ HTML too large for direct transmission, using chunks instead');
throw new Error('HTML слишком большой для прямой передачи, используем чанки');
}
// Создаем сообщение для прямой передачи HTML
const directMessage = {
type: 'HTML_DIRECT',
transferId,
pluginId,
pageKey,
requestId,
htmlData: html,
totalSize: html.length,
timestamp: Date.now(),
metadata: {
pluginId,
pageKey,
requestId,
totalSize: html.length,
timestamp: Date.now(),
transmissionMethod: 'direct'
}
};
console.log('[background][DIRECT_TRANSMISSION] Sending direct HTML message to offscreen...');
// Отправляем HTML в одном сообщении с обработкой ошибок
const directResponse = await chrome.runtime.sendMessage(directMessage);
if (chrome.runtime.lastError) {
throw new Error(chrome.runtime.lastError.message);
}
console.log('[background][DIRECT_TRANSMISSION] Direct HTML transmission completed successfully');
// Ждем подтверждения получения HTML от offscreen
console.log('[background][DIRECT_TRANSMISSION] Waiting for HTML receipt confirmation...');
const confirmResponse = await chrome.runtime.sendMessage({
type: 'CONFIRM_HTML_RECEIPT',
transferId,
pluginId,
pageKey,
requestId,
timestamp: Date.now()
}) as any;
if (chrome.runtime.lastError) {
console.warn('[background][DIRECT_TRANSMISSION] Confirmation failed:', (chrome.runtime.lastError as any).message);
} else if ((confirmResponse as any)?.confirmed) {
console.log('[background][DIRECT_TRANSMISSION] ✅ HTML receipt confirmed by offscreen');
} else {
console.warn('[background][DIRECT_TRANSMISSION] ⚠️ HTML receipt not confirmed by offscreen');
}
// Запускаем workflow в offscreen document с прямой передачей
try {
// Получить API ключ для передачи в offscreen
let geminiApiKey: string | undefined;
try {
geminiApiKey = await getApiKeyForModel('gemini-flash-lite') || undefined;
console.log('[background][DIRECT_TRANSMISSION] ✅ API key retrieved for workflow');
} catch (keyError) {
console.warn('[background][DIRECT_TRANSMISSION] ⚠️ Failed to get API key:', keyError);
geminiApiKey = undefined;
}
await executeWorkflowInOffscreen(pluginId, pageKey, transferId, requestId, false, html, geminiApiKey, pluginSettings);
console.log('[background][DIRECT_TRANSMISSION] Workflow execution initiated successfully');
} catch (workflowError) {
console.error('[background][DIRECT_TRANSMISSION] Failed to execute workflow:', workflowError);
throw workflowError;
}
} catch (error) {
console.error('[background][DIRECT_TRANSMISSION] Failed to send HTML directly:', error);
// Если прямая передача не удалась, пробуем отправить чанками как fallback
console.log('[background][DIRECT_TRANSMISSION] Direct transmission failed, falling back to chunked transmission');
throw error; // Передаем ошибку дальше для обработки в RUN_WORKFLOW
}
};
// DEPRECATED: Interfaces for chunked HTML streaming - no longer used
/*
interface HtmlChunkMessage {
type: 'HTML_CHUNK';
transferId: string;
chunkIndex: number;
totalChunks: number;
chunkData: string;
metadata: {
pluginId: string;
pageKey: string;
totalSize: number;
requestId: string;
};
}
interface HtmlChunkAckMessage {
type: 'HTML_CHUNK_ACK';
transferId: string;
chunkIndex: number;
received: boolean;
}
*/
// DEPRECATED: Global state for managing chunk transfers - no longer used
// Keeping minimal structure for backwards compatibility
const activeTransfers = new Map<string, any>();
// DEPRECATED: Session Storage Persistence Layer - replaced by direct data transmission
// Keeping for backwards compatibility but no longer used in main workflow
// === TRANSFER STORAGE VERIFICATION & RECOVERY SYSTEM ===
// Детальная диагностика состояния transfer'а
function diagnoseTransferState(transferId: string): {
exists: boolean;
isValid: boolean;
diagnostics: any;
} {
const transfer = activeTransfers.get(transferId);
const diagnostics: any = {
transferId,
timestamp: Date.now(),
exists: !!transfer,
storageSize: activeTransfers.size,
allTransferIds: Array.from(activeTransfers.keys())
};
if (!transfer) {
console.error(`[TRANSFER_DIAG] ❌ Transfer ${transferId} not found in active storage`);
return { exists: false, isValid: false, diagnostics };
}
// Проверяем валидность структуры transfer'а
const isValid = (
Array.isArray(transfer.chunks) &&
transfer.chunks.length > 0 &&
transfer.received instanceof Set &&
typeof transfer.totalChunks === 'number' &&
typeof transfer.resolve === 'function' &&
typeof transfer.reject === 'function'
);
diagnostics.isValid = isValid;
diagnostics.chunksCount = transfer.chunks.length;
diagnostics.receivedCount = transfer.received.size;
diagnostics.totalChunks = transfer.totalChunks;
diagnostics.createdAt = transfer.createdAt;
diagnostics.lastAccessed = transfer.lastAccessed;
diagnostics.age = Date.now() - transfer.createdAt;
if (!isValid) {
console.error(`[TRANSFER_DIAG] ❌ Transfer ${transferId} has invalid structure:`, diagnostics);
} else {
console.log(`[TRANSFER_DIAG] ✅ Transfer ${transferId} is valid:`, diagnostics);
}
return { exists: true, isValid, diagnostics };
}
// Верификация хранения transfer'а сразу после создания
function verifyTransferStorage(transferId: string, expectedChunks: string[]): boolean {
console.log(`[TRANSFER_VERIFY] 🔍 Verifying transfer ${transferId} storage immediately after creation`);
const { exists, isValid, diagnostics } = diagnoseTransferState(transferId);
if (!exists) {
console.error(`[TRANSFER_VERIFY] ❌ CRITICAL: Transfer ${transferId} not found immediately after creation!`);
console.error(`[TRANSFER_VERIFY] Storage state:`, diagnostics);
return false;
}
if (!isValid) {
console.error(`[TRANSFER_VERIFY] ❌ CRITICAL: Transfer ${transferId} has invalid structure!`);
console.error(`[TRANSFER_VERIFY] Transfer diagnostics:`, diagnostics);
return false;
}
// Дополнительные проверки
const transfer = activeTransfers.get(transferId)!;
const chunksMatch = transfer.chunks.length === expectedChunks.length;
const metadataValid = transfer.metadata && typeof transfer.metadata === 'object';
if (!chunksMatch) {
console.error(`[TRANSFER_VERIFY] ❌ CRITICAL: Chunks count mismatch! Expected: ${expectedChunks.length}, Got: ${transfer.chunks.length}`);
return false;
}
if (!metadataValid) {
console.error(`[TRANSFER_VERIFY] ❌ CRITICAL: Invalid metadata for transfer ${transferId}`);
return false;
}
console.log(`[TRANSFER_VERIFY] ✅ Transfer ${transferId} storage verification PASSED`);
console.log(`[TRANSFER_VERIFY] - Chunks: ${transfer.chunks.length}`);
console.log(`[TRANSFER_VERIFY] - Received: ${transfer.received.size}/${transfer.totalChunks}`);
console.log(`[TRANSFER_VERIFY] - Metadata valid: ${metadataValid}`);
return true;
}
// Многоуровневая проверка transfer'а с попытками восстановления (ОБНОВЛЕНО)
async function multiLayerTransferCheck(transferId: string): Promise<{
found: boolean;
transfer: any;
recoveryAttempted: boolean;
diagnostics: Record<string, any>;
}> {
console.log(`[MULTI_LAYER_CHECK] 🔍 Starting enhanced multi-layer transfer check for ${transferId}`);
// === НОВЫЙ УРОВЕНЬ 0: Проверка в EnhancedChunkManager (приоритетная) ===
try {
console.log(`[MULTI_LAYER_CHECK] 🔍 Checking EnhancedChunkManager layers for transfer ${transferId}`);
// Проверяем все слои хранения из EnhancedChunkManager
const chunkManagerLayers = [
{ name: 'active_transfers', check: () => (globalThis as any).chunkManager?.transfers?.get?.(transferId) },
{ name: 'completed_transfers', check: () => (globalThis as any).chunkManager?.completedTransfers?.get?.(transferId) },
{ name: 'global_refs', check: () => (globalThis as any).chunkManager?.globalTransferRefs?.get?.(transferId) },
{ name: 'emergency_backup', check: () => (globalThis as any).chunkManager?.emergencyBackup?.get?.(transferId) }
];
// Диагностика доступности chunkManager
const chunkManager = (globalThis as any).chunkManager;
console.log(`[MULTI_LAYER_CHECK] ChunkManager available: ${!!chunkManager}`);
if (chunkManager) {
console.log(`[MULTI_LAYER_CHECK] ChunkManager storage sizes:`, {
active: chunkManager.transfers?.size || 0,
completed: chunkManager.completedTransfers?.size || 0,
globalRefs: chunkManager.globalTransferRefs?.size || 0,
emergency: chunkManager.emergencyBackup?.size || 0
});
}
for (const layer of chunkManagerLayers) {
try {
const transfer = layer.check();
console.log(`[MULTI_LAYER_CHECK] Checking layer ${layer.name} for ${transferId}: ${!!transfer}`);
if (transfer) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer ${transferId} found in ${layer.name}`);
console.log(`[MULTI_LAYER_CHECK] Transfer details:`, {
chunks: transfer.chunks?.length || 0,
totalSize: transfer.totalSize || 0,
startTime: transfer.startTime,
htmlAssembledConfirmed: transfer.htmlAssembledConfirmed
});
// Обновляем время последнего доступа если возможно
if (transfer.lastAccessed !== undefined) {
transfer.lastAccessed = Date.now();
}
return {
found: true,
transfer,
recoveryAttempted: false,
diagnostics: { source: layer.name, age: Date.now() - (transfer.createdAt || transfer.startTime || Date.now()) }
};
}
} catch (layerError) {
console.warn(`[MULTI_LAYER_CHECK] Error checking layer ${layer.name}:`, layerError);
}
}
console.log(`[MULTI_LAYER_CHECK] ❌ Transfer ${transferId} not found in any EnhancedChunkManager layer`);
} catch (error) {
console.warn(`[MULTI_LAYER_CHECK] ⚠️ Error checking EnhancedChunkManager layers:`, error);
}
// Уровень 1: Проверка в activeTransfers (локальный)
let transfer = activeTransfers.get(transferId);
if (transfer) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer ${transferId} found in primary storage`);
// Обновляем время последнего доступа
transfer.lastAccessed = Date.now();
return {
found: true,
transfer,
recoveryAttempted: false,
diagnostics: { source: 'primary', age: Date.now() - transfer.createdAt }
};
}
console.log(`[MULTI_LAYER_CHECK] ❌ Transfer ${transferId} not found in primary storage`);
// Уровень 2: Поиск по частичному совпадению ID (на случай усечения)
const partialMatches = Array.from(activeTransfers.keys()).filter(key =>
key.includes(transferId) || transferId.includes(key)
);
if (partialMatches.length > 0) {
console.log(`[MULTI_LAYER_CHECK] 🔄 Found partial matches for ${transferId}:`, partialMatches);
transfer = activeTransfers.get(partialMatches[0]);
if (transfer) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer recovered using partial match: ${partialMatches[0]}`);
transfer.lastAccessed = Date.now();
return {
found: true,
transfer,
recoveryAttempted: true,
diagnostics: { source: 'partial_match', originalId: partialMatches[0] }
};
}
}
// Уровень 3: Поиск в globalThis (на случай хранения в другом месте)
const globalKeys = Object.keys(globalThis).filter(key =>
key.includes('transfer') || key.includes(transferId)
);
if (globalKeys.length > 0) {
console.log(`[MULTI_LAYER_CHECK] 🔄 Found potential global storage keys:`, globalKeys);
for (const key of globalKeys) {
const globalTransfer = (globalThis as any)[key];
if (globalTransfer && typeof globalTransfer === 'object' && globalTransfer.chunks) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer recovered from global storage: ${key}`);
// Восстанавливаем в activeTransfers
activeTransfers.set(transferId, {
...globalTransfer,
createdAt: globalTransfer.createdAt || Date.now(),
lastAccessed: Date.now()
});
return {
found: true,
transfer: activeTransfers.get(transferId),
recoveryAttempted: true,
diagnostics: { source: 'global_recovery', globalKey: key }
};
}
}
}
// Уровень 4: Проверка на наличие в offscreen document
try {
console.log(`[MULTI_LAYER_CHECK] 🔄 Checking offscreen document for transfer ${transferId}`);
const offscreenCheck = await chrome.runtime.sendMessage({
type: 'CHECK_TRANSFER_STATUS',
transferId,
timestamp: Date.now()
}).catch(() => null);
if (offscreenCheck?.transferExists) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer ${transferId} exists in offscreen document`);
// Создаем заглушку transfer'а для синхронизации
const stubTransfer = {
chunks: [],
received: new Set(),
totalChunks: offscreenCheck.totalChunks || 0,
metadata: offscreenCheck.metadata || {},
resolve: () => {},
reject: () => {},
timeout: 0,
createdAt: Date.now(),
lastAccessed: Date.now()
};
activeTransfers.set(transferId, stubTransfer);
return {
found: true,
transfer: stubTransfer,
recoveryAttempted: true,
diagnostics: { source: 'offscreen_stub', totalChunks: stubTransfer.totalChunks }
};
}
} catch (error) {
console.warn(`[MULTI_LAYER_CHECK] Offscreen check failed:`, error);
}
// Уровень 5: Проверка ultra emergency storage (новый)
try {
const ultraEmergency = (globalThis as any).emergencyTransfers?.[transferId];
if (ultraEmergency?.transfer) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer ${transferId} found in ultra emergency storage`);
return {
found: true,
transfer: ultraEmergency.transfer,
recoveryAttempted: true,
diagnostics: { source: 'ultra_emergency', age: Date.now() - (ultraEmergency.timestamp || Date.now()) }
};
}
} catch (error) {
console.warn(`[MULTI_LAYER_CHECK] Ultra emergency check failed:`, error);
}
// Уровень 6: Проверка fixed transfers array (новый)
try {
const fixedTransfers = (globalThis as any).fixedTransfers;
if (Array.isArray(fixedTransfers)) {
const fixedTransfer = fixedTransfers.find((t: any) => t.id === transferId);
if (fixedTransfer?.transfer) {
console.log(`[MULTI_LAYER_CHECK] ✅ Transfer ${transferId} found in fixed transfers array`);
return {
found: true,
transfer: fixedTransfer.transfer,
recoveryAttempted: true,
diagnostics: { source: 'fixed_transfers', age: Date.now() - (fixedTransfer.timestamp || Date.now()) }
};
}
}
} catch (error) {
console.warn(`[MULTI_LAYER_CHECK] Fixed transfers check failed:`, error);
}
console.error(`[MULTI_LAYER_CHECK] ❌ Transfer ${transferId} not found in any storage layer`);
return {
found: false,
transfer: null,
recoveryAttempted: true,
diagnostics: { source: 'not_found', checkedLayers: ['chunk_manager', 'primary', 'partial', 'global', 'offscreen', 'ultra_emergency', 'fixed'] }
};
}
// Fallback механизм восстановления для полностью потерянных transfer'ов
async function fallbackTransferRecoveryForAssembled(msg: any): Promise<boolean> {
try {
const transferId = msg.transferId;
console.log(`[FALLBACK_RECOVERY] 🔧 Starting fallback recovery for assembled transfer ${transferId}`);
// Попытка 1: Восстановление на основе данных из HTML_ASSEMBLED сообщения
if (msg.assembledData || msg.htmlData) {
console.log(`[FALLBACK_RECOVERY] 📦 Found assembled data in message, creating recovery transfer`);
const recoveryTransfer = {
chunks: [], // Данные уже собраны
received: new Set(),
totalChunks: 0,
metadata: {
pluginId: msg.pluginId,
pageKey: msg.pageKey,
requestId: msg.requestId,
totalSize: msg.assembledData?.length || msg.htmlData?.length || 0,
timestamp: Date.now(),
recovery: true,
fallback: true
},
resolve: () => console.log(`[FALLBACK_RECOVERY] Recovery transfer ${transferId} resolved`),
reject: (error: any) => console.error(`[FALLBACK_RECOVERY] Recovery transfer ${transferId} rejected:`, error),
timeout: 0,
createdAt: Date.now(),
lastAccessed: Date.now(),
pageHtml: msg.assembledData || msg.htmlData,
isRecovery: true
};
activeTransfers.set(transferId, recoveryTransfer);
console.log(`[FALLBACK_RECOVERY] ✅ Recovery transfer created for ${transferId}`);
// Продолжаем обработку с восстановленным transfer'ом
await processRecoveredAssembledTransfer(msg, recoveryTransfer);
return true;
}
// Попытка 2: Запрос данных из offscreen document
console.log(`[FALLBACK_RECOVERY] 🔄 Requesting assembled data from offscreen document`);
const offscreenData = await chrome.runtime.sendMessage({
type: 'REQUEST_ASSEMBLED_DATA',
transferId,
timestamp: Date.now()
}).catch(() => null);
if (offscreenData?.assembledData) {
console.log(`[FALLBACK_RECOVERY] 📦 Received assembled data from offscreen`);
const recoveryTransfer = {
chunks: [],
received: new Set(),
totalChunks: 0,
metadata: {
...offscreenData.metadata,
recovery: true,
fallback: true,
timestamp: Date.now()
},
resolve: () => console.log(`[FALLBACK_RECOVERY] Offscreen recovery transfer ${transferId} resolved`),
reject: (error: any) => console.error(`[FALLBACK_RECOVERY] Offscreen recovery transfer ${transferId} rejected:`, error),
timeout: 0,
createdAt: Date.now(),
lastAccessed: Date.now(),
pageHtml: offscreenData.assembledData,
isRecovery: true
};
activeTransfers.set(transferId, recoveryTransfer);
console.log(`[FALLBACK_RECOVERY] ✅ Offscreen recovery transfer created for ${transferId}`);
await processRecoveredAssembledTransfer(msg, recoveryTransfer);
return true;
}
// Попытка 3: Создание минимального transfer'а для продолжения workflow
console.log(`[FALLBACK_RECOVERY] 📝 Creating minimal transfer for workflow continuation`);
const minimalTransfer = {
chunks: [],
received: new Set(),
totalChunks: 0,
metadata: {
pluginId: msg.pluginId,
pageKey: msg.pageKey,
requestId: msg.requestId,
totalSize: 0,
timestamp: Date.now(),
recovery: true,
fallback: true,
minimal: true
},
resolve: () => console.log(`[FALLBACK_RECOVERY] Minimal transfer ${transferId} resolved`),
reject: (error: any) => console.error(`[FALLBACK_RECOVERY] Minimal transfer ${transferId} rejected:`, error),
timeout: 0,
createdAt: Date.now(),
lastAccessed: Date.now(),
isRecovery: true,
minimalMode: true
};
activeTransfers.set(transferId, minimalTransfer);
console.log(`[FALLBACK_RECOVERY] ✅ Minimal recovery transfer created for ${transferId}`);
await processRecoveredAssembledTransfer(msg, minimalTransfer);
return true;
} catch (error) {
console.error(`[FALLBACK_RECOVERY] ❌ Fallback recovery failed for transfer ${msg.transferId}:`, error);
return false;
}
}
// УЛУЧШЕННАЯ ОБРАБОТКА ВОССТАНОВЛЕННОГО ASSEMBLED TRANSFER'А С ПОЛНОЙ ПОДДЕРЖКОЙ MISSING ДАННЫХ
async function processRecoveredAssembledTransfer(msg: any, transfer: any): Promise<void> {
const transferId = msg.transferId;
console.log(`[RECOVERY_PROCESSING] 🔄 Processing recovered assembled transfer ${transferId}`);
try {
// Устанавливаем флаг завершения с дополнительными проверками
const setTransferCompleted = (globalThis as any)[`setTransferCompleted_${transferId}`];
if (setTransferCompleted) {
setTransferCompleted(true);
console.log(`[RECOVERY_PROCESSING] ✅ Recovery transfer completion flag set for ${transferId}`);
} else {
console.warn(`[RECOVERY_PROCESSING] ⚠️ setTransferCompleted function not found - creating fallback`);
(globalThis as any)[`setTransferCompleted_${transferId}`] = () => {
console.log(`[RECOVERY_PROCESSING] Fallback completion flag set for ${transferId}`);
};
}
// УЛУЧШЕННАЯ ОБРАБОТКА MISSING PLUGINID/PAGEKEY С ВОССТАНОВЛЕНИЕМ ИЗ МЕТАДАННЫХ
let pluginId = msg.pluginId;
let pageKey = msg.pageKey;
// ПОПЫТКА ВОССТАНОВЛЕНИЯ PLUGINID ИЗ РАЗЛИЧНЫХ ИСТОЧНИКОВ
if (!pluginId) {
console.log(`[RECOVERY_PROCESSING] 🔍 Attempting to recover pluginId for transfer ${transferId}`);
// Источник 1: Метаданные transfer'а
if (transfer.metadata?.pluginId) {
pluginId = transfer.metadata.pluginId;
console.log(`[RECOVERY_PROCESSING] ✅ Recovered pluginId from transfer metadata: ${pluginId}`);
}
// Источник 2: Глобальное хранилище
if (!pluginId) {
const globalMetadata = (globalThis as any).transferMetadata?.[transferId];
if (globalMetadata?.pluginId) {
pluginId = globalMetadata.pluginId;
console.log(`[RECOVERY_PROCESSING] ✅ Recovered pluginId from global metadata: ${pluginId}`);
}
}
// Источник 3: Запрос к offscreen document
if (!pluginId) {
try {
const offscreenData = await chrome.runtime.sendMessage({
type: 'GET_TRANSFER_PLUGIN_INFO',
transferId,
timestamp: Date.now()
}).catch(() => null);
if (offscreenData?.pluginId) {
pluginId = offscreenData.pluginId;
console.log(`[RECOVERY_PROCESSING] ✅ Recovered pluginId from offscreen: ${pluginId}`);
}
} catch (error) {
console.warn(`[RECOVERY_PROCESSING] Failed to query offscreen for pluginId:`, error);
}
}
// Источник 4: Fallback - извлечение из transferId
if (!pluginId && transferId.includes('_html')) {
const parts = transferId.split('_');
if (parts.length >= 3) {
pluginId = parts.slice(0, parts.length - 2).join('_');
console.log(`[RECOVERY_PROCESSING] 🔧 Extracted pluginId from transferId: ${pluginId}`);
}
}
}
// ПОПЫТКА ВОССТАНОВЛЕНИЯ PAGEKEY ИЗ РАЗЛИЧНЫХ ИСТОЧНИКОВ
if (!pageKey) {
console.log(`[RECOVERY_PROCESSING] 🔍 Attempting to recover pageKey for transfer ${transferId}`);
// Источник 1: Метаданные transfer'а
if (transfer.metadata?.pageKey) {
pageKey = transfer.metadata.pageKey;
console.log(`[RECOVERY_PROCESSING] ✅ Recovered pageKey from transfer metadata: ${pageKey}`);
}
// Источник 2: Глобальное хранилище
if (!pageKey) {
const globalMetadata = (globalThis as any).transferMetadata?.[transferId];
if (globalMetadata?.pageKey) {
pageKey = globalMetadata.pageKey;
console.log(`[RECOVERY_PROCESSING] ✅ Recovered pageKey from global metadata: ${pageKey}`);
}
}
// Источник 3: Определение из активной вкладки
if (!pageKey) {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs[0]?.url) {
const { getPageKey } = await import('../../../packages/shared/lib/utils/helpers');
pageKey = getPageKey(tabs[0].url);
console.log(`[RECOVERY_PROCESSING] ✅ Generated pageKey from active tab: ${pageKey}`);
}
} catch (error) {
console.warn(`[RECOVERY_PROCESSING] Failed to get pageKey from active tab:`, error);
}
}
// Источник 4: Fallback pageKey
if (!pageKey) {
pageKey = `recovered_page_${Date.now()}`;
console.log(`[RECOVERY_PROCESSING] 🔧 Using fallback pageKey: ${pageKey}`);
}
}
// ВАЛИДАЦИЯ ВОССТАНОВЛЕННЫХ ДАННЫХ
if (!pluginId) {
console.error(`[RECOVERY_PROCESSING] ❌ CRITICAL: Cannot determine pluginId for recovered transfer ${transferId}`);
throw new Error(`Missing pluginId - recovery failed`);
}
if (!pageKey) {
console.error(`[RECOVERY_PROCESSING] ❌ CRITICAL: Cannot determine pageKey for recovered transfer ${transferId}`);
throw new Error(`Missing pageKey - recovery failed`);
}
console.log(`[RECOVERY_PROCESSING] ✅ Recovery data validated - pluginId: ${pluginId}, pageKey: ${pageKey}`);
// ПОДГОТОВКА EXECUTE_WORKFLOW СООБЩЕНИЯ
const executeMessage: any = {
type: 'EXECUTE_WORKFLOW',
pluginId,
pageKey,
requestId: msg.requestId || transferId,
transferId: transferId,
useChunks: false, // Данные уже собраны
pageHtml: transfer.assembledData || transfer.html,
assembledData: transfer.assembledData || transfer.html,
pluginSettings: transfer.metadata?.pluginSettings, // Добавлено: передаем pluginSettings из метаданных
recovery: true,
recoverySource: transfer.isRecovery ? 'fallback_recovery' : 'recovered',
timestamp: Date.now()
};
// Получить API ключ для Gemini и добавить к сообщению
try {
const geminiApiKey = await getApiKeyForModel('gemini-flash-lite');
executeMessage.geminiApiKey = geminiApiKey;
console.log('[RECOVERY_PROCESSING] ✅ API key added to EXECUTE_WORKFLOW message');
} catch (keyError) {
console.warn('[RECOVERY_PROCESSING] ⚠️ Failed to get API key for EXECUTE_WORKFLOW:', keyError);
}
// ДОПОЛНИТЕЛЬНАЯ ВАЛИДАЦИЯ ASSEMBLED DATA
if (!executeMessage.assembledData || executeMessage.assembledData.length === 0) {
console.warn(`[RECOVERY_PROCESSING] ⚠️ Assembled data is empty for transfer ${transferId}`);
// ПОПЫТКА ПОЛУЧИТЬ ДАННЫЕ ИЗ ДРУГИХ ИСТОЧНИКОВ
if (transfer.chunks && Array.isArray(transfer.chunks)) {
executeMessage.pageHtml = transfer.chunks.join('');
console.log(`[RECOVERY_PROCESSING] ✅ Reassembled data from chunks: ${executeMessage.pageHtml.length} chars`);
} else {
console.warn(`[RECOVERY_PROCESSING] ⚠️ No chunks available for reassembly`);
}
}
console.log(`[RECOVERY_PROCESSING] 🚀 Sending recovery EXECUTE_WORKFLOW for ${transferId} (${executeMessage.pageHtml?.length || 0} chars)`);
await chrome.runtime.sendMessage(executeMessage);
console.log(`[RECOVERY_PROCESSING] ✅ Recovery EXECUTE_WORKFLOW sent successfully for ${transferId}`);
// ДОПОЛНИТЕЛЬНОЕ ЛОГИРОВАНИЕ ДЛЯ ОТСЛЕЖИВАНИЯ
console.log(`[RECOVERY_PROCESSING] 📊 Recovery summary for ${transferId}:`, {
pluginId,
pageKey,
dataLength: executeMessage.pageHtml?.length || 0,
recoveryType: executeMessage.recoverySource,
timestamp: executeMessage.timestamp
});
} catch (error) {
console.error(`[RECOVERY_PROCESSING] ❌ Failed to process recovered transfer ${transferId}:`, error);
console.error(`[RECOVERY_PROCESSING] Error details:`, {
message: (error as Error).message,
stack: (error as Error).stack,
transferId,
hasAssembledData: !!transfer?.assembledData,
pluginId: msg.pluginId,
pageKey: msg.pageKey
});
throw error;
} finally {
// УЛУЧШЕННАЯ ОЧИСТКА С ДОПОЛНИТЕЛЬНЫМИ ПРОВЕРКАМИ
console.log(`[RECOVERY_PROCESSING] 🧹 Starting cleanup for transfer ${transferId}`);
if (activeTransfers.has(transferId)) {
activeTransfers.delete(transferId);
console.log(`[RECOVERY_PROCESSING] ✅ Recovery transfer ${transferId} cleaned up from active transfers`);
} else {
console.log(`[RECOVERY_PROCESSING] ⚠️ Transfer ${transferId} was already cleaned up`);
}
// ОЧИСТКА ГЛОБАЛЬНЫХ ССЫЛОК
if ((globalThis as any)[`setTransferCompleted_${transferId}`]) {
delete (globalThis as any)[`setTransferCompleted_${transferId}`];
console.log(`[RECOVERY_PROCESSING] ✅ Recovery transfer completion function cleaned up for ${transferId}`);
}
// ОЧИСТКА ГЛОБАЛЬНЫХ МЕТАДАННЫХ ПОСЛЕ ЗАДЕРЖКИ
setTimeout(() => {
if ((globalThis as any).transferMetadata?.[transferId]) {
delete (globalThis as any).transferMetadata[transferId];
console.log(`[RECOVERY_PROCESSING] 🧹 Global metadata cleaned up for ${transferId}`);
}
}, 5000); // Даем время на завершение всех операций
}
}
// DEPRECATED: Function to split HTML into chunks - replaced by direct data exchange
console.log('[background] Background script initialization completed successfully');
console.log('[background] Extension ID:', chrome.runtime.id);
console.log('[background] Offscreen API supported:', offscreenSupported());
console.log('[background] Ready to handle workflow requests with htmlTransmissionMode support');
// Функция для обновления настроек плагина
const updatePluginSetting = async (pluginId: string, setting: string, value: boolean) => {
const settings = await pluginSettingsStorage.get();
const pluginSettings = settings[pluginId] || { enabled: true, autorun: false };
// Обновляем настройку
pluginSettings[setting] = value;
// Если плагин отключен, то отключаем и автозапуск
if (setting === 'enabled' && !value) {
pluginSettings.autorun = false;
}
// Сохраняем обновленные настройки
await pluginSettingsStorage.set({
...settings,
[pluginId]: pluginSettings,
});
console.log(`[background] Updated plugin setting for ${pluginId}:`, setting, '=', value);
return { success: true };
};
// Функция для проверки и запуска плагина с учетом настроек
const runPluginIfEnabled = async (pluginId: string) => {
try {
// Получаем настройки плагина
const settings = await getPluginSettings(pluginId);
// Проверяем, включен ли плагин
if (!settings.enabled) {
console.log(`[background] Plugin ${pluginId} is disabled, not running`);
return { success: false, reason: 'Plugin is disabled' };
}
// Запускаем рабочий процесс плагина
return { success: true };
} catch (error) {
console.error(`[background] Error running plugin ${pluginId}:`, error);
return { error: (error as Error).message };
}
};
// Обработчик для удаления чата плагина
const handleDeletePluginChat = async (message: any, sendResponse: (response?: any) => void) => {
console.log('[background] DELETE_PLUGIN_CHAT processing:', message.pluginId, message.pageKey);
try {
const result = await pluginChatApi.deleteChat(message.pluginId, message.pageKey);
console.log('[background] DELETE_PLUGIN_CHAT completed successfully for:', { pluginId: message.pluginId, pageKey: message.pageKey });
// Отправляем событие обновления чата после успешного удаления
broadcastChatUpdate(message.pluginId, message.pageKey);
sendResponse(result);
} catch (error) {