Running LibreOffice WASM Inside Electron — and Turning LLM Edits into Character-Level Word Tracked Changes

2026-12-05来源 dev.toEnglish

简体中文 · Repository · MCP Quickstart · Editor Primitives

When people build AI tools for legal or document-heavy work, the default architecture is a chat sidebar next to a Markdown editor, or a server-side script that rewrites .docx XML and hands back a download link.

Both break down the moment a real deal or dispute starts. Lawyers do not deliver Markdown; counterparties open the final file in Microsoft Word or WPS, expect intact numbering, tables, styles and margin redlines, and reject any edit they cannot inspect and accept or reject individually.

To make an IDE for .docx work, we embedded LibreOffice 24.2.8 compiled to WebAssembly (built on the Allotropia / zetaoffice distro/allotropia/zeta-24-2 branch) inside an Electron workbench and built a character-level redline engine and a local MCP server on top of it.

What follows is not a product brochure. It is a field report of the eight hardest engineering problems we hit in production — with the exact measurements, failure modes, and links to the code and regression tests in this repository.

1. The 40% CPU tax hidden inside Embind ASSERTIONS

Our first round of full-machine latency traces (frontend/tests/desktop-e2e/office-interaction-latency.mjs) showed the office worker burning CPU on seemingly trivial operations: reading UI state took 114 ms, writing a single spreadsheet cell took 127 ms, and saving a 3.3 MB .docx took 11.5 seconds.

The culprit was not LibreOffice's layout engine. The stock soffice.js glue had been built with Embind ASSERTIONS enabled. Every time a C++ smart pointer crossed into JavaScript, attachFinalizer constructed new Error(), called captureStackTrace, and materialized .stack purely so it could print a "leaked C++ instance" warning on GC.

In our worker traces, that stack-capture alone accounted for ~40% of worker CPU.

Stripping the stack-trace capture at asset-fetch time (while keeping the actual FinalizationRegistry cleanup intact, in desktop/scripts/lowa-js-patches.js) dropped real-engine timings immediately:

Operation (real LOWA engine, same fixture) Before After
get_ui_state 114 ms 28 ms
Read slide / page 110 ms 16 ms
Write Calc cell 127 ms 17 ms
First save of article.docx 11.5 s 3.6 s

Lesson: if you embed a large Emscripten/Embind module, profile the JS glue boundary before touching C++.

2. The 1 GB WASM heap ceiling and silent OOM freezes

During soak testing with a 150-page redlined contract, autosave leaked ~10 MB per cycle. After roughly 30 cycles, the WASM engine hit its 1 GB heap ceiling and aborted — leaving the <canvas> frozen on the last rendered frame so it looked editable while every subsequent save failed.

Tracing the leak uncovered three distinct layers:

  1. V8 GC laziness in a tiny worker heap. zetajs releases C++ UNO proxies through FinalizationRegistry, but the worker's JS heap is tiny compared to the linear WASM memory behind those proxies. V8 had no reason to run GC. We added explicit zetajs.release() calls on superseded paragraph index arrays once no UNO command is in flight.
  2. Thrashing indexes across revision views. Reading final text for the AI agent temporarily toggles the margin view and back; clearing the paragraph index on every toggle multiplied native allocations. We switched to view-keyed parked indexes (parkedParaIndexes) that stay valid as long as reviewRevision has not changed.
  3. Unreclaimable native LibreOffice memory. Even after releasing every JS proxy, iterating paragraphs via nextElement leaked ~0.9 KB per paragraph, and each load_document retained ~22 MB inside native LibreOffice state.

Because you cannot patch away every allocator edge inside a 20-million-line C++ office suite, we added a non-allocating high-watermark heap probe (get_engine_heap — crucially, never probing via malloc). After a clean save, when the user is idle and not in an IME composition, if heap usage crosses the threshold (recycleAt: 0.7), the host silently swaps in a fresh WASM engine instance and restores the exact cursor position via get_view_position / restore_view_position. (Covered by npm run test:lowa-heap-cycles and frontend/tests/desktop-e2e/engine-renew.mjs.)

3. Keeping cold starts fast without burning 4.5 GB of RAM

Booting a fresh LibreOffice WASM instance takes ~2.9–3.1 seconds. To keep document switching snappy, we originally kept a pre-warmed blank spare engine in a pool (librePool.js).

The problem showed up immediately on 8 GB and 16 GB laptops: each live LOWA instance carries roughly 1.3–1.6 GiB of working set. Keeping a warm spare beside a single open document pushed total Electron RSS to 4,466 MiB.

Two targeted fixes cut memory dramatically without ruining perceived speed:

  • Conditional spare policy: On machines with < 32 GiB RAM, we pre-warm a spare when zero documents are open (so the very first document opens hot), drop the blank spare once a single document is active, and only spin up a spare again when a second document is opened. On real Electron measurements (same file, same machine), total RSS with one open document dropped from 4,466 MiB → 3,046 MiB, and returning from two documents to one dropped from 4,146 MiB → 2,172 MiB. The trade-off is a single cold open (615 ms → 2,875 ms) only when opening a second simultaneous document.
  • Recycling QuickLook's borrowed engine: Spacebar slide previews used to discard their borrowed engine after closing, forcing a 3.1 s cold start when the user immediately opened a file. Now releaseLibreHiddenInstance(..., { recycle: true }) clears state with load_document({ blank: true }) (note: empty bytes do not clear the current document; an explicit blank reset is required) and returns the hot instance to the pool, keeping the subsequent document open at 0.43–0.47 s.

4. Dragging a window between a Retina display and a 1x monitor

Users dragging the desktop window from a 2x MacBook display onto a 1x external monitor saw the Word page suddenly zoom in, shift right, and clip the right margin permanently — resizing the window never fixed it.

The root cause was a subtle mismatch between Qt for WebAssembly and LibreOffice's layout engine: Qt re-read emscripten_get_device_pixel_ratio() on every relayout, while LibreOffice locked its layout scaling factor at engine startup. Once the two diverged, coordinates and rulers never agreed again.

The fix is five lines of inline JavaScript at the top of editor.html (before editor-main.js loads): pin window.devicePixelRatio to its startup value for the lifetime of that guest frame. (Regression-tested by simulating a 2 → 1 DPR switch over CDP across Writer, Calc and Impress in frontend/tests/desktop-e2e/resize-recenter.mjs.)

5. Why naive diffing breaks legal redlines (70% → 30% reads as 730%)

In Microsoft Word and LibreOffice Writer, calling range.setString(newText) with RecordChanges = true produces a brute-force whole-paragraph delete + whole-paragraph insert. If an AI assistant changes one date or cap inside a 600-character clause, lawyers refuse to review a wall of strikethrough text.

So our worker (frontend/src/zetaoffice/public/office_thread.js) computes minimal edits right next to the UNO engine — never in the backend or middle layer, where whitespace normalization would shift offsets:

  1. Myers O((N + M) · D) instead of LCS DP. Our first prototype used LCS dynamic programming with a 500×500 cell cap (250,000 ops), falling back to whole-block replacement above that limit. Legal clauses routinely exceed 600 characters, so changing one word at the start and one at the end collapsed the entire paragraph into a full rewrite. Myers scales with the edit distance D, so a two-word change in a 1,000-character clause still yields exactly two surgical hunks.
  2. Atomic numeric tokens. Character-level diffing turns 70% → 30% into delete "7", insert "3" followed by untouched 0%. In inline redline view, a human lawyer scans 730% — a dangerous visual bug in contracts. Our numericTokenEdits() pass expands any edit touching digits (Arabic, full-width, Chinese numerals, %, ‰, decimal/thousand separators) to the full numeric token, so 70% → 30% always renders as 70% 30%.
  3. Single-character coincidence coalescing. When two edit hunks are separated by a single accidentally shared character (common in Chinese with 的 or 方), we merge them into one readable replacement; gaps of two or more characters stay separate.
  4. Right-to-left application inside lockModel / unlockModel. Hunks are sorted descending by character offset and applied right-to-left inside a single lockModel / finally { unlockModel } barrier. Applying left-to-right would invalidate every subsequent offset; omitting lockModel forces a full relayout and JS Modify event on every hunk.

6. Anchors, not character offsets — and the w:date timezone trap

Early prototypes located edits by JS indexOf offsets into extracted plain text. That failed systematically: page breaks, hidden runs, table cells, and deleted redline text do not map 1:1 between plain text and UNO XTextRange.

Instead, AI WorkDeck enforces an anchor-first contract (docs/AI_EDITOR_PRIMITIVES.md):

  • find_text_locations returns opaque bookmark anchors (anchorId) with surrounding context (contextBefore / contextAfter).
  • Every read for the AI runs inside runAgentCommandInMarginView so deleted redline text is excluded from the active body stream (preventing the classic Tika bug where a tracked edit 7 → 15 extracts as "715 days" — we also wrote a dedicated OOXML pre-pass, DocxPendingRevisionText, for backend extraction).
  • Before replacing at an anchor, outsideAnchorEcho checks whether the model accidentally echoed surrounding unchanged text from the same paragraph inside newText (a common LLM failure that duplicates half a clause) and rejects the write cleanly before touching the document.

We also built a dedicated 8-document real-engine round-trip guard (npm run test:lowa-revision-roundtrip) that opens complex .docx fixtures, exports them, and compares every w:ins, w:del, move range, w:rPrChange, w:pPrChange, comment, and accept-all / reject-all plain text.

That guard caught two subtle OOXML pitfalls:

  • The w:date local-time convention: Despite ending with a literal Z, Microsoft Word writes w:date in the author's local wall-clock time (true UTC lives separately in Word 365's w16du:dateUtc, MS-DOCX §2.12.2.1). Converting w:date to UTC shifts timestamps by an entire timezone when opened in Word.
  • The 4,107-redline autosave cliff: Our move-range bookmark repair helper originally enumerated every redline on every save (2–7 ms per redline in WASM → 10 seconds wasted per autosave on a heavily negotiated agreement). Caching a monotonic (model, redlineCount, epoch) invariant cut save time on that document from 11.7 seconds down to ~1 second.

7. Letting Claude Code, Cursor, and Codex edit .docx safely over local MCP

Once you have a reliable native .docx redline engine on localhost, an obvious question follows: why force developers and power users to use only one built-in chat panel?

In v0.93, we exposed a loopback-only Model Context Protocol server (http://127.0.0.1:5269/mcp, plus a zero-dependency stdio bridge in tools/mcp-stdio-bridge/bridge.mjs for Claude Desktop and stdio-only clients).

The write tool is deliberately proposal-only:

propose_revision(fileId, baseVersion, edits: [{ find, replace, reason }]) 

Three design invariants make it safe for real work:

  1. Zero silent overwrites. propose_revision never mutates the .docx. It checks baseVersion against the file's current version and verifies upfront that every find matches exactly one location in sequential order; any missing or ambiguous match rejects the entire batch with a line-by-line diagnostic.
  2. Explicit human gate, then native redlines. Accepted proposals are applied all-or-nothing inside the editor as character-level w:ins / w:del tracked changes — so even after accepting a proposal, every individual change remains reviewable inside the document and in Microsoft Word.
  3. Client attribution and security boundaries. The bridge forwards clientInfo.name from MCP initialize so redlines are signed with the originating client (for example Claude Code · MCP) and counted as AI edits rather than a colleague's edits. The server enforces constant-time bearer verification (SHA-256 stored), refuses any request carrying an Origin header (blocking browser-based cross-origin attacks), caps payloads at 4 MB, and binds strictly to loopback.

8. Try it in 30 seconds or inspect the code

Everything described above is open source under AGPL-3.0-or-later:

  • Self-contained local demo (no account, no model key):
 docker run --rm -p 127.0.0.1:8080:8080 ghcr.io/ai-workdeck/aiworkdeck-demo:latest 

(Or build locally with docker compose -f demo/compose.yml up --build — walkthrough in docs/demo.md.)

  • Connect Claude Code / Cursor / Claude Desktop: docs/mcp-server.md
  • Key code pointers:
    • Worker redline diff & UNO primitives: frontend/src/zetaoffice/public/office_thread.js
    • Engine pool & heap recycling: frontend/src/composables/librePool.js
    • Embind patch: desktop/scripts/lowa-js-patches.js
    • Revision round-trip guard: frontend/tests/lowa-e2e/_revision-structure.mjs
    • Local MCP stdio bridge: tools/mcp-stdio-bridge/bridge.mjs

If you have wrestled with LibreOffice WASM, OOXML tracked changes, or agentic document editing, we would genuinely love to compare notes in Issues or Discussions.

原文:https://www.a8q9.cn/en/article/running-libreoffice-wasm-inside-electron-and-turning-llm-edits-into-character-le-c5cffd.html

相关文章