-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1636 lines (1428 loc) · 49.7 KB
/
Copy pathbackground.js
File metadata and controls
1636 lines (1428 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Background service worker for Brightspace LLM Assistant
// Enhanced version with retry logic and better error handling
console.log('Background service worker loaded at', new Date().toISOString());
self.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled promise rejection in service worker:', event.reason);
});
self.addEventListener('error', (event) => {
console.error('Unhandled error in service worker:', event.message || event.error);
});
// Load PDF.js for PDF text extraction
let pdfjsLib = null;
try {
importScripts('pdf.min.js');
pdfjsLib = globalThis.pdfjsLib;
if (pdfjsLib) {
// In service worker, set workerSrc to the worker file
// Using absolute URL is safer
try {
pdfjsLib.GlobalWorkerOptions.workerSrc = chrome.runtime.getURL('pdf.worker.min.js');
console.log('✓ PDF.js loaded with workerSrc set to:', pdfjsLib.GlobalWorkerOptions.workerSrc);
} catch (e) {
console.warn('Could not set workerSrc with getURL, fallback to relative:', e);
// Try relative path
try {
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
console.log('✓ PDF.js worker set to relative path');
} catch (workerError) {
console.error('Failed to set worker path:', workerError);
}
}
}
} catch (error) {
console.error('Failed to load PDF.js:', error);
console.log('PDF extraction will be limited');
}
// Helper to ensure offscreen document exists for PDF rendering
async function ensureOffscreenDocument() {
// Check if offscreen document already exists
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT']
});
if (existingContexts.length === 0) {
// Create offscreen document
try {
await chrome.offscreen.createDocument({
url: chrome.runtime.getURL('offscreen.html'),
reasons: ['DOM_SCRAPING'], // We need DOM access for canvas
justification: 'PDF rendering requires canvas element creation'
});
console.log('✓ Offscreen document created for PDF rendering');
} catch (error) {
console.error('Failed to create offscreen document:', error);
throw error;
}
}
// Wait for offscreen to be ready (handshake)
// This ensures the message listener is registered before we send real work
const maxRetries = 20; // Wait up to 10 seconds
for (let i = 0; i < maxRetries; i++) {
try {
const response = await new Promise((resolve) => {
chrome.runtime.sendMessage({ action: 'ping' }, (res) => {
if (chrome.runtime.lastError) {
resolve(null);
} else {
resolve(res);
}
});
});
if (response && response.success && response.message === 'pong') {
console.log('✓ Offscreen document is ready and responding');
return; // Success!
}
} catch (e) {
// Ignore and retry
}
// Wait 500ms before retry
await new Promise(r => setTimeout(r, 500));
}
console.warn('Offscreen document did not respond to ping, but continuing anyway...');
}
// Helper to send messages to offscreen document
async function sendMessageToOffscreen(message) {
try {
await ensureOffscreenDocument();
console.log('Sending message to offscreen document:', message.action);
// Add timeout to prevent hanging (increased to 60s for large files)
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Offscreen document timeout after 60s')), 60000);
});
const messagePromise = new Promise((resolve, reject) => {
console.log('Calling chrome.runtime.sendMessage...');
chrome.runtime.sendMessage({ ...message, target: 'offscreen' }, (response) => {
console.log('Got response from sendMessage:', response ? 'Response received' : 'No response');
if (chrome.runtime.lastError) {
console.error('Runtime error from offscreen:', chrome.runtime.lastError);
reject(new Error(chrome.runtime.lastError.message));
} else if (!response) {
// Sometimes sendMessage returns undefined if port closes, but lastError is set.
// If lastError NOT set and response undefined, it means connection closed prematurely?
reject(new Error('No response from offscreen document'));
} else if (!response.success) {
console.error('Offscreen returned error:', response.error);
reject(new Error(response.error || 'Offscreen document failed'));
} else {
if (typeof response.text === 'string') {
console.log(`✓ Received ${response.text.length} chars from offscreen`);
resolve(response.text);
return;
}
console.log(`✓ Received ${response.images?.length || 0} images from offscreen`);
resolve(response.images);
}
});
});
return await Promise.race([messagePromise, timeoutPromise]);
} catch (error) {
console.error('Failed to communicate with offscreen document:', error);
throw error;
}
}
// Dedicated renderer tab + port for PDF conversion
let rendererPort = null;
let rendererTabId = null;
let rendererReadyPromise = null;
let rendererReadyResolve = null;
let rendererReadyReject = null;
let rendererReadyTimeoutId = null;
const pendingRenderRequests = new Map();
let offscreenPort = null;
let offscreenReadyPromise = null;
let offscreenReadyResolve = null;
let offscreenReadyReject = null;
let offscreenReadyTimeoutId = null;
const pendingOffscreenRequests = new Map();
let offscreenReady = false;
function markOffscreenReady() {
offscreenReady = true;
if (offscreenReadyTimeoutId) {
clearTimeout(offscreenReadyTimeoutId);
offscreenReadyTimeoutId = null;
}
if (offscreenReadyResolve) {
offscreenReadyResolve();
offscreenReadyResolve = null;
offscreenReadyReject = null;
offscreenReadyPromise = null;
}
}
function arrayBufferToDataUrl(buffer, mimeType) {
if (!buffer || buffer.byteLength === 0) {
throw new Error('Empty image buffer');
}
const bytes = new Uint8Array(buffer);
const chunkSize = 0x8000;
let binary = '';
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
const base64 = btoa(binary);
return `data:${mimeType};base64,${base64}`;
}
chrome.runtime.onConnect.addListener((port) => {
if (port.name === 'pdf-offscreen') {
offscreenPort = port;
console.log('✓ Offscreen port connected');
markOffscreenReady();
port.onMessage.addListener((message) => {
if (message?.type === 'ready') {
markOffscreenReady();
return;
}
const { requestId } = message || {};
if (!requestId || !pendingOffscreenRequests.has(requestId)) return;
const pending = pendingOffscreenRequests.get(requestId);
if (pending.resetTimeout) pending.resetTimeout();
if (message.type === 'progress') {
return;
}
if (message.type === 'page' && message.image) {
const image = message.image;
if (image.dataUrl && typeof image.dataUrl === 'string' && image.dataUrl.length > 50) {
pending.images.push(image);
} else {
console.warn('Skipping empty offscreen data URL for page', image.pageNum);
}
return;
}
if (message.type === 'done') {
pending.done = true;
if (pending.inflight === 0) {
pendingOffscreenRequests.delete(requestId);
pending.resolve(pending.images);
}
return;
}
if (message.type === 'error') {
pendingOffscreenRequests.delete(requestId);
pending.reject(new Error(message.error || 'Offscreen renderer failed'));
}
});
port.onDisconnect.addListener(() => {
for (const pending of pendingOffscreenRequests.values()) {
pending.reject(new Error('Offscreen renderer disconnected'));
}
pendingOffscreenRequests.clear();
offscreenPort = null;
offscreenReady = false;
});
return;
}
if (port.name !== 'pdf-renderer') return;
rendererPort = port;
rendererTabId = port.sender?.tab?.id ?? rendererTabId;
port.onMessage.addListener((message) => {
if (message?.type === 'error' && !message.requestId) {
if (rendererReadyTimeoutId) {
clearTimeout(rendererReadyTimeoutId);
rendererReadyTimeoutId = null;
}
if (rendererReadyReject) {
rendererReadyReject(new Error(message.error || 'Renderer tab failed to initialize'));
rendererReadyResolve = null;
rendererReadyReject = null;
rendererReadyPromise = null;
}
return;
}
if (message?.type === 'ready') {
if (rendererReadyTimeoutId) {
clearTimeout(rendererReadyTimeoutId);
rendererReadyTimeoutId = null;
}
if (rendererReadyResolve) {
rendererReadyResolve();
rendererReadyResolve = null;
rendererReadyReject = null;
rendererReadyPromise = null;
}
return;
}
const { requestId } = message || {};
if (!requestId || !pendingRenderRequests.has(requestId)) return;
const pending = pendingRenderRequests.get(requestId);
if (pending.resetTimeout) pending.resetTimeout();
if (message.type === 'page' && message.image) {
const image = message.image;
if (image.buffer) {
pending.inflight += 1;
const buffer = image.buffer;
const mimeType = image.mimeType || 'image/jpeg';
Promise.resolve()
.then(() => arrayBufferToDataUrl(buffer, mimeType))
.then((dataUrl) => {
pending.images.push({
dataUrl,
pageNum: image.pageNum,
fileName: image.fileName
});
})
.catch((err) => {
console.warn('Failed to decode renderer image buffer:', err);
})
.finally(() => {
pending.inflight -= 1;
if (pending.done && pending.inflight === 0) {
pendingRenderRequests.delete(requestId);
pending.resolve(pending.images);
}
});
return;
}
if (image.dataUrl) {
if (typeof image.dataUrl === 'string' && image.dataUrl.length > 50) {
pending.images.push(image);
} else {
console.warn('Skipping empty renderer data URL for page', image.pageNum);
}
return;
}
}
if (message.type === 'done') {
pending.done = true;
if (pending.inflight === 0) {
pendingRenderRequests.delete(requestId);
pending.resolve(pending.images);
}
return;
}
if (message.type === 'error') {
pendingRenderRequests.delete(requestId);
pending.reject(new Error(message.error || 'Renderer tab failed'));
}
});
port.onDisconnect.addListener(() => {
for (const pending of pendingRenderRequests.values()) {
pending.reject(new Error('Renderer tab disconnected'));
}
pendingRenderRequests.clear();
rendererPort = null;
rendererTabId = null;
});
});
async function ensureRendererTab() {
if (rendererPort) return;
if (!rendererReadyPromise) {
rendererReadyPromise = new Promise((resolve, reject) => {
rendererReadyResolve = resolve;
rendererReadyReject = reject;
});
const url = chrome.runtime.getURL('renderer.html');
const existingTabs = await chrome.tabs.query({ url });
if (existingTabs && existingTabs.length > 0) {
rendererTabId = existingTabs[0].id;
await chrome.tabs.reload(rendererTabId);
} else {
const tab = await chrome.tabs.create({ url, active: false });
rendererTabId = tab.id;
}
rendererReadyTimeoutId = setTimeout(() => {
if (rendererReadyReject) {
rendererReadyReject(new Error('Renderer tab did not become ready'));
}
rendererReadyPromise = null;
rendererReadyResolve = null;
rendererReadyReject = null;
rendererReadyTimeoutId = null;
}, 15000);
}
await rendererReadyPromise;
}
async function sendMessageToRenderer(message) {
await ensureRendererTab();
if (!rendererPort) {
throw new Error('Renderer tab port not available');
}
const requestId = `render-${Date.now()}-${Math.random().toString(16).slice(2)}`;
const images = [];
let timeoutId = null;
const responsePromise = new Promise((resolve, reject) => {
const resetTimeout = () => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
pendingRenderRequests.delete(requestId);
reject(new Error('Renderer tab timeout after 120s'));
}, 120000);
};
pendingRenderRequests.set(requestId, {
resolve,
reject,
images,
inflight: 0,
done: false,
resetTimeout
});
resetTimeout();
});
rendererPort.postMessage({
...message,
requestId
});
try {
return await responsePromise;
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
}
async function ensureOffscreenPort() {
await ensureOffscreenDocument();
if (offscreenPort && offscreenReady) return;
if (!offscreenReadyPromise) {
offscreenReadyPromise = new Promise((resolve, reject) => {
offscreenReadyResolve = resolve;
offscreenReadyReject = reject;
});
offscreenReadyTimeoutId = setTimeout(() => {
if (offscreenReadyReject) {
offscreenReadyReject(new Error('Offscreen renderer did not become ready'));
}
offscreenReady = false;
offscreenReadyPromise = null;
offscreenReadyResolve = null;
offscreenReadyReject = null;
offscreenReadyTimeoutId = null;
}, 15000);
}
if (offscreenPort && !offscreenReady) {
try {
offscreenPort.postMessage({ type: 'ping' });
} catch (e) {
console.warn('Failed to ping offscreen port:', e);
}
}
await offscreenReadyPromise;
}
async function sendMessageToOffscreenPort(message) {
await ensureOffscreenPort();
if (!offscreenPort) {
throw new Error('Offscreen renderer port not available');
}
const requestId = `offscreen-${Date.now()}-${Math.random().toString(16).slice(2)}`;
const images = [];
let timeoutId = null;
const responsePromise = new Promise((resolve, reject) => {
const resetTimeout = () => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
pendingOffscreenRequests.delete(requestId);
reject(new Error('Offscreen renderer timeout after 120s'));
}, 120000);
};
pendingOffscreenRequests.set(requestId, {
resolve,
reject,
images,
inflight: 0,
done: false,
resetTimeout
});
resetTimeout();
});
offscreenPort.postMessage({
...message,
requestId
});
try {
return await responsePromise;
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('Background received message:', request?.action, 'from', sender?.id || sender?.tab?.id || 'unknown');
if (request.action === 'askQuestion') {
handleQuestionRequest(request)
.then((response) => sendResponse(response))
.catch((error) => {
console.error('Error in askQuestion handler:', error);
sendResponse({
success: false,
error: error.message || 'An unknown error occurred'
});
});
}
return true; // Keep channel open for async response
});
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== 'askQuestion') {
return;
}
port.onMessage.addListener((request) => {
handleQuestionRequest(request)
.then((response) => port.postMessage(response))
.catch((error) => {
console.error('Error in askQuestion handler (port):', error);
port.postMessage({
success: false,
error: error.message || 'An unknown error occurred'
});
});
});
});
async function handleQuestionRequest(request) {
const {
question,
files,
apiKey,
driveAccessToken = null,
proxyUrl,
vectorApiUrl = null,
vectorApiKey = null,
useLocalLLM = false,
localModelName = 'llama3.2:3b-instruct',
hfModel = 'google/gemma-2-2b-it'
} = request;
try {
console.log('handleQuestionRequest start', {
questionLength: question?.length || 0,
fileCount: files?.length || 0,
useLocalLLM,
hfModel
});
// Validate inputs
if (!question) {
throw new Error('Question is required');
}
if (!useLocalLLM && !apiKey) {
throw new Error('Provide a Hugging Face API key or enable Local Ollama.');
}
if (!files || files.length === 0) {
throw new Error('No files available. Please upload files first.');
}
// Extract text from files
const extractionResult = await extractTextFromFiles(files, driveAccessToken);
if (extractionResult.documents.length === 0) {
throw new Error('Could not extract text from files. Try uploading .txt or text-based PDFs.');
}
console.log(`Successfully extracted text from ${extractionResult.documents.length} file(s)`);
if (!driveAccessToken) {
throw new Error('Google Drive authorization required to load vector store.');
}
console.log('Building RAG context...');
let ragContext;
try {
if (vectorApiUrl) {
ragContext = await buildRagContextWithServer(
question,
extractionResult.documents,
apiKey,
vectorApiUrl,
vectorApiKey
);
} else {
ragContext = await buildRagContext(
question,
extractionResult.documents,
apiKey,
driveAccessToken
);
}
} catch (ragError) {
console.warn('RAG indexing failed, falling back to full text:', ragError);
ragContext = extractionResult.documents
.map(doc => `[Document: ${doc.fileName}]\n${doc.text}`)
.join('\n\n---\n\n');
}
console.log('RAG context built, length:', ragContext.length);
console.log('Calling LLM...');
// Call LLM with local preference and fallback options
const answer = await callLlamaLLMWithRetry(
question,
ragContext,
apiKey,
3,
proxyUrl,
useLocalLLM,
localModelName,
hfModel
);
console.log('LLM call completed');
console.log('handleQuestionRequest success, answer length:', answer?.length || 0);
return {
success: true,
answer: answer
};
} catch (error) {
console.error('Error in askQuestion:', error);
return {
success: false,
error: error.message || 'An unknown error occurred'
};
}
}
async function extractTextFromFiles(files, driveAccessToken) {
const documents = [];
console.log(`=== extractTextFromFiles called with ${files.length} files ===`);
for (const file of files.slice(0, 10)) { // Limit to first 10 files
try {
let result;
console.log(`Processing file: ${file.name}, type: ${file.type}, url: ${file.url}`);
// Check if it's a manually uploaded file with content
if (file.driveFileId) {
if (!driveAccessToken) {
throw new Error('Google Drive authorization required to read uploaded files.');
}
console.log(' → Drive file detected, downloading from Drive');
const blob = await downloadDriveFileBlob(file.driveFileId, driveAccessToken);
result = await extractTextFromBlob(blob, file.type, file.name);
} else if (file.content && file.url && file.url.startsWith('local-file://')) {
console.log(' → Has content and local-file URL, calling extractFromDataURL');
result = await extractFromDataURL(file.content, file.type, file.name);
} else {
console.log(` → No content or not local-file, calling fetchFileContent`);
result = await fetchFileContent(file.url);
}
console.log(`Extracted result type: ${typeof result}`);
if (result) {
if (typeof result === 'string' && result.length > 0) {
// Skip placeholder messages
if (result.includes('Add pdf.js library') || result.includes('Add mammoth.js library')) {
console.warn(`Skipping ${file.name}: requires library for extraction`);
continue;
}
console.log(`Adding text content from ${file.name}: ${result.substring(0, 50)}...`);
documents.push({
fileName: file.name,
fileUrl: file.url,
text: result
});
}
}
} catch (error) {
console.error(`Error extracting from ${file.name}:`, error);
}
}
console.log(`=== extractTextFromFiles done: ${documents.length} document(s) ===`);
return { documents };
}
async function extractFromDataURL(dataUrl, fileType, fileName) {
try {
console.log(`extractFromDataURL called: fileName=${fileName}, fileType=${fileType}`);
// Convert data URL to blob
const response = await fetch(dataUrl);
const blob = await response.blob();
return await extractTextFromBlob(blob, fileType, fileName, dataUrl);
} catch (error) {
console.error('Error extracting from data URL:', error);
return null;
}
}
async function extractTextFromBlob(blob, fileType, fileName, dataUrl = null) {
console.log(`File: ${fileName}, MIME: ${blob.type}, Size: ${blob.size} bytes`);
const lowerName = fileName.toLowerCase();
const mimeType = blob.type || '';
if (fileType === 'text' || lowerName.endsWith('.txt') || mimeType.includes('text/plain')) {
console.log('Detected as text file');
const text = await blob.text();
console.log(`Extracted ${text.length} chars from text file`);
return text;
}
if (fileType === 'pdf' || lowerName.endsWith('.pdf') || mimeType.includes('pdf')) {
console.log('✓ PDF detected - extracting text');
try {
if (dataUrl) {
const text = await sendMessageToOffscreen({
action: 'extractPDFText',
pdfDataUrl: dataUrl,
fileName: fileName
});
if (text && text.length > 50) {
console.log(`✓ Successfully extracted ${text.length} chars from PDF`);
return text;
}
}
const arrayBuffer = await blob.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);
const arrayData = Array.from(bytes);
const text = await sendMessageToOffscreen({
action: 'extractPDFText',
arrayBuffer: arrayData,
fileName: fileName
});
if (text && text.length > 50) {
console.log(`✓ Successfully extracted ${text.length} chars from PDF`);
return text;
}
console.warn('PDF extraction returned empty or short text');
return '[PDF appears empty or unreadable. Try a text-based PDF or convert to .txt]';
} catch (e) {
console.error('PDF text extraction failed:', e);
return `[Error extracting PDF: ${e.message}. Try converting to .txt format.]`;
}
}
if (fileType === 'document' || lowerName.endsWith('.docx') || lowerName.endsWith('.doc') || mimeType.includes('word')) {
console.warn('Word document detected - attempting text extraction');
return `[Unable to extract text from Word document: ${fileName}. Please save as .txt or PDF instead.]`;
}
try {
const text = await blob.text();
if (text && text.length > 0) {
console.log(`Extracted ${text.length} chars from unknown file type`);
return text;
}
} catch (e) {
console.error('Generic text extraction failed:', e);
}
return null;
}
async function downloadDriveFileBlob(fileId, token) {
const url = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`;
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});
if (!response.ok) {
const errorText = await response.text().catch(() => '');
throw new Error(`Drive download failed (${response.status}): ${errorText || response.statusText}`);
}
return await response.blob();
}
async function extractPDFText(arrayBuffer) {
if (!pdfjsLib) {
throw new Error('PDF.js not loaded');
}
try {
console.log('Attempting PDF text extraction (service worker context)');
const loadingTask = pdfjsLib.getDocument({
data: arrayBuffer,
disableWorker: true,
useWorkerFetch: false,
useRangeRequests: false
});
const pdf = await loadingTask.promise;
console.log(`PDF loaded: ${pdf.numPages} pages`);
let fullText = '';
const maxPages = Math.min(pdf.numPages, 20); // Limit to 20 pages
// Extract text from each page
for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
try {
const page = await pdf.getPage(pageNum);
const textContent = await page.getTextContent();
const pageText = textContent.items
.map(item => item.str)
.join(' ');
console.log(`Page ${pageNum}: extracted ${pageText.length} chars - sample: "${pageText.substring(0, 100)}..."`);
fullText += `\n\n--- Page ${pageNum} ---\n${pageText}`;
} catch (pageError) {
console.warn(`Error extracting page ${pageNum}:`, pageError);
}
}
console.log(`✓ Extracted ${fullText.length} total characters from PDF`);
console.log(`SAMPLE OF EXTRACTED TEXT (first 200 chars):\n"${fullText.substring(0, 200)}"`);
// Return as text, not images (workaround for service worker limitation)
return fullText.trim();
} catch (error) {
console.error('PDF text extraction failed:', error);
throw error;
}
}
async function fetchFileContent(url) {
try {
const response = await fetch(url, {
method: 'GET',
credentials: 'include' // Include cookies for Brightspace authentication
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('text')) {
return await response.text();
} else if (contentType && contentType.includes('pdf')) {
const arrayBuffer = await response.arrayBuffer();
const arrayData = Array.from(new Uint8Array(arrayBuffer));
const text = await sendMessageToOffscreen({
action: 'extractPDFText',
arrayBuffer: arrayData
});
return text;
} else if (contentType && contentType.includes('word')) {
return 'Word document detected. Add mammoth.js library to extract full text.';
} else {
return await response.text();
}
} catch (error) {
console.error(`Error fetching ${url}:`, error);
return null;
}
}
function createPrompt(question, context) {
return `You are a helpful academic assistant answering questions about course materials based on the provided excerpts from course documents.
COURSE EXCERPTS:
${context}
QUESTION: ${question}
Please provide a clear, accurate, and concise answer based ONLY on the course materials provided above. If the information is not in the materials, say "This information is not available in the provided course materials."
ANSWER:`;
}
function trimContextToTokenLimit(context, maxTokens = 12000) {
// Rough estimate: 1 token ≈ 4 characters
const maxCharacters = maxTokens * 4;
if (context.length <= maxCharacters) {
return context;
}
// Keep beginning and end
const half = maxCharacters / 2;
return context.substring(0, half) + '\n... (content trimmed) ...\n' +
context.substring(context.length - half);
}
const VECTOR_STORE_VERSION = 3;
const EMBEDDING_MODEL = 'Qwen/Qwen3-Embedding-8B';
const RAG_TOP_K = 8;
const RAG_CHUNK_SIZE = 1200;
const RAG_CHUNK_OVERLAP = 150;
const RAG_MAX_CHUNKS_PER_DOC = 80;
async function buildRagContext(question, documents, apiKey, driveAccessToken) {
console.log('Loading vector store from Drive...');
const store = await loadVectorStore(driveAccessToken);
console.log('Vector store loaded. Files:', Object.keys(store.files || {}).length);
const fileIdMap = new Map();
const updatedStore = { ...store, files: { ...(store.files || {}) } };
for (const doc of documents) {
const fileId = buildFileId(doc);
fileIdMap.set(fileId, doc);
const contentHash = hashText(doc.text || '');
const existing = updatedStore.files[fileId];
if (existing && existing.contentHash === contentHash) {
continue;
}
console.log('Chunking document:', doc.fileName);
const chunks = chunkTextForEmbeddings(doc.text || '');
const limitedChunks = chunks.slice(0, RAG_MAX_CHUNKS_PER_DOC);
console.log('Embedding chunks:', limitedChunks.length);
const embeddings = await embedTexts(limitedChunks, apiKey);
const chunkEntries = limitedChunks.map((text, index) => ({
id: `${fileId}::${index}`,
text,
embedding: normalizeEmbedding(embeddings[index] || [])
}));
updatedStore.files[fileId] = {
fileName: doc.fileName,
fileUrl: doc.fileUrl || '',
contentHash,
updatedAt: new Date().toISOString(),
chunks: chunkEntries
};
}
console.log('Saving vector store to Drive...');
await saveVectorStore(updatedStore, driveAccessToken);
console.log('Vector store saved.');
console.log('Embedding query...');
const queryEmbedding = normalizeEmbedding(
(await embedTexts([question], apiKey))[0] || []
);
console.log('Query embedding ready.');
const scored = [];
for (const [fileId, doc] of fileIdMap.entries()) {
const entry = updatedStore.files[fileId];
if (!entry || !entry.chunks) continue;
for (const chunk of entry.chunks) {
scored.push({
fileName: entry.fileName || doc.fileName,
text: chunk.text,
score: cosineSimilarity(queryEmbedding, chunk.embedding || [])
});
}
}
scored.sort((a, b) => b.score - a.score);
const topChunks = scored.slice(0, RAG_TOP_K);
if (topChunks.length === 0) {
return documents.map(doc => `[Document: ${doc.fileName}]\n${doc.text}`).join('\n\n---\n\n');
}
return topChunks.map((chunk, index) => {
return `[Excerpt ${index + 1}] (Source: ${chunk.fileName})\n${chunk.text}`;
}).join('\n\n');
}
async function buildRagContextWithServer(question, documents, apiKey, vectorApiUrl, vectorApiKey) {
const fileIdMap = new Map();
const upsertPayload = [];
for (const doc of documents) {
const fileId = buildFileId(doc);
fileIdMap.set(fileId, doc);
const chunks = chunkTextForEmbeddings(doc.text || '');
const limitedChunks = chunks.slice(0, RAG_MAX_CHUNKS_PER_DOC);
console.log('Embedding chunks for server:', limitedChunks.length);
const embeddings = await embedTexts(limitedChunks, apiKey);
limitedChunks.forEach((text, index) => {
upsertPayload.push({
fileId,
fileName: doc.fileName,
chunkId: `${fileId}::${index}`,
text,
embedding: normalizeEmbedding(embeddings[index] || [])
});
});
}
if (upsertPayload.length > 0) {
console.log('Upserting vectors to server:', upsertPayload.length);
await upsertVectorsToServer(vectorApiUrl, vectorApiKey, upsertPayload);
}
console.log('Embedding query for server...');
const queryEmbedding = normalizeEmbedding(
(await embedTexts([question], apiKey))[0] || []
);