Skip to content

Free open-source image editor for the browser

Clarify architecture and validation guidelines (#23)

Rodrigo Belfioreee4c0d748b33
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..d452fe5
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,23 @@
+## Change
+
+<!-- Describe the problem and resulting behavior. -->
+
+## Validation
+
+<!-- Report the four required checks from README.md and any verification gaps. -->
+
+## Visual evidence
+
+<!-- UI additions or changes: embed actual screenshots with the affected controls
+visible in context for visual approval. Show before/after for existing UI changes
+and representative states for new UI. Rendered output alone is insufficient.
+Rendering changes: also show before/after output. Nonvisual code changes: show
+the exercised workflow. Name the fixture and settings; images must be accessible
+from this PR. Documentation-only changes may mark this section not applicable. -->
+
+## Rendering performance
+
+<!-- Follow PERFORMANCE.md: reproducible base/head comparison, workload and
+environment, timing scope, sample counts, median/p95, and interpretation.
+Separate neutral/bypass overhead from the cost of new active behavior.
+If rendering work is unaffected, explain why. Report missing evidence explicitly. -->
diff --git a/AGENTS.md b/AGENTS.md
index c876681..f322835 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,70 +1,71 @@
# OpenLight
-A Vite, React, and vgpu app. Bun for install and scripts. Biome for format and lint.
+Build a professional photo editor with little, readable code. Vite, React, vgpu, Bun, and Biome.
-Demonstrate a professional photo editor with little, readable code.
+Write committed code, comments, documentation, and UI text in English. Use [CONTEXT.md](CONTEXT.md) for domain terms. [README.md](README.md#development) covers setup; [API.md](API.md) documents browser commands; [REVIEW.md](REVIEW.md) guides reviews.
-`src/main.tsx` owns runtime and provider composition.
+## Simplicity
-Write committed code, comments, documentation, and UI text in English. Research drafts may use another language while uncommitted.
-Use `CONTEXT.md` for document, scene, and image-source terminology.
+- Give each module, function, and component one coherent responsibility. Entry points compose; resource owners manage their own lifecycles.
+- Judge simplicity across the complete operation, including callers and cleanup. Moving lines into forwarding helpers does not simplify it. Keep cohesive work together; use no arbitrary file-size limits.
+- Start with direct functions and library calls. Add abstractions, dependencies, validation, scheduling, or caching for a current requirement. Prefer a few repeated lines over coupling unrelated behavior.
+- Extract a component when a region owns distinct state, refs, or behavior. Keep helpers local unless they have a separate responsibility or a real shared use. Define functions above their consumers.
+- Keep control flow linear: guard clauses, braces, and `const` by default. Avoid nested ternaries and dense logic in JSX; use early returns or components for meaningful branches.
+- Model actual states with precise types and explicit dependencies. Keep one source of truth; avoid casts and permissive types that conceal mismatches. Validate external input at its boundary and preserve useful errors.
+- Prefer named exports and imports. Use a default export when an integration requires or clearly benefits from it.
-## Size
+## Layers and ownership
-Keep each file focused on one responsibility and one abstraction level. Entry points compose; providers, hooks, and domain modules own lifecycles and policy.
-Start with direct functions and thin UI composition. Add a layer only when it owns a distinct responsibility or removes duplication.
-Evaluate simplicity across the whole feature, including lifecycle code and consumers. Keep cohesive work together; moving lines into forwarding helpers is not a reduction.
-Prefer direct vgpu operations. Add wrappers, validation, scheduling, or caching only for a current requirement.
-One component per responsibility: when a component holds state or refs that only part of its markup uses, extract that part into its own component. Within a file, define a function above the function that uses it.
+| Layer | Owns |
+| --- | --- |
+| 0 — `lib/` | Low-level code independent of OpenLight: math and utilities that could be standalone libraries. Keep it here when maintaining the small implementation is cheaper than a dependency, or when it is a candidate for extraction. |
+| 1 — shared primitives | Infrastructure generic within OpenLight: engine contracts, document and resource management, reusable `components/` and `hooks/`. Engine code works without React; React bindings depend on it. |
+| 2 — `features/` | Removable product capabilities. A feature owns its processing, shaders, parameters, commands, components, and hooks as needed. Most product behavior belongs here. |
+| 3 — `app/` | Application shell, user entry points, and explicit composition of features and shared primitives. |
-## Engine and React
+Dependencies between layers point downward. Features do not import each other; `app/` connects them. Shared primitives must not import concrete features. Being reusable within OpenLight or independent of React does not qualify code for `lib/`.
-React owns UI composition, controls, and mounting engine outputs. Commands perform decoding and other processing imperatively, with explicit workspace or document dependencies. The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays outside React state and props.
+The current layout predates these boundaries: `lib/editor` contains shared engine code, and some feature processing still lives in `lib/`. Follow ownership for new code and migrate existing code when the task needs that boundary; do not turn an unrelated change into a directory reorganization.
-Hooks and providers connect stable imperative instances to mounting and cleanup. Each resource owner disposes what it creates. Canvas and histogram components attach engine outputs to the UI.
+Keep ordinary feature changes in the feature, its tests, and explicit app composition. Change shared primitives when a concrete requirement needs a new capability. Features need neither identical file layouts nor a universal plugin interface. Keep the histogram in its feature.
-Each document owns a vanilla Zustand scene store, history, and image resources. The scene contains serializable data and refers to image sources by ID; files and GPU targets stay outside history. The workspace owns document replacement and loading state. UI interactions and browser commands use the same imperative edits; history groups them without knowing loaders or tools.
+`src/` holds entrypoints, ambient types, and global styles. Use `@/` across folders and relative imports within a folder. `src/main.tsx` mounts the runtime and providers. `app/editor/modes.tsx` composes modes: a `Panel` uses the shared canvas; a `View` supplies its own viewport.
-## Structure
+## Engine and React
-Prefer named exports (`export function`) and named imports. Use default exports only when a concrete integration requires or clearly benefits from them, such as a worker loader or dynamic-import consumer that expects a default export.
+Keep document edits and rendering callable without React, a mounted UI, or an implicit active document. Pass workspace, document, and GPU dependencies explicitly. Feature processing must be importable without its React panel; keep browser input and display adapters outside processing.
-The `src/` root holds entrypoints, ambient types, and global styles. Import across folders through the `@/` alias (`@/hooks/use-pointer`); relative paths stay inside a folder. Source modules belong to these folders:
+Each document owns a vanilla Zustand scene store, history, and image resources. Scenes contain immutable, serializable content and image-source IDs; files and GPU resources stay outside history. The workspace owns document replacement and loading state.
-- `app/`: application shell, app-wide state, and composition. It may import every folder below; no folder imports it. `app/editor/modes.tsx` registers the editor modes: each mode is a `Panel` rendered into the shared panel over the shared canvas, or a `View` that brings its own viewport, like Crop.
-- `features/`: removable product capabilities. A feature owns its UI, state, and behavior; removing its folder and `app/` composition leaves the rest working. Features never import each other.
-- `components/`: generic React presentation grouped by role, such as `ui/` and `layout/`. It contains no product workflows.
-- `hooks/`: generic React hooks without OpenLight business logic.
-- `lib/`: framework-independent low-level code that could become an external package.
+UI controls and browser commands call the same imperative edits. History groups changes without knowing loaders or tools: a slider or curve gesture is one edit; cancellation restores the previous scene. Preview settings and navigation stay outside content history.
-Dependencies point downward: `app/` may import every folder; `features/` may import `components/`, `hooks/`, and `lib/`; `components/` and `hooks/` may import `lib/`.
-Keep feature-specific components, hooks, and helpers inside their feature. Move them to a generic folder only when their interface no longer contains feature concepts.
-Keep the histogram in `features/`; revisit its placement only when its responsibilities change.
+React composes controls and mounts engine outputs. The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays outside React state and props. Hooks and providers connect stable instances to mounting and cleanup. Every resource owner disposes what it creates.
## Styling
-Tailwind classes stay inline in the component that renders them; reuse styling by composing React components or repeating classes (whichever is fewer lines), never by sharing class-string constants across files. Use `cva` for a component's variants; promote a style to a token in `src/index.css` only when it is app-global, like a shadow or a font style.
+Keep Tailwind classes inline. Reuse presentation through components or repeat classes, whichever is simpler; do not share class-string constants across files. Use `cva` for variants and `src/index.css` for app-global tokens such as shadows and typography.
+
+## GPU invariants
+
+- Use `vgpu-react` for React bindings and `vgpu` for GPU operations. Create pipelines once per engine instance and reuse them.
+- Keep `.wgsl` beside its owner. The Vite loader and ambient types are configured.
+- The working space is linear Rec.2020 in `rgba16float`. Decoders convert into it; display converts out. Processing outputs preserve the input format and primaries unless the operation explicitly converts them.
+- The adjustment shader's parameters use UI units. Its fitted constants are calibration data; preserve them when reorganizing code.
+- Preserve HDR headroom through exposure, curves, and vibrance. Exposure clips negatives and applies one luminance gain to all channels. `display()` in `lib/color.wgsl` maps out-of-gamut colors toward their luminance.
+- TIFF and camera RAW use `raw-webgpu`. OpenLight adapts package resources to document ownership; codec implementation and coverage belong to the package.
-## GPU
+## Tests and completion
-All React bindings come from `vgpu-react`; everything else comes from `vgpu`.
+Prefer a few broad integration tests. Use Bun and real application modules with `vgpu/mock` for document, history, loader, and renderer orchestration. The mock does not execute shaders. Use Playwright for GPU pixels, browser interaction, and real format fixtures.
-- `useGpu()` returns the `Gpu`. Every vgpu call takes it as the first argument.
-- Build pipelines once per engine instance and reuse them across frames.
-- `useSurface(canvasRef, options)` turns a `<canvas>` into a render target and disposes it on cleanup. Changing `clearColor` updates the surface in place; changing other options recreates it.
-- `useFrameLoop` renders every animation frame. `useFrame` returns a function that renders once, for pointer and other events.
-- Shader code lives in `.wgsl` files beside the module that owns it, or in `lib/` for reusable GPU operations. The Vite loader and ambient types are already configured.
-- The working space is linear Rec.2020 in `rgba16float`. Decoders convert into it, the editor shader converts out of it; nothing in between assumes a format or primaries, so both can change (an 8-bit variant is planned).
-- `lib/adjustments/adjustments.wgsl` works in that space; its `Adjustments` struct mirrors the TypeScript type in the UI's units, and its constants were fitted against reference exports; treat them as data, not formulas to tidy.
-- `lib/decode` converts every format into the working space. Browser-decoded formats go through `linearize`. TIFF and camera RAW use `raw-webgpu`; OpenLight adapts the returned GPU resources to document ownership. Codec implementation and coverage belong to the package.
-- Samples above 1.0 (HDR) keep their headroom through exposure, curves, and vibrance; negatives clip at exposure. Exposure scales all channels by one luminance gain so hue holds, and `display()` in `lib/color.wgsl` maps out-of-gamut colors toward their luminance, so bright saturated light rolls off to white instead of clipping per channel.
+Extend the main editing session with named steps for controls, preview, histogram, undo/redo, and export. Steps may live in separate modules. Keep independent rendering and loading checks separate. Assert known pixel values with appropriate tolerances; changed state or screenshots alone do not establish rendering correctness.
-## Testing
+Maintain the semantic [control API](API.md) for local, CI, and remote use. Exercise UI behavior through the DOM. Wait for observable results; avoid production completion tracking added only for tests. Test the behavior being changed rather than forcing every feature through the same test structure.
-Prefer a few broad integration tests over many granular tests. Run document, history, loader, and renderer orchestration checks in Bun using real application modules and `vgpu/mock`. Keep GPU pixel, browser UI, and codec checks in Playwright; the mock does not execute shaders. Keep one main editing session that opens a fixture, changes controls, checks the preview and histogram, edits curves, uses undo/redo, and exports. Extend that session with named steps instead of adding a test per control. Check actual pixels against known values, with a small tolerance when needed; changed state or a changed screenshot alone does not prove correct rendering. Keep independent loading and rendering checks separate, and load real files for format coverage. Use browser-free tests for invariants that the editing session cannot meaningfully exercise. Codec libraries keep their tests and fixtures outside OpenLight; the app keeps only integration fixtures.
+Run `bun run check`, `bun run build`, `bun run test`, and `bun run test:browser` after changes and before a commit. Browser setup and focused commands are in [README.md](README.md#validation).
-Maintain a browser-side control API with semantic commands for loading, editing, and reading state. Extend it with new workflows; it must work in local browsers, CI, and remote sessions. Use DOM interaction when testing the UI itself. Wait for visible results without adding production completion tracking.
+Every code PR includes actual application screenshots or rendered output demonstrating the result. UI additions or changes require screenshots of the affected interface in context, with the new or changed controls visible for visual approval; rendered output alone is insufficient. Show before/after for changes to existing UI or image output, representative states for new UI, and the affected workflow for nonvisual code changes. Embed accessible images in the PR and name the fixture and settings. Documentation-only changes may mark visual evidence not applicable.
-## Done
+Assess performance on every code change; changes affecting GPU work require reproducible before/after evidence under [PERFORMANCE.md](PERFORMANCE.md). Report unavailable checks and measurements as verification gaps.
-`bun run check` formats and lints. `bun run build` type-checks. `bun run test` runs browser-free tests. `bun run test:browser` runs GPU/browser tests. Run all of them after changing files and before a commit; CI runs only the first three.
+Keep documentation close to its purpose and link rather than duplicate rules. Describe existing APIs accurately and label unimplemented designs explicitly.
diff --git a/API.md b/API.md
index 4cce8ca..3bd952e 100644
--- a/API.md
+++ b/API.md
@@ -1,6 +1,6 @@
# Control API
-`window.openlight` exposes the editor's commands while the app is mounted. Commands act on the current document. Load an image before editing or exporting.
+`window.openlight` is the browser entry point for the imperative [controls](src/app/controls.ts). It is available after the app initializes and acts on the current document. Load an image before editing or exporting. UI controls and this API use the same document edits.
## Example
@@ -30,7 +30,7 @@ These methods accept browser `File` objects and return `Promise<void>`. Await th
| `loadImage(file)` | Loads a file as an image, replacing the current document and its history. |
| `importXmp(file)` | Applies supported Camera Raw adjustments as one undoable edit. |
-Loading calls are queued. XMP import requires a loaded document and is skipped if none is ready. Image decoding failures appear in the workspace's error state and do not reject the loading promise. Check `getState().documentId` after loading to confirm a document is available.
+Loading calls are queued. XMP import is skipped if no document is ready; an invalid XMP import can reject without blocking later loads. Image decoding failures appear in the workspace's error state and do not reject the loading promise. Check `getState().documentId` to confirm success. Loading completion does not guarantee the preview has rendered.
## Editing
@@ -49,13 +49,15 @@ Loading calls are queued. XMP import requires a loaded document and is skipped i
`setColorMixer(color, change)` updates one of `red`, `orange`, `yellow`, `green`, `aqua`, `blue`, `purple`, or `magenta`. Supply any of `hue`, `saturation`, and `luminance`, each a finite number from -100 to 100. Other colors and unspecified channels keep their values. `resetColorMixer()` resets every color as one undoable edit. A full shift of 100 rotates hue by 30°, scales saturation from zero to double, or moves luminance by one stop, weighted by each pixel's distance to the color's Oklab hue. Hue and saturation edits preserve luminance, and neutrals are unaffected.
-For RAW sources, `setWhiteBalance({ temperature, tint })` sets absolute Kelvin and DNG tint, preserving unspecified values. Temperature accepts 2000–25000 K and tint accepts -150–150, with either range extended to include the file's As Shot value. `setWhiteBalance()` restores the source's initial balance. When camera multipliers are unavailable, that initial balance is the decoder's daylight fallback. The command throws for non-RAW sources or invalid values. Edits enter history immediately; preview development runs asynchronously, and export waits for the captured scene's development. The incremental temperature/tint adjustments remain separate RGB adjustments.
+For RAW sources, `setWhiteBalance({ temperature, tint })` sets absolute Kelvin and DNG tint, preserving unspecified values. Temperature accepts 2000–25000 K and tint accepts -150–150, extending either range to include the file's As Shot value. `setWhiteBalance()` restores that value (the decoder's daylight fallback if camera multipliers are unavailable). Non-RAW sources and invalid values throw. Incremental temperature/tint remain separate RGB adjustments.
-`editScene(change)` shallowly merges a partial [Scene](src/lib/editor/scene.ts) into the document as an undoable edit. Supply complete values for nested fields such as `frame`. Prefer `setAdjustments` and `setToneCurve` for their validation.
+Edits update the scene and history synchronously. Rendering may finish later, particularly RAW development. Tests should wait for visible results; `exportImage()` renders and waits for its captured scene independently of the preview.
+
+`editScene(change)` shallowly merges a partial [Scene](src/lib/editor/scene.ts) as an undoable edit. Supply complete nested values such as `frame`. This low-level command validates frame geometry only; prefer the adjustment, curve, color-mixer, and white-balance commands for their validation.
## History
-Each edit creates an undo step unless a group is open. Preview changes are outside history.
+Each content change creates an undo step unless a group is open. No-op edits add no history. Preview changes stay outside history. Groups do not nest.
| Method | Behavior |
| --- | --- |
@@ -65,9 +67,23 @@ Each edit creates an undo step unless a group is open. Preview changes are outsi
| `undo()` | Commits any open group, then undoes one step. |
| `redo()` | Commits any open group, then redoes one step if available. |
+Group related synchronous edits and cancel on failure. Finish asynchronous preparation before opening a group:
+
+```js
+editor.beginEdit();
+try {
+ editor.setAdjustments({ exposure: 0.5 });
+ editor.setToneCurve([{ x: 0, y: 0 }, { x: 0.5, y: 0.6 }, { x: 1, y: 1 }]);
+ editor.commitEdit();
+} catch (error) {
+ editor.cancelEdit();
+ throw error;
+}
+```
+
## Preview
-`setPreview(change)` updates only the supplied preview settings.
+`setPreview(change)` merges the supplied preview settings without runtime validation. Use the values below.
| Field | Values | Default |
| --- | --- | --- |
diff --git a/CONTEXT.md b/CONTEXT.md
index b3801ee..4004ee5 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -1,26 +1,14 @@
-# OpenLight
+# Domain terms
OpenLight edits documents containing image content and adjustments.
-## Language
+| Term | Meaning |
+| --- | --- |
+| **Document** | An independent editing session with its own canvas, history, and resources. Opening an image creates a document containing that image. |
+| **Scene** | The document's serializable content: canvas geometry, image-source references, and adjustments. Files and GPU resources live outside it. |
+| **Image source** | An image used as input to the document's composition. It is content within a document. |
+| **Edit** | One reversible content change. A continuous slider or curve drag is one edit, as is importing a set of adjustments. |
+| **Workspace** | The open-document session. It currently holds at most one document, replaced when another image is opened. |
+| **Mode** | An editor task area: Adjust, Layers, Retouch, Crop, or Export. Switching modes changes tools and panels, not the document. |
-**Document**:
-An independent editing session with its own canvas and history. Opening an image creates a document containing that image.
-_Avoid_: Image, input file, scene
-
-**Scene**:
-The current content of a document, including its canvas dimensions, image references, and adjustments.
-_Avoid_: Open file, texture
-
-**Image source**:
-An image used as input to a document's composition. It is content within the document, not the document itself.
-
-**Edit**:
-One reversible change to document content. A continuous slider or curve drag is one edit, as is importing a set of adjustments.
-
-**Workspace**:
-The application's open-document session. It currently contains at most one document, replaced when another image is opened.
-
-**Mode**:
-One of the editor's task areas: Adjust, Layers, Retouch, Crop, or Export. Switching modes changes the visible tools and panel, not the document.
-_Avoid_: Tab, page, persona, tool
+Use these names consistently in code, UI text, and documentation.
diff --git a/PERFORMANCE.md b/PERFORMANCE.md
new file mode 100644
index 0000000..e89faa7
--- /dev/null
+++ b/PERFORMANCE.md
@@ -0,0 +1,28 @@
+# Rendering performance
+
+Changes affecting GPU work require before/after evidence in the PR, including shader, pipeline, scheduling, and resource-lifetime changes. Measure intentional added cost separately from regressions in existing behavior. For changes that do not affect rendering work, explain why.
+
+## Measure the workload
+
+1. Record base and changed revisions, reproduction command or script, fixture, dimensions, working format, and parameters. Use the same device, backend, runtime, and flags for both revisions.
+2. Separate setup and first-render costs from repeated rendering. Warm up the measured path, collect repeated completed samples, and report warmup count, sample count, median, and p95. Report missing samples and differences within measurement noise.
+3. Measure affected passes or nodes and completed rendering. For a new effect, compare the previous workload with the changed revision's neutral or bypassed path, then report representative active cost. Include pass counts and intermediate texture sizes when they explain the result.
+4. Check correctness alongside timing. Investigate unexpected regressions and explain intentional tradeoffs before calling the change ready. Use workload-specific expectations rather than universal thresholds across hardware.
+
+| Measurement | Scope |
+| --- | --- |
+| CPU preparation | Work to prepare and encode commands. `performance.now()` around encoding measures this. |
+| GPU duration | Timestamped GPU passes. A sum covers only the measured passes. |
+| Completed-render latency | Elapsed time through completion of submitted work. State whether preparation, readback, display, or encoding is included. |
+
+Keep unrelated work off the queue during isolated measurements. Label software adapters such as SwiftShader: their results describe that backend, not hardware GPU performance. Do not extrapolate their timings or speedup ratios to physical GPUs; validate frame budgets on reference hardware. Mocks do not execute shaders. If timestamps are unsupported, measure completed-render latency and mark GPU timing unavailable; never substitute CPU encoding time or zero for a missing GPU measurement.
+
+## Instrumentation
+
+**Current:** the renderer composes passes directly. vgpu provides `timer(gpu)`, `timer.span(name)`, and `FramePassOptions.timer` for render-pass timing. The optional `timestamp-query` feature must be supported and enabled when creating the device. Results arrive asynchronously via `timer.onResults`; `gpu.settled()` covers pending timing readbacks in isolated runs or teardown. See the [vgpu guide](https://github.com/vercel-labs/vgpu/blob/main/docs/topics/performance-playbook.docs.md#13-time-passes-before-optimizing-timer).
+
+**Planned node contract:** a node is a processing operation that may execute several GPU passes. Shared, opt-in instrumentation must work without React, identify each node instance and its passes, and collect timing centrally. Nodes declare work; they do not implement their own timing framework. Report bypasses and missing coverage explicitly, and sum a node's GPU durations only when all its passes were measured. Keep interactive timing readback asynchronous, without a queue wait after every node. The node engine and shared profiler are not implemented yet.
+
+Fused shader operations share a pass duration; they are not individually timed. Compute dispatches and opaque package operations need supported instrumentation before claiming GPU timing coverage. Editing must work when profiling is unavailable.
+
+Include reproducible results and their interpretation in the PR. An isolated benchmark explains cost; the complete workload establishes application impact. An environment failure is a verification gap, not evidence of unchanged performance.
diff --git a/README.md b/README.md
index 647bf4e..60a86a5 100644
--- a/README.md
+++ b/README.md
@@ -1,27 +1,19 @@
# OpenLight
-**An open-source image editor for the browser, built with [vgpu.sh](https://vgpu.sh)**
+**An open-source photo editor for the browser, built with [vgpu.sh](https://vgpu.sh).**
-Image processing runs locally with WebGPU. Built with TypeScript and React.
+Image processing runs locally with WebGPU. Built with TypeScript and React; requires a WebGPU-capable browser.
## Features
-- Light and color adjustments
-- Color Mixer with eight hue, saturation, and luminance ranges
-- Tone curves
-- Clarity and sharpening
-- Crop, rotate, straighten, and flip
-- Undo and redo
-- Before/after comparison
-- RGB histogram
-- Highlight and shadow clipping overlays
-- Pan and zoom
-- Camera Raw XMP import
-- TIFF import at 16-bit and floating-point precision, decoded on the GPU
-- Camera RAW and DNG import through LibRaw, with absolute white balance and As Shot reset
-- PNG, JPEG, and WebP export with resizing, a live preview, and file size
-
-Requires a WebGPU-capable browser.
+- Light and color adjustments, tone curves, clarity, and sharpening.
+- Color Mixer with eight hue, saturation, and luminance ranges.
+- Crop, rotate, straighten, flip, pan, and zoom.
+- Undo/redo, before/after comparison, RGB histogram, and clipping overlays.
+- Camera Raw XMP import; HEIC, TIFF at 16-bit and floating-point precision, and camera RAW/DNG with absolute white balance and As Shot reset.
+- PNG, JPEG, and WebP export with resizing, live preview, and file size.
+
+Documents currently live in memory; export saves a flattened image. Layers and Retouch modes are placeholders.
RAW decoding and GPU development use [raw-webgpu](https://github.com/roprgm/raw-webgpu), which documents format support and limitations. OpenLight owns editing, history and preview/export lifetimes.
@@ -32,24 +24,63 @@ bun install
bun dev
```
-Run `bun run check` to format and lint, `bun run build` to type-check and build, and `bun run test` for integration tests. GPU and UI tests run with `bun run test:browser`, which requires Chromium with WebGPU.
+### Browser setup
-## Scripting
+Install the Chromium version matching the project's Playwright dependency:
-`window.openlight` exposes commands for loading, editing, undo/redo, and export. See the [API reference](API.md).
+```sh
+bunx --no-install playwright install --with-deps chromium
+```
-## License
+On Linux, installing system dependencies requires administrator access. If Chromium is already installed but libraries such as `libnspr4.so` are missing, run `bunx --no-install playwright install-deps chromium`. In environments without administrator access, use a browser environment with those dependencies supplied. See [Playwright's setup instructions](https://playwright.dev/docs/browsers#install-system-dependencies).
-[MIT](LICENSE)
+[playwright.config.ts](playwright.config.ts) starts Vite automatically and selects Chromium's bundled SwiftShader on Linux and Windows. Linux also uses SwiftShader's Vulkan backend for image transfers and offscreen export. These tests execute WebGPU on the CPU without a physical GPU or a separate SwiftShader installation. Use this configuration when testing; another browser session does not inherit its launch flags.
-The bundled RAW decoder includes separately licensed libraries. See [NOTICE](NOTICE).
+If the environment blocks local ports or browser processes, use its permitted execution mechanism. A launch failure or missing system library is an environment problem, not a shader failure.
+
+### Validation
+
+| Command | Checks |
+| --- | --- |
+| `bun run check` | Format and lint; writes fixes. |
+| `bun run build` | Type-check and production build. |
+| `bun run test` | Browser-free integration tests using real modules and `vgpu/mock`. |
+| `bun run test:browser` | GPU pixels, UI, and codec integration in Chromium. |
+
+Run all four after changes and before committing. [CI](.github/workflows/ci.yml) currently checks formatting/lint, Bun tests, and the build; it does not run browser tests.
+
+During development, select an existing test by path:
+
+```sh
+bun run test tests/renderer.test.ts
+bun run test:browser tests/rendering.e2e.ts --workers=1
+```
+
+One browser worker reduces CPU contention with SwiftShader. The mock does not execute shaders; use browser tests to check actual pixels. Reuse [browser fixtures](tests/fixtures.ts) and [image readers](tests/images.ts), and extend the [editing session](tests/editing.e2e.ts) for UI workflows.
+
+### Rendering benchmarks
+
+After [browser setup](#browser-setup), run `bun run test:browser --config playwright.bench.config.ts` separately from other GPU/browser work. It measures the renderer without the mixer, with neutral settings, and with all eight ranges active (hue 20, saturation 25, luminance 10). The fixture is a deterministic 2400×1600 linear Rec.2020 gradient containing neutrals, saturated colors, and HDR values; exposure is 0.25 and contrast is 10. Each workload uses 8 warmups and 40 measured samples.
+
+Results and rendered PNGs are written under `test-results/benchmarks`. JSON includes environment details, individual samples, median/p95, renderer setup, first render, completed-render latency, and isolated mixer GPU timestamps when supported. Display, readback, and image encoding run outside the measured rendering loop. Software-adapter results describe that backend only. A hardware measurement requires a browser configuration that does not force SwiftShader; record the adapter actually used.
+
+For revision comparisons, run the same benchmark files and browser configuration in both checkouts. Revisions predating the mixer can run `--grep 'rendering baseline'`. The benchmark is opt-in and excluded from the regular test suite; correctness remains covered by the GPU pixel test and editing session. See [PERFORMANCE.md](PERFORMANCE.md) for measurement scope and interpretation.
+
+## Scripting
+
+`window.openlight` exposes commands for loading, editing, undo/redo, and export. See the [API reference](API.md).
-## Rendering benchmarks
+## Contributing
-Install the matching browser with `bunx --no-install playwright install --with-deps chromium`. The Playwright configuration uses SwiftShader's Vulkan backend on Linux for rendering and image transfers without a physical GPU.
+- [AGENTS.md](AGENTS.md): architecture, ownership, coding rules, and completion requirements.
+- [CONTEXT.md](CONTEXT.md): domain vocabulary.
+- [REVIEW.md](REVIEW.md): review questions and actionable findings.
+- [PERFORMANCE.md](PERFORMANCE.md): rendering measurements and the planned node instrumentation contract.
-Run `bun run test:browser --config playwright.bench.config.ts` separately from other GPU/browser work. It measures the renderer without the mixer, with neutral settings, and with all eight ranges active (hue 20, saturation 25, luminance 10). The fixture is a deterministic 2400×1600 linear Rec.2020 gradient containing neutrals, saturated colors, and HDR values; exposure is 0.25 and contrast is 10. Each workload uses 8 warmups and 40 measured samples.
+Code PRs include visual evidence: UI additions or changes require screenshots of the actual interface for visual review. GPU changes also need a reproducible performance comparison. Use the [PR template](.github/pull_request_template.md) and the evidence rules in [AGENTS.md](AGENTS.md#tests-and-completion).
-Results and rendered PNGs are written under `test-results/benchmarks`. JSON includes environment details, individual samples, median/p95, renderer setup, first render, completed-render latency, and isolated mixer GPU timestamps when supported. Display, readback, and image encoding run outside the measured rendering loop. Software-adapter results describe that backend only.
+## License
-For revision comparisons, run the same benchmark files and browser configuration in both checkouts. Revisions predating the mixer can run `--grep 'rendering baseline'`. The benchmark is opt-in and excluded from the regular test suite; correctness remains covered by the GPU pixel test and editing session.
+[MIT](LICENSE)
+
+The bundled RAW decoder includes separately licensed libraries. See [NOTICE](NOTICE).
diff --git a/REVIEW.md b/REVIEW.md
index acf7888..e03e46c 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -1,60 +1,19 @@
-# Code Review
+# Code review
-Code should read like a small, complete example from official library documentation: direct, minimal, and understandable at a glance.
+Use [AGENTS.md](AGENTS.md) for architecture and coding rules. Review the complete path from user action through edits, processing, and resource cleanup. Code should be a small, readable example of how the application works.
-Judge simplicity across the complete reading path, including callers and resource lifecycles. Preserve correct behavior, error handling, and cleanup. Repository instructions, documentation, and tests define project-specific rules and verification.
+## Review questions
-## Responsibilities and placement
+- **Ownership:** Does each module have one responsibility? Does feature behavior stay with its feature? Is shared code independent of its consumers? `lib/` must meet the layer-0 definition, not merely have multiple callers.
+- **Simplicity:** Does an abstraction reduce the work of understanding callers and lifecycles? Could a direct function or a few repeated lines be clearer? Avoid extra configuration, forwarding layers, and speculative extension points.
+- **State and boundaries:** Is each fact stored once? Are inputs and dependencies explicit, invalid states represented clearly, and external data validated at its boundary? Do errors retain enough context to fix them?
+- **Behavior and lifetime:** Do edits, grouping, cancellation, and undo work together? Can asynchronous work outlive or overwrite its document? Does each owner release resources, subscriptions, and pending work correctly?
+- **Evidence:** Do tests check actual behavior and pixels where relevant? Can reviewers assess every new or changed UI from actual screenshots with the affected controls visible? Rendered output does not replace UI screenshots. Does the PR include [rendering measurements](PERFORMANCE.md) when GPU work changes? Check reported limitations as well as passing results.
-- Give each function, component, hook, and file one coherent responsibility.
-- Keep functions at one abstraction level. When an operation's mechanics interrupt a higher-level sequence, give it a named function, even with only one caller.
-- Decide function boundaries and file placement separately. A helper can stay local, above its consumer. Move general-purpose operations into `lib` for actual or concretely expected reuse, or when an independent capability benefits from its own module.
-- Keep a self-contained leaf module together when its name, location, and structure make its purpose clear. Its private implementation steps can differ technically without requiring separate files. Judge size in context; use no arbitrary line limits.
-- Keep lower-level modules independent of their application and feature consumers.
-- Prefer direct language and library APIs. Add wrappers for a distinct responsibility or a simpler calling interface; avoid forwarding helpers and speculative extension points.
-- Share behavior that has the same meaning and should change together. A few repeated lines are preferable to an abstraction combining unrelated concepts.
+## Findings and tradeoffs
-## Components
+For each finding, name the affected code, the concrete problem or reading burden, and the smallest useful correction. Distinguish necessary changes from optional reorganization. Do not split cohesive code solely to reduce line counts.
-- Put generic UI components in `components/ui`, even with one consumer. Keep product-specific UI with its feature. This does not require extracting every native element into a primitive.
-- Private components supporting one consumer can live in its file, at module scope and above it. Keep small, clear interactions together until a part needs independent use or obscures the composition. Existing feature folders can make an optional extraction worthwhile.
-- Move state and behavior serving a distinct region into the component responsible for that region. Extract the responsibility together; a large hook containing unrelated work is still mixed responsibility.
-- Let pages and application components compose capabilities. Keep low-level mechanics outside their rendering code.
+Accept a departure from a coding guideline when it demonstrably improves readability, reduces total complexity, or improves performance with evidence. Explain the tradeoff in the PR. Ordinary implementation choices do not require an approval ceremony.
-## Linear control flow
-
-- Use guard clauses and early returns. Investigate nested decisions for mixed responsibilities, repeated checks, or unnecessary state combinations.
-- Allow ternaries only for semantically clear value choices that naturally fit on one line, such as `const label = active ? "Pause" : "Play"`. Never nest them. Revisit the structure behind a multiline ternary instead of mechanically expanding it into `if/else`.
-- Avoid ternaries in JSX by default. Calculate values before rendering; use early returns or named components for meaningful conditional regions. A simple boolean `condition && <Element />` is fine for one optional element.
-- Keep imperative work, dense boolean chains, immediately invoked functions, and mutable assembly out of JSX.
-- Use braces for control flow. Prefer `const`; use `let` for genuine reassignment.
-
-## Data and API contracts
-
-- Model actual needs with the simplest accurate types. Avoid arbitrary extra data, permissive types, casts, and conversion layers introduced merely to make callers fit.
-- Make names describe the operation or data they represent, including units when relevant. Calls should be understandable without opening the implementation. Avoid flags that select unrelated behaviors or permit meaningless combinations.
-- Use comments for constraints and decisions the code cannot express, rather than narrating implementation.
-- Use optional inputs when absence has meaning. Make them required when the work needs them and callers already have them. A local guard can handle legitimate absence; repeated checks for the same dependency suggest resolving availability at its owner. Do not complicate consumers solely to remove optional syntax.
-- Represent distinct states explicitly, using a small discriminated union when helpful. Preserve meaningful differences between absence, empty results, loading, and failure. Avoid fallbacks and assertions that conceal broken assumptions.
-- Keep one source of truth and derive dependent values.
-- Validate external data at its boundary rather than repeatedly checking trusted internal values.
-- Design APIs around what they need, own, and produce, with explicit dependencies. Callers should be able to combine behaviors without unnecessary coordination, duplicate resources, or awkward adapters; assess input and output shapes by their effect on composition.
-- Give each resource an owner responsible for its lifecycle and cleanup. Accept externally owned resources as dependencies when appropriate. Keep creation inside the module when lifecycle management is part of its responsibility.
-- Catch errors to recover, translate, or add useful context; preserve failure information.
-
-## Exceptions
-
-Apply these rules by default. Accept an exception when it provides at least one concrete benefit:
-
-- Better performance supported by measurements or specific work avoided.
-- Easier reading of the complete operation and its consumers.
-- Fewer lines with equal or better readability.
-
-Explain the rule, benefit, and tradeoff in the review or change description. Clear, cohesive code does not need an exception merely because another organization is possible.
-
-## How to review
-
-1. Read the affected code, callers, and dependencies. Check responsibilities and contracts before individual expressions.
-2. For each finding, identify the code, relevant rule, concrete burden, and smallest sound correction. Readability issues count even when behavior is correct; distinguish them from optional reorganization.
-3. Evaluate the whole proposed result. Explain what becomes easier to understand, including any new indirection or tradeoff.
-4. Run the repository's required checks and report verification gaps.
+Report required checks and remaining verification gaps. An image supplements tests; a performance claim needs measurements of the affected workload.