OpenFini

Docs / Concepts

concept / research

Concept: optimization and native engines

Status: concept / research, not a commitment. Written on 2026-12-05 together with studio-gap-analysis.md. It decides where heavy work should run (main thread, workers, WebAssembly, WebGPU, or native Rust in the desktop app), lists the hotspots found in the code, proposes a measurement harness with budgets, and orders the work into waves of about four parallel pull requests.

It builds on, and does not repeat:

  • performance.md: design rules, current measurements, the worker pool, size budgets.
  • roadmap-next-major.md item R5 (Pixel live filters off the main thread, lazy effects registry, i18n split, an optional Wasm path for blur, unsharp and bilateral). This document turns R5.5 into a general engine strategy and extends it to the other studios.
  • world-studio.md sections 4 and 17 (renderer backends, performance targets and memory limits for 3D). World keeps its own plan; this page only adds the shared parts.

Contents#

  1. Principles
  2. Where each kind of work runs
  3. Hotspots found in the code
  4. Engine architecture: one Rust core, two targets
  5. WebGPU compute
  6. Desktop-only native paths
  7. Memory and start-up
  8. Measurement harness and budgets
  9. Candidate libraries and licenses
  10. Risks
  11. Wave plan
  12. Open questions
  13. Sources

Principles#

  1. Measure, then move. performance.md already says "add a job to jobs.js only with a measurement". The same rule applies to every language boundary: a kernel moves to Wasm, WebGPU or Rust only with a benchmark that shows at least 3× on the reference machines and a size cost recorded in scripts/size-budget.json.
  2. The JavaScript implementation stays the reference. Every accelerated kernel has a golden test against the pure JS version (results equal, or within ±1 per 8-bit channel where floating-point order differs). Tests keep passing on machines without Rust, WebGPU or Wasm, and the PWA works everywhere.
  3. The PWA and the desktop app share one engine. Kernels are written once in Rust and compiled to WebAssembly so the browser, the PWA and the desktop WebView all get the speed. Native-only Rust is reserved for work that needs the file system, system codecs or more memory than a WebView allows.
  4. Never cross IPC per frame. Data that lives in the WebView and is touched every frame (viewport pixels, live filters, compositing) stays in the WebView: worker, Wasm or GPU. Tauri IPC is for file-bound and long-running jobs.
  5. Bounded and cancellable. Every off-thread job takes an AbortSignal, reports progress and has a memory ceiling, as the worker pool already does.
  6. Small by default. Wasm modules and GPU shaders are lazy chunks, outside the start-up budget, cached by the service worker on first use (as pdf.js is today).

Where each kind of work runs#

Kind of workFirst choiceSecondLast resortNever
Per-pixel adjustments on the viewport (levels, curves, HSL, color grade)WebGPU compute or fragment shaderWasm SIMD in a workerJS in a workerRust over IPC
Neighborhood filters (blur, unsharp, median, bilateral, guided filter)WebGPU compute (separable passes)Wasm SIMD in workers, tiledJS in workersRust over IPC
Whole-image operations (resize, rotate, warp, inpaint, trace)Wasm SIMD in workers, one tile per workerJS in workers—main thread
File parsing (PSD, TIFF, IDML, XLSX, PPTX, DOCX, Sketch, .fig)JS or Wasm in a worker, streaming—main thread for files under 1 MB—
Text shaping and line breakingWasm shaper (lazy) + JS line breaker, cached per runJS-only shaping for Latin——
Spreadsheet recalculationJS incremental on the main thread under a budget, worker aboveWasm engine only if JS misses the budget——
Video decode and encodeWebCodecs in a workerNative Rust encoder on the desktop (Linux, pro codecs)Seek-per-frame (today's fallback)—
RAW decodeRust → Wasm (pack)Native Rust on the desktop for very large files——
Mesh operations (World)JS kernel in workers (World plan)Rust → Wasm for proven hotspots; manifold Wasm for booleans—main thread
Hashing, compression, collecting media, thumbnails of foldersNative Rust on the desktopWasm or CompressionStream in a worker——

Hotspots found in the code#

Sizes from wc -l; times from performance.md where measured. "Unmeasured" rows are the first job of wave E0.

AreaCodeWhat is slow todayEvidenceTarget placement
Pixel live filters and adjustmentsengine/pixel/filters.js (315 lines), adjustments.js (1 177), fx-blur.js (494), blur.js (383), develop.js (670)Computed in JS on the viewport pixels on the main thread; 12 MP + HSL + live Gaussian blur = 133 ms per frame (45 ms as a half-resolution draft); Gaussian blur on 2 MP ≈ 110 ms; Develop ≈ 180 msperformance.md "Known limits" and "Pixel engine"Worker (R5.2) → Wasm SIMD (E2.1) → WebGPU (E3.1)
Pixel compositingengine/backends/canvas.js, engine/pixel/image.jsLayers are canvases; getImageData / putImageData gaps of ~115 ms on big resizes; 12 MP document holds 88 MB heapperformance.md worker pool tableTiled typed-array store (R13.2, E5.1); GPU display compositing (E3.2)
Content-aware fill / object eraserengine/pixel/inpaint.js (372)Falls back to a blurry fill above ~60 000 px because patch synthesis is too slow in JSknown-limits.md PixelWasm PatchMatch on a pyramid (E2.3, closes R20.1)
Resampling and warpsengine/pixel/transform.js, transform3d.jsLanczos 4000×3000 → 2000×1500 ≈ 480 ms per layer (already in a worker)performance.mdWasm SIMD resize (E2.2)
Selection tracing and masksengine/pixel/selection.js (1 189)Contour tracing on a 4000² disc ≈ 100 ms on the main threadperformance.mdWorker job first (E1.2), Wasm if still over budget
Text layoutengine/layout/text-layout.js (2 057), line-break.js, sfnt.js (937, kerning from kern/GPOS only)Unmeasured for long documents; no shaping engine yet; reflow of a long story is synchronousR9, R15 need itShaper in Wasm (E2.4), reflow per story with a dirty range, measured on a 300-page fixture (E0.4)
Spreadsheet recalculationoffice/sheet/formula.js (983), functions.js (873), model.js (829)Already incremental with a dependency index and post-order evaluation; unmeasured on 100k-formula sheets; full recalc on open runs on the main threadoffice-sheet.md "Formulas"Budgeted slices on the main thread, worker above a threshold (E1.3)
Office and image file parsingoffice/sheet/xlsx.js (864), office/slides/pptx.js, engine/office/docx.js, engine/formats/psd.js (1 262), idml.js, tiff.js; unzip in engine/office/zip.js with fflateUnzip on open stays on the main thread (~35 ms for an 11 MB document.json); PSD and Office parsing are synchronousperformance.md worker poolWorker parsing with transferable results (E1.2); DecompressionStream("deflate-raw") where available
Scene exportscene/export.js, decode.js, demux.js, mux.js, render.js, gl.jsWebCodecs path ~12× real time at 720p in Chromium; seek-per-frame fallback ~real time; MP4 export often unavailable on WebKitGTK; no files over 4 GBscene-studio.md Formats and LimitsEncoder and muxer in a worker; native encoder on the desktop (E4.1)
Vector booleansengine/vector/boolean.js (275) on vendored polygon-clippingFine for destructive operations; unmeasured against R8's live target (60 fps for 200-node shapes)R8.2 acceptanceBenchmark; Rust boolean crate in Wasm if JS misses the target (E2.1 follow-up)
Proto renderingengine/proto, app/src/protoHas its own perf harness (tests/proto/perf, scripts/proto-perf.mjs)Proto concept §4.3Keep; fold into the shared harness (E0.1)
World mesh kernelengine/world/mesh (planned, JS)Targets in world-studio.md 17.1 (100k-vertex edits < 50 ms, subdivision level 2 of 10k quads < 100 ms)World planMeasure in World's tasks; Rust → Wasm only for misses (E5.3)
Start-upscripts/size-budget.json (start-up 354 KiB budget, 343.6 KiB measured)Close to the cap; the pixel effects registry (~41 KiB) and all locales load at startknown-limits.md, refactoring-audit.mdR5.3, R5.4 (E1.4)

Engine architecture: one Rust core, two targets#

engines/                      new Cargo workspace (outside src-tauri, so the app builds without it)
  crates/
    of-kernels/               pixel kernels: blur, unsharp, bilateral, median, color conversions, LUTs
    of-resample/              resize, rotate, warp (Lanczos, bicubic), homography
    of-inpaint/               PatchMatch on a pyramid, membrane blend
    of-shape/                 text shaping wrapper (decision in E2.4)
    of-raw/                   DNG decoder and demosaic (E4.2)
    of-codec/                 native-only: encode and mux (E4.1)
  wasm/                       thin wasm-bindgen (or plain extern "C") wrappers, one module per crate
app/vendor/engines/           built .wasm files, committed with SHA-256 sums, listed in THIRD_PARTY_NOTICES.md
app/src/engine/native/        JS loader: capability probe, instantiate per worker, fallbacks, golden-test hooks
src-tauri/                    links of-raw and of-codec natively for the desktop-only paths
  • Build. npm run engines:build runs cargo build --target wasm32-unknown-unknown --release with -C target-feature=+simd128, then wasm-opt -Oz. CI rebuilds on every change under engines/ and fails when the committed artifact's hash differs, so contributors without Rust never need to build it and reviewers see a reproducible binary.
  • Threads. WebAssembly threads need SharedArrayBuffer, which needs a cross-origin-isolated page (COOP + COEP). OpenFini is not isolated, and turning it on would break cross-origin images, the Code studio preview, Figma plugin frames and embeds. So: single-threaded Wasm instances, one per pool worker, with parallelism through tiles (the pattern the worker pool already uses). The desktop app could later isolate its own origin through Tauri's custom protocol headers; that is an open question, not a dependency.
  • Memory. Each instance gets a growable linear memory capped per job (for example 512 MiB); tiles are copied in and out with transferable ArrayBuffers; no long-lived pixel data lives inside Wasm memory.
  • API shape. engine/native/kernels.js exposes the same function signatures as the JS modules (gaussianBlurImage(src, sigma)), so callers do not change; a capability probe picks WebGPU, Wasm or JS once per session and the Doctor report records the choice.
  • Testing. Golden tests run every kernel through JS and Wasm in Node (Node runs Wasm SIMD) with random and fixture images; property tests check alpha handling, edges and odd sizes.

WebGPU compute#

WebGPU is available in Chromium and WebView2 (Windows desktop app), Safari 26 and WKWebView on macOS 26 and iOS 26, and Firefox on Windows since 141. It is not available in WebKitGTK, so the Linux desktop app and older macOS always use the Wasm path. World already plans a WebGPU backend with device-loss handling (world-studio.md 4.2); the 2D studios should share its device probe and GPU memory meter rather than create a second one.

  • Scope. Per-pixel adjustments, separable convolutions and the live filter stack of the viewport (about 1–4 MP), with the result drawn straight to a canvas. Export, history and saved pixels keep using the CPU path, which stays the reference (the "two compositors tested against each other" idea also used by PhotoCraft).
  • Precision. Compute in f16/f32 textures; parity tests compare GPU and CPU output within a tolerance on SwiftShader in CI and on real GPUs by hand.
  • Scene. Scene's effects run on WebGL 2 today (scene/gl.js, with a CPU fallback). Moving them to WebGPU is not a goal by itself; only LUTs and scopes (SC-5) are new GPU work.

Desktop-only native paths#

Tauri commands are a good fit for file-bound work; a per-frame pixel exchange is not. Tauri 2 can return binary data without JSON (tauri::ipc::Response) and stream it through Channel, but every call is still a serialized message through the WebView's fetch path, so the cost per call must be measured (E0.3) before any design depends on it. OpenFini already streams with a Channel in src-tauri/src/ollama.rs.

PathWhy nativeShape
Video encode on Linux and pro formats (E4.1)WebKitGTK often lacks encoders; no ProRes; MP4 over 4 GBFrames rendered in the WebView, converted to YUV 4:2:0 in Wasm (about 3 MB per 1080p frame instead of 8 MB RGBA), streamed to Rust; Rust muxes and hands off to an encoder. Default encoder: a user-installed ffmpeg found on the PATH (ADR 0029 desktop path), run as a separate process, never bundled (license and patent reasons). Optional bundled encoders only with royalty-free codecs (AV1 via rav1e, VP9) after a license review
RAW decode of large files (E4.2)50–100 MB files, memory-heavy demosaicSame crate as the Wasm pack, native for speed and memory on the desktop
Large-file IO (E4.3)PSB over 2 GB, hashing referenced media, collecting projectsStreaming readers in Rust returning tiles or metadata, not whole files
Proxy generation (SC-6)Long camera filesBackground job through the same encoder path

Security: every new command validates sizes and paths through fileaccess.rs, parsers are fuzzed (cargo fuzz) before they ship, and native parsers run in a short-lived worker thread with a memory cap.

Memory and start-up#

  • Pixel layers as tiles. The tiled store of R13.2 (256×256 tiles of typed arrays, canvas only as a display cache) is the base for 16-bit, smart objects and lower peaks. Add cold-tile compression (LZ4 in Wasm) for tiles not touched for 30 s and an LRU over decompressed tiles; history already stores dirty rectangles.
  • Memory meter. One shared meter for CPU tiles, GPU textures (World's meter) and Scene media; the status bar shows pressure; low-power mode lowers caps (performance.md "Low-power mode").
  • Worker lifetime. Wasm instances are freed after 60 s idle (the World rule), so a session that used a filter once does not keep megabytes alive.
  • Start-up. Lower the start-up budget from 354 KiB to ≤ 320 KiB: lazy pixel effects registry (R5.3, ~41 KiB), locale split (R5.4), and a check that no Wasm module or GPU code enters the static import closure. Record the desktop cold start (window shown, first interactive frame) with the --smoke run of R4.1.

Measurement harness and budgets#

Harness (E0.1). One command, npm run bench, with three layers:

  1. Node micro-benchmarks for pure kernels (extends tests/pixel/bench.mjs): median of 7 runs after warm-up, output as JSON.
  2. Browser scenarios in headless Chromium (the pattern of scripts/proto-perf.mjs): open a fixture, perform a scripted interaction, record User Timing marks, longtask entries and frame times through PerformanceObserver, JS heap where exposed.
  3. Desktop scenarios later, through the --smoke flag of R4.1.

Results go to perf/results/<machine>.json; a checked-in perf/baseline.json holds reference numbers per scenario. CI runs layer 1 on every PR and fails on a regression above 25 % (shared runners are noisy); layer 2 runs nightly and posts a trend table. Fixtures are generated (no third-party files): a 12 MP photo-like image, a 300-page story, a 100k-formula workbook, a 50-slide deck, a 2 000-element board, a 1 080p 60-second clip.

Budgets (reference: a 2023 laptop with integrated graphics; numbers in parentheses are today's where measured):

ScenarioBudget
Longest main-thread task while dragging a slider of a live filter on a 12 MP document≤ 50 ms (today up to 133 ms)
Live filter stack (HSL + Gaussian blur) on a 1.2 MP viewport, full quality≤ 33 ms per frame (today 133 ms)
Gaussian blur, 2 MP, sigma 10≤ 25 ms in Wasm (today ~110 ms JS)
Content-aware fill of a 4000×3000 corner region≤ 3 s with texture (today: blurry above 60 000 px)
Open a 200 MB layered PSDfirst view ≤ 3 s, UI never blocked > 100 ms
Recalculate after one edit in a 100k-formula workbook (chain of 1 000 dependents)≤ 50 ms; full recalc on open ≤ 1 s, off the main thread
Reflow a 300-page story after typing on page 1≤ 100 ms to the visible page, rest in idle slices
Scene export 1080p, H.264≥ 3× real time where WebCodecs exists; ≥ 1× on Linux with the native path
Start-up JavaScript (gzip, static closure)≤ 320 KiB (today 343.6 of 354)
JS heap with a 12 MP document≤ 64 MB plus tiles in use (today 88 MB)
Any Wasm module≤ 150 KiB gzip each, lazy; total of all engine modules ≤ 600 KiB

Candidate libraries and licenses#

Only permissive licenses go into the app (clean-room.md rule 6). Checked through the GitHub API on 2026-12-05; GitHub shows one detected license even for dual-licensed crates, so each must be re-checked at the pinned version.

NeedCandidateLicenseNote
Resize kernels (reference or reuse)fast_image_resizeMIT OR Apache-2.0SIMD, wasm32 support
Text shapingrustybuzz (Rust port of HarfBuzz) / harfbuzzjs (HarfBuzz in Wasm)MIT / MIT (HarfBuzz itself "Old MIT")E2.4 compares size and speed; R9.1 estimated 300–400 KiB for harfbuzzjs
Text layout (ideas)parleyApache-2.0 OR MITUsed by PhotoCraft's text crate
Polygon booleansi_overlayMIT OR Apache-2.0For live booleans if polygon-clipping misses 60 fps
Polygon booleans (alternative)Clipper2Boost Software License 1.0Permissive; C++ to Wasm
Mesh booleans (World)manifoldApache-2.0Already planned in World
Mesh optimization (World)meshoptimizerMITAlready planned in World
Spreadsheet oracleIronCalcMIT OR Apache-2.0Test vectors and semantics, not embedded by default
AV1 encode (optional)rav1eBSD-2-ClauseRoyalty-free codec
H.264 encodeopenh264BSD-2-Clause, but patent coverage only for Cisco's own binariesDo not bundle; prefer OS encoders or user ffmpeg
RAW decoderawloaderLGPL-2.1Not for static linking into the MIT core
RAW / PSD (Rust)craft-libs (craft-raw, craft-psd)MIT OR Apache-2.0Young (since 2026-09-30); review per the ArtCraft verdict
Image processing (ideas)photonApache-2.0Rust/Wasm image filters

Risks#

RiskEffectMitigation
A second language and toolchain (Rust for Wasm) raises the contribution barrierFewer contributors to kernelsCommitted, hash-checked artifacts; JS stays the reference so tests run without Rust; small crates with one purpose
JS and Wasm/GPU results driftExport differs from preview, flaky testsGolden and parity tests with explicit tolerances; export always uses the CPU reference path
Download size growsBreaks the "light" promisePer-module budget, lazy loading, wasm-opt -Oz, no module in the start-up closure
WebGPU driver bugs and device lossCrashes or black viewportsShare World's backend with device-loss recovery; blocklist via the Doctor report; Wasm fallback always present
WebKitGTK lacks WebGPU and WebCodecs encodersLinux stays slowerWasm path and native encoder are designed for Linux first
IPC overhead larger than expectedNative paths slower than WasmE0.3 measures before E4 starts; per-frame IPC is ruled out by principle 4
Codec patents and licensesLegal exposureNever bundle H.264/HEVC encoders; use OS encoders, WebCodecs or a user-installed ffmpeg
Native parsers are an attack surfaceCrafted files crash or exploit the appcargo fuzz corpora in CI, size limits, Wasm sandbox for untrusted files in the browser
Reusing young third-party crates (Craft libs)Churn, hidden license issuesPin, vendor, review, re-check NOTICE files; prefer own code from public specs
Benchmarks on shared CI runners are noisyFalse alarms or missed regressions25 % threshold for PR checks, nightly trends, manual numbers on reference machines in PR descriptions

Wave plan#

Each task is one pull request with its own benchmark numbers in the description. About four run in parallel; a wave starts when its dependencies are merged. Waves E0 to E2 can run alongside World 1.4.x because they touch different files.

WaveTasks (parallel)Gate
E0 MeasureE0.1 npm run bench harness (Node + headless Chromium layers, JSON results, baseline, CI regression check) · E0.2 long-task and frame-time instrumentation behind Settings ▸ Developer, recorded in the Doctor report · E0.3 Tauri IPC benchmark (JSON vs ipc::Response vs Channel, 1–64 MB, three OSes) and ADR 0036 "native engines" · E0.4 generated fixtures (300-page story, 100k-formula workbook, 50-slide deck, 2 000-element board, 12 MP image, 60 s clip)Baseline recorded for every row of the budget table
E1 Off the main thread (no new language)E1.1 live filters in the worker pool with tiles and cancellation (R5.2) · E1.2 file parsing in workers (unzip on open, PSD, TIFF, XLSX, PPTX, DOCX, IDML) with DecompressionStream where available · E1.3 spreadsheet recalc in time slices and a worker above a formula-count threshold · E1.4 start-up savings (R5.3 lazy effects registry, R5.4 locale split), budget loweredLongest task while dragging a live filter ≤ 50 ms; start-up ≤ 330 KiB
E2 Rust → Wasm foundationE2.1 engines/ workspace, build and hash check, engine/native loader with fallbacks, golden-test harness, first kernels (box and Gaussian blur, unsharp) · E2.2 resample, rotate and warp kernels; color conversions · E2.3 PatchMatch inpainting on a pyramid (closes R20.1) · E2.4 shaping decision and integration (rustybuzz vs harfbuzzjs; feeds R9)Blur 2 MP ≤ 25 ms; 4000×3000 content-aware fill ≤ 3 s; shaping ADR accepted
E3 GPUE3.1 WebGPU compute for adjustments and separable filters on the viewport · E3.2 GPU display compositing of Pixel layers (blend modes; CPU stays reference) · E3.3 GPU/CPU parity harness on SwiftShader in CI · E3.4 shared device probe and GPU memory meter with WorldLive stack on a 1.2 MP viewport ≤ 33 ms on WebGPU machines; parity tests green
E4 Desktop nativeE4.1 native video export path (user ffmpeg detection, YUV in Wasm, Channel streaming, 64-bit MP4) · E4.2 RAW decode crate (DNG first; review of craft-raw vs own code; Wasm pack + native) · E4.3 streaming large-file IO (PSB, media hashing, project collect) · E4.4 cargo fuzz for every native parser in CILinux 1080p export ≥ 1× real time; DNG opens; fuzzers run nightly
E5 Memory and scaleE5.1 tiled typed-array layer store (R13.2) on top of the Wasm kernels · E5.2 cold-tile LZ4 compression, LRU and the shared memory meter · E5.3 World kernel hotspots ported to Wasm where 17.1 targets were missed · E5.4 budgets enforced in CI and documented in performance.md12 MP document heap ≤ 64 MB plus tiles; 100 MP document opens

Dependencies: E1 needs E0.1; E2.1 needs E0.1; E2.2–E2.4 need E2.1; E3 needs E1.1 (the async render pipeline) and E0.2; E4.1 needs E0.3; E5.1 needs E2.1 and is the start of R13 (2.0).

Open questions#

  • Should the desktop app become cross-origin isolated (custom protocol headers) to enable Wasm threads there, at the cost of two code paths?
  • Where are the .wasm artifacts built for releases: in the app repository's CI (simplest) or in the engine-packs repository planned in R11.1?
  • Which reference machines are the owner's own, so the budget table can be checked by hand on each release?
  • Is a bundled royalty-free encoder (rav1e AV1) worth its size, or is "use WebCodecs, else your ffmpeg" enough?

Sources#

Accessed 2026-12-05.

Edit on GitHub → docs/concepts/optimization-native-engines.md