Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

docs(architecture): overview, document model and preview

Etienne Lescotfffd5ffcda7a
diff --git a/technical-documentation/architecture/document-model.md b/technical-documentation/architecture/document-model.md
new file mode 100644
index 000000000..121f81884
--- /dev/null
+++ b/technical-documentation/architecture/document-model.md
@@ -0,0 +1,166 @@
+# Document model
+
+The single source of truth for an OpenScreen project is `AxcutDocument`, a Zod-typed
+JSON object defined in `src/lib/ai-edition/schema/index.ts` and persisted as one file
+per project on disk. The renderer holds one instance in a Zustand store
+(`src/lib/ai-edition/store/projectStore.ts`); the main process owns persistence
+(`electron/ai-edition/document-service.ts`); and every editor surface — timeline,
+preview, floating inspector, captions, LLM agent — reads and writes that one
+document. The model is the contract the rest of the editor hangs off; this page is
+the contract.
+
+## `schemaVersion` and top-level shape
+
+`axcutSchemaVersion` is **5** — exported as a literal at
+`src/lib/ai-edition/schema/index.ts:24`. Every document on disk carries
+`schemaVersion: 5`; anything older is upgraded on parse (see [Migrations](#migrations))
+and anything unknown is rejected by the `z.literal(5)` check at line 477.
+
+| Field | Holds | Notes |
+|---|---|---|
+| `schemaVersion` | `5` | Bumping requires a migration; see the chain below. |
+| `project` | `{ id, title, createdAt, updatedAt, primaryAssetId? }` | One project per file. |
+| `assets[]` | `AxcutAsset` (one per recorded/imported media file) | Carries `originalPath`, `cameraTrack`, `durationSec` (renderer probes). |
+| `transcript` | `AxcutTranscript \| null` | Legacy primary transcript; left for back-compat, no longer the source of truth. |
+| `transcripts[]` | `AxcutTranscript[]` | Per-asset transcripts; what the captions layer actually reads. |
+| `timeline` | `{ clips[], gaps[], trimRanges[], muteRanges[], speedRanges[], captionRanges[] }` | Clips carry their own in/out (`sourceStartSec`/`sourceEndSec`); see [timeline-model.md](timeline-model.md). |
+| `annotations[]` | `AxcutAnnotationRegion[]` | Text/image/figure/blur overlays, anchored to a clip (`clipId?`). |
+| `zoomRanges[]` | `AxcutZoomRegion[]` | Zoom-in effects, depth 1–6, anchored to a clip (`clipId?`). |
+| `legacyEditor` | OpenScreen v2 `ProjectEditorState` passthrough | Appearance/cursor settings not yet first-class in v5. |
+| `agent` | `{ baseIntent?, pendingQuestions[], suggestions[], lastAppliedOperations[], lastReasoningSummary? }` | LLM agent state. |
+| `preview` | `{ strategy: "seek" \| "mse-proxy", revision: number }` | `revision` is the bump used to invalidate cached frames after an edit. |
+| `export` | `{ preset, lastJobId }` | The last export run. |
+| `history` | `{ revisions: AxcutRevision[] }` | Append-only revision log; declared by the schema (line 506) and currently populated only by tests. Undo/redo in the editor uses the in-memory `pushHistory` snapshot stack in `src/lib/ai-edition/store/undo.ts` rather than the persisted revision list — see [Undo / history](#undo--history). |
+
+## Migrations
+
+Migrations are **one-way and forward-only**. There is no version downgrade path: a
+newer document that lands on an older build is rejected by the `schemaVersion`
+literal, not silently truncated. The current chain is implemented inline in the
+schema file (`src/lib/ai-edition/schema/index.ts`) so every `documentSchema.parse(...)`
+call site gets the upgrade for free.
+
+### v3 → v4 (`upgradeV3DocumentToV4`, lines 522-542)
+
+v3 documents carried a single project-level `cameraTrack`; v4 moves it onto the
+owning asset. The preprocessor pulls the legacy `cameraTrack` field off the
+document root and copies it onto the asset identified by `project.primaryAssetId`
+(or the first asset if that is unset), then strips the root field and rewrites
+`schemaVersion: 4`. v2 documents are not touched by this preprocessor — they are
+handled by the separate `migrateProjectDataToAxcutDocument` pure function described
+below — and unknown versions pass through unchanged into the literal check at the
+top of `documentSchemaShape`.
+
+### v4 → v5 (`upgradeV4DocumentToV5`, lines 557-596)
+
+v5 makes modifiers (zoom, annotation, speed, camera-fullscreen) clip-anchored:
+each region is split into one fragment per covered clip, with the source-time
+window (`clipId`, `sourceStartSec`, `sourceEndSec`) as the source of truth and
+`startMs`/`endMs` re-derived as a transition cache. The preprocessor reads the
+RAW clip layout out of `timeline.clips` and runs every region array through
+`anchorRegionsWithDerivedMs` (`src/lib/ai-edition/timeline/timelineMap.ts:376`):
+
+- `document.zoomRanges`
+- `document.annotations`
+- `document.legacyEditor.speedRegions`
+- `document.legacyEditor.cameraFullscreenRegions`
+
+A region that covers no clip — zero-length, or off the end of the timeline — is
+dropped, because it could never play. A document with no clips has nothing to
+anchor to, so its regions pass through untouched (the anchor is optional during
+the transition, see the v5 schema at line 403-407). The `v4→v5` migration lives
+**only** in this preprocessor — `document/migrate.ts` deliberately emits a v4
+draft (line 209) so the same code path is reused for the legacy import.
+
+### Legacy v2 → current (`migrateProjectDataToAxcutDocument`, `document/migrate.ts`)
+
+OpenScreen's pre-merge editor stored projects as `EditorProjectData` (an envelope
+versioned `PROJECT_VERSION = 2`, defined at
+`src/components/video-editor/projectPersistence.ts:66`). On first open in the new
+editor, the renderer calls this function to produce a current-shape document. The
+migration is **pure** — no DOM, no fs, no network — and maps each `EditorProjectData`
+field into the equivalent v5 slot:
+
+- The single recorded screen video becomes one asset plus one clip spanning its
+ source, with the webcam path lifted into `asset.cameraTrack`.
+- `editor.trimRegions` (kept ranges) invert into `timeline.trimRanges` (kept ranges
+ in source seconds). v2 semantics matched v5 here — both are "kept", not "cut".
+- `editor.speedRegions`, `editor.zoomRegions`, and `editor.annotationRegions` carry
+ over into `legacyEditor.speedRegions`, `document.zoomRanges`, and
+ `document.annotations` respectively (with v4→v5 anchoring applied during the
+ parse at the end).
+- The full `editor` blob — wallpaper, cursor theme, webcam layout, blur settings,
+ and the other ~20 fields without a first-class home — round-trips through
+ `legacyEditor` so toggling AI-edition off then back on is lossless.
+
+The function returns the v5 result by emitting a v4-shaped draft and letting
+`documentSchema.parse` run it through the v4→v5 preprocessor described above.
+That is why the draft is labelled `schemaVersion: 4` and not `axcutSchemaVersion`
+(see the comment at `document/migrate.ts:201-207`): labelling it already-v5 would
+make the preprocessor skip the anchoring and leave the imported regions without
+clip anchors.
+
+## Persistence
+
+There are exactly two owners of the document bytes: the renderer store and the
+main-process service. They never duplicate fields and never diverge on shape — the
+service stores exactly what `JSON.stringify(document, null, 2)` produces.
+
+| | Renderer | Main process |
+|---|---|---|
+| Code | `src/lib/ai-edition/store/projectStore.ts` | `electron/ai-edition/document-service.ts` |
+| Role | Live editor state, transport (`playing`, `currentTimeSec`, `sourceDurationSec`), `dirty`/`lastSavedAt` | Read, write, list, add asset, remove asset |
+| Transport | `nativeBridgeClient.aiEdition.*` IPC | — |
+| On disk | — | `userData/projects/<id>.openscreen` (one JSON per project) |
+| Extension | — | **`.openscreen`**. Older builds wrote the same v3/v4 documents under `.axcut`; the service renames them to `.openscreen` on first access (`migrateLegacyExtensions`, lines 119-145). The file content is unchanged — the extension migration is a pure rename keyed off the schema version in the JSON, not the file name. |
+| Atomicity | — | Temp + rename per save (`writeProjectNow`, lines 354-394), with a per-project write queue (`writeQueues`, line 106) so two concurrent saves serialise and an interrupted write cannot leave a half-written document behind. |
+
+Both layers run every read through `documentSchema.parse` so an on-disk document
+of any supported version comes out as the current `AxcutDocument` shape; the
+renderer never holds a stale `schemaVersion: 3` snapshot.
+
+## Undo / history
+
+The schema declares a `history.revisions[]` field (`schema/index.ts:506-510`) for
+an append-only revision log, populated by tests today and reserved for future
+revision browsing. The interactive undo/redo in the editor uses a different,
+lighter mechanism so the user can undo any edit, including one made by the LLM,
+without growing the persisted document.
+
+The mechanism lives in `src/lib/ai-edition/store/undo.ts`:
+
+- A bounded snapshot stack (`past[]`, `future[]`, `MAX_HISTORY = 50`) holds the
+ previous document JSON per project.
+- Every call to `setDocument` in the project store (`projectStore.ts:218-232`)
+ pushes the outgoing document onto `past` before swapping in the new one
+ (`pushHistory`, `undo.ts:18-25`). The push is deferred via a dynamic
+ `import("./undo")` so the store does not load the undo module at module-init
+ time.
+- `undo()` and `redo()` (`undo.ts:30-66`) swap snapshots back through
+ `setDocument`, with an `enabled` flag that suppresses a recursive push during
+ the swap itself.
+- `useUndoRedoShortcuts` (`undo.ts:68-103`) wires Cmd+Z / Cmd+Shift+Z / Ctrl+Y to
+ the snapshot stack, ignoring key events whose target is a text input or
+ contenteditable so typing in the transcript or rename field does not get
+ intercepted.
+
+A whole LLM agent batch undoes as one unit because every tool mutation goes
+through `setDocument`. The chat service applies each tool call by computing the
+next document and calling `saveDocument`; the snapshot is taken at the
+`setDocument` boundary of each call, so undoing a batch of N tool calls means N
+Cmd+Z presses, and each one unwinds one tool's effect in reverse order. The
+batch atomicity a single undo button would need lives in the chat UI's "undo last
+agent turn" affordance (not yet wired — see [Known gaps](#known-gaps)).
+
+## Known gaps
+
+- `history.revisions` is declared by the schema but only the renderer snapshot
+ stack is populated today. A persisted revision log would let "undo" survive
+ app restarts and give users a history view; both are deferred.
+- The chat-service undo of a full agent turn is not implemented. The undo button
+ undoes one tool call at a time; a per-turn undo would require checkpointing
+ the document at the start of each chat turn (one push per turn, not per tool
+ call).
+- The `agent.baseIntent` field is persisted but not yet populated by the chat
+ runtime; the LLM tool loop fills `lastReasoningSummary` only after the v6
+ compaction step lands.
\ No newline at end of file
diff --git a/technical-documentation/architecture/overview.md b/technical-documentation/architecture/overview.md
index cb7656d27..515092a9d 100644
--- a/technical-documentation/architecture/overview.md
+++ b/technical-documentation/architecture/overview.md
@@ -1,80 +1,125 @@
-# AI-Edition — Data Flow
+# Architecture overview
-Companion to [`ai-edition-roadmap.md`](ai-edition-roadmap.md) (status/phasing) and
-[`ai-edition-collision-analysis.md`](ai-edition-collision-analysis.md) (why decisions were
-made). This doc answers a narrower question: **what talks to what, and who owns the truth**,
-transcribed from a whiteboard sketch and cross-checked against the current code
-(`feat/ai-edition`, 2026-07-02).
+OpenScreen is an Electron + React + TypeScript screen recorder and video editor. The
+main process lives in `electron/`; the renderer is a single Vite-built SPA whose entry
+point is `src/App.tsx`. `App.tsx` reads `?windowType=` from the URL and lazy-loads one
+window component. The four real window types — verified against `src/App.tsx:71-125`
+and `electron/windows.ts` — are:
-## 1. Diagram
+- `editor` — the main studio (`AiEditionShell`, `createEditorWindow`).
+- `hud-overlay` — the floating record bar (`LaunchWindow`, `createHudOverlayWindow`).
+- `source-selector` — the screen/window picker (`SourceSelector`, `createSourceSelectorWindow`).
+- `countdown-overlay` — the pre-roll overlay (`CountdownOverlay`, `createCountdownOverlayWindow`).
+
+A fifth, frameless `NotesWindow` is reached via a separate `showNotes=true` query,
+not `windowType`.
+
+The studio is built on a single source of truth — the `AxcutDocument` v5 Zod schema
+described in [document-model.md](document-model.md). Every pane in the editor is a
+view over the same in-memory document held in a Zustand store
+(`src/lib/ai-edition/store/projectStore.ts`); the main process persists it as JSON in
+the OS-standard user data directory via `electron/ai-edition/document-service.ts`.
+What reads or writes the document, and how the user-facing surfaces hang off it, is
+the subject of the rest of this page.
+
+## Authoring levels
+
+The editor presents three overlapping levels to the user, with one extra layer —
+the document itself — sitting underneath them as the single source of truth:
+
+```mermaid
+flowchart LR
+ subgraph levels["Authoring levels"]
+ direction TB
+ M["<b>Edits / Modifiers level</b><br/>zooms, speeds, trims, …"]
+ T["<b>Timeline level</b><br/>clip order (1, 2, …)"]
+ C["<b>Clip level</b><br/>attached media: screen · camera · mic · system audio<br/>crop + in/out timestamps"]
+ end
+ DSL[["<b>DSL — AxcutDocument</b><br/>single source of truth"]]
+ P["Preview"]
+ R["Render / Export"]
+
+ M -- "authored above the timeline,<br/>stored down on the clip" --> C
+ T --> DSL
+ C --> DSL
+ DSL --> P
+ DSL --> R
+```
+
+The load-bearing point is that **modifiers are presented above the timeline in the
+UX but stored down on the clip in the data**. A zoom the user draws over clip 2 lives
+in `document.zoomRanges[]` but is anchored to that clip's `clipId` in source time; the
+pill on the ruler is then projected back from the clip, not authored in ruler space.
+That is exactly the invariant [timeline-model.md](timeline-model.md) exists to
+protect, and the reason a second authoring layer was added on top of the clip
+geometry instead of competing with it.
+
+## Who reads and writes the document
+
+The renderer holds one in-memory `AxcutDocument` and zero parallel "preview state"
+or "timeline state" copies. Every pane reads from that document; every user action
+goes back through it.
```mermaid
flowchart TD
User(("User"))
- Chat["Chat UI\n(LeftPanel.tsx)"]
- LLM["LLM Provider\n(llm-call.ts,\nprovider-registry.ts)"]
- DSL[["DSL File\n= AxcutDocument\n(schema/index.ts)\n— SSOT —"]]
- Store["projectStore.ts\n(Zustand, in-memory)"]
- Disk[(".openscreen v3 file\non disk\n(document-service.ts)")]
+ Chat["LeftPanel.tsx<br/>(chat + media list)"]
+ LLM["LLM provider<br/>electron/ai-edition/llm-call.ts<br/>provider-registry.ts"]
+ DSL[["AxcutDocument<br/>src/lib/ai-edition/schema/index.ts<br/>— SSOT —"]]
+ Store["useProjectStore<br/>(Zustand, in renderer)"]
+ Disk[(".openscreen JSON<br/>userData/projects/<id>.openscreen<br/>document-service.ts")]
- MT1["Media Transcript\n(source A)"]
- MT2["Media Transcript\n(source B)"]
+ MT1["Media transcript<br/>(local Whisper)"]
+ MT2["Media transcript<br/>(2nd asset / mic)"]
- Timeline["Timeline\n(TimelinePane.tsx)"]
- VPreview["Virtual Preview\n(VirtualPreview.tsx /\nPreviewCanvas.tsx)"]
- VTranscript["Virtual Transcript\n(TranscriptEditor.tsx)"]
+ Timeline["Timeline<br/>v4/V4Timeline.tsx"]
+ VPreview["Preview<br/>Preview.tsx → PreviewCanvas.tsx"]
+ VTranscript["Transcript<br/>CaptionsPane.tsx + src/lib/ai-edition/captions/"]
User <--> Chat
Chat <--> LLM
- LLM -- "tool calls\n(agent-tools.ts:\naddSkip, setClipRange,\nreplaceTimeline...)" --> DSL
+ LLM -- "tool calls<br/>agent-tools.ts:<br/>addZoom, setClipRange,<br/>replaceTimeline, …" --> DSL
- MT1 -- "ingest on\ntranscribe/import" --> DSL
- MT2 -- "ingest on\ntranscribe/import" --> DSL
+ MT1 -- "ingest on<br/>transcribe/import" --> DSL
+ MT2 -- "ingest on<br/>transcribe/import" --> DSL
- User -- "direct edits" --> Timeline
- User -- "direct edits" --> VTranscript
+ User -- "direct edits<br/>(drag, resize, …)" --> Timeline
+ User -- "direct edits<br/>(cue edits, settings)" --> VTranscript
DSL <==> Store
Store <==> Disk
- DSL <-.->|"read/write\n(store actions)"| Timeline
- DSL <-.->|"read/write\n(store actions)"| VPreview
- DSL <-.->|"read/write\n(store actions)"| VTranscript
+ DSL <-.->|"read/write<br/>(store actions)"| Timeline
+ DSL <-.->|"read/write<br/>(store actions)"| VPreview
+ DSL <-.->|"read/write<br/>(store actions)"| VTranscript
```
-## 2. What each node is, in code
-
-| Sketch label | Code | Notes |
-|---|---|---|
-| **DSL File / SSOT** | `AxcutDocument` — Zod schema in `src/lib/ai-edition/schema/` | `project · assets[] · transcripts[] · timeline{clips,gaps,skip/mute/speed/captionRanges} · annotations[] · zoomRanges[] · legacyEditor · agent · preview · export · history`. Every pane below is a **view over this one document** — nothing keeps its own parallel state. |
-| **DSL (persistence)** | `store/projectStore.ts` (Zustand, renderer) + `electron/ai-edition/document-service.ts` (main process) | Renderer holds the live document in a Zustand store; main process persists it to `userData/projects/<id>.axcut`. Legacy `.openscreen` v2 files migrate to v3 on first open (`lib/ai-edition/document/migrate*.ts`). |
-| **Chat** | `src/components/ai-edition/LeftPanel.tsx` | Sends user messages to the LLM via IPC into `electron/ai-edition/chat-service.ts`. |
-| **LLM** | `electron/ai-edition/llm-call.ts` + `provider-registry.ts` | Fetch-based calls, OpenAI-compatible + Anthropic today (8 providers registered; OAuth device-flow/PAT still stubbed — roadmap P2.2). |
-| **Edits (LLM → DSL)** | `electron/ai-edition/agent-tools.ts` + tool-loop in `chat-service.ts` | The model doesn't free-write the document; it calls a fixed tool schema (`getCurrentDocument`, `getTranscript`, `addSkip`, `setSkipRange`, `setClipRange`, `replaceTimeline`, …). Each tool call is validated, applied to the store, and checkpointed first so the user can undo a whole batch (roadmap P1.1–P1.8). |
-| **Media Transcript(s)** | Local Whisper (`@xenova/transformers`, in-browser, not gated by `AI_FEATURES_ENABLED`) | Produces `transcripts[]` entries keyed to an asset. The two boxes in the sketch are two independent transcript sources (e.g. two recorded assets / mic + system audio) that both land in the same document — there's no per-source document fork. |
-| **Timeline** | `src/components/ai-edition/TimelinePane.tsx` | Renders `timeline.clips` + lanes (skip/speed/annotation/zoom ranges). Read/write against the store; drag, resize, reorder all dispatch store actions that mutate the DSL document (see roadmap §5 P0 table for the viewport/zoom/pan mechanics). |
-| **Virtual Preview** | `VirtualPreview.tsx` / `PreviewCanvas.tsx` | Renders the composited frame (wallpaper, blur, webcam PiP, cursor overlay, zoom, annotations) by reading the document at the current playhead time — it never owns edit state, only projects it. |
-| **Virtual Transcript** | `TranscriptEditor.tsx` | Editable view of `transcripts[]`; user edits here write back into the DSL document (word-level edits, not a separate buffer). |
-
-## 3. Read this diagram as two loops
-
-1. **Human loop** — User edits the Timeline / Transcript directly, or talks to the Chat panel,
- which drives the LLM, which edits the DSL document through the tool schema (never raw JSON
- patches). Both paths converge on the same document.
-2. **Machine loop** — Media assets get transcribed locally (Whisper) and merged into the
- document's `transcripts[]`. Preview and Timeline are pure projections of the document at a
- given time/zoom — there is no independent "preview state" to desync from the DSL.
-
-The one-document-many-views design is why the sketch draws `DSL File` as the hub: every arrow
-either writes into it (Chat/LLM tool calls, direct user edits, transcript ingestion) or reads a
-projection out of it (Timeline, Virtual Preview, Virtual Transcript). Persistence
-(`projectStore.ts` ↔ `.openscreen` file) is a straight serialize/deserialize of the same shape,
-not a separate model.
-
-## 4. Open gaps vs. this flow (see roadmap §5 for detail)
-
-- Chat history is still in-memory per session (`chat-service.ts`), not persisted to SQLite —
- roadmap P2.1.
-- LLM auth is API-key only; OAuth device-flow/PAT is stubbed — roadmap P2.2.
-- Streaming responses (SSE-style token rendering in Chat) not implemented — roadmap P2.4.
-- Tool-call permission gate (confirm before a write tool runs) not implemented — roadmap P2.5.
+Read this diagram as two loops:
+
+1. **Human loop.** The user edits the Timeline directly (clip reorder, region resize,
+ skip placement) or talks to the Chat panel, which drives the LLM, which edits the
+ document through the fixed tool schema — never raw JSON patches. Both paths
+ converge on the same `AxcutDocument`.
+2. **Machine loop.** Media assets get transcribed locally (Whisper via the renderer
+ worker) and merged into `document.transcripts[]`. Preview and Timeline are pure
+ projections of the document at a given time/zoom — there is no independent
+ "preview state" to desync from the DSL.
+
+Persistence (`useProjectStore` ↔ `.openscreen` file on disk) is a straight
+serialize/deserialize of the same shape, not a separate model — see
+[document-model.md](document-model.md#persistence).
+
+## Where to go next
+
+The four pages that explain the editing model itself, in the order they build on each
+other:
+
+1. [document-model.md](document-model.md) — the document every surface projects.
+2. [timeline-model.md](timeline-model.md) — how time and modifiers are addressed inside it.
+3. [editor-shell.md](editor-shell.md) — the surfaces the user drives.
+4. [preview.md](preview.md) and [export-pipeline.md](export-pipeline.md) — the two consumers
+ that turn the document back into pixels.
+
+[decisions.md](decisions.md) records what is settled and what was tried and rejected —
+read it before proposing a structural change. The full index of every architecture,
+engineering and testing page is in [the tree README](../README.md).
\ No newline at end of file
diff --git a/technical-documentation/architecture/preview.md b/technical-documentation/architecture/preview.md
new file mode 100644
index 000000000..000bd2b6c
--- /dev/null
+++ b/technical-documentation/architecture/preview.md
@@ -0,0 +1,326 @@
+# Preview
+
+The preview is the editor's frame-at-the-playhead surface. It is composited by the same
+Rust + Direct3D 11 native crate that drives MP4 export — `poc-d3d/` reached via the
+`compositor_view.node` napi-rs addon — and pulled into the renderer as an RGBA8
+bitmap that paints onto an HTML `<canvas>`. The DOM around the canvas hosts the
+interactive-only layers (zoom gimbal, annotation selection, PiP webcam drag) that
+need real hitboxes. Everything visible in the preview comes out of the same
+compositor that writes the export; parity is the property of one renderer, not a
+discipline across two.
+
+This document describes the live composition path. The export pipe
+([architecture/export-pipeline.md](export-pipeline.md)) shares the same compositor
+and scene contract; the GPU-resident path it builds on is documented in
+[architecture/native-compositor.md](native-compositor.md). Performance numbers
+(preview fluidity, bench methodology, the trade-offs that drove this design) live
+in [engineering/rendering-performance.md](../engineering/rendering-performance.md).
+
+## The two paths
+
+Two paths exist in the source tree. The native one is live; the Pixi-based second
+implementation is shipped but not reached from the editor surface.
+
+### Path A — native D3D compositor overlay (live)
+
+Mounted as the first child of `.previewFrame` by
+[`NativeCompositorOverlay.tsx`](../../src/components/ai-edition/NativeCompositorOverlay.tsx).
+It owns the `<canvas>`, drives a `useNativeCompositorView` hook that allocates an
+offscreen `compositor_view` view sized to the canvas's device-pixel rect
+([`useNativeCompositorView.ts:73`](../../src/native/hooks/useNativeCompositorView.ts:73)),
+and pushes a `SceneDescription` JSON every time the document or the editor
+settings change. Wallpaper, screen video, webcam, cursor, zoom regions, annotations
+— every visible pixel comes from this view. The DOM neighbours it (the `.screenStage`
+wrapper, the `<video>` for screen decode, the `WebcamOverlay` `<video>`, the
+`AnnotationLayer`, the `ZoomFocusOverlay`, the webcam drag hitbox) are *interactive
+overlays*: their pixels are hidden in CSS, only their pointer-event geometry counts.
+
+The path is enabled by the *presence of the native addon* — there is no flag,
+no capability probe, no per-document switch. The compositing service loads
+`compositor_view.node` at startup via
+[`compositorViewService.ts`](../../electron/native-bridge/services/compositorViewService.ts:271)
+(`ensureAddon`); when the binary is missing the service logs once
+(`[compositor-view] native addon not present; running as no-op`,
+[`compositorViewService.ts:288`](../../electron/native-bridge/services/compositorViewService.ts:288))
+and returns synthetic negative view ids whose `readFrame` always returns `null`, so
+the whole overlay stays inert. In that mode the renderer's own `<video>` element
+keeps playing (decode is the responsibility of the DOM, not the compositor), but
+nothing composites a frame — the canvas stays empty. The editor ships like this
+on platforms where the addon isn't built; the dev build brings the addon in.
+
+The renderer→addon IPC goes through `native-bridge:invoke` with a single
+`compositor` domain
+([`compositorViewClient.ts:24`](../../src/native/compositorViewClient.ts:24)). The
+service in the main process loads the addon from
+`electron/native/bin/<platform>-<arch>/compositor_view.node` (packaged) or
+`electron/native/compositor-view/build/compositor_view.node` (dev), with an
+`OPENSCREEN_COMPOSITOR_VIEW_NODE` env override for the standalone builds. The
+ffmpeg shared-DLL directory is prepended to `PATH` before the require so the
+addon's `LoadLibrary("avcodec-NN.dll")` resolves against the same pinned build the
+crate links against
+([`compositorViewService.ts:206`](../../electron/native-bridge/services/compositorViewService.ts:206)).
+
+### Path B — Pixi/WebGL single-canvas screen compositor (shipped, not mounted)
+
+[`preview-compositor/PreviewCompositor.tsx`](../../src/components/ai-edition/preview-compositor/PreviewCompositor.tsx)
+is the screen-only successor that decodes straight into a Pixi `VideoSource` and
+composites video + zoom + mask in one GPU draw call. It is not mounted by the
+editor shell; `PreviewCanvas.tsx:393-411` deliberately falls back to the
+`VirtualPreview` legacy path with a comment recording why
+("`PreviewCompositor` (Pixi v8) regressed the screen preview … `setPixiReady` +
+`canvasSize === {0,0}` on mount produces a 1x1 canvas that the resize effect never
+widens"). The module stays in the tree as the route the next Pixi hardening
+attempts to revive, but no flag in this branch re-enables it. `PreviewCompositor`
+is therefore dead code today and is referenced in this doc only as the
+"two paths" it was advertised as offering; the live path is the native overlay.
+
+There is no fallback to a CPU/Canvas2D legacy compositor: before the native view
+ships a frame, only the wallpaper painted by CSS is visible, and the cursor / zoom
+DOM layers depend on the layout math (not the compositor) to know where to land.
+That is a product gap, not a fallback path. The native preview is the only
+compositor in service.
+
+## Scene description
+
+`document → SceneDescription → JSON` is the contract the app hands the native
+compositor so it can compute the composed frame itself; the renderer does no
+per-frame math.
+
+[`buildSceneDescription`](../../src/native/sceneDescription.ts:419)
+(`src/native/sceneDescription.ts`) is a pure data mapping from an `AxcutDocument` plus the
+current editor settings to a `SceneDescription` JSON string. It resolves:
+
+- **Visible clips.** [`resolveVisibleClips`](../../src/native/sceneDescription.ts:411)
+ is the single shared clip list: `resolvePlaybackSegments(document.timeline.clips, document.timeline.trimRanges)`
+ (trim-narrowed, so word-level cuts from the transcript editor actually reach the
+ compositor instead of only affecting the transcript panel's own strikethrough)
+ sorted by `timelineStartSec` and filtered to clips whose asset has a resolvable
+ `originalPath`. The same call backs `buildSceneDescription`, the native-export
+ clip list in `ExportDialog`, and the active-clip lookup in
+ `NativeCompositorOverlay` — three previously-divergent sites that are now the
+ same expression.
+- **Scene regions.** Zoom, Full Camera, speed, annotations, and captions are stored
+ in *RAW document* time (trims still occupy their place) but applied at each
+ frame's *source time* (the compositor matches each decoded frame's PTS, not a
+ timeline counter). [`projectRegionsToSource`](../../src/lib/ai-edition/timeline/timelineMap.ts)
+ bridges the two reference frames by resolving each region against every visible
+ segment's own raw extent and emitting one entry per source-time span it covers,
+ tagged with the segment's `clipIndex`. Captions piggyback on annotations
+ (`captionCuesToTextRegions` produces text annotations at the same zIndex layer)
+ so the compositor draws them with the same path; deliberately no separate
+ caption layer in the native code.
+- **Layout.** The webcam rect is resolved by the same
+ [`computeCompositeLayout`](../../src/lib/compositeLayout.ts) call the legacy
+ `frameRenderer` runs and shipped to the addon as `layout.webcamRect` /
+ `layout.screenRect` in fractions of the output frame. The native side consumes
+ those verbatim and applies the padding-slider and reactive-zoom adjustments on
+ top, so preview/export never disagree on placement. Per-clip screen resolutions
+ and crops mean a multi-clip document that mixes recording shapes (e.g. a 16:9
+ screen crop clipped to 9:16 beside another native 9:16 clip) lays out exactly
+ like a single recorded ratio; `layout.layoutByClip` is index-aligned with
+ `clips` and `cropByClip` and the Rust `for_clip_window` selects the entry for
+ the clip being composed.
+- **Lengths as fractions.** Every length that crosses the contract is a fraction
+ of its own reference box — `roundnessFrac` of the output frame's short side,
+ `screenRadiusFrac` of the screen box's short side, annotation `x/y/w/h` of the
+ screen rect, `padding` 0..1. There are no render-target pixels in the payload:
+ the native compositor rasterises the preview into a small contain-fitted frame
+ and the export at full output size, so a pixel meant two different things on
+ the two sides of the boundary; a fraction has no unit to get wrong. The slider
+ itself stays in pixels for the user — the division happens once, here.
+
+The descriptor mirrors the Rust struct in
+[`poc-d3d/src/scene.rs`](../../poc-d3d/src/scene.rs); field rename is `camelCase`
+on both sides. The Rust consumer (`compositor.rs::compose_frame`,
+[`poc-d3d/src/compositor.rs:1421`](../../poc-d3d/src/compositor.rs:1421)) reads
+the JSON per frame, derives the per-clip and per-frame values it needs (zoom
+state from `regions.rs::zoom_state_at`, camera-fullscreen progress from
+`regions.rs::camera_fullscreen_progress_at`, screen crop from
+`SceneCrop::belongs`), and only then issues GPU draw calls. Region visibility is
+expressed as `[startSec, endSec)` intervals and matched against `t = source_time`;
+a region straddling a clip boundary emits one entry per covered clip via
+`projectRegionsToSource`.
+
+## Frame delivery
+
+The native compositor runs *off-screen* (no OS window, no HWND ever crosses
+IPC), and the renderer pulls composed frames out of it. The protocol is the load-bearing
+contract between the two:
+
+```ts
+readFrame(id: number, sinceGen: number): { gen, width, height, data } | null
+```
+
+(`addons.d.ts` declares it as `CompositorViewAddon.readFrame`,
+[`electron/native/compositor-view/addon.d.ts:93`](../../electron/native/compositor-view/addon.d.ts:93);
+the renderer-facing type is `CompositorFramePacket`,
+[`contracts.ts:120`](../../src/native/contracts.ts:120).)
+
+The contract, with the invariant on the consumer side:
+
+1. **Self-describing packet.** A returned object carries its own
+ `width`/`height`/`data`. The drawing buffer is resized to those values
+ *before* `putImageData` runs
+ ([`useNativeCompositorView.ts:195`](../../src/native/hooks/useNativeCompositorView.ts:195)),
+ so pixels and canvas can never drift apart: there is no separate source of
+ truth for "how big the bitmap is right now" — every packet carries it.
+2. **Generation-gated.** `gen` is a monotonic per-frame generation (≥ 1). The
+ renderer holds the last one it painted and passes it back as `sinceGen`; the
+ addon returns `null` whenever `gen <= sinceGen`. An idle preview pays
+ nothing: no buffer clone, no IPC crossing, no canvas copy, no `putImageData`.
+ The null return is the dominant case while the preview sits still (paused
+ editing). One in-flight `readFrame` at a time
+ ([`useNativeCompositorView.ts:155`](../../src/native/hooks/useNativeCompositorView.ts:155))
+ so two responses can't land out of order and rewind `lastGen`.
+3. **`data` is RGBA8, `width * height * 4` bytes.** The renderer wraps it via
+ `new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength)` —
+ `ImageData` rejects `SharedArrayBuffer`-backed arrays, and the IPC binary is
+ never shared, so the cast is safe. `createImageBitmap` decodes off the main
+ thread (UI stays at 60/120 Hz) and snapshots the view, then `putImageData` is
+ the synchronous fallback if bitmap creation is unavailable.
+4. **Verify before trusting.** `data.byteLength !== width * height * 4 || width === 0 || height === 0`
+ is a hard bail
+ ([`useNativeCompositorView.ts:190`](../../src/native/hooks/useNativeCompositorView.ts:190)):
+ a mismatch would corrupt the image silently. The consumer never assumes a
+ size — every draw is preceded by a resize of the canvas's drawing buffer to
+ the packet's declared `width`/`height`.
+5. **Pull loop cadence.** The renderer pulls on every other rAF tick (`PULL_LOOP_TICK_DIVISOR = 2`,
+ [`useNativeCompositorView.ts:70`](../../src/native/hooks/useNativeCompositorView.ts:70)),
+ so IPC + GPU readback + `putImageData` run at roughly 30 fps on 60/120 Hz
+ displays without changing perceived smoothness.
+
+The renderer-side wrapper mirrors this verbatim in the Electron main process
+([`compositorViewService.ts:339`](../../electron/native-bridge/services/compositorViewService.ts:339)),
+so when the addon is absent the IPC layer returns `null` too — the renderer
+never has to special-case "addon missing".
+
+## Playback sync
+
+The native view runs its own clock while playing, so the renderer only pushes a
+seek when the user actually *moves* the playhead (scrub, step, or wrap-around to
+a new clip). The mapping sits in
+[`useNativePlaybackSync.ts`](../../src/native/useNativePlaybackSync.ts).
+
+- **Play / pause → free-run.** `setNativePlaying` toggles the addon's free-run
+ decoder. While playing, `currentTimeSec` ticks every rAF in the renderer;
+ pushing that per tick would force a rewind+seek seek each frame *and* fight
+ the addon's free-run (the render thread prioritises app-requested frames over
+ free-run). So `useNativePlaybackSync` only pushes `setNativeTime` while the
+ transport is paused.
+- **RAW → native source.** The playhead `currentTimeSec` is in *RAW virtual*
+ time (trims still occupy their space on the ruler — same reference the V4
+ timeline and the webcam overlay use), but the native stream plays *compressed*
+ segments (`resolveVisibleClips`, trims removed). `resolveNativePosition`
+ bridges the two: it maps the RAW playhead via `document.timeline.clips` (the
+ raw layout) to find the segment that contains it, then returns the segment's
+ `clipIndex` + source time. Without this bridge a RAW playhead against a
+ compressed clip list pointed at the wrong clip after a trim — wrong camera,
+ misaligned screen.
+- **Drift re-anchor.** During free-run the two clocks can drift; once the
+ additive error exceeds 100 ms (`Math.abs(sourceTimeSec - expectedSourceTimeSec) > 0.1`,
+ [`useNativePlaybackSync.ts:94`](../../src/native/useNativePlaybackSync.ts:94))
+ the hook re-issues `setNativeTime`. `useNativePlaybackSync:18` calls this a
+ known limitation acceptable for the ~6 s fixture it's measured on; a pause
+ resets the drift by construction.
+
+The overlay's rect is kept aligned with the DOM via the same primitives used
+elsewhere in the renderer:
+
+- `computeDeviceRect` (`src/native/nativeViewRect.ts`) turns
+ `getBoundingClientRect()` into a device-pixel `CompositorViewRect`,
+ rounding every axis to dodge the truncated / off-by-one windows the addon
+ produces on non-integer inputs.
+- `rectsEqual` skips the `setRect` push when nothing has changed
+ ([`nativeViewRect.ts:33`](../../src/native/nativeViewRect.ts:33)) — the
+ the ResizeObserver (`useNativeCompositorView.ts:259`) and a coalesced rAF
+ schedule steady-state scrolling and resizes without re-pushing the rect.
+- The overlay reuses the canvas's CSS `width: 100%; height: 100%` for its
+ display box (`NativeCompositorOverlay.tsx:217`); the addon's `rect.x`/`rect.y`
+ are vestigial (ignored native-side per
+ [`addon.d.ts:18`](../../electron/native/compositor-view/addon.d.ts:18) and
+ kept on the wire for source compatibility).
+
+Clip changes across the playhead boundary are atomic at the
+`setActiveClip(viewId, screenPath, webcamPath, webcamOffsetSec, clipIndex, sourceTimeSec)`
+RPC
+([`compositorViewClient.ts:93`](../../src/native/compositorViewClient.ts:93)):
+when the playhead crosses into a clip whose `assetId` / `webcamPath` differs
+from the previous one, `NativeCompositorOverlay.tsx:175-203` pauses native across
+the decoder swap, awaits `setActiveClip`, and re-reads the live transport *now*
+(not from a captured `isPlaying`) before resuming — so a user pause that lands
+in the middle of a clip transition is honoured, not silently undone.
+
+## Known gaps
+
+- **Live preview is video-only.** `poc-d3d/src/live.rs` (1628 lines) handles only
+ the video packet stream; audio is decoded and mixed in
+ [`audio.rs::decode_clip_audio`](../../poc-d3d/src/audio.rs) for the export
+ path and not for the live view. Editing playback is therefore silent against
+ the exported file; users hear audio only when the export runs. There is no
+ flag in this branch that re-routes live audio.
+- **Long-recording scrub drift.** `useNativePlaybackSync:18` documents the
+ accepted-at-fixture-time drift between the app's rAF playhead and the addon's
+ free-run clock as a known limitation; a pause re-aligns them. A scrub further
+ than 100 ms past expected position triggers an explicit re-anchor; below that
+ the two clocks run independently until something forces a sync. Long recordings
+ measured at the bench in
+ [engineering/rendering-performance.md](../engineering/rendering-performance.md)
+ stay below the threshold in practice, but no systematic measurement exists.
+- **Add-on absent = blank frame.** When `compositor_view.node` is missing
+ (development with the addon not yet built, or a packaged build for an
+ unsupported architecture) the overlay renders no pixels: only the DOM/CSS
+ wallpaper and the interactive layers show. There is no CPU/Canvas2D fallback
+ path; the live preview is gated on the addon being present.
+
+## A single frame, end-to-end
+
+The labelled arrows are the IPC + state edges; everything inside one box is in-process.
+
+```mermaid
+sequenceDiagram
+ participant Doc as AxcutDocument
+ participant TSD as src/native/sceneDescription.ts
+ participant Overlay as NativeCompositorOverlay.tsx
+ participant Hook as useNativeCompositorView.ts
+ participant IPC as native-bridge:invoke<br/>(compositor domain)
+ participant Svc as compositorViewService.ts
+ participant Addon as compositor_view.node
+ participant Canvas as renderer <canvas>
+
+ Doc->>TSD: buildSceneDescription(doc, settings)
+ TSD-->>Overlay: SceneDescription JSON
+ Overlay->>IPC: setScene(viewId, json)
+ IPC->>Svc: dispatch
+ Svc->>Addon: setScene(id, json)
+
+ Overlay->>Hook: ResizeObserver on canvas
+ Hook->>IPC: setRect(viewId, deviceRect)
+ IPC->>Svc: dispatch
+ Svc->>Addon: setRect(id, rect)
+ Addon-->>Svc: ok
+
+ Note over Addon,Canvas: compositing thread runs off-screen<br/>(D3D11VA decode → compositor → RGBA8 staging)
+
+ loop every other rAF tick (~30 fps)
+ Hook->>IPC: readFrame(viewId, lastGen)
+ IPC->>Svc: dispatch
+ Svc->>Addon: readFrame(id, sinceGen)
+ alt same generation or no frame
+ Addon-->>Svc: null
+ Svc-->>Hook: null
+ Hook-->>Canvas: (canvas untouched, idle path costs nothing)
+ else new generation
+ Addon-->>Svc: { gen, width, height, data }
+ Svc-->>Hook: { gen, width, height, data }
+ Hook->>Hook: validate byteLength === width*height*4
+ Hook->>Canvas: canvas.width = width; canvas.height = height<br/>createImageBitmap → drawImage
+ Hook->>Hook: lastGen = gen
+ end
+ end
+
+ Overlay->>IPC: setActiveClip(viewId, screenPath, webcamPath,<br/>webcamOffsetSec, clipIndex, sourceTimeSec)
+ IPC->>Svc: dispatch
+ Svc->>Addon: setActiveClip(...)
+ Overlay->>IPC: setPlaying(viewId, playing) (per play/pause)
+ IPC->>Svc: dispatch
+```