Browser translation tools generally fall into two camps: full-page replacement, which hides the original wording when a term looks off, and interleaved bilingual injection, which doubles paragraph height and pushes complex layouts out of alignment. When reading documentation, research blogs, or technical discussions, neither feels right. You want the original page untouched on one side, a clean translation on the other, and both scrolling together so your eye lands on the exact same paragraph when you glance across.

Duet-Translator is a zero-build, plain JavaScript Manifest V3 extension for Edge and Chrome built around that layout. Both panes load the real web page side by side, scroll in paragraph-level sync, translate only what is near your viewport, cache aggressively in IndexedDB and against LLM prefix caches, and work with any engine you supply—from self-hosted vLLM, SGLang, and Ollama endpoints to DeepSeek, MiniMax, OpenRouter, or DeepL.

Duet-Translator side-by-side split view on English Wikipedia Typography article: original English on the left, Chinese translation by DeepSeek V4.1 Flash on the right, with the hovered paragraph highlighted in blue and amber across both panes.
Fig. 1. Duet-Translator reading the English Wikipedia article "Typography" side by side. The top Shadow DOM bar shows translation progress, token/cost meter, sync toggle, hover highlight, and engine selector; hovering a paragraph highlights its counterpart on the opposite side.

Why Two Same-Origin Iframes

The first architectural decision is how to put two copies of a live web page in one tab. Several tempting shortcuts break on modern sites:

ApproachTrade-off
Clone DOM for the right paneCSS-in-JS styles injected via insertRule live outside DOM attributes; lazy images and JS interactions break
Reader mode extractionStrips the site's typography, navigation, tables, and visual context
Two browser windowsSeparate tabs and histories; awkward to resize and keep synchronized
Two iframes inside an extension pageCross-origin: X-Frame-Options: SAMEORIGIN blocks loading, cookies become third-party, and the address bar shows chrome-extension://
Top-level same-origin dual iframes (chosen)First-party cookies and SAMEORIGIN work natively, the URL bar stays unchanged, and each pane renders at a true half-width viewport

When you toggle split view in Duet-Translator, shell.js covers the active tab with a full-screen overlay and mounts two iframes pointing to the current URL. Both iframes inherit the site's origin and login session, and responsive layouts naturally adapt to half the window width without horizontal overflow.

Two safeguards make this work on strict sites. For domains returning X-Frame-Options: DENY or CSP frame-ancestors 'none' (such as GitHub repositories), the background Service Worker installs a temporary per-tab declarativeNetRequest session rule that strips only those framing response headers for subframes of that single tab, and removes the rule as soon as split view or the tab closes. Both iframes also carry sandbox without allow-top-navigation so frame-busting scripts cannot redirect the outer tab. Users who prefer strict CSP preservation can disable the header rule in settings.

Duet-Translator architecture diagram: top-level Active Tab runs shell.js coordinating left and right same-origin iframes via token-verified postMessage, while background Service Worker sw.js manages DNR rules, two-tier cache.js, demand scheduler, and providers.js.
Fig. 2. Extension architecture. shell.js coordinates scroll synchronization and navigation inside the active tab; pane.js and segment.js run inside each iframe; sw.js handles DNR rules, two-tier caching, batch scheduling, streaming SSE parsing, and engine adapters. Open full size

Paragraph-Aligned Scroll Synchronization

A naive scrollTop ratio fails almost immediately when translating between languages: Chinese prose is typically much more compact vertically than English, while technical explanations or expanded footnotes can run longer. Even if both panes start together, they drift apart by half a screen mid-article.

Segmentation and Deterministic Keys

Both panes run identical segmentation code (shared/segment.js) that walks the DOM and classifies translation units into three kinds:

  • Block element nodes: block containers holding only inline content (p, li, h1–h6, td, or text-only divs).
  • Inline run slices: bare text runs sitting alongside sibling blocks inside mixed containers (such as Hacker News comments), measured via DOM Range without mutating nodes.
  • Non-translated mark anchors: height-matched structural landmarks (pre, video, canvas) that stay identical across panes.

Non-content nodes (script, style, code, pre, textarea, svg, [translate=no], .notranslate, contenteditable) are skipped. Each unit receives a deterministic key computed from its normalized source text plus occurrence index on the page:

key = hash(normalizedSourceText) + "." + occurrenceIndex

Because the right pane translates in place and stores unit state exclusively in a WeakMap rather than writing attributes onto page nodes, its unit keys stay identical to the original left pane after translation finishes.

Overlap Filtering, LIS, and the Sliding Focus Line

Each pane converts its unit bounding boxes into scroll-content coordinates {k, t, b, n} (top, bottom, and character count) and reports them to shell.js via token-verified postMessage. The pure coordination module (shared/sync-core.js) turns those pairs into bidirectional scroll maps through four steps:

  1. Pair top and bottom edges. Matching keys produce two anchor points, (tL, tR) and (bL, bR), so interpolation scales proportionally inside tall paragraphs—when a translated paragraph is twice as tall, scrolling halfway through the source lands halfway through the translation.
  2. Filter side-by-side elements. Normal body paragraphs do not overlap vertically; floats, image captions, infobox rows, table cells in the same row, and multi-column cards do. Their anchors would cut across body paragraphs and distort intra-paragraph interpolation. Keeping only the segment with the largest character count in each vertically overlapping group drops maximum sync error on English Wikipedia from 292 px to 0 px and on Chinese Wikipedia from 185 px to 0 px.
  3. Denoise with LIS. After sorting anchors by left coordinate, taking the longest strictly increasing subsequence (LIS) of right coordinates strips out-of-order noise from sticky headers or A/B-tested sidebars that load differently between frames.
  4. Map along a sliding focus line. Rather than aligning only the top edge of the viewport (which prevents both panes from reaching the bottom together), the focus line moves smoothly from viewport top at scroll start to viewport bottom at scroll end:
progress   r = t / (H - vh)
focusLine  p = t + r * vh          // top of viewport at top; bottom at bottom
mapped     q = map(p)              // piecewise-linear interpolation between anchors
target     t' = q * (H' - vh') / H'

Solving for t' guarantees that both panes hit top and bottom simultaneously while keeping the paragraph under your gaze aligned at every intermediate scroll position.

Scroll-Cause Classification and Oscillation Control

Because programmatic scrolling fires scroll events too, naive two-way listeners quickly ping-pong. Each pane classifies every scroll event in priority order before reporting:

  1. prog: matches the last target sent by shell.js—checked first so a recently active pane cannot echo back and steal leadership.
  2. user: wheel, keyboard, touch, or pointer input within 700 ms; takes control only if its input timestamp is newer than the current driver.
  3. layout: DOM resize or translation insertion within 700 ms; keeps the driver stationary while the follower re-snaps to alignment.
  4. other: structural jumps such as in-page hash navigation.

On documentation sites or SPAs where window itself does not scroll, pane.js selects the scrollable overflow-y: auto|scroll container holding the most translatable prose—breaking ties by viewport area so split Markdown-plus-preview editors track the preview pane rather than a larger code editor.

Preserving Formatting and Streaming Translations

Pages rely heavily on inline links, bold emphasis, inline code, and citation footnotes. Stripping them produces walls of plain text; asking an LLM to emit raw HTML invites broken tags and lost event handlers. Duet-Translator instead serializes inline DOM trees into compact numbered placeholders:

<p>See <a href="...">this reference</a> and the <code>&lt;p&gt;</code> element.</p>
  -> "See <g1>this reference</g1> and the <x2/> element."

<gN>...</gN> wraps translatable inline elements, and on write-back Duet-Translator reuses the original DOM node objects so SPA link handlers remain intact. Atomic nodes such as <code>, images, icons, and line breaks become <xN/> slots reinserted verbatim. Single-node wrappers like <li><a>Home</a></li> are peeled before sending to avoid unnecessary markup, and if a model scrambles placeholder nesting, the validator falls back cleanly to plain text plus trailing atomic nodes and refuses to persist the corrupted output in cache.

For OpenAI-compatible engines, requests stream a JSON string array over SSE. An incremental parser in sw.js strips reasoning <think>...</think> blocks and markdown code fences, tracks top-level commas to dispatch completed segments immediately via chrome.tabs.sendMessage, and also extracts partial unclosed JSON strings every 150 ms for intra-paragraph streaming previews. If a request is aborted or fails mid-stream, the pane reconstructs the original DOM from the serialized source so half-translated fragments are never left behind or re-sent as source text. If a batch still comes back with a mismatched length, the scheduler falls back to binary-splitting and eventually single-segment retries.

Disabling unnecessary chain-of-thought reasoning via extraBody makes a dramatic difference for interactive browsing. On the English Wikipedia Typography page (275 visible segments) with DeepSeek V4.1 Flash, disabling thinking ({"thinking":{"type":"disabled"}}) dropped single-paragraph latency from 5.1 s to 1.9 s and cut output tokens from 411 to 68 compared with reasoning_effort: low; on MiniMax M3.1 Flash, lowering reasoning effort cut latency from 9.1 s to 4.5 s and output tokens from 508 to 146.

Recursive Self-Improvement: Optimizing Cost and Latency in a Closed Loop

Early versions of Duet-Translator already translated only the visible viewport plus a 0.5-screen prefetch margin, waited 300 ms after scrolling stopped, and aborted off-screen requests—keeping real Wikipedia usage to roughly 11,600 characters across four stops out of 46,600 visible characters (~75% less text sent). Yet first-screen paint still took 5.7 s, revisiting a page took 1.6 s, and jumping rapidly between sections left the reader waiting 4–6 s. Rather than tweaking heuristics by intuition, I gave Claude Code a bounded autonomous Recursive Self-Improvement (RSI) loop (1–2 hours, backed by subagents) with one rule: build a measurement harness first, then iterate strictly via hypothesize → patch → benchmark → keep only measured wins.

Building a Reproducible LLM and Browser Harness

Before touching scheduling or caching code, the loop built test/bench/ so every candidate change ran in real headless Chromium against deterministic network and billing physics:

  • Simulated OpenAI-compatible LLM (llm-sim.mjs). Models DeepSeek V4 Flash latency (600 ms base TTFT plus 0.05 ms per uncached input token, 45 tok/s SSE streaming), 64-token prefix caching, and real billing ($0.14 / $0.0028 / $0.28 per 1M miss / prefix-hit / output tokens), including aborted-stream output token billing.
  • Playwright reading scenarios (bench.mjs & compare.mjs). Drives five realistic reading patterns against frozen extension/ snapshots via EXT_DIR: slow read (12 × 0.4-screen steps, 3.5 s dwell), revisit (warm profile reopened in a new tab), fast skim (flick to bottom, stop, flick back), forum thread (150 nested comments with heavy duplicate reply/share strings), and later jump reading (A → B → C rapid skips).
  • 120-day cache eviction replay (cache-policy.mjs). Simulates 25 sites × 40 shared navigation strings, 60 cross-site strings, 40 visits/day, 30% revisits, and periodic 6,000–15,000-segment whole-page flushes.

Alongside the harness, the scheduling and caching core was tightened into the live architecture:

  • Prefix-cache-friendly prompt layout: a fixed system prompt sits at message index 0 (with page title pushed to the tail) to maximize provider prefix-cache hits.
  • Runaway-loop guard: a max_tokens ceiling prevents infinite generation loops, persisting parameter fallbacks in chrome.storage.session across 30 s MV3 worker recycles.
  • Pre-flight batch sizing: optional per-engine contextTokens limits split batches before dispatch for smaller self-hosted models.
  • Two-tier local caching: a 4,000-entry memory LRU backed by a 64 MB / 90-day IndexedDB store keyed by SHA-1 namespaces.
  • Live telemetry: a green token/cost meter embedded directly in the top bar.

Six Rounds of Hypothesize, Measure, Keep, and Revert

Each round was diffed against the frozen baseline commit (10f056a). Regressions and dead ends were surfaced by the harness and reverted rather than papered over:

RoundHypothesis & ChangeMeasured Outcome & Verdict
R1Add two-tier LRU, scroll-time cache backfill, in-page dedup, in-flight coalescingSkim segs −40%, forum segs −14%; caught regression: forum 1st segment +23% (2.99 s → 3.69 s) from awaiting a 300-seg cache sweep upfront
R2Split cache lookup into near (≤120 segs) vs. wide (bg); visible-first wave; 2 s dwell prefetchBlocked sweep fixed; caught two flaws: greedy bin-packing pushed trailing visible blocks to wave 2, and dwell prefetch cost +10% with zero p90 gain
R3Balanced bin-packing + startup timer bug found in trace (lastScrollTs=0 vs. new iframe performance.now()=0 triggered 1.5 s fallback)Open 1st seg 2.49 s → 1.10 s; revisit 1.56 s → 0.15 s (0 req); caught single-slot prefetch queuing spiking slow-read p90 (1.17 s → 2.90 s)
R4Pipeline prefetch across free slots + revert dwell prefetchRestored slow-read wait and eliminated the +10% prefetch cost overhead
R5Sweep concurrency 4 / 6 / 8 under 1/50 prefix-cache billing6 cut skim wait −32% and forum 1st screen −45% at flat cost (8 added no gain); DeepSeek preset raised 4 → 6
AuditRe-audit original prompt before closing loopCaught new Array(n) sparse-hole bug (hit rate always read 100%) and missing memory-LRU writeback; added cache-policy.mjs and contextTokens pre-flight split (6 → 2+1+2+1)
R6Dogfooding surfaced slow A → B → C jumps; added jump scenario, 150 ms intra-paragraph previews, and pre-move preemptionPreemption alone failed (6.4 s: single-block calls were non-streaming); naive position preemption thrashed aborts 6 → 34 from layout wobble; pre-move rule held aborts to 17 and cut C wait 4.8 s → 1.57 s
Duet-Translator RSI latency chart: six horizontal grouped bar comparisons across Open page first segment, Open page first screen, Revisit warm cache, Fast skim stop wait p90, 150-comment Forum first screen, and Jump A-B-C mean wait.
Fig. 3. End-to-end latency progression from frozen baseline through Round 5 and Round 6 under simulated DeepSeek V4 Flash streaming and prefix-cache billing. Open full size

Before-and-After Results and Cache Eviction Study

Across the four core scenarios, Round 5 cut first-paragraph latency by 60% and revisit latency by 90% while edging total cost down by 2.7%. Because the baseline already restricted translation to the visible area, single-pass token cost was already near its floor—the biggest cost savings came from stripping duplicate segments, aborting scrolled-past requests, and capping runaway loops. Adding Round 6 streaming previews and jump preemption trades a modest +3.6% net cost over baseline (+6.5% over R5) for sub-second perceived responses when skimming or jumping:

ScenarioMetricBaselineAfter R5After R6 (Previews)
Open pageFirst segment / 1st screen2.49 s / 5.73 s0.98 s / 3.31 s0.78 s / 2.13 s (−69% / −63%)
Revisit page1st screen (warm cache)1.56 s0.15 s (0 req)0.15 s (−90%, 0 req)
Fast skimStop wait p90 / segs7.78 s (30 segs)4.20 s (20 segs)2.28 s (25 segs, −71%)
150-comment forumSegs sent / 1st screen110 / 8.04 s95 / 4.29 s96 / 3.27 s (−59%)
Slow readStep wait mean / p900.48 s / 1.17 s0.51 s / 1.48 s0 ms / 0 ms
Jump A → B → C (c=6)Mean wait / p904.78 s / 5.56 s (pre-R6)—1.57 s / 2.22 s (−67%)
4-scenario totalSimulated API cost$0.003644$0.003544 (−2.7%)$0.003776 (+3.6%)

Two caveats apply to these numbers: absolute timings come from the local llm-sim.mjs physics model (use test/e2e/live.mjs to check a live endpoint's exact TTFT and throughput), and Round 6's 0 ms slow-read wait reflects intra-paragraph streaming previews appearing immediately rather than waiting for full-paragraph completion.

In the 120-day eviction study (test/bench/cache-policy.mjs), switching from FIFO to LRU eliminated roughly three-quarters of avoidable misses under tight capacity, LFU performed worst by letting stale high-frequency entries cling forever, and adding a second chance (halving hits and advancing the timestamp for entries hit ≥2 times) protected shared navigation strings when a periodic whole-page translation flushed the cache:

Capacity & Workload (hit rate)FIFOLRULFULRU + 2nd Chance
10k entries, daily browsing94.3%98.5%90.9%98.5%
25k entries, daily browsing98.2%99.9%96.5%99.9%
10k entries, +6k whole-page flush / 10d91.0%94.8%90.6%96.3%
25k entries, +15k whole-page flush / 10d93.8%98.2%95.4%98.3%

Try It

There is no build step. Load the unpacked extension/ directory directly in Edge or Chrome:

git clone https://github.com/SuperFCR/Duet-Translator.git
  1. Open edge://extensions (or chrome://extensions) and enable Developer mode.
  2. Click Load unpacked and select the extension/ folder inside the cloned repository.
  3. In the welcome page or toolbar popup, pick an engine (DeepSeek V4.1 Flash, MiniMax M3.1 Flash, DeepL, or a self-hosted OpenAI-compatible server—for remote GPU boxes, forward with ssh -L 8000:localhost:8000 gpu-host and set base URL http://127.0.0.1:8000/v1), test the connection, and press Alt+Shift+Y (⌥⇧Y on macOS) on any page.

To run the unit, e2e, and simulated-LLM benchmark suites locally:

cd Duet-Translator/test
npm install
npx playwright install chromium
npm run test:unit
npm run test:e2e
node bench/bench.mjs

Citation

Cited as:

Feng, Chaoran. (Nov 2026). Duet-Translator: Side-by-Side Web Translation with Paragraph-Aligned Scrolling. Chaoran Feng's Blog. https://www.falcary.com/blogs/duet-translator/.

Or

@article{feng2026duettranslator,
  title   = "Duet-Translator: Side-by-Side Web Translation with Paragraph-Aligned Scrolling",
  author  = "Feng, Chaoran",
  journal = "falcary.com",
  year    = "2026",
  month   = "Nov",
  url     = "https://www.falcary.com/blogs/duet-translator/"
}

References

  1. Duet-Translator source repository, github.com/SuperFCR/Duet-Translator.
  2. Duet-Translator architecture and RSI benchmark log, docs/DESIGN.md and test/bench/README.md.
  3. Chrome Developers. chrome.declarativeNetRequest (Manifest V3).
  4. DeepSeek API Docs. Context Caching on Disk.
  5. DeepL API Docs. XML Handling in Translation Requests.