-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathbackground.js
More file actions
47 lines (40 loc) · 1.52 KB
/
Copy pathbackground.js
File metadata and controls
47 lines (40 loc) · 1.52 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
import { callAI } from './lib/adapter.js';
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "GENERATE") {
// We handle the work asynchronously to prevent blocking the service worker
handleGenerateProcess(request);
// Return true to indicate we might respond asynchronously,
// though for streaming we will use chrome.runtime.sendMessage
return true;
}
});
async function handleGenerateProcess(request) {
const { provider, apiKey, model, baseUrl, tokens, screenshotBase64 } = request;
try {
const result = await callAI({ provider, apiKey, model, baseUrl, tokens, screenshotBase64 });
// Check if the adapter returned an async generator/iterable (streaming supported)
if (result && typeof result[Symbol.asyncIterator] === 'function') {
for await (const chunk of result) {
chrome.runtime.sendMessage({
type: "CHUNK",
text: chunk
});
}
} else {
// Fallback: The provider doesn't support streaming (or we haven't implemented it in the adapter yet)
// Send the entire response as a single chunk
chrome.runtime.sendMessage({
type: "CHUNK",
text: result
});
}
// Indicate completion
chrome.runtime.sendMessage({ type: "DONE" });
} catch (error) {
console.error("[Background Service Worker Error]:", error);
chrome.runtime.sendMessage({
type: "ERROR",
message: error.message || "An unknown error occurred during AI generation."
});
}
}