-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
892 lines (757 loc) · 31.8 KB
/
background.js
File metadata and controls
892 lines (757 loc) · 31.8 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
// Background service worker for Page Summarizer
// Load bundled WebSocket classes and MCP adapter (avoiding ES6 imports in service worker)
try {
self.importScripts('websocket-bundle.js');
self.importScripts('mcp-adapter-bundle.js');
} catch (e) {
console.error('Failed to load bundles:', e);
}
// Store for WebSocket connections
const wsConnections = new Map();
// MCP Adapter instance
let mcpAdapter = null;
// Audio streaming state
// Note: Audio processing happens in popup, not in service worker
let isStreamingActive = false;
// Global reference to audio player window
let audioPlayerWindow = null;
let audioPlayerWindowOpening = false;
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'generateSummary') {
handleGenerateSummary(request.content, request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'explainText') {
handleExplainText(request.text, request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'generateSpeech') {
handleSpeechGeneration(request.text, request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'generateSpeechStream') {
handleStreamingSpeech(request.text, request.settings, request.tabId)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'stopStreaming') {
stopStreamingAudio();
sendResponse({ success: true });
return true;
} else if (request.action === 'testDaisysConnection') {
testDaisysAPIWithMCP(request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'generateVoice') {
handleVoiceGenerationWithMCP(request.voiceData, request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'getModels') {
getDaisysModelsWithMCP(request.settings)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
} else if (request.action === 'openAudioPlayer') {
openAudioPlayerWindow(request.mode, request.audioUrl)
.then(sendResponse)
.catch(error => sendResponse({ error: error.message }));
return true;
}
});
// Open or focus audio player window
async function openAudioPlayerWindow(mode = 'streaming', audioUrl = null) {
// Prevent rapid window creation attempts
if (audioPlayerWindowOpening) {
console.log('Audio player window is already being opened');
return { success: false, error: 'Window operation in progress' };
}
audioPlayerWindowOpening = true;
try {
// Check if window already exists
if (audioPlayerWindow) {
try {
// Get window info to check if it still exists
const window = await chrome.windows.get(audioPlayerWindow);
// Window exists, focus it and send new audio
await chrome.windows.update(audioPlayerWindow, { focused: true });
// Get all tabs in the window
const tabs = await chrome.tabs.query({ windowId: audioPlayerWindow });
if (tabs.length > 0) {
// Stop current audio first
try {
await chrome.tabs.sendMessage(tabs[0].id, {
action: 'stopAudio'
});
} catch (err) {
console.log('Error stopping audio:', err);
}
// Small delay to ensure audio is stopped
await new Promise(resolve => setTimeout(resolve, 200));
// Update the URL with new parameters
const newUrl = chrome.runtime.getURL(`audio_player.html?mode=${mode}${audioUrl ? `&url=${encodeURIComponent(audioUrl)}` : ''}`);
await chrome.tabs.update(tabs[0].id, { url: newUrl });
}
audioPlayerWindowOpening = false;
return { success: true, windowId: audioPlayerWindow };
} catch (e) {
// Window doesn't exist anymore, clear reference
console.log('Window no longer exists, clearing reference');
audioPlayerWindow = null;
}
}
// Create new window
const params = {
url: chrome.runtime.getURL(`audio_player.html?mode=${mode}${audioUrl ? `&url=${encodeURIComponent(audioUrl)}` : ''}`),
type: 'popup',
width: 340,
height: 180,
top: 100,
left: 100
};
const window = await chrome.windows.create(params);
audioPlayerWindow = window.id;
// Listen for window close
chrome.windows.onRemoved.addListener(function windowCloseListener(windowId) {
if (windowId === audioPlayerWindow) {
audioPlayerWindow = null;
chrome.windows.onRemoved.removeListener(windowCloseListener);
}
});
return { success: true, windowId: audioPlayerWindow };
} catch (error) {
console.error('Error opening audio player window:', error);
throw error;
} finally {
// Always reset the flag
audioPlayerWindowOpening = false;
}
}
// Get or create MCP adapter instance
async function getMCPAdapter(settings) {
if (!mcpAdapter) {
mcpAdapter = new DaisysMCPAdapter();
}
// Ensure adapter is initialized
if (!mcpAdapter.authToken) {
await mcpAdapter.initialize(settings.daisysEmail, settings.daisysPassword);
}
return mcpAdapter;
}
// Stop streaming audio
function stopStreamingAudio() {
isStreamingActive = false;
// Close any open websockets
wsConnections.forEach(connection => {
if (connection.connector) {
connection.connector.close();
}
});
wsConnections.clear();
}
// Listen for keyboard shortcuts
chrome.commands.onCommand.addListener(async (command) => {
if (command === 'summarize-page') {
await handleHotkeySummarizePage();
} else if (command === 'explain-selection') {
await handleHotkeyExplainSelection();
}
});
// Handle hotkey for page summarization
async function handleHotkeySummarizePage() {
try {
// Get active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
console.error('Cannot summarize browser internal pages');
return;
}
// Get saved settings
const settings = await chrome.storage.local.get([
'daisysEmail', 'daisysPassword', 'selectedVoiceId',
'llmProvider', 'llmApiKey', 'llmEndpoint', 'llmModel'
]);
if (!settings.llmProvider || !settings.llmApiKey) {
console.error('Please configure LLM settings first');
return;
}
if (!settings.daisysEmail || !settings.daisysPassword || !settings.selectedVoiceId) {
console.error('Please configure DAISYS settings first');
return;
}
// Inject content script
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Wait a bit for script to load
await new Promise(resolve => setTimeout(resolve, 100));
// Extract content
const contentResponse = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
if (!contentResponse || !contentResponse.content) {
console.error('Failed to extract page content');
return;
}
// Generate summary
const summaryResult = await handleGenerateSummary(contentResponse.content, settings);
if (!summaryResult.summary) {
console.error('Failed to generate summary');
return;
}
// Try streaming speech first
try {
console.log('[Background] Attempting streaming speech...');
// Open audio player window for hotkey usage
await openAudioPlayerWindow('streaming');
await handleStreamingSpeech(summaryResult.summary, settings, tab.id);
} catch (streamError) {
console.log('[Background] Streaming failed, trying regular generation:', streamError.message);
// Notify user about fallback
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Switching to Standard Mode',
message: 'Streaming unavailable, generating full audio...'
});
// Fallback to regular generation
try {
const result = await handleSpeechGeneration(summaryResult.summary, settings);
// Open audio player window with URL
await openAudioPlayerWindow('url', result.audioUrl);
} catch (fallbackError) {
console.error('Both streaming and regular generation failed:', fallbackError);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Summary Error',
message: 'Failed to generate audio. Please check your settings.'
});
}
}
} catch (error) {
console.error('Hotkey summary error:', error);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Summary Error',
message: error.message || 'Failed to generate summary'
});
}
}
// Handle hotkey for text explanation
async function handleHotkeyExplainSelection() {
try {
// Get active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
console.error('Cannot explain text on browser internal pages');
return;
}
// Get saved settings
const settings = await chrome.storage.local.get([
'daisysEmail', 'daisysPassword', 'selectedVoiceId',
'llmProvider', 'llmApiKey', 'llmEndpoint', 'llmModel'
]);
if (!settings.llmProvider || !settings.llmApiKey) {
console.error('Please configure LLM settings first');
return;
}
if (!settings.daisysEmail || !settings.daisysPassword || !settings.selectedVoiceId) {
console.error('Please configure DAISYS settings first');
return;
}
// Inject content script
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Wait a bit for script to load
await new Promise(resolve => setTimeout(resolve, 100));
// Get selected text
const selectionResponse = await chrome.tabs.sendMessage(tab.id, { action: 'getSelectedText' });
if (!selectionResponse || !selectionResponse.selectedText) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'No Text Selected',
message: 'Please select some text first, then try again.'
});
return;
}
// Generate explanation
const explanationResult = await handleExplainText(selectionResponse.selectedText, settings);
if (!explanationResult.explanation) {
console.error('Failed to generate explanation');
return;
}
// Try streaming speech
try {
console.log('[Background] Attempting streaming speech for explanation...');
// Open audio player window for hotkey usage
await openAudioPlayerWindow('streaming');
await handleStreamingSpeech(explanationResult.explanation, settings, tab.id);
} catch (streamError) {
console.log('[Background] Streaming failed, trying regular generation:', streamError.message);
// Fallback to regular generation
try {
const result = await handleSpeechGeneration(explanationResult.explanation, settings);
// Open audio player window with URL
await openAudioPlayerWindow('url', result.audioUrl);
} catch (fallbackError) {
console.error('Both streaming and regular generation failed:', fallbackError);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Explanation Error',
message: 'Failed to generate audio explanation.'
});
}
}
} catch (error) {
console.error('Hotkey explain error:', error);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Explanation Error',
message: error.message || 'Failed to generate explanation'
});
}
}
// Handle page summary generation using LLM
async function handleGenerateSummary(content, settings) {
const { llmProvider, llmApiKey, llmEndpoint, llmModel } = settings;
const systemPrompt = `You are a helpful accessibility assistant. Your job is to summarize webpage content in a clear, concise way that sounds natural when spoken aloud.
Guidelines:
- For SHORT pages (single topic): Create 1-2 paragraphs (3-5 sentences each)
- For LONG pages (multiple topics):
* Start with a brief overview paragraph
* Then organize content into 3-5 main categories/sections
* Provide a short summary (2-3 sentences) for each category
* Use clear transitions like "First," "Next," "Additionally," "Finally"
- Use simple, conversational language
- Make it sound natural for text-to-speech
- Avoid technical jargon unless necessary
- Be factual and informative
- ALWAYS output in English, regardless of the input language`;
const userPrompt = `Please summarize this webpage content. If the page covers multiple distinct topics, organize them into categories. Always respond in English:\n\n${content}`;
try {
let response;
if (llmProvider === 'openai') {
response = await callOpenAI(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'anthropic') {
response = await callAnthropic(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'xai') {
response = await callXAI(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'custom' && llmEndpoint) {
response = await callCustomLLM(llmEndpoint, llmApiKey, llmModel, systemPrompt, userPrompt);
} else {
throw new Error('Invalid LLM provider configuration');
}
return { summary: response };
} catch (error) {
console.error('Summary generation error:', error);
throw new Error(`Failed to generate summary: ${error.message}`);
}
}
// Handle text explanation using LLM
async function handleExplainText(text, settings) {
const { llmProvider, llmApiKey, llmEndpoint, llmModel } = settings;
const systemPrompt = `You are a helpful accessibility assistant. Your job is to explain difficult or complex text in simpler terms.
Guidelines:
- Use everyday language
- Break down complex concepts
- Provide context when helpful
- Keep explanations concise but clear
- Make it sound natural for text-to-speech
- Be patient and helpful
- ALWAYS output in English, regardless of the input language`;
const userPrompt = `Please explain this text in simpler terms, as if speaking to someone who needs clarification. Always respond in English:\n\n"${text}"`;
try {
let response;
if (llmProvider === 'openai') {
response = await callOpenAI(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'anthropic') {
response = await callAnthropic(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'xai') {
response = await callXAI(llmApiKey, llmModel, systemPrompt, userPrompt);
} else if (llmProvider === 'custom' && llmEndpoint) {
response = await callCustomLLM(llmEndpoint, llmApiKey, llmModel, systemPrompt, userPrompt);
} else {
throw new Error('Invalid LLM provider configuration');
}
return { explanation: response };
} catch (error) {
console.error('Explanation generation error:', error);
throw new Error(`Failed to generate explanation: ${error.message}`);
}
}
// OpenAI API call
async function callOpenAI(apiKey, model, systemPrompt, userPrompt) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model || 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
max_tokens: 800,
temperature: 0.7
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`OpenAI API error: ${error}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
// Anthropic Claude API call
async function callAnthropic(apiKey, model, systemPrompt, userPrompt) {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: model || 'claude-3-sonnet-20240229',
max_tokens: 800,
temperature: 0.7,
messages: [
{ role: 'user', content: `${systemPrompt}\n\n${userPrompt}` }
]
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Anthropic API error: ${error}`);
}
const data = await response.json();
return data.content[0].text;
}
// xAI Grok API call
async function callXAI(apiKey, model, systemPrompt, userPrompt) {
const response = await fetch('https://api.x.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model || 'grok-2-1212',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
max_tokens: 800,
temperature: 0.7
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`xAI Grok API error: ${error}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
// Custom LLM API call
async function callCustomLLM(endpoint, apiKey, model, systemPrompt, userPrompt) {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
max_tokens: 800,
temperature: 0.7
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Custom LLM API error: ${error}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
// Process audio chunks in the background
// Note: Service workers cannot use AudioContext, so we just pass data to popup
function processAudioChunkInBackground(audioData, metadata) {
if (!isStreamingActive) return;
// Service workers can't process audio directly
// This function is not used anymore - audio is processed in popup
console.log('[Background] Audio chunk received, should be processed in popup');
}
function concatUint8Arrays(a, b) {
const result = new Uint8Array(a.length + b.length);
result.set(a, 0);
result.set(b, a.length);
return result;
}
// This function is no longer used - audio processing happens in popup
// Service workers cannot use AudioContext API
async function tryDecodeAndPlayChunk() {
// Deprecated - kept for reference only
console.warn('[Background] tryDecodeAndPlayChunk called but service workers cannot process audio');
}
// Handle streaming speech generation using MCP adapter
async function handleStreamingSpeech(text, settings, tabId) {
const { selectedVoiceId } = settings;
// Reset streaming state
isStreamingActive = true;
try {
// Get MCP adapter
const adapter = await getMCPAdapter(settings);
console.log('[Background] Attempting streaming TTS with voice:', selectedVoiceId);
// Use MCP adapter to get streaming response
const streamResponse = await adapter.textToSpeech({
text: text,
voice_id: selectedVoiceId,
streaming: true
});
if (streamResponse.type !== 'streaming') {
console.log('[Background] Adapter returned non-streaming response, switching to URL mode');
throw new Error('Expected streaming response but got URL response');
}
const { wsUrl, requestData } = streamResponse;
console.log('[Background] Got WebSocket URL, connecting...');
// Create WebSocket connection
const wsConnector = new WebsocketConnector(
async () => wsUrl,
(status) => {
console.log('WebSocket status:', status);
// Send status to audio player window
if (audioPlayerWindow) {
chrome.tabs.query({ windowId: audioPlayerWindow }, (tabs) => {
if (tabs.length > 0) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'streamingStatus',
status: status,
tabId: tabId
}).catch(() => {});
}
});
}
// Also try sending to popup
chrome.runtime.sendMessage({
action: 'streamingStatus',
status: status,
tabId: tabId
}).catch(() => {
// Popup might not be open, ignore error
});
}
);
// Create stream handler
const wsStream = new WebsocketStream(wsConnector);
// Store connection for cleanup
wsConnections.set(tabId, { connector: wsConnector, stream: wsStream });
// Connect to WebSocket
await wsConnector.connect();
// Get request ID from MCP adapter response
const requestId = requestData.request_id;
// Send generation command from MCP adapter response
wsStream.send(requestData);
// Process message stream
const messageStream = wsStream.messageStream(requestId);
for await (const message of messageStream) {
if (message.type === 'status') {
console.log('Status update:', JSON.stringify(message.data));
// Send status to audio player window
if (audioPlayerWindow) {
chrome.tabs.query({ windowId: audioPlayerWindow }, (tabs) => {
if (tabs.length > 0) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'streamingMessage',
type: 'status',
data: message.data,
tabId: tabId
}).catch(() => {});
}
});
}
// Also try sending to popup
chrome.runtime.sendMessage({
action: 'streamingMessage',
type: 'status',
data: message.data,
tabId: tabId
}).catch(() => {
// Popup might not be open, ignore error
});
if (message.data.status === 'error') {
throw new Error(message.data.message || 'Streaming error');
}
} else if (message.type === 'audio') {
console.log('[Background] Audio chunk received:', {
partId: message.data.metadata.part_id,
size: message.data.audioData.byteLength,
metadata: message.data.metadata
});
// Convert ArrayBuffer to array for message passing
const audioArray = Array.from(new Uint8Array(message.data.audioData));
// Send audio chunk to audio player window
if (audioPlayerWindow) {
chrome.tabs.query({ windowId: audioPlayerWindow }, (tabs) => {
if (tabs.length > 0) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'streamingMessage',
type: 'audioChunk',
audioData: audioArray,
metadata: message.data.metadata,
tabId: tabId
}).catch(() => {});
}
});
}
// Also try sending to popup
chrome.runtime.sendMessage({
action: 'streamingMessage',
type: 'audioChunk',
audioData: audioArray,
metadata: message.data.metadata,
tabId: tabId
}).catch(() => {
// Popup might not be open, ignore error
});
} else {
console.log('[Background] Unknown message type:', message.type, message);
}
}
// Streaming complete
if (audioPlayerWindow) {
chrome.tabs.query({ windowId: audioPlayerWindow }, (tabs) => {
if (tabs.length > 0) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'streamingComplete',
tabId: tabId
}).catch(() => {});
}
});
}
chrome.runtime.sendMessage({
action: 'streamingComplete',
tabId: tabId
}).catch(() => {
// Popup might not be open, ignore error
});
return { success: true };
} catch (error) {
console.error('[Background] Streaming speech error:', error);
// Clean up connection
const connection = wsConnections.get(tabId);
if (connection) {
connection.connector.close();
wsConnections.delete(tabId);
}
// Check if it's a WebSocket availability issue
if (error.message.includes('WebSocket') || error.message.includes('streaming')) {
console.log('[Background] WebSocket streaming not available, will use fallback');
throw new Error('WebSocket streaming unavailable - use fallback mode');
}
throw new Error(`Failed to stream speech: ${error.message}`);
}
}
// Handle voice generation using MCP adapter
async function handleVoiceGenerationWithMCP(voiceData, settings) {
const { name, gender, model } = voiceData;
try {
// Get MCP adapter
const adapter = await getMCPAdapter(settings);
// Use MCP adapter to create voice
const voiceInfo = await adapter.createVoice({
name: name,
gender: gender,
model: model,
expression: 5 // Normal expression for accessibility
});
return {
success: true,
voice: {
id: voiceInfo.voice_id,
name: voiceInfo.name,
gender: voiceInfo.gender,
model: voiceInfo.model
}
};
} catch (error) {
console.error('Voice generation error:', error);
throw new Error(`Failed to generate voice: ${error.message}`);
}
}
// Get available DAISYS models using MCP adapter
async function getDaisysModelsWithMCP(settings) {
try {
// Get MCP adapter
const adapter = await getMCPAdapter(settings);
// Use MCP adapter to get models
const models = await adapter.getModels({});
return {
success: true,
models: models
};
} catch (error) {
console.error('Get models error:', error);
throw new Error(`Failed to get models: ${error.message}`);
}
}
// Handle regular speech generation (non-streaming) using MCP adapter
async function handleSpeechGeneration(text, settings) {
const { selectedVoiceId } = settings;
try {
// Get MCP adapter
const adapter = await getMCPAdapter(settings);
// Use MCP adapter for non-streaming TTS
const result = await adapter.textToSpeech({
text: text,
voice_id: selectedVoiceId,
audio_format: 'wav',
streaming: false
});
if (result.type !== 'url') {
throw new Error('Expected URL response for non-streaming TTS');
}
const audioUrl = result.audioUrl;
return { audioUrl };
} catch (error) {
console.error('Speech generation error:', error);
throw new Error(`Failed to generate speech: ${error.message}`);
}
}
// Test DAISYS API connection and fetch voices using MCP adapter
async function testDaisysAPIWithMCP(settings) {
try {
// Get MCP adapter
const adapter = await getMCPAdapter(settings);
// Use MCP adapter to get voices
const voices = await adapter.getVoices({});
return {
success: true,
voices: voices.map(v => ({
id: v.voice_id,
name: v.name,
gender: v.gender,
model: v.model
}))
};
} catch (error) {
console.error('DAISYS API test error:', error);
throw new Error(`DAISYS API test failed: ${error.message}`);
}
}