Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1677 lines (1549 loc) · 74 KB
/
Copy pathbackground.js
File metadata and controls
1677 lines (1549 loc) · 74 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
// Service worker: translates the screen Kindle Cloud Reader shows. The page
// script (content.js) says which screen that is ("pageShown", from the
// reader's own page data) and hands over its paragraphs and a clean drawing
// of it. Two engines:
// - "ocr": Tesseract reads each paragraph locally, then Haiku translates the
// text alone, optionally with Sonnet reviewing the draft. Fast, and the
// model never sees a book page. Translations are cached per paragraph, by
// its position range in the book, so they're reused whatever the layout.
// - "vision": Opus reads a screenshot and translates it in one call.
// See docs/design.md and docs/page-pipeline-v2.md.
importScripts("ocr-layout.js", "styled-text.js", "context-pages.js");
// Vision engine: only Opus. In testing, Sonnet 5.5 and Haiku 5.5 declined to
// translate screenshots of Kindle book pages (citing copyright).
const MODEL = "claude-opus-5-5";
// OCR engine: models for translating and reviewing plain text, with the
// lowest thinking setting each accepts (a straight translation; thinking only
// adds latency). Sonnet 5.5 rejects "disabled".
const TEXT_MODELS = {
"claude-sonnet-5-5": { type: "between_tools" },
"claude-haiku-5-5": { type: "disabled" },
};
// Translation quality levels (options page): who drafts, and who reviews the
// draft. The reviewer returns only the paragraphs it changes, which keeps its
// output, and so its latency and cost, small.
const QUALITY = {
haiku: { translate: "claude-haiku-5-5" },
review: { translate: "claude-haiku-5-5", review: "claude-sonnet-5-5" },
};
// Server-side fallback when a safety classifier declines the request.
// Opus 5.5 runs a biology classifier that Opus 5 doesn't, so "default"
// routing can leave benign pages (e.g. a history of biological warfare)
// declined; naming Opus 5 / Opus 4.8 explicitly retries them there.
const FALLBACK = {
beta: "server-side-fallback-2026-06-01",
fallbacks: [{ model: "claude-opus-5" }, { model: "claude-opus-4-8" }],
};
const DEFAULTS = {
apiKey: "",
engine: "ocr",
quality: "review",
effort: "low",
autoTranslate: true,
prefetch: true,
referencePages: false,
referenceTokens: 16000,
targetLang: "繁體中文(台灣用語)",
overlay: true,
};
// Image size we send. Within the model's limits, returned coordinates map 1:1
// to our pixels; above either limit the API downscales again and every box
// shrinks toward the top-left (seen: 2576×1593 = 4.1 MP came back at ~0.956×).
// The pixel cap sits a little under the documented 3.75 MP.
const MAX_EDGE = 2576;
const MAX_PIXELS = 3_700_000;
const API_TIMEOUT_MS = 180_000;
// A screen's translation is only requested once it has stayed on screen this
// long, so pages flipped past quickly are never sent. Drawing a cached
// translation doesn't wait.
const SETTLE_MS = 1200;
// The next screen is translated ahead once the current one has been on
// screen this long (and is translated), so flipping through translated pages
// doesn't start and cancel a request on each.
const PREFETCH_DWELL_MS = 2000;
// Claude sometimes answers a page with a summary instead of a translation,
// citing copyright, and the same page often translates fine on the next
// try. Retry that many times; after that show the summary, uncached.
const SUMMARY_RETRIES = 1;
const READER_RE = /^https:\/\/read\.amazon\.(com|co\.jp|co\.uk|de|ca|com\.au)\//;
let panelPorts = new Set();
// Jobs. The foreground job translates the screen on show; only it draws. When
// the reader moves on, it isn't cancelled but moved to the background: it
// finishes, fills the cache, and its paragraphs are then free wherever they
// show up again. A prefetch job translates the next screen ahead. Each job:
// { kind: "page" | "prefetch", page (screen), force, controller (cancels its
// OCR wait and API calls), detached, done }.
let current = null;
const background = new Set();
let prefetching = null;
// Translations being requested, by paragraph cache key, so a job that needs
// a paragraph another job is already paying for waits for it instead.
const inflight = new Map();
// Screens being read (OCR), by record key, for the same reason.
const reading = new Map();
// Screens turned past while translating keep going, up to this many; beyond
// it the oldest is cancelled, so paging on doesn't pile up requests.
const MAX_BACKGROUND = 1;
let settleTimer = null;
let prefetchTimer = null;
// ---- Screens ----
// A screen as content.js names it: { key (layout), start, end (position
// range), asin, revision, width, height (CSS px), fill, ink }, plus the tab
// it's in ({ tabId, windowId }) once the worker knows it.
function screenId(page) {
return page ? `${page.key}|${page.start}` : null;
}
function sameScreen(a, b) {
return !!a && !!b && screenId(a) === screenId(b);
}
function describeScreen(page) {
return `位置 ${page.start}–${page.end}`;
}
// Chrome stops this service worker after ~30 s idle, wiping module state, so
// what's on screen, what's drawn and the cache live in session storage
// (cleared when the browser closes).
async function getShown() {
return (await chrome.storage.session.get("shown")).shown ?? null;
}
async function setShown(page) {
if (page) await chrome.storage.session.set({ shown: page });
else await chrome.storage.session.remove("shown");
}
// The screen whose translation is on the page (or, with the overlay off, in
// the side panel). While it's the one on screen, the side panel's button
// retranslates (skipping the cache) and is labelled that way.
async function getDrawn() {
return (await chrome.storage.session.get("drawn")).drawn ?? null;
}
async function setDrawn(page) {
if (page) await chrome.storage.session.set({ drawn: screenId(page) });
else await chrome.storage.session.remove("drawn");
broadcast({ type: "pageState", retranslate: !!page });
}
// ---- Cache ----
// Per paragraph: { source, text, savedAt } under its position range in the
// book, the same in any layout (plus a hash of the highlights over it, which
// the reader can add or remove any time). Per screen: how the screen splits
// into paragraphs, with their boxes and OCR words (its "record"), under the
// layout key and its start. The vision engine's whole-screen results under
// vision:.
const CACHE_PARAS = 5000;
const CACHE_PAGES = 500;
let cacheChain = Promise.resolve(); // index updates one at a time
function paraKey(page, p) {
return `para:${page.asin}:${page.revision}:${p.start}-${p.end}`;
}
// Whether a record paragraph has any words to translate.
function hasText(p) {
return (p.words || []).length > 0;
}
// A record paragraph as sent to Claude: its words, the italic and bold ones
// and those under a highlight marked (<i>, <b>, <h1>, <h2>… one number per
// highlight colour, docs/text-styles.md), the colour of each highlight mark,
// and its cache key, which changes with the highlights over it.
function paraSource(page, p) {
const highlights = (page.highlights || []).filter((h) => h.start <= p.end && h.end >= p.start);
const colors = [...new Set(highlights.map((h) => h.color))];
const marks = Object.fromEntries(colors.map((c, i) => [`h${i + 1}`, c]));
const words = (p.words || []).map((w) => {
const styles = [...(w.styles || [])];
for (const h of highlights) if (h.boxes.some((b) => centreIn(w, b))) styles.push(`h${colors.indexOf(h.color) + 1}`);
return { text: w.text, styles };
});
const source = words.some((w) => w.styles.length) ? tagWords(words) : wordsText(words);
const marked = highlights.length ? `:h${hashOf(highlights.map((h) => `${h.start}-${h.end}-${h.color}`).sort().join(";"))}` : "";
return { key: paraKey(page, p) + marked, source, marks };
}
function centreIn(w, b) {
const x = (w.x0 + w.x1) / 2;
const y = (w.y0 + w.y1) / 2;
return x >= b.x0 - 2 && x <= b.x1 + 2 && y >= b.y0 - 2 && y <= b.y1 + 2;
}
function hashOf(str) {
let h = 2166136261;
for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619);
return (h >>> 0).toString(36);
}
function recordKey(page) {
return `page:${page.key}:${page.start}`;
}
function visionKey(page) {
return `vision:${page.key}:${page.start}`;
}
// Store `items` (key → value) and keep the newest CACHE_PARAS paragraphs and
// CACHE_PAGES screens.
function cacheWrite(items) {
const run = cacheChain.then(async () => {
const { cacheIndex = { paras: [], pages: [] } } = await chrome.storage.session.get("cacheIndex");
for (const key of Object.keys(items)) {
const list = key.startsWith("para:") ? cacheIndex.paras : cacheIndex.pages;
const i = list.indexOf(key);
if (i >= 0) list.splice(i, 1);
list.push(key);
}
const dropped = [
...cacheIndex.paras.splice(0, Math.max(0, cacheIndex.paras.length - CACHE_PARAS)),
...cacheIndex.pages.splice(0, Math.max(0, cacheIndex.pages.length - CACHE_PAGES)),
];
const kept = { ...items };
for (const key of dropped) delete kept[key]; // past the limit in this very write
if (dropped.length) await chrome.storage.session.remove(dropped);
try {
await chrome.storage.session.set({ ...kept, cacheIndex });
} catch (err) {
// Chrome caps session storage (10 MB), which the counts above can
// outgrow on a long read: then nothing could be cached any more and
// every screen failed. Make room and try once more.
if (!/quota/i.test(err?.message || "")) throw err;
const freed = [];
for (const list of [cacheIndex.paras, cacheIndex.pages]) {
const older = list.slice(0, Math.floor(list.length / 2)).filter((k) => !(k in items));
freed.push(...older);
for (const k of older) list.splice(list.indexOf(k), 1);
}
await chrome.storage.session.remove(freed);
log(`快取空間已滿${await sessionBytes()},丟掉較舊的一半(${freed.length} 筆)`);
await chrome.storage.session.set({ ...kept, cacheIndex });
}
});
cacheChain = run.catch(() => {});
return run;
}
// "(用了 9.8 MB)", or nothing when Chrome can't say.
async function sessionBytes() {
try {
return `(用了 ${((await chrome.storage.session.getBytesInUse(null)) / 1048576).toFixed(1)} MB)`;
} catch (_) {
return "";
}
}
async function cacheRead(keys) {
return keys.length ? chrome.storage.session.get(keys) : {};
}
// The cached translation of each of the record's paragraphs that has text
// (blank for what Claude took for noise), as paragraph key → text; null
// when any is missing.
async function cachedTexts(page, record) {
const keys = record.paras.filter(hasText).map((p) => paraSource(page, p).key);
const have = await cacheRead(keys);
const texts = new Map();
for (const k of keys) if (have[k]) texts.set(k, have[k].text);
return texts.size === keys.length ? texts : null;
}
// Whether everything `page` needs is in the cache (a screen without text
// needs nothing).
async function screenDone(page) {
const record = (await chrome.storage.session.get(recordKey(page)))[recordKey(page)];
return !!record && (!record.paras.some(hasText) || !!(await cachedTexts(page, record)));
}
// Draw `page` from the cache if everything it needs is there. `post`: also
// add it to the side panel's list (not when merely redrawing).
async function drawFromCache(page, settings, { post = true } = {}) {
if (settings.engine === "vision") {
const record = (await chrome.storage.session.get(visionKey(page)))[visionKey(page)];
if (!record) return false;
log(`命中快取(看圖模式,${record.paras.length} 個區塊),不呼叫 API`);
await draw(page, record, (p) => p.text, { cached: true, post });
return true;
}
const record = (await chrome.storage.session.get(recordKey(page)))[recordKey(page)];
if (!record) return false;
const texts = await cachedTexts(page, record);
if (!texts) return false;
log(`命中快取(${texts.size} 段),不呼叫 API`);
await draw(page, record, (p) => texts.get(paraSource(page, p).key), { cached: true, post });
return true;
}
// ---- Reference pages ----
// With the options page's switch on, two things are kept per book in local
// storage (context-pages.js):
// - the paragraphs drawn on screen (source and final translation), for a
// week; the review is sent the ones before its page. Index refBooks.
// - the names the review settled on (source → translation), for 30 days
// after each was last seen; every translation and review is sent the ones
// on its page. Index nameBooks.
// An index maps each book's key to when it was last written, so books not
// read for that long are dropped too.
let bookChain = Promise.resolve(); // one read-modify-write at a time
function refKey(page) {
return `ref:${page.asin}:${page.revision}`;
}
function namesKey(page) {
return `names:${page.asin}:${page.revision}`;
}
// Read `key` (or `empty`), let `change(book, now)` edit it, write it back,
// and drop the books in `index` not written for `maxAge`.
function bookUpdate(key, index, maxAge, empty, change) {
const run = bookChain.then(async () => {
const now = Date.now();
const { [key]: book = empty, [index]: books = {} } = await chrome.storage.local.get([key, index]);
const out = change(book, now);
const stale = Object.keys(books).filter((k) => k !== key && now - books[k] > maxAge);
for (const k of stale) delete books[k];
if (stale.length) await chrome.storage.local.remove(stale);
await chrome.storage.local.set({ [key]: book, [index]: { ...books, [key]: now } });
return out;
});
bookChain = run.catch(() => {});
return run;
}
function refUpdate(page, change) {
return bookUpdate(refKey(page), "refBooks", REF_MAX_AGE_MS, { paras: [], refStart: null }, change);
}
// The book's listed names that appear in `texts` ([{ source, text }]), or
// none: switch off, unknown book, nothing listed, or storage unreadable.
async function bookNames(settings, page, texts) {
if (!settings.referencePages || !page?.asin) return [];
try {
const key = namesKey(page);
const { [key]: book } = await chrome.storage.local.get(key);
return namesIn(mergeNames(book?.names, [], Date.now()).names, texts);
} catch (err) {
log(`讀不到人名對照表(${err.message || err}),這次不用`);
return [];
}
}
// Add the names a review found; a name already listed keeps its translation.
async function saveNames(page, found, tag) {
const res = await bookUpdate(namesKey(page), "nameBooks", NAMES_MAX_AGE_MS, { names: {} }, (book, now) => {
const res = mergeNames(book.names, found, now);
book.names = res.names;
return res;
});
if (res.added.length) log(`${tag}人名對照表新增:${res.added.map((n) => `${n.source} → ${n.text}`).join("、")}`);
if (res.conflicts.length) log(`${tag}人名對照表已有別的譯法,沿用原本的:${res.conflicts.map((c) => `${c.source} → ${c.kept}(這次是 ${c.text})`).join("、")}`);
return res;
}
// What saveNames would do with `found`, without keeping anything.
async function compareNames(page, found) {
const key = namesKey(page);
const { [key]: book } = await chrome.storage.local.get(key);
return mergeNames(book?.names, found, Date.now());
}
// The review used another translation for a listed name (`conflicts` from
// mergeNames): put the listed one back in the paragraphs (`items`, { id,
// source }) where the name appears, in `texts` (id → text). A one-character
// translation is left alone (申 would hit 申請), as is one inside the
// listed name (拉夫 in 格拉夫). Returns how many were replaced.
function restoreNames(conflicts, items, texts) {
let n = 0;
for (const c of conflicts) {
if ([...c.text].length < 2 || c.kept.includes(c.text)) continue;
for (const p of items) {
const text = texts.get(p.id);
if (!text?.includes(c.text) || !namesIn({ [c.source]: { text: c.kept } }, [p.source]).length) continue;
n += text.split(c.text).length - 1;
texts.set(p.id, text.replaceAll(c.text, c.kept));
}
}
return n;
}
// Keep the paragraphs of a screen just drawn (OCR engine only).
async function saveReference(page, record, textOf) {
if (!page.asin) return;
const paras = record.paras
.filter(hasText)
.map((p) => ({ start: p.start, end: p.end, source: paraSource(page, p).source, text: textOf(p) || "" }))
.filter((p) => stripMarks(p.text).trim());
if (!paras.length) return;
await refUpdate(page, (book, now) => {
book.paras = mergeParas(book.paras, paras, now);
});
}
// The content blocks that put the book's earlier paragraphs before the
// review prompt, or null (logged why) when there are none to send. Cache
// breakpoints go on the last closed block, which stays the same until the
// set is trimmed, and on the last block.
async function referenceContent(settings, page, tag) {
if (!page?.asin) {
log(`${tag}校對沒有參考前面的頁:不知道是哪一本書`);
return null;
}
const max = Math.min(100_000, Math.max(2000, Number(settings.referenceTokens) || DEFAULTS.referenceTokens));
const pick = await refUpdate(page, (book) => {
const pick = pickReference(book.paras, page.start, book.refStart, max);
book.refStart = pick.refStart;
return pick;
});
if (!pick.paras.length) {
log(`${tag}校對沒有參考前面的頁:這本書在${describeScreen(page)}之前還沒有翻過的段落`);
return null;
}
const how = pick.trimmed ? ",超過上限,丟掉較舊的一半" : pick.reset ? ",重新起算" : "";
log(`${tag}校對參考前面的頁:${pick.paras.length} 段(位置 ${pick.paras[0].start}–${pick.paras.at(-1).end}),約 ${pick.tokens} tokens${how}`);
const blocks = referenceBlocks(pick.paras);
const lastFull = blocks.findLastIndex((b) => b.full);
return [
{ type: "text", text: REFERENCE_INTRO },
...blocks.map((b, i) => ({
type: "text",
text: b.text,
...((i === lastFull || i === blocks.length - 1) && { cache_control: { type: "ephemeral" } }),
})),
];
}
const REFERENCE_INTRO = "以下是同一本書在這一頁之前、使用者已經讀過的段落,依書中的順序排列,每行一段:source 是原文,text 是已經定稿的譯文。這些段落只供參考,用來統一人名、專有名詞、稱呼和語氣。";
chrome.runtime.onInstalled.addListener(() => {
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
injectIntoOpenReaders();
});
// Installing or reloading the extension cuts off the content scripts in tabs
// already open. Give those tabs live copies now. They missed the page data
// fetched so far, so the screen is known again from the reader's next batch,
// or after reloading the tab.
async function injectIntoOpenReaders() {
const scripts = chrome.runtime.getManifest().content_scripts;
for (const tab of await chrome.tabs.query({ url: scripts[0].matches })) {
for (const cs of scripts) {
chrome.scripting.executeScript({ target: { tabId: tab.id }, files: cs.js, world: cs.world || "ISOLATED" }).catch(() => {});
}
}
}
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== "sidepanel") return;
panelPorts.add(port);
port.onDisconnect.addListener(() => panelPorts.delete(port));
for (const msg of unsent.splice(0)) port.postMessage(msg);
// Button label and "not translated yet" hint for a freshly opened panel.
Promise.all([getShown(), getDrawn()])
.then(([shown, drawn]) => port.postMessage({ type: "pageState", retranslate: !!shown && drawn === screenId(shown) }))
.catch(() => {});
port.onMessage.addListener((msg) => {
if (msg.type === "translateNow") {
log("手動翻譯:按下「翻譯這一頁」");
translateActivePage({ force: true });
}
if (msg.type === "captureNow") savePageData(port);
});
});
// Not an async listener: Chrome takes a listener's returned promise as its
// reply, so an async one answered every message, devCapture's included, with
// undefined before the right listener could.
chrome.runtime.onMessage.addListener((msg, sender) => {
if (msg.type === "pageShown") onPageShown(msg, sender);
if (msg.type === "pageLog") onPageLog(msg, sender);
});
// The reader shows another screen (or one couldn't be identified).
async function onPageShown(msg, sender) {
const tab = sender.tab;
if (!tab?.active) return;
clearTimeout(settleTimer);
clearTimeout(prefetchTimer);
// The page cleared its overlay: it belonged to the screen that's gone.
await setDrawn(null);
if (msg.error) {
await setShown(null);
if (!(await panelOpen())) return;
logTabId = tab.id;
log(`無法辨識目前這一頁:${msg.error}`);
broadcast({ type: "warn", text: msg.error });
return;
}
const page = { ...msg.page, tabId: tab.id, windowId: tab.windowId };
await setShown(page);
// Only translate when the panel is open, so we don't spend tokens silently.
if (!(await panelOpen())) return;
logTabId = tab.id;
const how = msg.tried ? `(比對 ${msg.tried} 個畫面,${msg.ms ?? "?"} 毫秒)` : "";
if (msg.highlights) log(`螢光標記改變了(${describeScreen(page)},${page.highlights?.length ?? 0} 個)`);
else log(`畫面換到${describeScreen(page)}${how}`);
if (current && !sameScreen(current.page, page)) detach(current);
const settings = await getSettings();
if (await drawFromCache(page, settings)) return;
if (!settings.autoTranslate) return;
if (current) return; // already translating this very screen
settleTimer = setTimeout(async () => {
if (sameScreen(await getShown(), page)) translateActivePage({ force: false });
}, SETTLE_MS);
}
function onPageLog(msg, sender) {
if (!sender.tab?.active) return;
panelOpen().then((open) => open && log(msg.text));
}
// Whether a side panel is open. Not panelPorts: Chrome stops this worker
// after 30 s idle, and the message that wakes it arrives before the panel
// has reconnected, so a page turn after a pause would be dropped.
async function panelOpen() {
if (panelPorts.size) return true;
return (await chrome.runtime.getContexts({ contextTypes: ["SIDE_PANEL"] })).length > 0;
}
chrome.commands.onCommand.addListener(async (cmd) => {
if (cmd === "toggle-overlay") {
const { overlay } = await chrome.storage.sync.get({ overlay: DEFAULTS.overlay });
await chrome.storage.sync.set({ overlay: !overlay }); // the page and side panel react to the change
return;
}
if (cmd !== "translate-page") return;
log("手動翻譯:Alt+T");
translateActivePage({ force: true });
});
// Translation / original switch (side panel or the button on the page). The
// page hides and shows its overlay itself; a translation made while it was
// off was never drawn, so draw it from the cache when it comes back on.
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "sync" && changes.overlay?.newValue) redrawShown();
});
async function redrawShown() {
const shown = await getShown();
if (!shown || current) return;
await drawFromCache(shown, await getSettings(), { post: false });
}
// Step-by-step trace shown at the bottom of the side panel. `image` (a data
// URL) is shown as a thumbnail under the line.
function log(text, image) {
broadcast({ type: "log", text, at: Date.now(), image });
}
// Messages sent while the panel is reconnecting (the worker just woke up)
// are kept and delivered when it's back, so the log has no holes.
const unsent = [];
// The log also goes to the reader tab's console ("[Kindle 翻譯]"), so it can
// be read alongside the page's own state when debugging.
let logTabId = null;
function broadcast(msg) {
if (msg.type === "log" && logTabId !== null) {
chrome.tabs.sendMessage(logTabId, { type: "debugLog", text: `${new Date(msg.at).toTimeString().slice(0, 8)}.${String(msg.at % 1000).padStart(3, "0")} ${msg.text}` }, { frameId: 0 }).catch(() => {});
}
if (!panelPorts.size && msg.type !== "pageState") {
unsent.push(msg);
if (unsent.length > 100) unsent.shift();
return;
}
for (const p of panelPorts) {
try {
p.postMessage(msg);
} catch (_) {}
}
}
async function getSettings() {
return { ...DEFAULTS, ...(await chrome.storage.sync.get(Object.keys(DEFAULTS))) };
}
// The active tab if it's a Kindle reader, else null.
async function readerTab() {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
return tab && READER_RE.test(tab.url || "") ? tab : null;
}
// Development aid: the shown screen's page data, as content.js keeps it
// (with the glyphs it uses), to debug or build tests with on this computer.
// 存下頁面資料 in the side panel: the panel saves the file.
async function savePageData(port) {
const tab = await readerTab();
if (!tab) {
broadcast({ type: "error", text: "目前分頁不是 Kindle Cloud Reader。" });
return;
}
let dump;
try {
dump = await sendToPage(tab.id, { type: "dumpPage" });
} catch (err) {
dump = { error: err.message };
}
if (!dump || dump.error) {
broadcast({ type: "error", text: `存不了頁面資料:${dump?.error || "頁面沒有回應"}` });
return;
}
const json = JSON.stringify(dump.data);
log(`已存下頁面資料:${dump.filename}(${Math.round(json.length / 1024)} KB)`);
try {
port.postMessage({ type: "savePage", filename: dump.filename, json });
} catch (_) {} // the panel closed meanwhile
}
// The same, asked for by a test tool driving the reader page (content.js
// relays it), sent straight to a receiver on this computer
// (tests/tools/receive-pages.js) instead of the downloads folder. Off unless
// the options page's developer switch is on; the page only learns whether it
// worked, never the data.
const DEV_RECEIVER = "http://127.0.0.1:8765/page";
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type !== "devCapture") return;
devCapture(sender.tab, msg.name).then(sendResponse, (err) => sendResponse({ ok: false, error: String(err?.message || err) }));
return true; // replies asynchronously
});
async function devCapture(tab, name) {
const { devCapture: enabled } = await chrome.storage.local.get({ devCapture: false });
if (!enabled) return { ok: false, error: "開發者開關沒有開啟(設定頁)" };
if (!tab?.active || !READER_RE.test(tab.url || "")) return { ok: false, error: "只能存目前顯示的 Kindle 分頁" };
const dump = await sendToPage(tab.id, { type: "dumpPage" });
if (!dump || dump.error) return { ok: false, error: dump?.error || "頁面沒有回應" };
const safe = typeof name === "string" && /^[a-z0-9][a-z0-9-]{0,80}$/.test(name) ? name : undefined;
const filename = safe ? `${safe}.json` : dump.filename;
const res = await fetch(DEV_RECEIVER, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ filename, data: dump.data }),
});
if (!res.ok) return { ok: false, error: `接收程式回應 HTTP ${res.status}` };
return { ok: true, filename };
}
// ---- Screenshots (vision engine only) ----
// Chrome allows only 2 captureVisibleTab calls per second
// (MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND) and throws past that, so every
// capture goes through this queue and is spaced out.
const CAPTURE_GAP_MS = 600;
let captureChain = Promise.resolve();
let lastCaptureAt = 0;
function capture(windowId) {
const run = captureChain.then(async () => {
const wait = lastCaptureAt + CAPTURE_GAP_MS - Date.now();
if (wait > 0) await new Promise((r) => setTimeout(r, wait));
try {
return await chrome.tabs.captureVisibleTab(windowId, { format: "jpeg", quality: 85 });
} finally {
lastCaptureAt = Date.now();
}
});
captureChain = run.catch(() => {});
return run;
}
// ---- Jobs ----
// Translate the screen on show. `force` (the button, Alt+T): on a screen
// whose translation is already drawn, ask Claude again instead of using the
// cache; and cancel a request already running for it.
async function translateActivePage({ force = false } = {}) {
const tab = await readerTab();
if (!tab) {
broadcast({ type: "error", text: "目前分頁不是 Kindle Cloud Reader。" });
return;
}
logTabId = tab.id;
const settings = await getSettings();
if (!settings.apiKey) {
broadcast({ type: "error", text: "請先到設定頁填入 Anthropic API key。", needsKey: true });
return;
}
let res;
try {
res = await sendToPage(tab.id, { type: "currentPage" });
} catch (err) {
res = { error: err.message };
}
if (!res?.page) {
const why = res?.error || "頁面沒有回應";
log(`無法辨識目前這一頁:${why}`);
broadcast({ type: "error", text: `無法辨識目前這一頁:${why}` });
return;
}
const page = { ...res.page, tabId: tab.id, windowId: tab.windowId };
await setShown(page);
const retranslate = force && (await getDrawn()) === screenId(page);
if (retranslate) log(`重新翻譯本頁(${describeScreen(page)}),不使用快取`);
else if (await drawFromCache(page, settings)) return;
if (current) {
if (sameScreen(current.page, page)) {
// Already on it: wait for it rather than pay twice, then see whether
// anything is still missing (a highlight added meanwhile). Only a
// retranslate (pressed again on a screen just redone) cancels it and
// starts over; tokens it already used are still billed.
if (!retranslate) {
await current.done;
if (current || ((await getDrawn()) === screenId(page) && (await screenDone(page)))) return;
return translateActivePage({ force: false });
}
log("手動翻譯:取消進行中的請求,改翻目前畫面");
current.controller.abort();
current = null;
} else {
detach(current);
}
}
const job = startJob("page", page, { force: retranslate, settings });
await job.done;
}
function startJob(kind, page, { force = false, settings }) {
const job = { kind, page, force, controller: new AbortController(), detached: false };
job.done = new Promise((resolve) => (job.finish = resolve));
if (kind === "page") current = job;
else prefetching = job;
// Calling an extension API resets the service worker's 30 s idle timer;
// reading a response stream alone doesn't.
const keepAlive = setInterval(() => chrome.runtime.getPlatformInfo(), 20_000);
(async () => {
try {
await runJob(job, settings);
} catch (err) {
const what = job.kind === "prefetch" ? "預讀" : job.detached ? "背景翻譯" : null;
if (err.name === "AbortError") log(what ? `已取消${what}(${describeScreen(job.page)})` : "已取消前一個請求");
else if (what) log(`${what}失敗:${err.message || err}`);
else {
broadcast({ type: "error", text: String(err.message || err) });
log(`失敗:${err.message || err}`);
}
} finally {
clearInterval(keepAlive);
background.delete(job);
if (prefetching === job) prefetching = null;
if (current === job) {
current = null;
// Lets the side panel stop its "translating… N s" timer even when this
// run ended without a result (cancelled, failed).
if (!job.drew) broadcast({ type: "idle" });
}
job.finish();
}
})();
return job;
}
// The reader moved on while `job` translated: let it finish in the
// background, caching what it gets, and free the foreground.
function detach(job) {
if (current === job) current = null;
job.detached = true;
background.add(job);
log(`畫面已換頁:先前那一頁(${describeScreen(job.page)})改在背景翻完並存快取`);
broadcast({ type: "idle" });
if (background.size > MAX_BACKGROUND) {
const oldest = [...background][0];
background.delete(oldest);
oldest.controller.abort();
log(oldest === job ? "背景翻譯已達上限,取消剛翻走的那一頁" : "背景翻譯已達上限,取消最早的一個");
}
}
async function runJob(job, settings) {
if (settings.engine === "vision") return runVision(job, settings);
const started = Date.now();
if (job.kind === "page") broadcast({ type: "working" });
const record = await screenRecord(job);
if (!record.paras.some(hasText)) {
log(`這一頁沒有文字(${describeScreen(job.page)}),不用翻譯`);
if (job.kind === "page" && !job.detached) schedulePrefetch(job.page);
return;
}
const out = await translateRecord(job, record, settings);
const what = job.kind === "prefetch" ? "預讀完成" : job.detached ? "背景翻完先前那一頁" : "翻譯完成";
log(`${what}:${describeScreen(job.page)},${out.sent} 段送出、${out.reused} 段沿用快取或其他請求,從開始共 ${seconds(started)} 秒${out.summary ? "(只拿到摘要,不存快取)" : ""}`);
if (out.notes) log(`Claude 的說明:${out.notes}`);
if (job.kind !== "page" || job.detached) return;
// Drawn only if the reader still shows it; the page checks that again.
if (!sameScreen(await getShown(), job.page)) {
log("翻譯期間畫面已換頁,這份譯文不畫上去(已存快取)");
return;
}
job.drew = true;
await draw(job.page, record, (p) => out.texts.get(paraSource(job.page, p).key), { fallbackModel: out.fallbackModel, summary: out.summary });
// After the result, which clears the status line.
if (out.summary) broadcast({ type: "warn", text: "Claude 只給了摘要,不是完整翻譯。可以按「重新翻譯本頁」再試。" });
}
// How `job.page` splits into paragraphs, with each one's OCR text: from the
// cache, from another job reading it right now, or read here.
async function screenRecord(job) {
const key = recordKey(job.page);
const cached = (await chrome.storage.session.get(key))[key];
if (cached) return cached;
if (reading.has(key)) {
log("這一頁正由其他請求辨識,等它完成");
const r = await reading.get(key);
if (r) return r;
}
let done;
reading.set(key, new Promise((r) => (done = r)));
try {
const record = await readScreen(job);
await cacheWrite({ [key]: record });
done(record);
return record;
} catch (err) {
done(null);
throw err;
} finally {
reading.delete(key);
}
}
// Ask the page for the screen's paragraphs and a drawing of it, and OCR it.
async function readScreen(job) {
const { page } = job;
const data = await sendToPage(page.tabId, { type: "pageData", key: page.key, start: page.start, image: true });
if (!data || data.error) throw new Error(`拿不到這一頁的頁面資料:${data?.error || "頁面沒有回應"}`);
job.controller.signal.throwIfAborted();
const record = { size: { width: data.page.width, height: data.page.height }, bg: data.page.fill, paras: [] };
if (!data.paragraphs.length) return record;
const started = Date.now();
const { scale } = data;
log(`OCR 辨識中(${data.paragraphs.length} 段,${data.columns.length} 欄)…`);
await ensureOffscreen();
const res = await chrome.runtime.sendMessage({
target: "offscreen",
type: "ocr",
image: data.image,
rects: data.columns.map(([x0, x1]) => ({
left: Math.round(x0 * scale),
top: 0,
width: Math.round((x1 - x0) * scale),
height: Math.round(data.page.height * scale),
})),
});
if (!res || res.error) throw new Error(`OCR 失敗:${res?.error || "offscreen 文件沒有回應"}`);
job.controller.signal.throwIfAborted();
// A tenth of a pixel is plenty, and keeps the cached screen small.
const px = (v) => Math.round((v / scale) * 10) / 10;
const toPage = (b) => ({ x0: px(b.x0), y0: px(b.y0), x1: px(b.x1), y1: px(b.y1) });
const lines = res.columns.flat().map((l) => ({ ...l, ...toPage(l), words: (l.words || []).map((w) => ({ ...w, ...toPage(w) })) }));
const words = assignWords(lines, data.paragraphs);
record.paras = data.paragraphs.map((p, i) => ({ start: p.start, end: p.end, kind: p.kind, column: p.column, boxes: p.boxes, fg: p.fg, words: words[i] }));
const empty = words.filter((w) => !w.length).length;
log(`OCR 完成:${seconds(started)} 秒,${lines.length} 行${empty ? `,${empty} 段沒有讀到字` : ""}`);
const read = words.filter((w) => w.length).map(wordsText);
if (read.length) log(`OCR 文字:${read.join(" ¶ ").slice(0, 400)}`);
return record;
}
// Translations for the record's paragraphs: cached ones (unless forced),
// ones another job is requesting (waited for), and the rest requested here.
// Resolves to { texts (paragraph key → text), sent, reused, notes,
// fallbackModel, summary }.
async function translateRecord(job, record, settings) {
const { page } = job;
const want = record.paras.filter(hasText).map((p) => ({ ...paraSource(page, p), column: p.column }));
const keyOf = (p) => p.key;
const texts = new Map();
if (!job.force) {
const have = await cacheRead(want.map(keyOf));
for (const p of want) if (have[keyOf(p)]) texts.set(keyOf(p), have[keyOf(p)].text);
}
let pending = want.filter((p) => !texts.has(keyOf(p)));
const out = { texts, sent: 0, reused: texts.size, notes: "", fallbackModel: null, summary: false };
if (texts.size) log(`${texts.size} 段已在快取,${pending.length} 段要翻譯`);
for (let round = 0; pending.length; round++) {
// Someone else paying for a paragraph: wait for theirs (first round only).
const waits = round === 0 && !job.force ? pending.filter((p) => inflight.has(keyOf(p))) : [];
const waited = waits.map((p) => inflight.get(keyOf(p)));
const send = pending.filter((p) => !waits.includes(p));
if (waits.length) log(`${waits.length} 段正由其他請求翻譯,等它們完成`);
const own = new Map(send.map((p) => [keyOf(p), deferred()]));
for (const [k, d] of own) inflight.set(k, d.promise);
let got = null;
try {
if (send.length) {
got = await requestTranslations(settings, send, job.controller.signal, page);
out.sent += send.length;
out.notes = [out.notes, got.notes].filter(Boolean).join(" ");
out.fallbackModel ??= got.fallbackModel;
out.summary ||= got.summary;
const items = {};
send.forEach((p, i) => {
// Blank too: what Claude takes for noise stays blank, rather than
// being asked for again every time the screen comes back.
const text = got.texts[i] || "";
texts.set(keyOf(p), text);
items[keyOf(p)] = { source: p.source, text, savedAt: Date.now() };
});
// A summary isn't cached, so the screen is asked for again next time.
if (!got.summary && Object.keys(items).length) await cacheWrite(items);
}
} finally {
for (const [k, d] of own) {
d.resolve(texts.has(k) ? texts.get(k) : null);
if (inflight.get(k) === d.promise) inflight.delete(k);
}
}
const results = await Promise.all(waited);
waits.forEach((p, i) => results[i] !== null && texts.set(keyOf(p), results[i]));
out.reused += results.filter((r) => r !== null).length;
// Only what the other job failed to get goes round again.
pending = waits.filter((p, i) => results[i] === null);
if (round >= 1) break;
}
return out;
}
// Translate paragraphs ({ source, column }) of the screen `page` with the
// configured quality level, retrying a summary. Resolves to { texts (by
// index), notes, fallbackModel, summary }. A translation whose style marks
// don't hold up (unpaired, crossed, or not in its source) keeps its words
// without them.
async function requestTranslations(settings, paras, jobSignal, page) {
const plan = qualityOf(settings);
const items = paras.map((p, id) => ({ id, text: p.source }));
const chunks = splitParas(items, paras);
const names = await bookNames(settings, page, items.map((p) => p.text));
if (names.length) log(`人名對照表:這一頁用到 ${names.length} 個(${names.map((n) => `${n.source} → ${n.text}`).join("、")})`);
let out;
for (let attempt = 0; ; attempt++) {
// Output speed is the bottleneck, so translate the chunks side by side.
const failed = new AbortController(); // one chunk failing stops the others
const signal = AbortSignal.any([jobSignal, failed.signal]);
let outs;
try {
// Drafts side by side, then one review of the whole screen: it only
// outputs what it changes, so splitting it would save little time.
const drafts = await Promise.all(chunks.map((chunk, i) => translateChunk(settings, chunk, chunks.length > 1 ? `[${i + 1}/${chunks.length}] ` : "", signal, names)));
outs = plan.review ? await reviewDrafts(settings, plan.review, chunks, drafts, signal, page, names) : drafts;
} catch (err) {
failed.abort(); // don't leave the other calls running
throw err;
}
const byId = new Map(outs.flatMap((o) => o.translations || []).map((t) => [t.id, (t.text || "").trim()]));
out = {
texts: items.map((p) => byId.get(p.id) || ""),
notes: outs.map((o) => (o.notes || "").trim()).filter(Boolean).join(" "),
summarized: outs.some((o) => o.summarized === true),
model: outs.find((o) => o.model !== plan.translate)?.model ?? outs[0].model, // shows when Opus stepped in
names: outs.find((o) => o.names)?.names,
};
if (!isSummary(out)) break;
if (attempt >= SUMMARY_RETRIES) {
log(`重試後仍然只給摘要,先顯示摘要(不存快取):${out.notes || "沒有說明"}`);
break;
}
log(`Claude 這次只給摘要,不是翻譯(${out.notes || "沒有說明"}),自動重新請求`);
}
// A summary isn't kept, its names included.
if (out.names && !isSummary(out)) await saveNames(page, out.names, "").catch((err) => log(`人名對照表沒有存下來:${err.message || err}`));
const texts = out.texts.map((text, i) => {
const checked = checkMarks(text, items[i].text);
if (!checked.ok) log(`第 ${i + 1} 段譯文的樣式標記不完整,改用不帶樣式的譯文`);
return checked.text;
});
return { texts, notes: out.notes, fallbackModel: out.model !== plan.translate ? out.model : null, summary: isSummary(out) };
}
function deferred() {
let resolve;
const promise = new Promise((r) => (resolve = r));
return { promise, resolve };
}
// Draw a screen's translation on the page and post it to the side panel.
// `textOf(para)` gives each record paragraph's translation (or nothing).
async function draw(page, record, textOf, { cached = false, post = true, fallbackModel = null, summary = false } = {}) {
// Several screens can be shown in quick succession, each handled while the
// last is still being looked up; only the one on screen now is drawn.
if (!sameScreen(await getShown(), page)) return;
const settings = await getSettings();
const blocks = record.paras
.map((p) => ({ kind: p.kind, text: textOf(p) || "", boxes: p.boxes, fg: p.fg, marks: p.words ? paraSource(page, p).marks : {} }))
.filter((b) => stripMarks(b.text).trim());
if (post) broadcast({ type: "result", text: blocksToText(blocks), cached, fallbackModel, summary });
if (!blocks.length) {
broadcast({ type: "warn", text: "這一頁沒有可以畫的譯文。" });
return;
}
if (settings.overlay) await showOnPage(page, record, blocks);