-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
539 lines (476 loc) · 20 KB
/
Copy pathbackground.js
File metadata and controls
539 lines (476 loc) · 20 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
let thinkingModeEnabled = false;
function onExecuted(result) {}
function onExecutedCapture(result) {
var capture_exec = browser.tabs.executeScript({
file: "capture.js"
});
capture_exec.then(onExecuted, onError);
}
function onError(error) {}
function runScripts() {
var readability_exec = browser.tabs.executeScript({
file: "lib/Readability.js"
});
readability_exec.then(onExecutedCapture, onError);
}
chrome.runtime.onInstalled.addListener(function(details) {
chrome.storage.sync.set({
"ronProtocol": "capture",
"ronTemplate": "orp",
"rnnProtocol": "roam-ref",
"rnnTemplate": "p",
"clockedProtocol": "capture",
"clockedTemplate": "orc",
"journalProtocol": "capture",
"journalTemplate": "orj",
"elfeedProtocol": "elfeed-summary",
"apiKey": '',
"modelName": 'gpt-4o-mini',
"apiKeyDS": '',
"modelNameDS": 'deepseek-v4-pro',
"apiKeyKM": '',
"modelNameKM": 'moonshot-v1-32k',
"prompt": 'I will provide you a web page content. You should ignore the noise text in it. if it is a tumor biology or medicine related paper, please summarize in 4 sections: how the biology experiment design, how the data generated, what is the innovative points the paper proposed, what is the conclusion. If it is a software or algorithm or tool paper, please summarize in 5 sections: what is the input, what is the output, what is model or algorithm, what is the innovative points, and what is the conclusion.Please summarize each section in no more than 10 bullets in simple Chinese. If it is not a tumor biology or medicine related paper, please just summarze it in no more than 10 bullets in simple Chinese. Please do not reply with "好的..", just give me the summary directly.',
"useNewStyleLinks": true,
"toUseModel": "DeepSeek",
"debug": false,
});
});
// Helper: escape text for org-protocol URIs
function escapeIt(text) {
return encodeURIComponent(text)
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/'/g, "%27");
}
// Build and trigger org-protocol URI from the background page
function triggerOrgProtocol(uri, debug) {
if (debug) {
console.log(uri);
}
location.href = uri;
}
// Create right-click context menu for DeepSeek thinking mode
browser.contextMenus.create({
id: "gpt2org-thinking",
title: "GPT2Org (Deep Think)",
contexts: ["page"],
icons: {
"256": "img/icon.png"
}
});
// Context menu: Org-protocol (selection only)
browser.contextMenus.create({
id: "gpt2org-org-protocol",
title: "GPT2Org - Org-protocol",
contexts: ["all"],
icons: {
"256": "img/icon.png"
}
});
// Context menu: Journal (selection only)
browser.contextMenus.create({
id: "gpt2org-journal",
title: "GPT2Org - Journal",
contexts: ["all"],
icons: {
"256": "img/icon.png"
}
});
// Context menu: Clock-in (selection only)
browser.contextMenus.create({
id: "gpt2org-clock-in",
title: "GPT2Org - Clock-in",
contexts: ["all"],
icons: {
"256": "img/icon.png"
}
});
// Handle context menu click
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "gpt2org-thinking") {
thinkingModeEnabled = true;
browser.browserAction.openPopup({ windowId: tab.windowId });
}
if (info.menuItemId === "gpt2org-org-protocol") {
chrome.storage.sync.get(null, (data) => {
const escapedText = escapeIt(info.selectionText);
const encodedUrl = encodeURIComponent(tab.url);
const escapedTitle = escapeIt(tab.title);
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.ronProtocol +
"?template=" + data.ronTemplate +
"&url=" + encodedUrl +
"&title=" + escapedTitle +
"&body=" + escapedText;
} else {
uri = "org-protocol://" +
data.ronProtocol +
":/" + data.ronTemplate +
"/" + encodedUrl +
"/" + escapedTitle +
"/" + escapedText;
}
triggerOrgProtocol(uri, data.debug);
});
}
if (info.menuItemId === "gpt2org-journal") {
chrome.storage.sync.get(null, (data) => {
const escapedText = escapeIt(info.selectionText);
const encodedUrl = encodeURIComponent(tab.url);
const escapedTitle = escapeIt(tab.title);
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.journalProtocol +
"?template=" + data.journalTemplate +
"&url=" + encodedUrl +
"&title=" + escapedTitle +
"&body=" + escapedText;
} else {
uri = "org-protocol://" +
data.journalProtocol +
":/" + data.journalTemplate +
"/" + encodedUrl +
"/" + escapedTitle +
"/" + escapedText;
}
triggerOrgProtocol(uri, data.debug);
});
}
if (info.menuItemId === "gpt2org-clock-in") {
chrome.storage.sync.get(null, (data) => {
const escapedText = escapeIt(info.selectionText);
const encodedUrl = encodeURIComponent(tab.url);
const escapedTitle = escapeIt(tab.title);
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.clockedProtocol +
"?template=" + data.clockedTemplate +
"&url=" + encodedUrl +
"&title=" + escapedTitle +
"&body=" + escapedText;
} else {
uri = "org-protocol://" +
data.clockedProtocol +
":/" + data.clockedTemplate +
"/" + encodedUrl +
"/" + escapedTitle +
"/" + escapedText;
}
triggerOrgProtocol(uri, data.debug);
});
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "capture") {
runScripts();
}
});
// Add summarize funcs //
async function hashString(str) {
return crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)).then((hashBuffer) => {
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
return hashHex;
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "summarizeContent") {
// Capture and reset thinking mode flag so it only applies to this request
const useThinkingMode = thinkingModeEnabled;
thinkingModeEnabled = false;
chrome.storage.sync.get(null, async (data) => {
const apiKey = data.apiKey;
const model = data.modelName;
const apiKeyDS = data.apiKeyDS;
const modelDS = data.modelNameDS;
const apiKeyKM = data.apiKeyKM;
const modelKM = data.modelNameKM;
const prompt = data.prompt;
const toUseModel = data.toUseModel;
const requestUrl = request.url;
var hashStr = '';
if (toUseModel === "OpenAI") {
hashStr = `${apiKey}${prompt}${model}${toUseModel}${requestUrl}`;
} else if (toUseModel === "DeepSeek") {
hashStr = `${apiKeyDS}${prompt}${modelDS}${toUseModel}${requestUrl}${useThinkingMode ? 'thinking_on' : 'thinking_off'}`;
} else if (toUseModel === "Kimi") {
hashStr = `${apiKeyKM}${prompt}${modelKM}${toUseModel}${requestUrl}`;
} else {
hashStr = `${apiKeyDS}${prompt}${modelDS}${toUseModel}${requestUrl}${useThinkingMode ? 'thinking_on' : 'thinking_off'}`;
}
const hashedKey = await hashString(hashStr);
browser.storage.local.get(hashedKey).then((result) => {
if (result.hasOwnProperty(hashedKey)) {
const summary = result[hashedKey];
const decodedTitle = decodeURIComponent(request.title);
const decodedURL = decodeURIComponent(request.url);
navigator.clipboard.writeText(`Title: ${decodedTitle}\nURL: ${decodedURL}\nSummary:\n${summary}`);
chrome.runtime.sendMessage({
"action": "apiRequestCompleted",
"success": true,
"summary": summary,
"url": request.url,
"title": request.title,
});
} else {
if (data.toUseModel === "DeepSeek") {
apiUrl = "https://api.deepseek.com/chat/completions";
to_use_apikey = apiKeyDS;
to_use_model = modelDS;
} else if (data.toUseModel === "Kimi") {
apiUrl = "https://api.moonshot.cn/v1/chat/completions";
to_use_apikey = apiKeyKM;
to_use_model = modelKM;
} else {
apiUrl = "https://api.openai.com/v1/chat/completions";
to_use_apikey = apiKey;
to_use_model = model;
}
// ... inside chrome.runtime.onMessage.addListener for "summarizeContent"
// ... inside the else block (where data is NOT in cache) ...
if (to_use_apikey) {
// 1. Send a signal to Popup to start the UI (hide spinner)
chrome.runtime.sendMessage({
action: "streamStart"
});
const requestBody = {
"model": to_use_model,
"messages": [{
"role": "system",
"content": prompt
},
{
"role": "user",
"content": request.content
},
],
"stream": true
};
if (useThinkingMode) {
requestBody.thinking = { "type": "enabled" };
requestBody.reasoning_effort = "high";
}
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${to_use_apikey}`,
},
body: JSON.stringify(requestBody),
})
.then(async (response) => {
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let fullSummary = "";
while (true) {
const {
done,
value
} = await reader.read();
if (done) break;
const chunk = decoder.decode(value, {
stream: true
});
const lines = chunk.split("\n");
for (const line of lines) {
const trimmed = line.trim();
// Parse standard SSE format: "data: {...}"
if (trimmed.startsWith("data: ")) {
const dataStr = trimmed.slice(6);
if (dataStr === "[DONE]") continue; // Stream finished
try {
const json = JSON.parse(dataStr);
// OpenAI/DeepSeek/Kimi use choices[0].delta.content
const contentDelta = json.choices[0]?.delta?.content || "";
if (contentDelta) {
fullSummary += contentDelta;
// Send partial chunk to popup
chrome.runtime.sendMessage({
action: "streamChunk",
chunk: contentDelta
});
}
} catch (e) {
console.warn("Stream parse error:", e);
}
}
}
}
return fullSummary;
})
.then((summary) => {
// Stream is complete, perform final save and clipboard actions
const decodedTitle = decodeURIComponent(request.title);
const decodedURL = decodeURIComponent(request.url);
// Copy to clipboard
navigator.clipboard.writeText(`Title: ${decodedTitle}\nURL: ${decodedURL}\nSummary:\n${summary}`);
// Save to storage
browser.storage.local.set({
[hashedKey]: summary
})
.catch((error) => {
console.error('Error saving data:', error);
});
// Notify popup that everything is done
chrome.runtime.sendMessage({
"action": "apiRequestCompleted",
"success": true,
"summary": summary,
"url": request.url,
"title": request.title,
});
})
.catch((error) => {
console.error(error);
chrome.runtime.sendMessage({
"action": "apiRequestCompleted",
"success": false,
});
});
}
}
});
});
}
});
// add org or org-roam protocol ///////////////////////////////////////////////
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "saveOrg") {
chrome.storage.sync.get(null, (data) => {
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.ronProtocol +
"?template=" +
data.ronTemplate +
"&url=" +
request.url +
"&title=" +
request.title +
"&body=" +
request.content;
} else {
uri = "org-protocol://" +
data.ronProtocol +
":/" +
data.ronTemplate +
"/" +
request.url +
"/" +
request.title +
"/" +
request.content;
}
if (data.debug) {
console.log(uri); // Log the URI for debugging
}
location.href = uri;
});
}
if (request.action === "saveRoam") {
chrome.storage.sync.get(null, (data) => {
let uri = "org-protocol://" +
data.rnnProtocol +
"?template=" +
data.rnnTemplate +
"&ref=" +
request.url +
"&title=" +
request.title +
"&body=" +
request.content;
if (data.debug) {
console.log(uri); // Log the URI for debugging
}
location.href = uri;
});
}
if (request.action === "saveClocked") {
chrome.storage.sync.get(null, (data) => {
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.clockedProtocol +
"?template=" +
data.clockedTemplate +
"&url=" +
request.url +
"&title=" +
request.title +
"&body=" +
request.content;
} else {
uri = "org-protocol://" +
data.clockedProtocol +
":/" +
data.clockedTemplate +
"/" +
request.url +
"/" +
request.title +
"/" +
request.content;
}
if (data.debug) {
console.log(uri); // Log the URI for debugging
}
location.href = uri;
});
}
if (request.action === "saveJournal") {
chrome.storage.sync.get(null, (data) => {
let uri;
if (data.useNewStyleLinks) {
uri = "org-protocol://" +
data.journalProtocol +
"?template=" +
data.journalTemplate +
"&url=" +
request.url +
"&title=" +
request.title +
"&body=" +
request.content;
} else {
uri = "org-protocol://" +
data.journalProtocol +
":/" +
data.journalTemplate +
"/" +
request.url +
"/" +
request.title +
"/" +
request.content;
}
if (data.debug) {
console.log(uri); // Log the URI for debugging
}
location.href = uri;
});
}
if (request.action === "saveElfeed") {
chrome.storage.sync.get(null, (data) => {
let uri = "org-protocol://" +
data.elfeedProtocol +
"?url=" +
request.url +
"&title=" +
request.title +
"&summary=" +
request.content;
if (data.debug) {
console.log(uri); // Log the URI for debugging
}
location.href = uri;
});
}
});