Repository navigation
Expand file tree
/
Copy pathservice-worker.js
More file actions
260 lines (198 loc) · 8.45 KB
/
Copy pathservice-worker.js
File metadata and controls
260 lines (198 loc) · 8.45 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
const GEMINI_MODEL = "gemini-2.5-pro-preview-03-25";
const GEMINI_API_ENDPOINT_BASE = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}`;
const ongoingGenerations = new Map();
async function getApiKey() {
try {
const result = await chrome.storage.local.get(['geminiApiKey']);
return result.geminiApiKey;
} catch (error) {
return null;
}
}
function sendMessageToSidePanel(instanceId, message) {
if (!instanceId) {
return;
}
const messageToSend = { ...message, instanceId: instanceId };
chrome.runtime.sendMessage(messageToSend);
}
async function callGeminiStreamingApi(apiKey, prompt, instanceId, signal) {
if (!apiKey) {
sendMessageToSidePanel(instanceId, { action: "streamError", error: "API Key not set." });
return;
}
const url = `${GEMINI_API_ENDPOINT_BASE}:streamGenerateContent?key=${apiKey}&alt=sse`;
const requestBody = {
"contents": [{
"parts": [{
"text": prompt
}]
}],
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
signal: signal,
});
if (!response.ok) {
const errorText = await response.text();
let errorData = {};
try {
errorData = JSON.parse(errorText);
} catch (e) {
}
const errorMessage = errorData.error?.message || response.statusText || 'Unknown API error';
throw new Error(`API Error (${response.status}): ${errorMessage}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let initialChunkSent = false;
while (true) {
if (signal.aborted) {
throw new Error("Fetch aborted");
}
const { done, value } = await reader.read();
if (done) {
sendMessageToSidePanel(instanceId, { action: "streamEnd" });
break;
}
buffer += decoder.decode(value, { stream: true });
let lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonString = line.substring(6);
if (!jsonString) continue;
const data = JSON.parse(jsonString);
if (!initialChunkSent) {
sendMessageToSidePanel(instanceId, { action: "streamStart" });
initialChunkSent = true;
}
if (data.candidates && data.candidates[0]?.content?.parts?.[0]?.text) {
const chunk = data.candidates[0].content.parts[0].text;
sendMessageToSidePanel(instanceId, { action: "streamChunk", chunk: chunk });
} else if (data.promptFeedback) {
const blockReason = data.promptFeedback.blockReason || "Unknown";
const safetyRatings = data.promptFeedback.safetyRatings?.map(r => `${r.category}: ${r.probability}`).join(', ') || 'N/A';
const errorMsg = `[Content blocked due to: ${blockReason}. Safety Ratings: ${safetyRatings}]`;
sendMessageToSidePanel(instanceId, { action: "streamError", error: errorMsg });
return;
}
}
}
}
} catch (error) {
if (error.name === 'AbortError' || signal.aborted) {
sendMessageToSidePanel(instanceId, { action: "streamAbort" });
} else {
sendMessageToSidePanel(instanceId, { action: "streamError", error: error.message || "An unknown error occurred during streaming." });
}
} finally {
if (ongoingGenerations.has(instanceId)) {
ongoingGenerations.delete(instanceId);
}
}
}
chrome.runtime.onInstalled.addListener(() => {
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch((error) => { });
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const instanceId = request.instanceId;
if (request.action === "saveApiKey") {
chrome.storage.local.set({ geminiApiKey: request.apiKey }, () => {
if (chrome.runtime.lastError) {
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true });
}
});
return true;
}
if (request.action === "getApiKey") {
getApiKey().then(apiKey => {
sendResponse({ apiKey: apiKey });
}).catch(error => {
sendResponse({ apiKey: null, error: error.message });
});
return true;
}
if (request.action === "stopGeneration") {
if (!instanceId) {
sendResponse({ success: false, error: "Missing instance identifier." });
return false;
}
const controller = ongoingGenerations.get(instanceId);
if (controller) {
controller.abort();
sendResponse({ success: true, message: "Abort signal sent." });
} else {
sendResponse({ success: false, message: "No active generation to stop." });
}
return false;
}
if (request.action === "processChat") {
if (!instanceId) {
return false;
}
if (ongoingGenerations.has(instanceId)) {
sendMessageToSidePanel(instanceId, { action: "streamError", error: "A request is already processing. Please wait or stop the current one." });
return false;
}
(async () => {
try {
const apiKey = await getApiKey();
if (!apiKey) {
sendMessageToSidePanel(instanceId, { action: "streamError", error: "API Key not found. Please save it first." });
return;
}
let activeContentTabId;
try {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
activeContentTabId = activeTab?.id;
if (!activeContentTabId) {
throw new Error("Could not find active tab.");
}
} catch (queryError) {
sendMessageToSidePanel(instanceId, { action: "streamError", error: "Could not find active tab to get content from." });
return;
}
let domResponse;
try {
domResponse = await chrome.tabs.sendMessage(activeContentTabId, { action: "getDOM" });
} catch (domError) {
const errorMsg = domError.message.includes("Receiving end does not exist")
? "Cannot connect to page content script. Try reloading the page."
: `Could not get page content: ${domError.message}.`;
sendMessageToSidePanel(instanceId, { action: "streamError", error: errorMsg });
return;
}
if (domResponse && domResponse.domContent !== undefined) {
const domContent = domResponse.domContent;
const userMessage = request.message;
const fullPrompt = `
--- START DOC ---
${domContent}
--- END DOC ---
${userMessage}`;
const controller = new AbortController();
ongoingGenerations.set(instanceId, controller);
callGeminiStreamingApi(apiKey, fullPrompt, instanceId, controller.signal);
} else {
const errorMsg = domResponse?.error || "Did not receive valid content from the page.";
sendMessageToSidePanel(instanceId, { action: "streamError", error: errorMsg });
}
} catch (error) {
sendMessageToSidePanel(instanceId, { action: "streamError", error: `An internal error occurred: ${error.message}` });
}
})();
// No return true needed here, communication handled by sendMessageToSidePanel
}
// Return false or undefined implicitly if no other handler returns true
});