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): cross-platform recording, and the native bridge

Etienne Lescot923fca723527
diff --git a/technical-documentation/architecture/native-bridge.md b/technical-documentation/architecture/native-bridge.md
index ef320f777..029d8dad1 100644
--- a/technical-documentation/architecture/native-bridge.md
+++ b/technical-documentation/architecture/native-bridge.md
@@ -1,39 +1,91 @@
-# Native Bridge Architecture
+# Native bridge architecture
-## Goal
-
-Provide a single, resilient source of truth for platform-native capabilities while keeping Electron transport thin and renderer APIs unified.
+The native bridge gives renderer code one typed interface for platform capabilities, project state, cursor telemetry, compositing, and AI-edition services. Shared contracts and the renderer client live in `src/native/`; Electron handlers and domain services live in `electron/ipc/` and `electron/native-bridge/`.
## Layers
-1. Native adapters
-Platform-specific providers implement stable domain interfaces such as cursor telemetry or system asset discovery.
+```mermaid
+flowchart LR
+ A[Native adapters\nplatform-specific capture/assets] --> S[Main-process services\nelectron/native-bridge/services]
+ S --> I[Unified IPC transport\nelectron/ipc/nativeBridge.ts]
+ I --> R[Renderer client\nsrc/native/client.ts]
+ R --> B[React components]
+```
+
+1. **Native adapters** implement platform-facing interfaces. Cursor telemetry is adapted by `electron/native-bridge/cursor/telemetryCursorAdapter.ts`; native compositor loading is isolated in the compositor service.
+2. **Main-process services** own state and domain behavior. They receive a `NativeBridgeStateStore` and application callbacks from `NativeBridgeContext` rather than exposing Electron primitives to React.
+3. **Unified IPC transport** is registered by `registerNativeBridgeHandlers` in `electron/ipc/nativeBridge.ts`. It handles one channel, validates the request shape, dispatches by domain and action, and wraps every result.
+4. **Renderer client** in `src/native/client.ts` generates request IDs, invokes the preload transport, unwraps successful data, and throws the contract error for failures. Renderer features use `nativeBridgeClient` rather than importing main-process services.
+
+The boundary is deliberately narrow: adapters know how to talk to an operating system or native addon; services translate that capability into app-domain operations; IPC carries typed data; the renderer consumes promises.
+
+## The invoke contract
+
+The transport channel and protocol version are constants in `src/native/contracts.ts`:
+
+```ts
+export const NATIVE_BRIDGE_CHANNEL = "native-bridge:invoke";
+export const NATIVE_BRIDGE_VERSION = 1;
+```
+
+`NativeBridgeRequest` is a discriminated union. Each request supplies a `domain`, an `action`, an optional action-specific `payload`, and an optional `requestId`. The handler first accepts only values with string `domain` and `action`; the union then supplies the compile-time list of valid operations.
+
+Responses use the `NativeBridgeResponse<TData>` union. A successful response is `NativeBridgeSuccess<TData>`:
+
+```ts
+interface NativeBridgeSuccess<TData> {
+ ok: true;
+ data: TData;
+ meta: NativeBridgeMeta;
+}
+```
+
+A failed response is `NativeBridgeFailure`:
+
+```ts
+interface NativeBridgeFailure {
+ ok: false;
+ error: NativeBridgeError;
+ meta: NativeBridgeMeta;
+}
+```
+
+`NativeBridgeMeta` contains the protocol `version`, the request ID, and `timestampMs`. `NativeBridgeError` contains a stable `code`, a user-facing `message`, and a `retryable` boolean. The defined `NativeBridgeErrorCode` values are `INVALID_REQUEST`, `UNSUPPORTED_ACTION`, `NOT_FOUND`, `UNAVAILABLE`, and `INTERNAL_ERROR`. Handlers create metadata even when a request is malformed, so callers can correlate failures.
+
+The single channel is `native-bridge:invoke`, registered with `ipcMain.handle` in `electron/ipc/nativeBridge.ts`. The preload exposes `invokeNativeBridge`; `src/native/client.ts` adds a UUID request ID when the caller omitted one and forwards the request. `requireNativeBridgeData<TData>` checks `ok`, returns `data` on success, and throws with the contract error message otherwise.
+
+Capabilities are queried with the `system` / `getCapabilities` request and return `SystemCapabilities`. That type reports the bridge version and normalized `NativePlatform`, cursor capabilities (`telemetry`, `systemAssets`, and `provider`), and whether a current project context is available. `nativeBridgeClient.system.getCapabilities()` is the capability query; clients should use it before attempting optional native behavior.
+
+## Services
+
+The files under `electron/native-bridge/services/` each own one domain. The IPC handler constructs them once during `registerNativeBridgeHandlers` and dispatches requests to the appropriate instance.
+
+| Service | What it owns |
+| --- | --- |
+| `systemService.ts` | Normalized platform identity, asset-base-path resolution, and the aggregate system/cursor capability response. |
+| `projectService.ts` | Current project/video context and project file load, save, path, and clear operations. |
+| `cursorService.ts` | Cursor capability reporting plus loading complete cursor recording data and telemetry through the cursor adapter. |
+| `compositorViewService.ts` | The native compositor-view addon lifecycle and view operations, with a safe no-op when the addon is unavailable. |
+| `aiEditionService.ts` | AI-edition project/document operations, LLM configuration actions, chat sessions, streaming chat, undo/rewind, context usage, and timeline operations. |
-2. Main-process services
-Services orchestrate adapters, own runtime state, and expose domain-level operations.
+The service table describes domains, not every action. The action-to-service mapping remains in the central dispatcher, which keeps transport validation and response envelopes consistent.
-3. Unified IPC transport
-Renderer code talks to a single `native-bridge:invoke` channel using versioned contracts.
+## The browser shim
-4. Renderer client
-React code should consume `src/native/client.ts` rather than binding directly to ad hoc Electron APIs.
+`src/native/browserShim.ts` detects a plain browser by the absence of `window.electronAPI` and by the `browser` or editor-window URL mode. In that mode it supplies a browser implementation of the expected surface so the renderer can run without an Electron shell. It fakes plausible desktop sources for the source picker, stores recording preferences in `localStorage`, uses a hidden file input and blob URLs for video selection, and provides project, chat, and LLM state backed by browser storage. Its `invokeNativeBridge` returns a successful null-shaped response for operations that do not need a browser implementation.
-## Principles
+The shim exists for fast renderer development in Chrome or Firefox: desktop capture, file dialogs, native addons, and main-process services do not exist in a normal browser tab. It therefore preserves the renderer's boot and interaction paths without pretending that browser mode has the native capability itself.
-- Single source of truth: runtime-native state lives in the Electron main process.
-- Capability-first: renderer can query support before attempting native behavior.
-- Versioned contracts: requests and responses are explicit and evolve predictably.
-- Resilience: every response uses a consistent result envelope with stable error codes.
+A new bridge operation must have a browser-shim entry when renderer code can call it in browser mode. Add the corresponding fake or safe default to `createShimElectronAPI` or `createShimBridgeClient`; otherwise browser-mode development breaks when the renderer reaches that operation. The shim's shape must continue to match the preload-facing API closely enough that the real client and browser client remain interchangeable.
-## Current rollout
+## Invariants
-This repository now contains the initial scaffold:
+- Renderer code crosses the native boundary through `src/native/client.ts` and its domain clients.
+- Main-process state stays behind services and `NativeBridgeStateStore`; it is not reconstructed independently in each renderer.
+- Every response carries `NativeBridgeMeta`, and every failure uses a `NativeBridgeErrorCode` rather than an arbitrary transport exception.
+- Capability probing is explicit. An unavailable addon or platform feature returns a capability or `UNAVAILABLE` result instead of making renderer code guess from the platform string.
+- The preload remains the only renderer-to-main transport surface for this bridge. `electron/preload.ts:22` exposes the `electronAPI` object, including its `invokeNativeBridge` method; the legacy object is still present for compatibility, while new native operations belong on the unified bridge.
-- shared contracts in `src/native/contracts.ts`
-- renderer SDK in `src/native/client.ts`
-- main-process state store in `electron/native-bridge/store.ts`
-- cursor telemetry adapter in `electron/native-bridge/cursor/telemetryCursorAdapter.ts`
-- domain services in `electron/native-bridge/services/*`
-- unified handler registration in `electron/ipc/nativeBridge.ts`
+## Known gaps
-The legacy `window.electronAPI` surface still exists for backward compatibility. New native-facing features should prefer the unified bridge client.
\ No newline at end of file
+The legacy `window.electronAPI` surface still exists in `electron/preload.ts:22` and remains broader than the unified native bridge. It is retained for compatibility with existing recording, project-window, and file operations. New native-facing operations should not extend that ad hoc surface: they should add a contract request, a service dispatch, a renderer client method, and a browser-shim entry.
diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.md
index 6ddd74557..ba58726ea 100644
--- a/technical-documentation/architecture/recording.md
+++ b/technical-documentation/architecture/recording.md
@@ -1,252 +1,62 @@
-# Windows Native Recorder Roadmap
-
-OpenScreen's Windows recorder should be owned by one native backend. Electron capture can remain available for non-Windows platforms and temporary developer diagnostics, but Windows production recording should not silently fall back to `getDisplayMedia` / `MediaRecorder`.
-
-## Goals
-
-- Capture displays and windows through Windows Graphics Capture (WGC).
-- Render the native Windows cursor as OpenScreen's high-quality scalable cursor overlay.
-- Capture system audio through WASAPI loopback.
-- Capture microphone audio through WASAPI.
-- Mix system audio and microphone audio into the primary screen recording.
-- Capture webcam video natively and compose it into the Windows helper MP4 during the native-recording migration.
-- Keep preview/export aligned because screen video, audio, webcam, and cursor share one native timing origin.
-- Keep exported MP4s Windows-friendly: H.264 video plus AAC audio. Opus-in-MP4 is not an acceptable Windows export target.
-- Package the native helper with the Windows app.
-
-## Non-Goals
-
-- Replacing the editor/export pipeline.
-- Replacing the editor/export pipeline. A later pass can reintroduce a separate editable native `webcamVideoPath`; the current Windows-native milestone prioritizes a helper-owned multi-flux MP4 with deterministic screen/audio/mic/webcam sync.
-- Adding a native fallback for macOS or Linux in this branch.
-
-## Target Architecture
-
-The renderer keeps the existing recording controls. On Windows, `useScreenRecorder` sends a complete recording request to Electron and does not assemble Windows `MediaStream` tracks with `MediaRecorder`.
-
-Electron owns the native recording session:
-
-- resolves the selected source;
-- resolves output paths;
-- starts cursor sampling;
-- starts the helper process;
-- sends pause/resume/stop/cancel commands;
-- writes `RecordingSession` manifests;
-- reports explicit errors when a Windows-native capability is unavailable.
-
-The helper owns Windows media capture:
-
-- WGC screen/window frames;
-- WASAPI system loopback;
-- WASAPI microphone input;
-- Media Foundation webcam capture;
-- DirectShow webcam fallback for virtual cameras not visible to Media Foundation;
-- Media Foundation encoding/muxing;
-- stream timestamp normalization.
-
-## Helper Contract V2
-
-The helper receives a single JSON argument:
-
-```json
-{
- "schemaVersion": 2,
- "recordingId": 1234567890,
- "source": {
- "type": "display",
- "sourceId": "screen:0:0",
- "displayId": 123,
- "windowHandle": null,
- "bounds": { "x": 0, "y": 0, "width": 1920, "height": 1080 }
- },
- "video": {
- "fps": 60,
- "width": 1920,
- "height": 1080,
- "bitrate": 18000000
- },
- "audio": {
- "system": { "enabled": true },
- "microphone": { "enabled": true, "deviceId": "default", "gain": 1.4 }
- },
- "webcam": {
- "enabled": true,
- "deviceId": "default",
- "deviceName": "Camera (NVIDIA Broadcast)",
- "width": 1280,
- "height": 720,
- "fps": 30,
- "bitrate": 18000000
- },
- "outputs": {
- "screenPath": "C:\\Users\\me\\recording-123.mp4",
- "manifestPath": "C:\\Users\\me\\recording-123.session.json"
- }
-}
-```
-
-The helper emits newline-delimited JSON events to stdout:
-
-```json
-{ "event": "ready", "schemaVersion": 2 }
-{ "event": "recording-started", "timestampMs": 1234567890 }
-{ "event": "warning", "code": "audio-device-unavailable", "message": "..." }
-{ "event": "recording-stopped", "screenPath": "..." }
-{ "event": "error", "code": "unsupported-window-source", "message": "..." }
-```
-
-During migration, Electron also accepts the current textual helper messages so existing display-only smoke tests keep working.
-
-## Implementation Phases
-
-### 1. Native Session Boundary
-
-- Add a structured Windows native recording request type.
-- Pass source kind, audio flags, microphone device, webcam flags, and output paths into the helper.
-- On Windows, do not silently fall back to Electron capture. If the helper is unavailable or a native feature is missing, show a clear error.
-- Keep Electron fallback only for non-Windows and optional developer diagnostics.
-
-Acceptance:
-
-- Display-only recording still works.
-- Enabling an unsupported native feature returns an explicit native error instead of recording through Electron.
-
-### 2. WASAPI System Audio
-
-Status: initial implementation landed. The helper captures the default render endpoint with WASAPI loopback, passes the runtime mix format into `MFEncoder`, and muxes AAC audio into the primary MP4. Long-run drift correction and explicit silence insertion remain follow-up hardening work.
-
-- Add `WasapiLoopbackCapture`.
-- Capture the default render endpoint in shared loopback mode.
-- Keep `WasapiLoopbackCapture` responsible only for device activation, packet capture, and packet timestamps.
-- Keep `MFEncoder` responsible for all Media Foundation stream definitions and muxing.
-- Feed the endpoint mix format into `MFEncoder` as the single source of truth for audio stream shape: sample rate, channel count, bits per sample, block alignment, average bytes/sec, and subtype (`PCM` or `Float`).
-- Encode the primary screen MP4 with H.264 video and AAC audio through one `IMFSinkWriter`.
-- Timestamp audio from the captured frame count in 100ns units. The first implementation uses the WASAPI packet timeline; later drift correction will add explicit silence or resampling if long recordings show measurable clock skew.
-- Treat microphone mixing as a later phase. System loopback must land first without introducing renderer-side audio code.
-
-Acceptance:
-
-- Screen MP4 has an AAC audio track when system audio is enabled.
-- A 5-minute recording has audio/video duration drift below one frame.
-
-SSOT rules for this phase:
-
-- `src/lib/nativeWindowsRecording.ts` is the renderer/main TypeScript request contract.
-- `docs/engineering/windows-native-recorder-roadmap.md` is the feature-level contract and phase checklist.
-- `WgcSession::captureWidth()/captureHeight()` is the encoded screen frame size until a dedicated native scaling stage exists.
-- `WasapiLoopbackCapture::inputFormat()` is the runtime audio format source used by `MFEncoder`.
-- The renderer passes both the browser webcam `deviceId` and selected display label as `deviceName`; `electron/native/wgc-capture/src/webcam_capture.*` is the only place that maps those values to Media Foundation devices.
-- Electron resolves the selected label to a DirectShow filter CLSID once and passes it as `webcamDirectShowClsid`; the helper must not independently guess among DirectShow filters.
-- No duplicated hard-coded audio format assumptions in `main.cpp`.
+# Recording architecture
-### 3. WASAPI Microphone
+Recording is a cross-platform session coordinated by Electron and rendered by a platform capture path. The recorder and HUD live in `src/components/launch/` and `src/hooks/useScreenRecorder.ts`; native capture helpers live in `electron/native/`, while Linux uses Chromium's display-media APIs.
-Status: initial implementation in progress. The helper can open the default WASAPI capture endpoint, apply the OpenScreen microphone gain, encode mic-only audio, and mix system loopback plus microphone through a single queued `AudioMixer` timeline when both endpoints expose the same runtime format. Audio endpoints are warmed before WGC starts, the mixer drops pre-roll and begins its paced timeline on the first encoded video frame, then cuts queued tail audio on stop so the MP4 does not drift past the video. Browser `deviceId` to MMDevice id mapping, resampling between mismatched endpoint formats, and drift correction remain follow-up hardening work.
+## Lifecycle
-- Add microphone device enumeration and stable device-id mapping.
-- Capture selected/default microphone through WASAPI.
-- Apply OpenScreen's current mic gain policy.
-- Mix microphone and system audio before AAC encoding.
-
-Acceptance:
-
-- Mic-only, system-only, and mixed audio recordings produce a valid AAC track.
-- Device unplug/permission failure produces an explicit error or warning.
-
-### 4. Webcam Capture
-
-Status: the webcam encoder's `writeBgraFrame()` calls are paced to real elapsed wall-clock time, anchored to the same recording-start origin used by screen video and the audio mixer (`CaptureControl::recordingStartedAt`) and reduced by the same accumulated pause duration (`CaptureControl::pausedDurationHns()`), duplicating the latest available camera frame when the camera hasn't produced a newer one by the next due slot. This replaced a `frameIndex / fps` clock that was purely a local counter with no anchor to the recording's actual start time or accumulated pause duration, so it drifted out of alignment with screen video and audio.
-
-Note: an earlier iteration of this fix tried timestamping each webcam frame with its true per-frame host-clock capture time (i.e. genuine variable-frame-rate timestamps) and passing that through to the encoder. That was verified *not* to work: Media Foundation's H.264 encoder MFT does not honor irregular per-sample timestamps for a VFR source -- empirically, correctly-varying, monotonically increasing input `SampleTime` values still produced perfectly evenly-spaced output samples, because the encoder numbers output samples sequentially at its configured nominal frame rate regardless of the timestamp attached to each input sample. Since the encoder can't be made to respect real capture time, the encoder's assumption is instead made true by controlling *when* `writeBgraFrame()` is called (a real-time-paced cadence), rather than *what timestamp* is attached to each call.
-
-- Add Media Foundation webcam source reader.
-- Select requested dimensions/fps or the nearest format accepted by Media Foundation.
-- Convert webcam samples to BGRA and compose them into the primary helper MP4 as an initial bottom-right picture-in-picture overlay.
-- Ignore black webcam warmup frames and keep the overlay hidden until the first visible frame is available, so virtual cameras do not flash a black picture-in-picture rectangle at recording start.
-- Keep the helper process as the SSOT for screen/window, WASAPI system audio, microphone, webcam, and mux timing.
-- Match the requested webcam through Media Foundation friendly names first, then browser device ids/symbolic links, so UI selection remains stable across Chromium and Windows native device namespaces.
-- Use the Electron-resolved DirectShow CLSID when the selected virtual camera, for example NVIDIA Broadcast, is registered for DirectShow but absent from Media Foundation enumeration.
-- Later: promote the same webcam capture source to a separate editable native `webcamVideoPath` if product requirements need post-recording layout edits.
-
-Acceptance:
-
-- Native display/window recordings can include webcam without returning to Electron capture.
-- `npm run test:wgc-webcam:win` validates the helper path when a webcam is available and skips explicitly when no webcam device exists.
-- Combined webcam + system audio + microphone produces one MP4 with H.264 video and AAC audio.
-
-### 5. Native Window Capture
-
-Status: initial implementation in progress. Electron parses the `window:<HWND>:...` desktop source id through the shared native Windows recording contract and passes `windowHandle` to the helper. The helper resolves the `HWND`, validates it with `IsWindow`, and creates the WGC item with `CreateForWindow(HWND)`. Resize/minimize/move hardening and protected-window diagnostics remain follow-up work.
-
-- Resolve Electron `window:*` selections to an `HWND`.
-- Use WGC `CreateForWindow(HWND)`.
-- Handle window close, minimize, resize, DPI scaling, and monitor moves.
-- Return clear errors for unsupported protected windows.
-
-Acceptance:
-
-- Capturing a normal app window works with cursor/audio/mic/webcam.
-- Window resize and movement do not corrupt the recording.
-
-### 6. Runtime Controls
-
-- Add pause/resume commands to the helper.
-- Add cancel command that removes partial screen/webcam outputs.
-- Keep restart as stop-discard-start from Electron until the helper supports a native restart event.
-
-Acceptance:
+```mermaid
+flowchart LR
+ H[HUD] --> S[Pick source]
+ S --> C[Countdown]
+ C --> R[Capture]
+ R --> T[Stop]
+ T --> F[Files on disk]
+ F --> E[Editor opens]
+```
-- Pause/resume keeps preview duration coherent.
-- Cancel leaves no stale media/session/cursor files.
+The HUD starts and controls a recording. The source selector chooses a display or window and the countdown gives the user time to prepare. Electron resolves the source and output paths, starts the selected capture backend, and records cursor telemetry alongside media. Stop finalizes the media and session files; the resulting paths are passed to the editor as recording assets.
-### 7. Test Pipeline
+## The HUD
-- `npm run test:wgc-helper:win`: display-only helper smoke test.
-- `npm run test:wgc-audio:win`: validates AAC track presence and duration.
-- `npm run test:wgc-window:win`: captures a fixture window by HWND.
-- `npm run test:wgc-webcam:win`: validates webcam output when a webcam is available, otherwise skips explicitly.
-- Packaging check: confirms the helper is in `app.asar.unpacked`.
-- Export check: exported MP4s generated from native recordings keep an AAC audio track when the source has audio.
-- `npm run test:wgc-mic:win`: validates default-microphone capture writes an AAC track when an input endpoint is available.
-- `npm run test:wgc-mixed-audio:win`: validates system loopback plus microphone writes one mixed AAC track when endpoint formats are compatible.
+`LaunchWindow` is the recording controller. Its control row exposes recording, pause, source, microphone, system-audio, webcam, cursor, settings, and stop/restart actions through the HUD controls. The overlay is click-through (`setIgnoreMouseEvents(true, { forward: true })` in `electron/windows.ts`), so it does not intercept the application being recorded; the HUD's own controls temporarily opt into pointer handling through the overlay IPC path.
-## Backlog
+Electron applies `setContentProtection(true)` to the HUD window (`electron/windows.ts:31`). This keeps the controller out of captures and also makes it invisible in screenshots. For a testing session only, `OPENSCREEN_DISABLE_CONTENT_PROTECTION=1` disables the protection; the code warns that the HUD then appears in captures. The tray icon is the reliable way to refocus OpenScreen or stop a recording when the click-through HUD is not convenient or is not visible.
-### Native Cursor Click Bounce Is Not Visibly Applied
+## Capture backends
-Status: open. Do not treat Windows native cursor `Click Bounce` as shipped.
+| Platform | Backend | Code | Produces |
+| --- | --- | --- | --- |
+| Windows | Windows Graphics Capture (WGC) helper (C++/Win32), with WASAPI and Media Foundation support | `electron/native/wgc-capture/` and `electron/windows.ts` | H.264 MP4 screen/window video; system/microphone AAC when enabled; webcam is muxed into the primary MP4 unless a separate webcam path is requested |
+| macOS | ScreenCaptureKit helper (Swift), with AVFoundation/VideoToolbox encoding | `electron/native/screencapturekit/` and `electron/native/README.md` | H.264 MP4 screen/window video and ScreenCaptureKit system audio; microphone may be native where supported; webcam currently remains a separate Electron sidecar |
+| Linux | Electron `getDisplayMedia` path | `src/hooks/useScreenRecorder.ts` and Electron recording IPC | Browser-recorded display/window media, with the session's separate media and telemetry files |
-Problem:
+The division is an invariant: the native helper owns capture, timing, and encoding; Electron owns session orchestration, output-path selection, persistence, and editor handoff. Linux keeps those media responsibilities in Electron because it has no native helper path here.
-- The cursor settings UI exposes `Size`, `Smoothing`, `Motion Blur`, and `Click Bounce`.
-- On Windows native cursor recordings, `Size`, `Smoothing`, and `Motion Blur` are visibly applied in preview/export.
-- `Click Bounce` still has no visible effect in manual packaged-app testing, even after adding click-related sample metadata.
+## Helper contract
-What has already been tried:
+A native session is a child process boundary. Electron starts the platform helper with one structured JSON request and sends runtime commands on stdin; `stop` finalizes the output. The helper emits newline-delimited JSON events on stdout. The shared shape contains `schemaVersion`, `recordingId`, a `source` (display or window and its bounds), `video`, `audio`, optional `webcam`, optional cursor mode, and `outputs` paths. The helper reports `ready`, `recording-started`, warnings, errors, and `recording-stopped` events. Windows accepts legacy textual start/stop messages during compatibility handling; the structured events are the reference contract.
-- Added `interactionType: "click" | "mouseup" | "move"` to native cursor samples.
-- Added polling-based left-button state through `GetAsyncKeyState`.
-- Added the `GetAsyncKeyState` low-bit path to catch quick clicks between samples.
-- Added a PowerShell/C# `WH_MOUSE_LL` mouse hook experiment and launched the sampler through a temporary `.ps1` file to avoid Windows command-line length limits.
-- Updated `npm run test:cursor-native:win` so the diagnostic can observe a synthetic short click and emit `clickSampleCount`.
+| Contract field or behavior | Windows | macOS |
+| --- | --- | --- |
+| Schema | `schemaVersion: 2` | `schemaVersion: 1` |
+| Source identity | `sourceId`, `displayId`, optional `windowHandle` | `sourceId`, `displayId`, optional `windowId` |
+| Video | FPS, dimensions, bitrate | FPS, dimensions, bitrate, and `hideSystemCursor` |
+| Audio | System loopback and selected microphone flags/device metadata | System audio and microphone flags/device metadata; microphone support is runtime-gated |
+| Webcam | Native Media Foundation first, exact Electron-resolved DirectShow fallback; muxed into primary MP4 by default | Electron sidecar attached to the session |
+| Output | `screenPath`, session manifest, and optional `webcamPath` | `screenPath` and session manifest |
+| Runtime control | stdin pause/resume/stop/cancel; JSON events plus legacy text compatibility | Process events and the same lifecycle commands as the process boundary evolves |
-Current diagnosis:
+Electron resolves selected sources, devices, and paths before launching the helper. The helper does not guess a DirectShow camera: Windows receives the resolved selection. A helper error is reported explicitly rather than silently switching a Windows native feature to browser capture.
-- The diagnostic can observe synthetic click events, but this has not translated into a visible `Click Bounce` effect in the real packaged app.
-- The test currently proves that some click metadata can be recorded, not that the full OpenScreen record -> preview -> export path displays a bounce at the expected time.
-- The current native implementation may be animating from metadata that is not present in the real recording session, may be using the wrong timestamp origin, or may be applying a scale change too subtle to notice on the DOM/native cursor path.
+## Output files and sidecars
-Next investigation when resumed:
+A session writes a screen video and a `.session.json` manifest. Windows normally muxes the webcam into that MP4; when `webcamPath` is supplied, it writes a separate webcam video. macOS currently writes the webcam as a separate Electron sidecar (`webcamVideoPath`) because native webcam composition is not part of the helper. Linux follows the Electron recorder's separate media-path convention. Audio that the selected backend captures is encoded into its screen output.
-- Inspect the actual `.cursor.json`/session sidecar generated by a packaged-app manual recording and confirm whether real clicks produce `interactionType: "click"` at the right `timeMs`.
-- Add a targeted end-to-end fixture that records a known click, loads the generated project, and asserts the preview/export cursor scale changes across adjacent frames.
-- Compare the native DOM cursor path against the older `PixiCursorOverlay` click visual state and decide whether native cursor bounce should be a scale-only animation, an additional click ring, or a short explicit keyframe animation independent of sample cadence.
-- If event capture remains unreliable in the PowerShell sampler, move click events into a small native cursor helper instead of PowerShell/C# script injection.
+Cursor samples are persisted as cursor telemetry rather than baked into editable-overlay recordings. The loader resolves the sidecar at `<videoPath>.cursor.json` or through the recording links; see [cursor.md](cursor.md) for the telemetry format and rendering path.
-## Ship Criteria
+## Known gaps
-- Windows display capture works with cursor, system audio, microphone, and webcam.
-- Windows window capture works with cursor, system audio, microphone, and webcam.
-- Preview and export show no cursor position drift.
-- Preview and export show no measurable audio/video/webcam drift.
-- Windows production builds do not depend on Electron capture fallback.
+- A window with odd client dimensions can produce black video: H.264 encoding requires even dimensions (`electron/native/wgc-capture/src/wgc_session.cpp:38`).
+- Stopping a recording can hang on the software encoder path (`electron/native/wgc-capture/src/main.cpp:755`).
+- Linux/Wayland can produce no usable frames because Chromium initializes Vulkan against the Ozone Wayland backend.
+- `preferSoftwareEncoder` is read when recording starts. The recorder has no UI for setting it; Windows also accepts `OPENSCREEN_WGC_PREFER_SOFTWARE_ENCODER=true` in the helper request path.