Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

Merge private main updates excluding Android and iOS apps

Augustus Otu3efdb84dc965
diff --git a/.gitignore b/.gitignore
index 1403634b..c8e97a59 100644
--- a/.gitignore
+++ b/.gitignore
@@ -95,3 +95,9 @@ xcuserdata/
# Signing certs — never commit
*.p12
*.pfx
+
+# Mobile apps stay in the private repository
+/Openreel Video/
+/Openreel Video Android/
+/apps/ios/
+/apps/android/
diff --git a/APP_STORE_SUBMISSION.txt b/APP_STORE_SUBMISSION.txt
new file mode 100644
index 00000000..247ad926
--- /dev/null
+++ b/APP_STORE_SUBMISSION.txt
@@ -0,0 +1,106 @@
+APP STORE SUBMISSION — OpenReel Video
+======================================
+
+APP INFORMATION
+---------------
+App Name: OpenReel Video
+Subtitle: Professional Video Editor
+Bundle ID: com.openreel.video
+Primary Category: Photo & Video
+Secondary Category: Productivity
+Content Rating: 4+ (no objectionable content)
+Price: Free
+Device Support: iPhone only (iPad not supported)
+Minimum OS Version: iOS 18.0
+
+
+PROMOTIONAL TEXT (170 chars max — shown above description, can update anytime)
+---------------
+Professional video editing on iPhone and iPad. Multi-track timeline, on-device smart tools, and hardware-accelerated export. No watermarks, ever.
+
+
+APP STORE DESCRIPTION (4000 chars max)
+---------------------------------------
+OpenReel Video is a full-featured video editor built for creators who want professional results on iPhone and iPad. Whether you're editing a short clip or a full production, OpenReel gives you the tools to do it without compromise.
+
+TIMELINE EDITING
+Work with unlimited video, audio, text, and graphics tracks on a multi-track timeline. Cut, trim, split, and ripple delete with frame-accurate precision. Scrub through your project in real time with Metal-powered GPU acceleration.
+
+EFFECTS AND COLOR
+Apply filters, blend modes, and video effects directly on the timeline. Fine-tune your look with color wheels, RGB curves, and HSL controls. Adjust brightness, contrast, saturation, and more with live preview.
+
+TEXT AND ANIMATION
+Add titles and captions with 20+ animation presets including typewriter, fade, slide, bounce, and glitch. Customize fonts, gradients, outlines, and shadows. Import SRT or VTT caption files.
+
+AUDIO TOOLS
+Mix multiple audio tracks with per-clip volume and fade controls. Apply EQ, compression, reverb, and noise reduction. Beat detection syncs your edits to the music automatically.
+
+ON-DEVICE SMART TOOLS
+Background removal, smart reframe, motion tracking, face and body analysis, stabilization, and silence cleanup use Apple's Vision, Metal, Core Image, and media frameworks on your device. No OpenReel GPU server is required.
+
+EXPORT
+Export in ProRes or HEVC using hardware encoding. Fast, high quality, and never watermarked.
+
+WEB APP INCLUDED
+OpenReel also runs in Chrome and Edge at openreel.video. Same project format across all your devices.
+
+
+KEYWORDS (100 chars max, comma separated)
+------------------------------------------
+video editor,video editing,timeline,captions,AI video,background removal,reframe,color grading
+
+
+SUPPORT & MARKETING URLS
+--------------------------
+Support URL: https://openreel.video
+Marketing URL: https://openreel.video
+Privacy Policy URL: https://openreel.video/privacy
+
+
+VERSION INFORMATION
+--------------------
+Version Number: 1.1.0
+Build Number: 1
+Copyright: 2026 Augustus Otu
+
+What's New (for version 1.1):
+Initial release. Professional multi-track video editing with on-device smart tools, real-time effects, caption import, and hardware-accelerated export.
+
+
+APP REVIEW INFORMATION
+-----------------------
+Demo Account Required: No
+Notes for reviewer:
+Background removal, smart reframe, motion tracking, and related smart tools run on the device. The app does not connect to an OpenReel-operated GPU server for these features. No login or account is required to use the editor.
+
+
+AGE RATING QUESTIONNAIRE
+--------------------------
+Made for Kids: No
+Cartoon or Fantasy Violence: No
+Realistic Violence: No
+Sexual Content: No
+Nudity: No
+Profanity: No
+Contests/Gambling: No
+Unrestricted Web Access: No
+Alcohol/Tobacco/Drugs: No
+Horror/Fear: No
+Medical/Treatment Info: No
+
+Rating Result: 4+
+
+
+CHECKLIST BEFORE SUBMITTING
+-----------------------------
+[ ] App icon uploaded (1024x1024 PNG, no alpha, no rounded corners)
+[ ] Screenshots uploaded for iPhone 6.9" (required), 6.5", 5.5"
+[ ] Privacy policy URL is live and accessible
+[ ] All required app metadata filled in App Store Connect
+[ ] Agreements, Tax, and Banking accepted at appstoreconnect.apple.com
+[ ] Export compliance answered (uses standard HTTPS encryption only — answer No to proprietary encryption)
+[ ] App build uploaded via Xcode or Transporter and processed
+[ ] Build selected under the version in App Store Connect
+[ ] Pricing set to Free
+[ ] Availability set (all territories or specific ones)
+[ ] Submit for Review
diff --git a/Openreel Video/Openreel Video.xcodeproj/project.xcworkspace/xcuserdata/augustusotu.xcuserdatad/UserInterfaceState.xcuserstate b/Openreel Video/Openreel Video.xcodeproj/project.xcworkspace/xcuserdata/augustusotu.xcuserdatad/UserInterfaceState.xcuserstate
deleted file mode 100644
index 24fedb0c..00000000
Binary files a/Openreel Video/Openreel Video.xcodeproj/project.xcworkspace/xcuserdata/augustusotu.xcuserdatad/UserInterfaceState.xcuserstate and /dev/null differ
diff --git a/Openreel Video/Openreel Video.xcodeproj/xcuserdata/augustusotu.xcuserdatad/xcschemes/xcschememanagement.plist b/Openreel Video/Openreel Video.xcodeproj/xcuserdata/augustusotu.xcuserdatad/xcschemes/xcschememanagement.plist
deleted file mode 100644
index f0eab0e6..00000000
--- a/Openreel Video/Openreel Video.xcodeproj/xcuserdata/augustusotu.xcuserdatad/xcschemes/xcschememanagement.plist
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>SchemeUserState</key>
- <dict>
- <key>Openreel Video.xcscheme_^#shared#^_</key>
- <dict>
- <key>orderHint</key>
- <integer>0</integer>
- </dict>
- </dict>
-</dict>
-</plist>
diff --git a/README.md b/README.md
index 2fec315a..5a1b3057 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,9 @@ OpenReel Video is a fully-featured browser-based video editor that runs entirely
### Try Online
Visit **[openreel.video](https://openreel.video)** to start editing immediately.
+To edit by chatting with OpenAI, Anthropic, or any OpenAI-compatible endpoint, follow the
+**[AI Editor setup guide](docs/AGENT-GUIDE.md#bring-your-own-key-web--desktop-chat)**.
+
### Run Locally
```bash
diff --git a/STORE_RELEASE_NOTES.md b/STORE_RELEASE_NOTES.md
new file mode 100644
index 00000000..d49e9a52
--- /dev/null
+++ b/STORE_RELEASE_NOTES.md
@@ -0,0 +1,105 @@
+# OpenReel — Store Release Notes
+
+Release: **iOS 1.2 (build 2)** · **Android 1.0.8 (versionCode 9)** — June 2026
+
+> **Scope note (read before pasting):**
+> - **iOS 1.2** follows 1.1. If your previously shipped App Store build predates the
+> features below, keep them all; otherwise trim to what's new since your last release.
+> - **Android 1.0.8** follows 1.0.7, which already shipped color wheels, Gaussian blur,
+> LUFS audio normalization, and audio-only export — so its "What's New" is intentionally
+> scoped to the new **on-device editing tools** plus polish. Don't re-announce 1.0.7 features.
+> - Full App Store listing copy (description, promo text, keywords) lives in
+> `APP_STORE_SUBMISSION.txt`. This file is only the per-release "What's New".
+
+---
+
+## Apple App Store — OpenReel Video 1.2
+
+Paste into **App Store Connect → Version 1.2 → What's New in This Version** (4000 char limit).
+
+```
+This is our biggest update yet — smarter on-device tools and a faster, smoother editor.
+
+ON-DEVICE SMART TOOLS
+Remove backgrounds, track subjects, smart-reframe shots, stabilize clips, and find
+silence using the iPhone's own Vision, Metal, and media frameworks. Your media does
+not need to be sent to an OpenReel GPU server.
+
+PRO AUDIO
+Broadcast-standard loudness normalization (LUFS / ITU-R BS.1770) and audio-only
+export to M4A or WAV. Plus text-to-speech voiceover — turn any script into narration.
+
+NEW CROP EDITOR
+Full-screen cropping with aspect-ratio presets, eight draggable handles, pan, and
+pinch-to-zoom.
+
+POLISH
+Smoother trimming and clip dragging, sharper timeline thumbnails, and more reliable
+exports.
+
+No watermarks. Ever.
+```
+
+---
+
+## Google Play — OpenReel Video 1.0.10 (versionCode 11)
+
+Paste into **Play Console → Release → Release notes** (`<en-US>` — **500 char limit**).
+
+```
+NEW: Aspect ratio & backgrounds
+• Change your video's aspect ratio without stretching — your clip keeps its shape
+• Fill the empty space with a blurred background or a solid color
+• Quick ratio picker under the preview (9:16, 16:9, 1:1 and more)
+
+SMOOTHER TIMELINE
+• CapCut-style centered playhead — just slide the timeline to scrub
+• See the exact frame as you drag a clip's trim handles
+
+Plus export reliability fixes and more accurate auto-captions after trimming.
+
+No watermarks, ever.
+```
+
+---
+
+## Google Play — OpenReel Video 1.0.8
+
+Paste into **Play Console → Release → Release notes** (`<en-US>` — **500 char limit**).
+
+```
+NEW: On-device editing tools
+• Track subjects with ML Kit
+• Remove green-screen backgrounds with chroma key
+• Find and trim silence locally
+• Create Shorts suggestions without uploading media
+
+Plus reliability and performance improvements across editing and export.
+
+No watermarks, ever.
+```
+
+---
+
+## Shared highlights (reference / social copy)
+
+This release's headline additions, drawn from the shipped changes:
+
+- **On-device smart tools** — local background removal, subject tracking, smart
+ reframe, stabilization, silence cleanup, and Shorts planning where supported.
+- **Pro audio export** — LUFS loudness normalization (ITU-R BS.1770) and audio-only
+ export (M4A / WAV).
+- **Text-to-speech voiceover** — generate narration tracks from text.
+- **Crop editor (iOS)** — full-screen crop with aspect presets, draggable handles,
+ pan and pinch-to-zoom.
+- **Stability** — fixed trim flicker across clip types and refined clip dragging for
+ frame-accurate edits.
+
+---
+
+## One-line / promo (≤170 chars, optional)
+
+```
+New on-device smart tools for tracking, reframing, stabilization, and silence cleanup.
+Pro audio loudness and a faster editor. No watermarks, ever.
+```
diff --git a/apps/cloud/.editorconfig b/apps/cloud/.editorconfig
new file mode 100644
index 00000000..a727df34
--- /dev/null
+++ b/apps/cloud/.editorconfig
@@ -0,0 +1,12 @@
+# http://editorconfig.org
+root = true
+
+[*]
+indent_style = tab
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.yml]
+indent_style = space
diff --git a/apps/cloud/.gitignore b/apps/cloud/.gitignore
new file mode 100644
index 00000000..4138168d
--- /dev/null
+++ b/apps/cloud/.gitignore
@@ -0,0 +1,167 @@
+# Logs
+
+logs
+_.log
+npm-debug.log_
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+.pnpm-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# Runtime data
+
+pids
+_.pid
+_.seed
+\*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+
+lib-cov
+
+# Coverage directory used by tools like istanbul
+
+coverage
+\*.lcov
+
+# nyc test coverage
+
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+
+bower_components
+
+# node-waf configuration
+
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+
+build/Release
+
+# Dependency directories
+
+node_modules/
+jspm_packages/
+
+# Snowpack dependency directory (https://snowpack.dev/)
+
+web_modules/
+
+# TypeScript cache
+
+\*.tsbuildinfo
+
+# Optional npm cache directory
+
+.npm
+
+# Optional eslint cache
+
+.eslintcache
+
+# Optional stylelint cache
+
+.stylelintcache
+
+# Microbundle cache
+
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+
+.node_repl_history
+
+# Output of 'npm pack'
+
+\*.tgz
+
+# Yarn Integrity file
+
+.yarn-integrity
+
+# parcel-bundler cache (https://parceljs.org/)
+
+.cache
+.parcel-cache
+
+# Next.js build output
+
+.next
+out
+
+# Nuxt.js build / generate output
+
+.nuxt
+dist
+
+# Gatsby files
+
+.cache/
+
+# Comment in the public line in if your project uses Gatsby and not Next.js
+
+# https://nextjs.org/blog/next-9-1#public-directory-support
+
+# public
+
+# vuepress build output
+
+.vuepress/dist
+
+# vuepress v2.x temp and cache directory
+
+.temp
+.cache
+
+# Docusaurus cache and generated files
+
+.docusaurus
+
+# Serverless directories
+
+.serverless/
+
+# FuseBox cache
+
+.fusebox/
+
+# DynamoDB Local files
+
+.dynamodb/
+
+# TernJS port file
+
+.tern-port
+
+# Stores VSCode versions used for testing VSCode extensions
+
+.vscode-test
+
+# yarn v2
+
+.yarn/cache
+.yarn/unplugged
+.yarn/build-state.yml
+.yarn/install-state.gz
+.pnp.\*
+
+# wrangler project
+
+.dev.vars*
+!.dev.vars.example
+.env*
+!.env.example
+.wrangler/
diff --git a/apps/cloud/.prettierrc b/apps/cloud/.prettierrc
new file mode 100644
index 00000000..5c7b5d3c
--- /dev/null
+++ b/apps/cloud/.prettierrc
@@ -0,0 +1,6 @@
+{
+ "printWidth": 140,
+ "singleQuote": true,
+ "semi": true,
+ "useTabs": true
+}
diff --git a/apps/cloud/README.md b/apps/cloud/README.md
new file mode 100644
index 00000000..3416fb87
--- /dev/null
+++ b/apps/cloud/README.md
@@ -0,0 +1,182 @@
+# OpenReel Cloud API
+
+Cloudflare Worker API for OpenReel template storage and sharing.
+
+## Features
+
+- **Template Storage**: Upload and store templates in Cloudflare R2
+- **Template Listing**: Browse all available templates
+- **Template Download**: Download individual templates
+- **Template Deletion**: Delete custom templates (built-ins protected)
+
+## Setup
+
+### 1. Create R2 Bucket
+
+```bash
+cd apps/cloud
+npx wrangler r2 bucket create openreel-templates
+```
+
+### 2. Deploy Worker
+
+```bash
+npm run deploy
+```
+
+The worker will be deployed to: `https://openreel-cloud.<your-subdomain>.workers.dev`
+
+## API Endpoints
+
+### GET `/`
+Get API information and available endpoints.
+
+**Response:**
+```json
+{
+ "name": "OpenReel Cloud API",
+ "version": "1.0.0",
+ "endpoints": {
+ "templates": {
+ "list": "GET /templates",
+ "get": "GET /templates/:id",
+ "upload": "POST /templates",
+ "delete": "DELETE /templates/:id"
+ }
+ }
+}
+```
+
+### GET `/templates`
+List all templates.
+
+**Query Parameters:**
+- `cursor` (optional): Pagination cursor
+
+**Response:**
+```json
+{
+ "templates": [
+ {
+ "id": "template-123",
+ "name": "My Template",
+ "category": "youtube",
+ "description": "A cool template",
+ "thumbnailUrl": null,
+ "placeholderCount": 2,
+ "duration": 30,
+ "createdAt": 1234567890,
+ "tags": ["intro", "animated"],
+ "author": "username"
+ }
+ ],
+ "cursor": "next-page-token",
+ "truncated": false
+}
+```
+
+### GET `/templates/:id`
+Get a specific template by ID.
+
+**Response:**
+```json
+{
+ "id": "template-123",
+ "name": "My Template",
+ "description": "A cool template",
+ "category": "youtube",
+ "settings": {
+ "width": 1920,
+ "height": 1080,
+ "frameRate": 30
+ },
+ "timeline": {
+ "tracks": [...],
+ "graphics": {...}
+ },
+ "placeholders": [...]
+}
+```
+
+### POST `/templates`
+Upload a new template.
+
+**Request Body:**
+```json
+{
+ "id": "template-123",
+ "name": "My Template",
+ "description": "Description",
+ "category": "youtube",
+ "timeline": {...},
+ "placeholders": [...],
+ "tags": ["intro"],
+ "author": "username"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "id": "template-123",
+ "message": "Template uploaded successfully"
+}
+```
+
+### DELETE `/templates/:id`
+Delete a template.
+
+**Response:**
+```json
+{
+ "success": true,
+ "message": "Template deleted successfully"
+}
+```
+
+### GET `/health`
+Health check endpoint.
+
+**Response:**
+```json
+{
+ "status": "healthy",
+ "timestamp": 1234567890
+}
+```
+
+## R2 Configuration
+
+The worker uses Cloudflare R2 for storage with the following configuration:
+
+- **Bucket Name**: `openreel-templates`
+- **Binding**: `TEMPLATES_BUCKET`
+- **Access**: Via Cloudflare Workers R2 API (no direct S3 access needed)
+
+## CORS
+
+CORS is configured to allow requests from:
+- `http://localhost:5173` (local development)
+- `https://app.openreel.video` (production)
+- `https://*.openreel-3pq.pages.dev` (Cloudflare Pages previews)
+
+## Local Development
+
+```bash
+npm run dev
+```
+
+The worker will be available at `http://localhost:8787`
+
+## Environment Variables
+
+Set in `wrangler.jsonc`:
+- `ENVIRONMENT`: `production` or `development`
+
+## Security Notes
+
+- Built-in templates (IDs starting with `builtin-`) cannot be deleted
+- Template IDs must be unique
+- All uploads are validated for required fields (id, name, timeline)
+- CORS is restricted to OpenReel domains only
diff --git a/apps/cloud/package-lock.json b/apps/cloud/package-lock.json
new file mode 100644
index 00000000..6a7bbe32
--- /dev/null
+++ b/apps/cloud/package-lock.json
@@ -0,0 +1,1610 @@
+{
+ "name": "cloud",
+ "version": "0.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "cloud",
+ "version": "0.0.0",
+ "dependencies": {
+ "hono": "^4.11.4"
+ },
+ "devDependencies": {
+ "typescript": "^5.5.2",
+ "wrangler": "^3.101.0"
+ }
+ },
+ "node_modules/@cloudflare/kv-asset-handler": {
+ "version": "0.3.4",
+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.3.4.tgz",
+ "integrity": "sha512-YLPHc8yASwjNkmcDMQMY35yiWjoKAKnhUbPRszBRS0YgH+IXtsMp61j+yTcnCE3oO2DgP0U3iejLC8FTtKDC8Q==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "mime": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=16.13"
+ }
+ },
+ "node_modules/@cloudflare/unenv-preset": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.0.2.tgz",
+ "integrity": "sha512-nyzYnlZjjV5xT3LizahG1Iu6mnrCaxglJ04rZLpDwlDVDZ7v46lNsfxhV3A/xtfgQuSHmLnc6SVI+KwBpc3Lwg==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "peerDependencies": {
+ "unenv": "2.0.0-rc.14",
+ "workerd": "^1.20250124.0"
+ },
+ "peerDependenciesMeta": {
+ "workerd": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-64": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20250718.0.tgz",
+ "integrity": "sha512-FHf4t7zbVN8yyXgQ/r/GqLPaYZSGUVzeR7RnL28Mwj2djyw2ZergvytVc7fdGcczl6PQh+VKGfZCfUqpJlbi9g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-arm64": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20250718.0.tgz",
+ "integrity": "sha512-fUiyUJYyqqp4NqJ0YgGtp4WJh/II/YZsUnEb6vVy5Oeas8lUOxnN+ZOJ8N/6/5LQCVAtYCChRiIrBbfhTn5Z8Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-64": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20250718.0.tgz",
+ "integrity": "sha512-5+eb3rtJMiEwp08Kryqzzu8d1rUcK+gdE442auo5eniMpT170Dz0QxBrqkg2Z48SFUPYbj+6uknuA5tzdRSUSg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-arm64": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20250718.0.tgz",
+ "integrity": "sha512-Aa2M/DVBEBQDdATMbn217zCSFKE+ud/teS+fFS+OQqKABLn0azO2qq6ANAHYOIE6Q3Sq4CxDIQr8lGdaJHwUog==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-windows-64": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20250718.0.tgz",
+ "integrity": "sha512-dY16RXKffmugnc67LTbyjdDHZn5NoTF1yHEf2fN4+OaOnoGSp3N1x77QubTDwqZ9zECWxgQfDLjddcH8dWeFhg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cspotcode/source-map-support": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.9"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.8.1.tgz",
+ "integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@esbuild-plugins/node-globals-polyfill": {
+ "version": "0.2.3",
+ "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-globals-polyfill/-/node-globals-polyfill-0.2.3.tgz",
+ "integrity": "sha512-r3MIryXDeXDOZh7ih1l/yE9ZLORCd5e8vWg02azWRGj5SPTuoh69A2AIyn0Z31V/kHBfZ4HgWJ+OK3GTTwLmnw==",
+ "dev": true,
+ "license": "ISC",
+ "peerDependencies": {
+ "esbuild": "*"
+ }
+ },
+ "node_modules/@esbuild-plugins/node-modules-polyfill": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-modules-polyfill/-/node-modules-polyfill-0.2.2.tgz",
+ "integrity": "sha512-LXV7QsWJxRuMYvKbiznh+U1ilIop3g2TeKRzUxOG5X3YITc8JyyTa90BmLwqqv0YnX4v32CSlG+vsziZp9dMvA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "escape-string-regexp": "^4.0.0",
+ "rollup-plugin-node-polyfills": "^0.2.1"
+ },
+ "peerDependencies": {
+ "esbuild": "*"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",
+ "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz",
+ "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz",
+ "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz",
+ "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",
+ "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz",
+ "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz",
+ "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz",
+ "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",
+ "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz",
+ "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz",
+ "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz",
+ "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz",
+ "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz",
+ "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz",
+ "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",
+ "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz",
+ "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz",
+ "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz",
+ "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",
+ "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz",
+ "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",
+ "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@fastify/busboy": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz",
+ "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
+ "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz",
+ "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz",
+ "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz",
+ "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz",
+ "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz",
+ "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz",
+ "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
+ "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz",
+ "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz",
+ "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz",
+ "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.0.5"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz",
+ "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz",
+ "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz",
+ "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz",
+ "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz",
+ "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz",
+ "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.2.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz",
+ "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz",
+ "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.0.3",
+ "@jridgewell/sourcemap-codec": "^1.4.10"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.14.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz",
+ "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-walk": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz",
+ "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/as-table": {
+ "version": "1.0.55",
+ "resolved": "https://registry.npmjs.org/as-table/-/as-table-1.0.55.tgz",
+ "integrity": "sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "printable-characters": "^1.0.42"
+ }
+ },
+ "node_modules/blake3-wasm": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
+ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/color": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
+ "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "color-convert": "^2.0.1",
+ "color-string": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=12.5.0"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/color-string": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
+ "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "color-name": "^1.0.0",
+ "simple-swizzle": "^0.2.2"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/data-uri-to-buffer": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-2.0.2.tgz",
+ "integrity": "sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/defu": {
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",
+ "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz",
+ "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/android-arm": "0.17.19",
+ "@esbuild/android-arm64": "0.17.19",
+ "@esbuild/android-x64": "0.17.19",
+ "@esbuild/darwin-arm64": "0.17.19",
+ "@esbuild/darwin-x64": "0.17.19",
+ "@esbuild/freebsd-arm64": "0.17.19",
+ "@esbuild/freebsd-x64": "0.17.19",
+ "@esbuild/linux-arm": "0.17.19",
+ "@esbuild/linux-arm64": "0.17.19",
+ "@esbuild/linux-ia32": "0.17.19",
+ "@esbuild/linux-loong64": "0.17.19",
+ "@esbuild/linux-mips64el": "0.17.19",
+ "@esbuild/linux-ppc64": "0.17.19",
+ "@esbuild/linux-riscv64": "0.17.19",
+ "@esbuild/linux-s390x": "0.17.19",
+ "@esbuild/linux-x64": "0.17.19",
+ "@esbuild/netbsd-x64": "0.17.19",
+ "@esbuild/openbsd-x64": "0.17.19",
+ "@esbuild/sunos-x64": "0.17.19",
+ "@esbuild/win32-arm64": "0.17.19",
+ "@esbuild/win32-ia32": "0.17.19",
+ "@esbuild/win32-x64": "0.17.19"
+ }
+ },
+ "node_modules/escape-string-regexp": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz",
+ "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/exit-hook": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz",
+ "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/exsolve": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz",
+ "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/get-source": {
+ "version": "2.0.12",
+ "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz",
+ "integrity": "sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==",
+ "dev": true,
+ "license": "Unlicense",
+ "dependencies": {
+ "data-uri-to-buffer": "^2.0.0",
+ "source-map": "^0.6.1"
+ }
+ },
+ "node_modules/glob-to-regexp": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/hono": {
+ "version": "4.11.4",
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz",
+ "integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.9.0"
+ }
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.3.4",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz",
+ "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/magic-string": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",
+ "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "sourcemap-codec": "^1.4.8"
+ }
+ },
+ "node_modules/mime": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "mime": "cli.js"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/miniflare": {
+ "version": "3.20250718.3",
+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-3.20250718.3.tgz",
+ "integrity": "sha512-JuPrDJhwLrNLEJiNLWO7ZzJrv/Vv9kZuwMYCfv0LskQDM6Eonw4OvywO3CH/wCGjgHzha/qyjUh8JQ068TjDgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "0.8.1",
+ "acorn": "8.14.0",
+ "acorn-walk": "8.3.2",
+ "exit-hook": "2.2.1",
+ "glob-to-regexp": "0.4.1",
+ "stoppable": "1.1.0",
+ "undici": "^5.28.5",
+ "workerd": "1.20250718.0",
+ "ws": "8.18.0",
+ "youch": "3.3.4",
+ "zod": "3.22.3"
+ },
+ "bin": {
+ "miniflare": "bootstrap.js"
+ },
+ "engines": {
+ "node": ">=16.13"
+ }
+ },
+ "node_modules/mustache": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",
+ "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "mustache": "bin/mustache"
+ }
+ },
+ "node_modules/ohash": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz",
+ "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/path-to-regexp": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/printable-characters": {
+ "version": "1.0.42",
+ "resolved": "https://registry.npmjs.org/printable-characters/-/printable-characters-1.0.42.tgz",
+ "integrity": "sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==",
+ "dev": true,
+ "license": "Unlicense"
+ },
+ "node_modules/rollup-plugin-inject": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz",
+ "integrity": "sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==",
+ "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "estree-walker": "^0.6.1",
+ "magic-string": "^0.25.3",
+ "rollup-pluginutils": "^2.8.1"
+ }
+ },
+ "node_modules/rollup-plugin-node-polyfills": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/rollup-plugin-node-polyfills/-/rollup-plugin-node-polyfills-0.2.1.tgz",
+ "integrity": "sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "rollup-plugin-inject": "^3.0.0"
+ }
+ },
+ "node_modules/rollup-pluginutils": {
+ "version": "2.8.2",
+ "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz",
+ "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "estree-walker": "^0.6.1"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.7.3",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "dev": true,
+ "license": "ISC",
+ "optional": true,
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",
+ "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "color": "^4.2.3",
+ "detect-libc": "^2.0.3",
+ "semver": "^7.6.3"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.33.5",
+ "@img/sharp-darwin-x64": "0.33.5",
+ "@img/sharp-libvips-darwin-arm64": "1.0.4",
+ "@img/sharp-libvips-darwin-x64": "1.0.4",
+ "@img/sharp-libvips-linux-arm": "1.0.5",
+ "@img/sharp-libvips-linux-arm64": "1.0.4",
+ "@img/sharp-libvips-linux-s390x": "1.0.4",
+ "@img/sharp-libvips-linux-x64": "1.0.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.0.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.0.4",
+ "@img/sharp-linux-arm": "0.33.5",
+ "@img/sharp-linux-arm64": "0.33.5",
+ "@img/sharp-linux-s390x": "0.33.5",
+ "@img/sharp-linux-x64": "0.33.5",
+ "@img/sharp-linuxmusl-arm64": "0.33.5",
+ "@img/sharp-linuxmusl-x64": "0.33.5",
+ "@img/sharp-wasm32": "0.33.5",
+ "@img/sharp-win32-ia32": "0.33.5",
+ "@img/sharp-win32-x64": "0.33.5"
+ }
+ },
+ "node_modules/simple-swizzle": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz",
+ "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "is-arrayish": "^0.3.1"
+ }
+ },
+ "node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/sourcemap-codec": {
+ "version": "1.4.8",
+ "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
+ "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
+ "deprecated": "Please use @jridgewell/sourcemap-codec instead",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/stacktracey": {
+ "version": "2.1.8",
+ "resolved": "https://registry.npmjs.org/stacktracey/-/stacktracey-2.1.8.tgz",
+ "integrity": "sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==",
+ "dev": true,
+ "license": "Unlicense",
+ "dependencies": {
+ "as-table": "^1.0.36",
+ "get-source": "^2.0.12"
+ }
+ },
+ "node_modules/stoppable": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz",
+ "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4",
+ "npm": ">=6"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/ufo": {
+ "version": "1.6.2",
+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.2.tgz",
+ "integrity": "sha512-heMioaxBcG9+Znsda5Q8sQbWnLJSl98AFDXTO80wELWEzX3hordXsTdxrIfMQoO9IY1MEnoGoPjpoKpMj+Yx0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/undici": {
+ "version": "5.29.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz",
+ "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/busboy": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.0"
+ }
+ },
+ "node_modules/unenv": {
+ "version": "2.0.0-rc.14",
+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.14.tgz",
+ "integrity": "sha512-od496pShMen7nOy5VmVJCnq8rptd45vh6Nx/r2iPbrba6pa6p+tS2ywuIHRZ/OBvSbQZB0kWvpO9XBNVFXHD3Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "defu": "^6.1.4",
+ "exsolve": "^1.0.1",
+ "ohash": "^2.0.10",
+ "pathe": "^2.0.3",
+ "ufo": "^1.5.4"
+ }
+ },
+ "node_modules/workerd": {
+ "version": "1.20250718.0",
+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20250718.0.tgz",
+ "integrity": "sha512-kqkIJP/eOfDlUyBzU7joBg+tl8aB25gEAGqDap+nFWb+WHhnooxjGHgxPBy3ipw2hnShPFNOQt5lFRxbwALirg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "workerd": "bin/workerd"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "@cloudflare/workerd-darwin-64": "1.20250718.0",
+ "@cloudflare/workerd-darwin-arm64": "1.20250718.0",
+ "@cloudflare/workerd-linux-64": "1.20250718.0",
+ "@cloudflare/workerd-linux-arm64": "1.20250718.0",
+ "@cloudflare/workerd-windows-64": "1.20250718.0"
+ }
+ },
+ "node_modules/wrangler": {
+ "version": "3.114.17",
+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.114.17.tgz",
+ "integrity": "sha512-tAvf7ly+tB+zwwrmjsCyJ2pJnnc7SZhbnNwXbH+OIdVas3zTSmjcZOjmLKcGGptssAA3RyTKhcF9BvKZzMUycA==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@cloudflare/kv-asset-handler": "0.3.4",
+ "@cloudflare/unenv-preset": "2.0.2",
+ "@esbuild-plugins/node-globals-polyfill": "0.2.3",
+ "@esbuild-plugins/node-modules-polyfill": "0.2.2",
+ "blake3-wasm": "2.1.5",
+ "esbuild": "0.17.19",
+ "miniflare": "3.20250718.3",
+ "path-to-regexp": "6.3.0",
+ "unenv": "2.0.0-rc.14",
+ "workerd": "1.20250718.0"
+ },
+ "bin": {
+ "wrangler": "bin/wrangler.js",
+ "wrangler2": "bin/wrangler.js"
+ },
+ "engines": {
+ "node": ">=16.17.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.2",
+ "sharp": "^0.33.5"
+ },
+ "peerDependencies": {
+ "@cloudflare/workers-types": "^4.20250408.0"
+ },
+ "peerDependenciesMeta": {
+ "@cloudflare/workers-types": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.18.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
+ "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/youch": {
+ "version": "3.3.4",
+ "resolved": "https://registry.npmjs.org/youch/-/youch-3.3.4.tgz",
+ "integrity": "sha512-UeVBXie8cA35DS6+nBkls68xaBBXCye0CNznrhszZjTbRVnJKQuNsyLKBTTL4ln1o1rh2PKtv35twV7irj5SEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cookie": "^0.7.1",
+ "mustache": "^4.2.0",
+ "stacktracey": "^2.1.8"
+ }
+ },
+ "node_modules/zod": {
+ "version": "3.22.3",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.3.tgz",
+ "integrity": "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/apps/cloud/package.json b/apps/cloud/package.json
new file mode 100644
index 00000000..22b07e13
--- /dev/null
+++ b/apps/cloud/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "cloud",
+ "version": "0.0.0",
+ "private": true,
+ "scripts": {
+ "deploy": "wrangler deploy",
+ "dev": "wrangler dev",
+ "start": "wrangler dev",
+ "typecheck": "tsc --noEmit",
+ "test:run": "vitest run",
+ "cf-typegen": "wrangler types"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "^4.20260117.0",
+ "typescript": "^5.5.2",
+ "vitest": "^1.6.0",
+ "wrangler": "^3.101.0"
+ },
+ "dependencies": {
+ "@openreel/fxpkg": "workspace:*",
+ "hono": "^4.11.4",
+ "jose": "^6.2.3",
+ "zod": "^4.4.3"
+ }
+}
diff --git a/apps/cloud/public/index.html b/apps/cloud/public/index.html
new file mode 100644
index 00000000..cf3e142c
--- /dev/null
+++ b/apps/cloud/public/index.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Hello, World!</title>
+ </head>
+ <body>
+ <h1 id="heading"></h1>
+ <p>This page comes from a static asset stored at `public/index.html` as configured in `wrangler.jsonc`.</p>
+ <script>
+ fetch('/message')
+ .then((resp) => resp.text())
+ .then((text) => {
+ const h1 = document.getElementById('heading');
+ h1.textContent = text;
+ });
+ </script>
+ </body>
+</html>
diff --git a/apps/cloud/src/crash/routes.ts b/apps/cloud/src/crash/routes.ts
new file mode 100644
index 00000000..af639d93
--- /dev/null
+++ b/apps/cloud/src/crash/routes.ts
@@ -0,0 +1,131 @@
+import { Hono } from "hono";
+import type { Context } from "hono";
+import type { Bindings } from "../marketplace/types";
+
+const crash = new Hono<{ Bindings: Bindings }>();
+
+const MAX_BODY_BYTES = 64 * 1024;
+const MAX_MESSAGE = 8000;
+const MAX_STACK = 16000;
+const MAX_SHORT = 128;
+const MAX_CONTEXT = 8000;
+
+function clip(value: unknown, max: number): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ if (!trimmed) return undefined;
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
+}
+
+function clipContext(value: unknown): unknown {
+ if (value === undefined || value === null) return undefined;
+ try {
+ const json = JSON.stringify(value);
+ if (json.length <= MAX_CONTEXT) return value;
+ return { truncated: true, preview: json.slice(0, MAX_CONTEXT) };
+ } catch {
+ return undefined;
+ }
+}
+
+crash.post("/crash", async (c) => {
+ const declaredLength = Number(c.req.header("content-length") ?? "0");
+ if (declaredLength > MAX_BODY_BYTES) {
+ return c.json({ error: "payload too large" }, 413);
+ }
+
+ let body: Record<string, unknown>;
+ try {
+ body = (await c.req.json()) as Record<string, unknown>;
+ } catch {
+ return c.json({ error: "invalid json" }, 400);
+ }
+ if (!body || typeof body !== "object") {
+ return c.json({ error: "invalid payload" }, 400);
+ }
+
+ const message = clip(body.message, MAX_MESSAGE);
+ if (!message) {
+ return c.json({ error: "message required" }, 400);
+ }
+
+ const cf = (c.req.raw as unknown as { cf?: { country?: string } }).cf;
+ const report = {
+ id: crypto.randomUUID(),
+ receivedAt: new Date().toISOString(),
+ message,
+ stack: clip(body.stack, MAX_STACK),
+ type: clip(body.type, MAX_SHORT) ?? "unknown",
+ source: clip(body.source, MAX_SHORT) ?? "unknown",
+ appVersion: clip(body.appVersion, MAX_SHORT) ?? "unknown",
+ platform: clip(body.platform, MAX_SHORT),
+ arch: clip(body.arch, MAX_SHORT),
+ osVersion: clip(body.osVersion, MAX_SHORT),
+ electronVersion: clip(body.electronVersion, MAX_SHORT),
+ context: clipContext(body.context),
+ ip: c.req.header("cf-connecting-ip"),
+ country: cf?.country,
+ userAgent: clip(c.req.header("user-agent"), 256),
+ };
+
+ console.log(JSON.stringify({ tag: "crash", ...report, stack: undefined }));
+
+ const bucket = c.env.CRASHES_BUCKET;
+ if (bucket) {
+ const day = report.receivedAt.slice(0, 10);
+ const key = `crashes/${day}/${report.appVersion}/${report.id}.json`;
+ try {
+ await bucket.put(key, JSON.stringify(report, null, 2), {
+ httpMetadata: { contentType: "application/json" },
+ customMetadata: {
+ type: report.type,
+ source: report.source,
+ appVersion: report.appVersion,
+ platform: report.platform ?? "",
+ },
+ });
+ } catch (error) {
+ console.error("crash store failed", error);
+ }
+ }
+
+ return c.json({ ok: true, id: report.id }, 201);
+});
+
+function authorized(c: Context<{ Bindings: Bindings }>): boolean {
+ const token = c.env.CRASH_ADMIN_TOKEN;
+ if (!token) return false;
+ return c.req.header("authorization") === `Bearer ${token}`;
+}
+
+crash.get("/crash", async (c) => {
+ if (!authorized(c)) return c.json({ error: "unauthorized" }, 401);
+
+ const bucket = c.env.CRASHES_BUCKET;
+ if (!bucket) return c.json({ crashes: [], truncated: false });
+
+ const key = c.req.query("key");
+ if (key) {
+ const object = await bucket.get(key);
+ if (!object) return c.json({ error: "not found" }, 404);
+ return c.json(await object.json());
+ }
+
+ const listed = await bucket.list({
+ prefix: c.req.query("prefix") ?? "crashes/",
+ limit: 100,
+ cursor: c.req.query("cursor") || undefined,
+ });
+ return c.json({
+ crashes: listed.objects.map((o) => ({
+ key: o.key,
+ size: o.size,
+ uploaded: o.uploaded,
+ ...o.customMetadata,
+ })),
+ cursor: listed.truncated ? (listed as { cursor?: string }).cursor : undefined,
+ truncated: listed.truncated,
+ });
+});
+
+export default crash;
diff --git a/apps/cloud/src/index.ts b/apps/cloud/src/index.ts
new file mode 100644
index 00000000..575fc7bb
--- /dev/null
+++ b/apps/cloud/src/index.ts
@@ -0,0 +1,415 @@
+import { Hono } from 'hono';
+import { cors } from 'hono/cors';
+import type { Bindings } from './marketplace/types';
+import marketplace from './marketplace/marketplace';
+import studio from './marketplace/studio';
+import events from './marketplace/events';
+import crash from './crash/routes';
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+app.use('/*', cors({
+ origin: (origin) => {
+ if (!origin) return origin;
+ const ok =
+ /^http:\/\/localhost:\d+$/.test(origin) ||
+ /\.openreel-studio\.pages\.dev$/.test(origin) ||
+ origin === 'https://openreel-studio.pages.dev' ||
+ /\.openreel\.video$/.test(origin) ||
+ origin === 'https://app.openreel.video' ||
+ origin === 'https://studio.openreel.video';
+ return ok ? origin : undefined;
+ },
+ allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
+ allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Bundle-ID', 'X-User-Id', 'X-Creator-Id', 'X-Creator-Handle'],
+ maxAge: 86400,
+}));
+
+// Marketplace + Studio API (STUDIO_PLAN §34), mounted under /v1.
+app.route('/v1', marketplace);
+app.route('/v1', studio);
+app.route('/v1', events);
+
+// Desktop/app crash + error collection (POST /crash; guarded GET /crash).
+app.route('/', crash);
+
+app.get('/', (c) => {
+ return c.json({
+ name: 'OpenReel Cloud API',
+ version: '1.0.0',
+ endpoints: {
+ marketplace: {
+ assets: 'GET /v1/assets',
+ asset: 'GET /v1/assets/:id',
+ install: 'POST /v1/assets/:id/install',
+ search: 'GET /v1/search?q=',
+ blueprints: 'GET /v1/blueprints',
+ nodelib: 'GET /v1/nodelib?abi=1.2',
+ },
+ studio: {
+ drafts: 'POST /v1/drafts · PUT /v1/drafts/:id',
+ validate: 'POST /v1/drafts/:id/validate',
+ submit: 'POST /v1/drafts/:id/submit',
+ review: 'POST /v1/submissions/:id/review',
+ },
+ events: 'POST /v1/events',
+ crash: 'POST /crash',
+ templates: {
+ list: 'GET /templates',
+ get: 'GET /templates/:id',
+ upload: 'POST /templates',
+ delete: 'DELETE /templates/:id',
+ },
+ },
+ });
+});
+
+app.get('/templates', async (c) => {
+ const bucket = c.env.TEMPLATES_BUCKET;
+ const { cursor } = c.req.query();
+
+ try {
+ const listed = await bucket.list({
+ limit: 100,
+ cursor: cursor || undefined,
+ });
+
+ const templates = await Promise.all(
+ listed.objects.map(async (obj) => {
+ const template = await bucket.get(obj.key);
+ if (!template) return null;
+ const data = await template.json() as Record<string, unknown>;
+ return {
+ id: obj.key.replace('.json', ''),
+ name: data.name,
+ category: data.category,
+ description: data.description,
+ thumbnailUrl: data.thumbnailUrl,
+ placeholderCount: (data.placeholders as unknown[] | undefined)?.length || 0,
+ duration: (data.timeline as Record<string, unknown> | undefined)?.duration || 0,
+ createdAt: data.createdAt,
+ tags: data.tags,
+ author: data.author,
+ };
+ })
+ );
+
+ return c.json({
+ templates: templates.filter(Boolean),
+ cursor: listed.truncated ? (listed as { cursor?: string }).cursor : undefined,
+ truncated: listed.truncated,
+ });
+ } catch (error) {
+ return c.json({ error: 'Failed to list templates' }, 500);
+ }
+});
+
+app.get('/templates/:id', async (c) => {
+ const id = c.req.param('id');
+ const bucket = c.env.TEMPLATES_BUCKET;
+
+ try {
+ const template = await bucket.get(`${id}.json`);
+
+ if (!template) {
+ return c.json({ error: 'Template not found' }, 404);
+ }
+
+ const data = await template.json();
+ return c.json(data);
+ } catch (error) {
+ return c.json({ error: 'Failed to get template' }, 500);
+ }
+});
+
+app.post('/templates', async (c) => {
+ const bucket = c.env.TEMPLATES_BUCKET;
+
+ try {
+ const body = await c.req.json();
+
+ if (!body.id || !body.name || !body.timeline) {
+ return c.json({ error: 'Invalid template format. Required: id, name, timeline' }, 400);
+ }
+
+ const templateId = body.id;
+ const key = `${templateId}.json`;
+
+ const existing = await bucket.get(key);
+ if (existing) {
+ return c.json({ error: 'Template with this ID already exists' }, 409);
+ }
+
+ const template = {
+ ...body,
+ createdAt: body.createdAt || Date.now(),
+ modifiedAt: Date.now(),
+ version: body.version || '1.0.0',
+ };
+
+ await bucket.put(key, JSON.stringify(template, null, 2), {
+ httpMetadata: {
+ contentType: 'application/json',
+ },
+ customMetadata: {
+ name: template.name,
+ category: template.category || 'custom',
+ author: template.author || 'anonymous',
+ },
+ });
+
+ return c.json({
+ success: true,
+ id: templateId,
+ message: 'Template uploaded successfully',
+ }, 201);
+ } catch (error) {
+ console.error('Upload error:', error);
+ return c.json({ error: 'Failed to upload template' }, 500);
+ }
+});
+
+app.delete('/templates/:id', async (c) => {
+ const id = c.req.param('id');
+ const bucket = c.env.TEMPLATES_BUCKET;
+
+ if (id.startsWith('builtin-')) {
+ return c.json({ error: 'Cannot delete built-in templates' }, 403);
+ }
+
+ try {
+ const key = `${id}.json`;
+ await bucket.delete(key);
+
+ return c.json({
+ success: true,
+ message: 'Template deleted successfully',
+ });
+ } catch (error) {
+ return c.json({ error: 'Failed to delete template' }, 500);
+ }
+});
+
+app.post('/shares', async (c) => {
+ const bucket = c.env.SHARES_BUCKET;
+
+ try {
+ const formData = await c.req.formData();
+ const file = formData.get('file') as File | null;
+
+ if (!file) {
+ return c.json({ error: 'No file provided' }, 400);
+ }
+
+ const shareId = crypto.randomUUID();
+ const expiresAt = Date.now() + 24 * 60 * 60 * 1000;
+
+ await bucket.put(`shares/${shareId}`, file.stream(), {
+ httpMetadata: {
+ contentType: file.type || 'video/webm',
+ },
+ customMetadata: {
+ filename: file.name,
+ expiresAt: expiresAt.toString(),
+ size: file.size.toString(),
+ },
+ });
+
+ return c.json({
+ shareId,
+ shareUrl: `https://app.openreel.video/#/share/${shareId}`,
+ expiresAt,
+ }, 201);
+ } catch (error) {
+ console.error('Share upload error:', error);
+ return c.json({ error: 'Failed to upload file for sharing' }, 500);
+ }
+});
+
+app.get('/shares/:id', async (c) => {
+ const bucket = c.env.SHARES_BUCKET;
+ const shareId = c.req.param('id');
+
+ try {
+ const object = await bucket.head(`shares/${shareId}`);
+
+ if (!object) {
+ return c.json({ error: 'Share not found' }, 404);
+ }
+
+ const expiresAt = parseInt(object.customMetadata?.expiresAt || '0');
+
+ if (Date.now() > expiresAt) {
+ await bucket.delete(`shares/${shareId}`);
+ return c.json({ error: 'Share link has expired' }, 410);
+ }
+
+ return c.json({
+ shareId,
+ filename: object.customMetadata?.filename || 'video.webm',
+ size: parseInt(object.customMetadata?.size || '0'),
+ expiresAt,
+ expiresIn: Math.floor((expiresAt - Date.now()) / 1000 / 60),
+ });
+ } catch (error) {
+ console.error('Get share error:', error);
+ return c.json({ error: 'Failed to get share info' }, 500);
+ }
+});
+
+app.get('/shares/:id/download', async (c) => {
+ const bucket = c.env.SHARES_BUCKET;
+ const shareId = c.req.param('id');
+
+ try {
+ const object = await bucket.get(`shares/${shareId}`);
+
+ if (!object) {
+ return c.json({ error: 'Share not found' }, 404);
+ }
+
+ const expiresAt = parseInt(object.customMetadata?.expiresAt || '0');
+
+ if (Date.now() > expiresAt) {
+ return c.json({ error: 'Share link has expired' }, 410);
+ }
+
+ const filename = object.customMetadata?.filename || 'video.webm';
+
+ return new Response(object.body, {
+ headers: {
+ 'Content-Type': object.httpMetadata?.contentType || 'video/webm',
+ 'Content-Disposition': `attachment; filename="${filename}"`,
+ 'Content-Length': object.size.toString(),
+ },
+ });
+ } catch (error) {
+ console.error('Download share error:', error);
+ return c.json({ error: 'Failed to download share' }, 500);
+ }
+});
+
+app.post('/highlights', async (c) => {
+ try {
+ const body = await c.req.json() as {
+ transcript: Array<{ text: string; start: number; end: number }>;
+ energy: Array<{ start: number; end: number; rmsDb: number; peakDb: number }>;
+ duration: number;
+ preferences?: {
+ targetClipCount?: number;
+ minClipDuration?: number;
+ maxClipDuration?: number;
+ contentType?: string;
+ };
+ };
+
+ if (!body.transcript || !Array.isArray(body.transcript) || body.transcript.length === 0) {
+ return c.json({ error: 'transcript array is required and must not be empty' }, 400);
+ }
+
+ const prefs = body.preferences || {};
+ const targetCount = prefs.targetClipCount || 5;
+ const minDuration = prefs.minClipDuration || 5;
+ const maxDuration = prefs.maxClipDuration || 60;
+ const contentType = prefs.contentType || 'video';
+
+ const transcriptText = body.transcript
+ .map((w) => `[${w.start.toFixed(1)}s] ${w.text}`)
+ .join(' ');
+
+ const energySummary = body.energy
+ .map((e) => `${e.start.toFixed(0)}-${e.end.toFixed(0)}s: ${e.rmsDb.toFixed(1)}dB peak:${e.peakDb.toFixed(1)}dB`)
+ .join('\n');
+
+ const prompt = `You are a video editor AI. Analyze this transcript and audio energy data to find the most engaging highlight clips.
+
+Content type: ${contentType}
+Total duration: ${body.duration.toFixed(1)}s
+Target number of clips: ${targetCount}
+Clip duration range: ${minDuration}-${maxDuration} seconds
+
+TRANSCRIPT (with timestamps):
+${transcriptText}
+
+AUDIO ENERGY (per segment):
+${energySummary}
+
+Find the ${targetCount} most engaging moments. Look for:
+- Key insights or surprising statements
+- Emotional peaks (high energy + impactful words)
+- Complete thoughts that stand alone as clips
+- Natural start/end points (sentence boundaries)
+
+Respond ONLY with valid JSON in this exact format:
+{"highlights":[{"start":0,"end":0,"score":0,"title":"","reason":""}]}
+
+Where start/end are seconds, score is 1-10, title is a short description, reason explains why it's engaging.`;
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.3-70b-instruct-fp8-fast', {
+ messages: [{ role: 'user', content: prompt }],
+ max_tokens: 2048,
+ });
+
+ let responseText = '';
+ if (typeof response === 'string') {
+ responseText = response;
+ } else if (response && typeof response === 'object') {
+ const resp = response as Record<string, unknown>;
+ if (typeof resp.response === 'string') {
+ responseText = resp.response;
+ } else {
+ responseText = JSON.stringify(response);
+ }
+ }
+
+ if (!responseText) {
+ return c.json({ error: 'Empty AI response' }, 500);
+ }
+
+ type Highlight = { start: number; end: number; score: number; title: string; reason: string };
+ let highlights: Highlight[] = [];
+
+ try {
+ const outer = JSON.parse(responseText);
+ if (Array.isArray(outer.highlights)) {
+ highlights = outer.highlights;
+ } else if (outer.response && Array.isArray(outer.response.highlights)) {
+ highlights = outer.response.highlights;
+ }
+ } catch {
+ const jsonMatch = responseText.match(/\{[\s\S]*"highlights"[\s\S]*\}/);
+ if (!jsonMatch) {
+ return c.json({ error: 'Failed to parse AI response', raw: responseText.slice(0, 500) }, 500);
+ }
+ const parsed = JSON.parse(jsonMatch[0]);
+ highlights = parsed.highlights || parsed.response?.highlights || [];
+ }
+
+ if (!Array.isArray(highlights) || highlights.length === 0) {
+ return c.json({ error: 'No highlights found in AI response' }, 500);
+ }
+
+ const validated = highlights
+ .filter((h) => h.start >= 0 && h.end > h.start && h.end <= body.duration)
+ .map((h) => ({
+ start: Math.max(0, h.start),
+ end: Math.min(body.duration, h.end),
+ score: Math.min(10, Math.max(1, Math.round(h.score))),
+ title: h.title || 'Highlight',
+ reason: h.reason || '',
+ }))
+ .sort((a, b) => b.score - a.score)
+ .slice(0, targetCount);
+
+ return c.json({ highlights: validated });
+ } catch (error) {
+ console.error('Highlights error:', error);
+ return c.json({ error: 'Failed to generate highlights', detail: error instanceof Error ? error.message : String(error) }, 500);
+ }
+});
+
+app.get('/health', (c) => {
+ return c.json({ status: 'healthy', timestamp: Date.now() });
+});
+
+export default app;
diff --git a/apps/cloud/src/marketplace/api.test.ts b/apps/cloud/src/marketplace/api.test.ts
new file mode 100644
index 00000000..d2699eb4
--- /dev/null
+++ b/apps/cloud/src/marketplace/api.test.ts
@@ -0,0 +1,138 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import app from "../index";
+import { sealEvent, getBlueprint } from "@openreel/fxpkg";
+
+// In-memory store is module-global; reset between suites by using fresh ids.
+const env = { ENVIRONMENT: "test", EVENT_HMAC_SECRET: "test-secret" } as unknown as Record<string, unknown>;
+const creatorHeaders = { "Content-Type": "application/json", "X-User-Id": "u-creator", "X-Creator-Id": "c-1", "X-Creator-Handle": "augani" };
+const userHeaders = { "Content-Type": "application/json", "X-User-Id": "u-viewer" };
+
+async function req(path: string, init?: RequestInit) {
+ return app.request(path, init, env as never);
+}
+
+describe("marketplace + studio API", () => {
+ let draftId = "";
+ let assetId = "";
+ let versionId = "";
+ let submissionId = "";
+
+ beforeEach(() => {
+ /* shared state across ordered tests */
+ });
+
+ it("lists blueprints and node library", async () => {
+ const bp = await req("/v1/blueprints");
+ expect(bp.status).toBe(200);
+ const bpJson = (await bp.json()) as { blueprints: Array<{ id: string }> };
+ expect(bpJson.blueprints.map((b) => b.id)).toContain("fire-aura.v1");
+
+ const nl = await req("/v1/nodelib?abi=1.0");
+ const nlJson = (await nl.json()) as { nodes: Array<{ id: string }> };
+ expect(nlJson.nodes.some((n) => n.id === "Source")).toBe(true);
+ expect(nlJson.nodes.some((n) => n.id === "Depth")).toBe(false); // 1.2 node
+ });
+
+ it("requires a creator for drafts", async () => {
+ const r = await req("/v1/drafts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ kind: "filter" }) });
+ expect(r.status).toBe(401);
+ });
+
+ it("creates and autosaves a draft from the passthrough blueprint", async () => {
+ const graph = getBlueprint("passthrough.v1")!.build({});
+ const create = await req("/v1/drafts", {
+ method: "POST",
+ headers: creatorHeaders,
+ body: JSON.stringify({ kind: "filter", title: "My Filter", graph, manifest_draft: { title: "My Filter", description: "test" } }),
+ });
+ expect(create.status).toBe(201);
+ draftId = ((await create.json()) as { id: string }).id;
+
+ const save = await req(`/v1/drafts/${draftId}`, { method: "PUT", headers: creatorHeaders, body: JSON.stringify({ title: "My Filter v2" }) });
+ expect(save.status).toBe(200);
+ });
+
+ it("validates the draft (pre-flight)", async () => {
+ const r = await req(`/v1/drafts/${draftId}/validate`, { method: "POST", headers: creatorHeaders });
+ const j = (await r.json()) as { validation: { ok: boolean }; compile?: { ok: boolean } };
+ expect(j.validation.ok).toBe(true);
+ expect(j.compile?.ok).toBe(true);
+ });
+
+ it("submits, passes auto-checks, and enters human review", async () => {
+ const r = await req(`/v1/drafts/${draftId}/submit`, { method: "POST", headers: creatorHeaders });
+ expect(r.status).toBe(201);
+ const j = (await r.json()) as { submission: { id: string; state: string }; asset: { id: string }; version: { id: string } };
+ expect(j.submission.state).toBe("human_review");
+ submissionId = j.submission.id;
+ assetId = j.asset.id;
+ versionId = j.version.id;
+ });
+
+ it("rejects a submission with a bad graph (no output)", async () => {
+ const bad = await req("/v1/drafts", {
+ method: "POST", headers: creatorHeaders,
+ body: JSON.stringify({ kind: "filter", title: "Broken", graph: { id: "b", kind: "filter", abi: "1.0", nodelibVersion: "1.0.0", nodes: [{ id: "s", type: "Source" }], edges: [], params: [] } }),
+ });
+ const badId = ((await bad.json()) as { id: string }).id;
+ const sub = await req(`/v1/drafts/${badId}/submit`, { method: "POST", headers: creatorHeaders });
+ expect(sub.status).toBe(422);
+ const j = (await sub.json()) as { submission: { state: string } };
+ expect(j.submission.state).toBe("creator_feedback");
+ });
+
+ it("reviewer approves → published; asset appears in discovery", async () => {
+ const review = await req(`/v1/submissions/${submissionId}/review`, { method: "POST", headers: creatorHeaders, body: JSON.stringify({ decision: "approve" }) });
+ expect(review.status).toBe(200);
+ const j = (await review.json()) as { submission: { state: string } };
+ expect(j.submission.state).toBe("published");
+
+ const list = await req("/v1/assets?sort=new");
+ const lj = (await list.json()) as { assets: Array<{ id: string }> };
+ expect(lj.assets.some((a) => a.id === assetId)).toBe(true);
+ });
+
+ it("downloads the published manifest + fxpkg uri", async () => {
+ const man = await req(`/v1/assets/${assetId}/versions/1/manifest`);
+ expect(man.status).toBe(200);
+ const dl = await req(`/v1/assets/${assetId}/versions/1/download`);
+ expect(dl.status).toBe(200);
+ expect(((await dl.json()) as { fxpkg_uri: string }).fxpkg_uri).toContain("fxpkg/");
+ });
+
+ it("installs into a user library", async () => {
+ const r = await req(`/v1/assets/${assetId}/install`, { method: "POST", headers: userHeaders });
+ expect(r.status).toBe(200);
+ const lib = await req("/v1/me/library", { headers: userHeaders });
+ expect(((await lib.json()) as { asset_ids: string[] }).asset_ids).toContain(assetId);
+ });
+
+ it("records a payable EXPORT_COMPLETED event and credits the creator", async () => {
+ const payload = {
+ asset_id: assetId,
+ export: {
+ gross_cents: 1000,
+ duration_ms: 8000,
+ contains_user_media: true,
+ content_hash: "hash-1",
+ day: "2026-05-26",
+ applied: [{ assetVersionId: versionId, kind: "filter", clipCount: 1, totalDurationMs: 8000 }],
+ },
+ };
+ const nonce = "nonce-1";
+ const signature = sealEvent(JSON.stringify(payload), nonce, "test-secret");
+ const r = await req("/v1/events", {
+ method: "POST", headers: userHeaders,
+ body: JSON.stringify({ events: [{ event_id: "exp-1", type: "EXPORT_COMPLETED", user_id: "u-viewer", session_nonce: nonce, signature, payload }] }),
+ });
+ const j = (await r.json()) as { results: Array<{ status: string }> };
+ expect(j.results[0].status).toBe("payable");
+
+ // duplicate is ignored
+ const dup = await req("/v1/events", {
+ method: "POST", headers: userHeaders,
+ body: JSON.stringify({ events: [{ event_id: "exp-1", type: "EXPORT_COMPLETED", user_id: "u-viewer", session_nonce: nonce, signature, payload }] }),
+ });
+ expect(((await dup.json()) as { results: Array<{ status: string }> }).results[0].status).toBe("duplicate");
+ });
+});
diff --git a/apps/cloud/src/marketplace/auth.ts b/apps/cloud/src/marketplace/auth.ts
new file mode 100644
index 00000000..c186ee34
--- /dev/null
+++ b/apps/cloud/src/marketplace/auth.ts
@@ -0,0 +1,39 @@
+import type { Context } from "hono";
+
+/**
+ * Auth shim (STUDIO_PLAN §45.3). Cross-platform identity is cookie (web) or
+ * bearer token (mobile); the marketplace API accepts either. This dev shim
+ * trusts `Authorization: Bearer <userId>` / `X-Creator-Id` so the surface is
+ * exercisable end-to-end; swap for real JWT/cookie verification in prod.
+ */
+export interface Identity {
+ userId: string;
+ creatorId?: string;
+ handle?: string;
+}
+
+export function getIdentity(c: Context): Identity | null {
+ const auth = c.req.header("authorization");
+ const bearer = auth?.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : undefined;
+ const userId = bearer || c.req.header("x-user-id");
+ if (!userId) return null;
+ const creatorId = c.req.header("x-creator-id") || userId;
+ const handle = c.req.header("x-creator-handle") || undefined;
+ return { userId, creatorId, handle };
+}
+
+export function requireUser(c: Context): Identity | Response {
+ const id = getIdentity(c);
+ if (!id) return c.json({ error: "unauthorized" }, 401);
+ return id;
+}
+
+export function requireCreator(c: Context): (Identity & { creatorId: string }) | Response {
+ const id = getIdentity(c);
+ if (!id || !id.creatorId) return c.json({ error: "creator_required" }, 401);
+ return { ...id, creatorId: id.creatorId };
+}
+
+export function isResponse(v: unknown): v is Response {
+ return v instanceof Response;
+}
diff --git a/apps/cloud/src/marketplace/autochecks.ts b/apps/cloud/src/marketplace/autochecks.ts
new file mode 100644
index 00000000..27d4f41e
--- /dev/null
+++ b/apps/cloud/src/marketplace/autochecks.ts
@@ -0,0 +1,125 @@
+import {
+ validateGraph,
+ compileFilter,
+ compileTemplate,
+ buildPackage,
+ checkSizes,
+ type Graph,
+ type AssetKind,
+ type AssetRequirements,
+ type DetectionCapability,
+ type TemplateSource,
+ type Manifest,
+} from "@openreel/fxpkg";
+
+export interface AutoCheckResult {
+ ok: boolean;
+ steps: Array<{ name: string; status: "pass" | "fail" | "skipped"; detail?: unknown }>;
+}
+
+const DETECTION_NODES: Record<string, DetectionCapability> = {
+ SubjectMask: "subject_mask",
+ SubjectMaskInverted: "subject_mask",
+ MaskEdgeEmitter: "subject_mask",
+ PoseLandmark: "pose",
+ PoseAllLandmarks: "pose",
+ LandmarkEmitter: "pose",
+ FaceLandmark: "face",
+ FaceBlendshape: "face",
+ Depth: "depth",
+};
+
+/** Derive declared requirements from the graph (used to fill the manifest, §7). */
+export function deriveRequirements(graph: Graph): AssetRequirements {
+ const detection = new Set<DetectionCapability>();
+ let maxParticles = 0;
+ let uses3d = false;
+ let history = 0;
+ for (const node of graph.nodes) {
+ const cap = DETECTION_NODES[node.type];
+ if (cap) detection.add(cap);
+ if (node.type === "ParticleEmitter") {
+ const max = typeof node.config?.max === "number" ? (node.config.max as number) : 2048;
+ maxParticles += max;
+ }
+ if (node.type === "Mesh3D") uses3d = true;
+ if (node.type === "FrameHistory" || node.type === "MaskHistory" || node.type === "Trail") history = Math.max(history, 16);
+ }
+ return {
+ webgpu: true,
+ detection: [...detection],
+ frame_history_depth: history,
+ max_particles: maxParticles,
+ uses_3d: uses3d,
+ max_resolution: [3840, 2160],
+ perf_budget_ms_per_frame: graph.kind === "effect" ? 16 : 8,
+ perf_budget_ms_detection: detection.size > 0 ? 8 : 0,
+ };
+}
+
+/** Auto-checks common to all kinds + kind-specific compile (STUDIO_PLAN §38). */
+export function runAutoChecks(
+ graph: Graph,
+ kind: AssetKind,
+ template?: TemplateSource,
+): AutoCheckResult {
+ const steps: AutoCheckResult["steps"] = [];
+
+ if (kind === "template") {
+ if (!template) {
+ steps.push({ name: "template_source", status: "fail", detail: "missing template source" });
+ return { ok: false, steps };
+ }
+ const compiled = compileTemplate(template);
+ steps.push({ name: "template_compile", status: compiled.ok ? "pass" : "fail", detail: compiled.ok ? undefined : compiled.errors });
+ return { ok: compiled.ok, steps };
+ }
+
+ const validation = validateGraph(graph);
+ steps.push({ name: "graph_validate", status: validation.ok ? "pass" : "fail", detail: validation.ok ? undefined : validation.errors });
+ if (!validation.ok) return { ok: false, steps };
+
+ if (kind === "filter") {
+ const compiled = compileFilter(graph);
+ steps.push({ name: "wgsl_compile", status: compiled.ok ? "pass" : "fail", detail: compiled.ok ? undefined : compiled.errors });
+ if (!compiled.ok) return { ok: false, steps };
+ const sizes = checkSizes({ "artifact/shaders/main.wgsl": compiled.wgsl });
+ steps.push({ name: "size_limits", status: sizes.ok ? "pass" : "fail", detail: sizes.ok ? undefined : sizes.violations });
+ return { ok: sizes.ok, steps };
+ }
+
+ // effects: validation passed; particle/codegen runtime lives in packages/core.
+ steps.push({ name: "effect_graph", status: "pass" });
+ return { ok: true, steps };
+}
+
+export interface ArtifactBuild {
+ ok: boolean;
+ files?: Record<string, string | Uint8Array>;
+ manifest?: Manifest;
+ errors?: unknown;
+}
+
+/** Compile + assemble the .fxpkg file map for storage (STUDIO_PLAN §6, §37.2). */
+export function buildArtifact(graph: Graph, manifestBase: Omit<Manifest, "checksums" | "requirements">): ArtifactBuild {
+ const requirements = deriveRequirements(graph);
+ const artifactFiles: Record<string, string> = {};
+
+ if (graph.kind === "filter") {
+ const compiled = compileFilter(graph);
+ if (!compiled.ok) return { ok: false, errors: compiled.errors };
+ artifactFiles["artifact/pipeline.json"] = JSON.stringify(compiled.pipeline);
+ artifactFiles["artifact/shaders/main.wgsl"] = compiled.wgsl;
+ } else if (graph.kind === "effect") {
+ // effect pipeline.json is emitted by the core runtime mapper; store the graph
+ artifactFiles["artifact/pipeline.json"] = JSON.stringify({ abi: graph.abi, kind: "effect", nodes: graph.nodes.length });
+ }
+
+ const res = buildPackage({
+ manifest: { ...manifestBase, requirements },
+ graph,
+ artifactFiles,
+ });
+ if (!res.ok) return { ok: false, errors: res.errors };
+ return { ok: true, files: res.bundle.files, manifest: res.bundle.manifest };
+}
diff --git a/apps/cloud/src/marketplace/events.ts b/apps/cloud/src/marketplace/events.ts
new file mode 100644
index 00000000..0ded10a8
--- /dev/null
+++ b/apps/cloud/src/marketplace/events.ts
@@ -0,0 +1,134 @@
+import { Hono } from "hono";
+import {
+ verifyEvent,
+ checkExportPayable,
+ exportDedupeKey,
+ computeAttribution,
+ payableValue,
+ creatorPayableCents,
+ payableAfter,
+ type AppliedAsset,
+ type EventType,
+ type EarningsEntry,
+} from "@openreel/fxpkg";
+import type { Bindings } from "./types";
+import { getStore } from "./store";
+import { rateLimit, SECOND } from "./ratelimit";
+
+const app = new Hono<{ Bindings: Bindings }>();
+const now = () => new Date().toISOString();
+
+interface IncomingEvent {
+ event_id: string;
+ type: EventType;
+ user_id: string;
+ session_nonce: string;
+ signature: string;
+ payload: {
+ asset_id?: string;
+ export?: {
+ gross_cents: number;
+ duration_ms: number;
+ contains_user_media: boolean;
+ content_hash: string;
+ applied: AppliedAsset[];
+ day: string;
+ };
+ };
+}
+
+// Batched event upload (§34.5, §41.2). Edge worker validates session token,
+// dedupes, rate-limits, then writes payable balances for EXPORT_COMPLETED.
+app.post("/events", rateLimit({ key: "events", limit: 10, windowMs: SECOND }), async (c) => {
+ const secret = c.env.EVENT_HMAC_SECRET;
+ const body = await c.req.json<{ events: IncomingEvent[] }>();
+ const store = getStore(c.env);
+ const results: Array<{ event_id: string; status: string; detail?: unknown }> = [];
+
+ for (const ev of body.events ?? []) {
+ // fraud-safe event sealing (§41.5): verify HMAC when a secret is configured
+ if (secret) {
+ const ok = verifyEvent(JSON.stringify(ev.payload), ev.session_nonce, secret, ev.signature);
+ if (!ok) {
+ results.push({ event_id: ev.event_id, status: "rejected", detail: "bad_signature" });
+ continue;
+ }
+ }
+
+ if (ev.type !== "EXPORT_COMPLETED" || !ev.payload.export) {
+ results.push({ event_id: ev.event_id, status: "accepted" });
+ continue;
+ }
+
+ const exp = ev.payload.export;
+ const check = checkExportPayable({
+ userId: ev.user_id,
+ assetId: ev.payload.asset_id ?? "",
+ day: exp.day,
+ durationMs: exp.duration_ms,
+ containsUserMedia: exp.contains_user_media,
+ contentHash: exp.content_hash,
+ });
+ if (!check.payable) {
+ results.push({ event_id: ev.event_id, status: "not_payable", detail: check.reasons });
+ continue;
+ }
+
+ const dedupe = exportDedupeKey({
+ userId: ev.user_id,
+ assetId: ev.payload.asset_id ?? "",
+ day: exp.day,
+ durationMs: exp.duration_ms,
+ containsUserMedia: exp.contains_user_media,
+ contentHash: exp.content_hash,
+ });
+ if (await store.seenExport(dedupe)) {
+ results.push({ event_id: ev.event_id, status: "duplicate" });
+ continue;
+ }
+ await store.markExport(dedupe);
+
+ const exportId = ev.event_id;
+ const attributions = computeAttribution(exportId, exp.applied);
+ await store.addAttributions(attributions);
+
+ const split = payableValue(exp.gross_cents);
+ for (const attr of attributions) {
+ const version = await findVersion(store, attr.assetVersionId);
+ if (!version) continue;
+ const creatorId = version.manifest.author.creator_id;
+ const creatorCents = creatorPayableCents(split.creatorPoolCents, attr.share);
+ const earnedAt = now();
+ const entry: EarningsEntry = {
+ id: crypto.randomUUID(),
+ creatorId,
+ exportId,
+ assetVersionId: attr.assetVersionId,
+ grossCents: exp.gross_cents,
+ creatorCents,
+ state: "pending",
+ earnedAt,
+ payableAt: payableAfter(earnedAt),
+ };
+ await store.addEarning(entry);
+ const bal = await store.getBalance(creatorId);
+ bal.pendingCents += creatorCents;
+ await store.setBalance({ ...bal });
+ }
+ results.push({ event_id: ev.event_id, status: "payable", detail: { gross_cents: exp.gross_cents, creator_pool_cents: split.creatorPoolCents } });
+ }
+
+ return c.json({ results });
+});
+
+async function findVersion(store: ReturnType<typeof getStore>, versionId: string) {
+ const { items } = await store.listAssets({});
+ for (const asset of items) {
+ const vs = await store.listVersions(asset.id);
+ const v = vs.find((x) => x.id === versionId);
+ if (v) return v;
+ }
+ return undefined;
+}
+
+export default app;
diff --git a/apps/cloud/src/marketplace/marketplace.ts b/apps/cloud/src/marketplace/marketplace.ts
new file mode 100644
index 00000000..20f21c27
--- /dev/null
+++ b/apps/cloud/src/marketplace/marketplace.ts
@@ -0,0 +1,129 @@
+import { Hono } from "hono";
+import { listBlueprints, paletteNodes, type AbiVersion, type AssetKind } from "@openreel/fxpkg";
+import type { Bindings } from "./types";
+import { getStore } from "./store";
+import { requireUser, isResponse } from "./auth";
+import { rateLimit, DAY } from "./ratelimit";
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ── Discovery + consumption (§34.1) ─────────────────────────────────────────
+app.get("/assets", async (c) => {
+ const q = c.req.query();
+ const { items, total } = await getStore(c.env).listAssets({
+ kind: q.kind as AssetKind | undefined,
+ category: q.category,
+ sort: (q.sort as "trending" | "new" | "installs") ?? "trending",
+ q: q.q,
+ page: q.page ? Number(q.page) : 1,
+ pageSize: q.page_size ? Number(q.page_size) : 24,
+ });
+ return c.json({
+ assets: items.map((a) => ({
+ id: a.id,
+ slug: a.slug,
+ kind: a.kind,
+ category: a.category,
+ currentVersion: a.currentVersion,
+ title: a.latest?.manifest.title,
+ description: a.latest?.manifest.description,
+ tags: a.latest?.manifest.tags,
+ author: a.latest?.manifest.author,
+ })),
+ total,
+ });
+});
+
+app.get("/assets/:id", async (c) => {
+ const store = getStore(c.env);
+ const asset = await store.getAsset(c.req.param("id"));
+ if (!asset) return c.json({ error: "not_found" }, 404);
+ const latest = await store.latestApproved(asset.id);
+ const versions = await store.listVersions(asset.id);
+ return c.json({ asset, latest, versions: versions.map((v) => ({ version: v.version, reviewState: v.reviewState, abi: v.abi })) });
+});
+
+app.get("/assets/:id/versions/:n", async (c) => {
+ const v = await getStore(c.env).getVersion(c.req.param("id"), Number(c.req.param("n")));
+ if (!v) return c.json({ error: "not_found" }, 404);
+ return c.json(v);
+});
+
+app.get("/assets/:id/versions/:n/manifest", async (c) => {
+ const v = await getStore(c.env).getVersion(c.req.param("id"), Number(c.req.param("n")));
+ if (!v) return c.json({ error: "not_found" }, 404);
+ return c.json(v.manifest);
+});
+
+app.get("/assets/:id/versions/:n/download", async (c) => {
+ const v = await getStore(c.env).getVersion(c.req.param("id"), Number(c.req.param("n")));
+ if (!v) return c.json({ error: "not_found" }, 404);
+ if (v.reviewState !== "published" && v.reviewState !== "approved") return c.json({ error: "not_published" }, 403);
+ // Immutable, long-cache URL (§6.4). With R2 bound this streams the artifact;
+ // otherwise returns the logical uri for the consumer to resolve.
+ const url = `/v1/assets/${v.assetId}/versions/${v.version}/fxpkg`;
+ return c.json({ fxpkg_uri: v.fxpkgUri, url, expires_in_s: 3600 });
+});
+
+app.get("/assets/:id/versions/:n/fxpkg", async (c) => {
+ const v = await getStore(c.env).getVersion(c.req.param("id"), Number(c.req.param("n")));
+ if (!v) return c.json({ error: "not_found" }, 404);
+ if (c.env.ASSETS_BUCKET) {
+ const obj = await c.env.ASSETS_BUCKET.get(`${v.fxpkgUri}.json`);
+ if (obj) return new Response(obj.body, { headers: { "Content-Type": "application/json", "Cache-Control": "public, max-age=31536000, immutable" } });
+ }
+ return c.json({ error: "artifact_unavailable" }, 404);
+});
+
+app.post("/assets/:id/install", rateLimit({ key: "install", limit: 1000, windowMs: DAY }), async (c) => {
+ const id = requireUser(c);
+ if (isResponse(id)) return id;
+ const store = getStore(c.env);
+ const asset = await store.getAsset(c.req.param("id") ?? "");
+ if (!asset) return c.json({ error: "not_found" }, 404);
+ await store.install(id.userId, asset.id);
+ return c.json({ installed: true, asset_id: asset.id });
+});
+
+app.get("/me/library", async (c) => {
+ const id = requireUser(c);
+ if (isResponse(id)) return id;
+ return c.json({ asset_ids: await getStore(c.env).listInstalls(id.userId) });
+});
+
+app.get("/search", async (c) => {
+ const q = c.req.query("q") ?? "";
+ const { items, total } = await getStore(c.env).listAssets({ q, sort: "trending" });
+ return c.json({ query: q, total, assets: items.map((a) => ({ id: a.id, slug: a.slug, kind: a.kind, title: a.latest?.manifest.title })) });
+});
+
+app.get("/creators/:handle", async (c) => {
+ const handle = c.req.param("handle");
+ const { items } = await getStore(c.env).listAssets({});
+ const assets = items.filter((a) => a.latest?.manifest.author.handle === handle);
+ return c.json({ handle, assets: assets.map((a) => ({ id: a.id, slug: a.slug, kind: a.kind, title: a.latest?.manifest.title })) });
+});
+
+// ── Authoring helpers: blueprints + node library (§9A, §12) ─────────────────
+app.get("/blueprints", (c) => {
+ return c.json({
+ blueprints: listBlueprints().map((b) => ({
+ id: b.id,
+ version: b.version,
+ kind: b.kind,
+ label: b.label,
+ difficulty: b.difficulty,
+ controls: b.controls,
+ })),
+ });
+});
+
+app.get("/nodelib", (c) => {
+ const abi = (c.req.query("abi") as AbiVersion) ?? "1.2";
+ return c.json({
+ abi,
+ nodes: paletteNodes(abi).map((n) => ({ id: n.id, category: n.category, label: n.label, inputs: n.inputs, outputs: n.outputs, minAbi: n.minAbi })),
+ });
+});
+
+export default app;
diff --git a/apps/cloud/src/marketplace/ratelimit.ts b/apps/cloud/src/marketplace/ratelimit.ts
new file mode 100644
index 00000000..783780f4
--- /dev/null
+++ b/apps/cloud/src/marketplace/ratelimit.ts
@@ -0,0 +1,34 @@
+import type { Context, Next } from "hono";
+
+/**
+ * Sliding-window rate limiter (STUDIO_PLAN §34.6). In-memory per isolate for
+ * dev; production enforces in Redis/KV with sliding-window counters. Limits:
+ * submissions 10/day, installs 1000/day, render previews 60/min, events 10/s,
+ * authoring 100/s.
+ */
+interface Window {
+ hits: number[];
+}
+const buckets = new Map<string, Window>();
+
+export function rateLimit(opts: { key: string; limit: number; windowMs: number; keyFn?: (c: Context) => string }) {
+ return async (c: Context, next: Next) => {
+ const id = opts.keyFn ? opts.keyFn(c) : (c.req.header("x-user-id") || c.req.header("authorization") || "anon");
+ const bucketKey = `${opts.key}:${id}`;
+ const now = Date.now();
+ const w = buckets.get(bucketKey) ?? { hits: [] };
+ w.hits = w.hits.filter((t) => now - t < opts.windowMs);
+ if (w.hits.length >= opts.limit) {
+ const retryAfter = Math.ceil((opts.windowMs - (now - w.hits[0])) / 1000);
+ c.header("Retry-After", String(Math.max(1, retryAfter)));
+ return c.json({ error: "rate_limited", retry_after_s: retryAfter }, 429);
+ }
+ w.hits.push(now);
+ buckets.set(bucketKey, w);
+ await next();
+ };
+}
+
+export const DAY = 86_400_000;
+export const MINUTE = 60_000;
+export const SECOND = 1_000;
diff --git a/apps/cloud/src/marketplace/store.ts b/apps/cloud/src/marketplace/store.ts
new file mode 100644
index 00000000..7870572b
--- /dev/null
+++ b/apps/cloud/src/marketplace/store.ts
@@ -0,0 +1,254 @@
+import type {
+ Asset,
+ AssetVersion,
+ Draft,
+ Submission,
+ EarningsEntry,
+ CreatorBalance,
+ Attribution,
+} from "@openreel/fxpkg";
+import type { AssetListFilter, Bindings, Store } from "./types";
+
+function sortAssets(items: Array<Asset & { latest?: AssetVersion }>, sort: AssetListFilter["sort"]): void {
+ if (sort === "new") {
+ items.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
+ }
+ // trending/installs ranking is computed by the search-indexer in prod (§36.2);
+ // default order is recency here.
+}
+
+function matchesFilter(asset: Asset, latest: AssetVersion | undefined, f: AssetListFilter): boolean {
+ if (f.kind && asset.kind !== f.kind) return false;
+ if (f.category && asset.category !== f.category) return false;
+ if (f.creatorId && asset.creatorId !== f.creatorId) return false;
+ if (f.q) {
+ const hay = `${asset.slug} ${latest?.manifest.title ?? ""} ${latest?.manifest.description ?? ""} ${(latest?.manifest.tags ?? []).join(" ")}`.toLowerCase();
+ if (!hay.includes(f.q.toLowerCase())) return false;
+ }
+ return true;
+}
+
+/** In-memory store: default when no durable binding is configured. Persists per isolate. */
+export class InMemoryStore implements Store {
+ private assets = new Map<string, Asset>();
+ private versions = new Map<string, AssetVersion[]>();
+ private drafts = new Map<string, Draft>();
+ private snapshots = new Map<string, unknown[]>();
+ private submissions = new Map<string, Submission>();
+ private installs = new Map<string, Set<string>>();
+ private earnings = new Map<string, EarningsEntry[]>();
+ private balances = new Map<string, CreatorBalance>();
+ private attributions: Attribution[] = [];
+ private exportsSeen = new Set<string>();
+
+ async putAsset(a: Asset) { this.assets.set(a.id, a); }
+ async getAsset(id: string) { return this.assets.get(id); }
+ async getAssetBySlug(creatorId: string, slug: string) {
+ return [...this.assets.values()].find((a) => a.creatorId === creatorId && a.slug === slug);
+ }
+ async listAssets(filter: AssetListFilter) {
+ const page = filter.page ?? 1;
+ const pageSize = filter.pageSize ?? 24;
+ const all: Array<Asset & { latest?: AssetVersion }> = [];
+ for (const asset of this.assets.values()) {
+ const latest = await this.latestApproved(asset.id);
+ if (!latest && filter.sort !== undefined) continue; // only published in discovery
+ if (matchesFilter(asset, latest, filter)) all.push({ ...asset, latest });
+ }
+ sortAssets(all, filter.sort);
+ const start = (page - 1) * pageSize;
+ return { items: all.slice(start, start + pageSize), total: all.length };
+ }
+
+ async putVersion(v: AssetVersion) {
+ const list = this.versions.get(v.assetId) ?? [];
+ const idx = list.findIndex((x) => x.version === v.version);
+ if (idx >= 0) list[idx] = v; else list.push(v);
+ this.versions.set(v.assetId, list);
+ }
+ async getVersion(assetId: string, version: number) {
+ return (this.versions.get(assetId) ?? []).find((v) => v.version === version);
+ }
+ async listVersions(assetId: string) {
+ return [...(this.versions.get(assetId) ?? [])].sort((a, b) => b.version - a.version);
+ }
+ async latestApproved(assetId: string) {
+ return (this.versions.get(assetId) ?? [])
+ .filter((v) => v.reviewState === "published" || v.reviewState === "approved")
+ .sort((a, b) => b.version - a.version)[0];
+ }
+
+ async putDraft(d: Draft) { this.drafts.set(d.id, d); }
+ async getDraft(id: string) { return this.drafts.get(id); }
+ async listDraftsByCreator(creatorId: string) {
+ return [...this.drafts.values()].filter((d) => d.creatorId === creatorId).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ }
+ async deleteDraft(id: string) { this.drafts.delete(id); }
+ async pushSnapshot(draftId: string, graph: unknown) {
+ const list = this.snapshots.get(draftId) ?? [];
+ list.unshift(graph);
+ this.snapshots.set(draftId, list.slice(0, 50)); // last 50 (§14.6)
+ }
+
+ async putSubmission(s: Submission) { this.submissions.set(s.id, s); }
+ async getSubmission(id: string) { return this.submissions.get(id); }
+ async listSubmissions(state?: string) {
+ const all = [...this.submissions.values()];
+ return state ? all.filter((s) => s.state === state) : all;
+ }
+
+ async install(userId: string, assetId: string) {
+ const set = this.installs.get(userId) ?? new Set();
+ set.add(assetId);
+ this.installs.set(userId, set);
+ }
+ async isInstalled(userId: string, assetId: string) { return this.installs.get(userId)?.has(assetId) ?? false; }
+ async listInstalls(userId: string) { return [...(this.installs.get(userId) ?? [])]; }
+
+ async addEarning(e: EarningsEntry) {
+ const list = this.earnings.get(e.creatorId) ?? [];
+ list.push(e);
+ this.earnings.set(e.creatorId, list);
+ }
+ async listEarnings(creatorId: string) { return [...(this.earnings.get(creatorId) ?? [])]; }
+ async getBalance(creatorId: string) {
+ return this.balances.get(creatorId) ?? { creatorId, pendingCents: 0, payableCents: 0, paidCents: 0, currency: "USD" };
+ }
+ async setBalance(b: CreatorBalance) { this.balances.set(b.creatorId, b); }
+
+ async addAttributions(a: Attribution[]) { this.attributions.push(...a); }
+
+ async seenExport(key: string) { return this.exportsSeen.has(key); }
+ async markExport(key: string) { this.exportsSeen.add(key); }
+}
+
+/** R2-backed store: durable across isolates. Keys are JSON objects; a maintained
+ * index doc supports listing/search at v1 scale (Meilisearch takes over per §36). */
+export class R2Store implements Store {
+ constructor(private bucket: R2Bucket) {}
+
+ private async readJson<T>(key: string): Promise<T | undefined> {
+ const obj = await this.bucket.get(key);
+ if (!obj) return undefined;
+ return (await obj.json()) as T;
+ }
+ private async writeJson(key: string, value: unknown): Promise<void> {
+ await this.bucket.put(key, JSON.stringify(value), { httpMetadata: { contentType: "application/json" } });
+ }
+
+ async putAsset(a: Asset) {
+ await this.writeJson(`assets/${a.id}.json`, a);
+ const idx = (await this.readJson<string[]>("index/assets.json")) ?? [];
+ if (!idx.includes(a.id)) { idx.push(a.id); await this.writeJson("index/assets.json", idx); }
+ await this.writeJson(`index/slug/${a.creatorId}/${a.slug}.json`, { id: a.id });
+ }
+ async getAsset(id: string) { return this.readJson<Asset>(`assets/${id}.json`); }
+ async getAssetBySlug(creatorId: string, slug: string) {
+ const ref = await this.readJson<{ id: string }>(`index/slug/${creatorId}/${slug}.json`);
+ return ref ? this.getAsset(ref.id) : undefined;
+ }
+ async listAssets(filter: AssetListFilter) {
+ const ids = (await this.readJson<string[]>("index/assets.json")) ?? [];
+ const items: Array<Asset & { latest?: AssetVersion }> = [];
+ for (const id of ids) {
+ const asset = await this.getAsset(id);
+ if (!asset) continue;
+ const latest = await this.latestApproved(id);
+ if (!latest && filter.sort !== undefined) continue;
+ if (matchesFilter(asset, latest, filter)) items.push({ ...asset, latest });
+ }
+ sortAssets(items, filter.sort);
+ const page = filter.page ?? 1;
+ const pageSize = filter.pageSize ?? 24;
+ const start = (page - 1) * pageSize;
+ return { items: items.slice(start, start + pageSize), total: items.length };
+ }
+
+ async putVersion(v: AssetVersion) {
+ await this.writeJson(`versions/${v.assetId}/${v.version}.json`, v);
+ const list = (await this.readJson<number[]>(`index/versions/${v.assetId}.json`)) ?? [];
+ if (!list.includes(v.version)) { list.push(v.version); await this.writeJson(`index/versions/${v.assetId}.json`, list); }
+ }
+ async getVersion(assetId: string, version: number) { return this.readJson<AssetVersion>(`versions/${assetId}/${version}.json`); }
+ async listVersions(assetId: string) {
+ const nums = (await this.readJson<number[]>(`index/versions/${assetId}.json`)) ?? [];
+ const out: AssetVersion[] = [];
+ for (const n of nums.sort((a, b) => b - a)) { const v = await this.getVersion(assetId, n); if (v) out.push(v); }
+ return out;
+ }
+ async latestApproved(assetId: string) {
+ return (await this.listVersions(assetId)).find((v) => v.reviewState === "published" || v.reviewState === "approved");
+ }
+
+ async putDraft(d: Draft) {
+ await this.writeJson(`drafts/${d.id}.json`, d);
+ const idx = (await this.readJson<string[]>(`index/drafts/${d.creatorId}.json`)) ?? [];
+ if (!idx.includes(d.id)) { idx.push(d.id); await this.writeJson(`index/drafts/${d.creatorId}.json`, idx); }
+ }
+ async getDraft(id: string) { return this.readJson<Draft>(`drafts/${id}.json`); }
+ async listDraftsByCreator(creatorId: string) {
+ const ids = (await this.readJson<string[]>(`index/drafts/${creatorId}.json`)) ?? [];
+ const out: Draft[] = [];
+ for (const id of ids) { const d = await this.getDraft(id); if (d) out.push(d); }
+ return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ }
+ async deleteDraft(id: string) { await this.bucket.delete(`drafts/${id}.json`); }
+ async pushSnapshot(draftId: string, graph: unknown) {
+ const key = `snapshots/${draftId}.json`;
+ const list = (await this.readJson<unknown[]>(key)) ?? [];
+ list.unshift(graph);
+ await this.writeJson(key, list.slice(0, 50));
+ }
+
+ async putSubmission(s: Submission) {
+ await this.writeJson(`submissions/${s.id}.json`, s);
+ const idx = (await this.readJson<string[]>("index/submissions.json")) ?? [];
+ if (!idx.includes(s.id)) { idx.push(s.id); await this.writeJson("index/submissions.json", idx); }
+ }
+ async getSubmission(id: string) { return this.readJson<Submission>(`submissions/${id}.json`); }
+ async listSubmissions(state?: string) {
+ const ids = (await this.readJson<string[]>("index/submissions.json")) ?? [];
+ const out: Submission[] = [];
+ for (const id of ids) { const s = await this.getSubmission(id); if (s && (!state || s.state === state)) out.push(s); }
+ return out;
+ }
+
+ async install(userId: string, assetId: string) {
+ const list = (await this.readJson<string[]>(`installs/${userId}.json`)) ?? [];
+ if (!list.includes(assetId)) { list.push(assetId); await this.writeJson(`installs/${userId}.json`, list); }
+ }
+ async isInstalled(userId: string, assetId: string) {
+ const list = (await this.readJson<string[]>(`installs/${userId}.json`)) ?? [];
+ return list.includes(assetId);
+ }
+ async listInstalls(userId: string) { return (await this.readJson<string[]>(`installs/${userId}.json`)) ?? []; }
+
+ async addEarning(e: EarningsEntry) {
+ const key = `earnings/${e.creatorId}.json`;
+ const list = (await this.readJson<EarningsEntry[]>(key)) ?? [];
+ list.push(e);
+ await this.writeJson(key, list);
+ }
+ async listEarnings(creatorId: string) { return (await this.readJson<EarningsEntry[]>(`earnings/${creatorId}.json`)) ?? []; }
+ async getBalance(creatorId: string) {
+ return (await this.readJson<CreatorBalance>(`balances/${creatorId}.json`)) ?? { creatorId, pendingCents: 0, payableCents: 0, paidCents: 0, currency: "USD" };
+ }
+ async setBalance(b: CreatorBalance) { await this.writeJson(`balances/${b.creatorId}.json`, b); }
+
+ async addAttributions(a: Attribution[]) {
+ if (!a.length) return;
+ const key = `attributions/${a[0].exportId}.json`;
+ await this.writeJson(key, a);
+ }
+
+ async seenExport(key: string) { return (await this.bucket.head(`exports-seen/${key}`)) !== null; }
+ async markExport(key: string) { await this.bucket.put(`exports-seen/${key}`, "1"); }
+}
+
+let memo: InMemoryStore | undefined;
+
+export function getStore(env: Bindings): Store {
+ if (env.ASSETS_BUCKET) return new R2Store(env.ASSETS_BUCKET);
+ if (!memo) memo = new InMemoryStore();
+ return memo;
+}
diff --git a/apps/cloud/src/marketplace/studio.ts b/apps/cloud/src/marketplace/studio.ts
new file mode 100644
index 00000000..e7e0aac8
--- /dev/null
+++ b/apps/cloud/src/marketplace/studio.ts
@@ -0,0 +1,261 @@
+import { Hono } from "hono";
+import {
+ validateGraph,
+ compileFilter,
+ compileTemplate,
+ canTransition,
+ type Graph,
+ type AssetKind,
+ type Draft,
+ type Asset,
+ type AssetVersion,
+ type Submission,
+ type SubmissionState,
+ type Manifest,
+ type TemplateSource,
+} from "@openreel/fxpkg";
+import type { Bindings } from "./types";
+import { getStore } from "./store";
+import { requireCreator, isResponse } from "./auth";
+import { runAutoChecks, buildArtifact } from "./autochecks";
+import { rateLimit, DAY, SECOND } from "./ratelimit";
+
+const app = new Hono<{ Bindings: Bindings }>();
+const now = () => new Date().toISOString();
+const slugify = (s: string) => s.toLowerCase().replace(/[^\w]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "untitled";
+
+// ── Drafts (§34.2) ─────────────────────────────────────────────────────────
+app.post("/drafts", rateLimit({ key: "authoring", limit: 100, windowMs: SECOND }), async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const body = await c.req.json<{ kind: AssetKind; title?: string; graph?: unknown; manifest_draft?: unknown }>();
+ if (!["template", "filter", "effect"].includes(body.kind)) return c.json({ error: "invalid_kind" }, 400);
+ const draft: Draft = {
+ id: crypto.randomUUID(),
+ creatorId: id.creatorId,
+ kind: body.kind,
+ title: body.title ?? "Untitled",
+ graph: body.graph ?? { id: "draft", kind: body.kind, abi: "1.0", nodelibVersion: "1.0.0", nodes: [], edges: [], params: [] },
+ manifestDraft: body.manifest_draft ?? {},
+ updatedAt: now(),
+ createdAt: now(),
+ };
+ await getStore(c.env).putDraft(draft);
+ return c.json(draft, 201);
+});
+
+app.get("/drafts", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ return c.json({ drafts: await getStore(c.env).listDraftsByCreator(id.creatorId) });
+});
+
+app.get("/drafts/:id", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const draft = await getStore(c.env).getDraft(c.req.param("id"));
+ if (!draft || draft.creatorId !== id.creatorId) return c.json({ error: "not_found" }, 404);
+ return c.json(draft);
+});
+
+app.put("/drafts/:id", rateLimit({ key: "authoring", limit: 100, windowMs: SECOND }), async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const store = getStore(c.env);
+ const draft = await store.getDraft(c.req.param("id") ?? "");
+ if (!draft || draft.creatorId !== id.creatorId) return c.json({ error: "not_found" }, 404);
+ const body = await c.req.json<{ graph?: unknown; manifest_draft?: unknown; title?: string }>();
+ if (body.graph !== undefined) {
+ draft.graph = body.graph;
+ await store.pushSnapshot(draft.id, body.graph);
+ }
+ if (body.manifest_draft !== undefined) draft.manifestDraft = body.manifest_draft;
+ if (body.title !== undefined) draft.title = body.title;
+ draft.updatedAt = now();
+ await store.putDraft(draft);
+ return c.json(draft);
+});
+
+// Client-side pre-flight (§37.2): compile + report without submitting.
+app.post("/drafts/:id/validate", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const draft = await getStore(c.env).getDraft(c.req.param("id"));
+ if (!draft || draft.creatorId !== id.creatorId) return c.json({ error: "not_found" }, 404);
+ const graph = draft.graph as Graph;
+ if (draft.kind === "template") {
+ const tpl = (draft.manifestDraft as { template?: TemplateSource })?.template;
+ return c.json(tpl ? compileTemplate(tpl) : { ok: false, errors: [{ code: "no_template", message: "no template source" }] });
+ }
+ const validation = validateGraph(graph);
+ const compile = draft.kind === "filter" && validation.ok ? compileFilter(graph) : undefined;
+ return c.json({ validation, compile });
+});
+
+// Submit for review (§37.1, §38).
+app.post("/drafts/:id/submit", rateLimit({ key: "submission", limit: 10, windowMs: DAY }), async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const store = getStore(c.env);
+ const draft = await store.getDraft(c.req.param("id") ?? "");
+ if (!draft || draft.creatorId !== id.creatorId) return c.json({ error: "not_found" }, 404);
+
+ const graph = draft.graph as Graph;
+ const md = draft.manifestDraft as Partial<Manifest> & { template?: TemplateSource };
+ const checks = runAutoChecks(graph, draft.kind, md.template);
+
+ const submissionId = crypto.randomUUID();
+ if (!checks.ok) {
+ const submission: Submission = {
+ id: submissionId,
+ draftId: draft.id,
+ creatorId: id.creatorId,
+ state: "creator_feedback",
+ fxpkgUri: "",
+ validatorLog: checks,
+ createdAt: now(),
+ updatedAt: now(),
+ };
+ await store.putSubmission(submission);
+ return c.json({ submission, checks }, 422);
+ }
+
+ // resolve / create asset + next version
+ const slug = slugify(draft.title ?? "untitled");
+ let asset = await store.getAssetBySlug(id.creatorId, slug);
+ if (!asset) {
+ asset = { id: crypto.randomUUID(), creatorId: id.creatorId, slug, kind: draft.kind, category: md.category, createdAt: now() };
+ await store.putAsset(asset);
+ }
+ const versions = await store.listVersions(asset.id);
+ const versionNum = (versions[0]?.version ?? 0) + 1;
+
+ const build = buildArtifact(graph, {
+ schema_version: "1.0.0",
+ kind: draft.kind,
+ id: `${id.handle ?? id.creatorId}/${slug}`,
+ version: `${versionNum}.0.0`,
+ abi: graph.abi ?? "1.0",
+ title: md.title ?? draft.title ?? "Untitled",
+ description: md.description ?? "",
+ category: md.category,
+ tags: md.tags ?? [],
+ author: { handle: id.handle ?? id.creatorId, creator_id: id.creatorId },
+ params: graph.params ?? [],
+ license: md.license ?? "MIT",
+ authoring: graph.authoring
+ ? { mode: graph.authoring.mode, blueprint_id: graph.authoring.blueprintId, blueprint_version: graph.authoring.blueprintVersion }
+ : undefined,
+ });
+ if (!build.ok || !build.manifest) return c.json({ error: "build_failed", detail: build.errors }, 422);
+
+ const fxpkgUri = `fxpkg/${asset.id}/${versionNum}/asset.fxpkg`;
+ if (c.env.ASSETS_BUCKET && build.files) {
+ await c.env.ASSETS_BUCKET.put(`${fxpkgUri}.json`, JSON.stringify(build.files), { httpMetadata: { contentType: "application/json" } });
+ }
+
+ const version: AssetVersion = {
+ id: crypto.randomUUID(),
+ assetId: asset.id,
+ version: versionNum,
+ abi: graph.abi ?? "1.0",
+ manifest: build.manifest,
+ fxpkgUri,
+ reviewState: "submitted",
+ submittedAt: now(),
+ };
+ await store.putVersion(version);
+
+ const submission: Submission = {
+ id: submissionId,
+ draftId: draft.id,
+ assetVersionId: version.id,
+ creatorId: id.creatorId,
+ state: "human_review",
+ fxpkgUri,
+ validatorLog: checks,
+ createdAt: now(),
+ updatedAt: now(),
+ };
+ await store.putSubmission(submission);
+ return c.json({ submission, asset, version, checks }, 201);
+});
+
+// ── Creator's published assets (§34.2) ──────────────────────────────────────
+app.get("/me/assets", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const { items } = await getStore(c.env).listAssets({ creatorId: id.creatorId });
+ return c.json({ assets: items });
+});
+
+app.post("/me/assets/:id/rollback", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const store = getStore(c.env);
+ const asset = await store.getAsset(c.req.param("id"));
+ if (!asset || asset.creatorId !== id.creatorId) return c.json({ error: "not_found" }, 404);
+ const body = await c.req.json<{ version: number }>();
+ const target = await store.getVersion(asset.id, body.version);
+ if (!target || (target.reviewState !== "approved" && target.reviewState !== "published")) {
+ return c.json({ error: "version_not_approved" }, 400);
+ }
+ asset.currentVersion = body.version;
+ await store.putAsset(asset);
+ return c.json({ asset });
+});
+
+// ── Review tooling (§39) ────────────────────────────────────────────────────
+app.get("/submissions", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const state = c.req.query("state");
+ return c.json({ submissions: await getStore(c.env).listSubmissions(state) });
+});
+
+app.post("/submissions/:id/review", async (c) => {
+ const id = requireCreator(c);
+ if (isResponse(id)) return id;
+ const store = getStore(c.env);
+ const submission = await store.getSubmission(c.req.param("id"));
+ if (!submission) return c.json({ error: "not_found" }, 404);
+ const body = await c.req.json<{ decision: "approve" | "reject" | "changes"; notes?: string }>();
+ const target: SubmissionState = body.decision === "approve" ? "approved" : body.decision === "reject" ? "rejected" : "changes_requested";
+ if (!canTransition(submission.state, target)) {
+ return c.json({ error: "invalid_transition", from: submission.state, to: target }, 409);
+ }
+ submission.state = target;
+ submission.reviewerNotes = body.notes;
+ submission.reviewerId = id.creatorId;
+ submission.updatedAt = now();
+ await store.putSubmission(submission);
+
+ if (target === "approved" && submission.assetVersionId) {
+ const asset = await findAssetForVersion(store, submission.assetVersionId);
+ if (asset) {
+ const versions = await store.listVersions(asset.id);
+ const v = versions.find((x) => x.id === submission.assetVersionId);
+ if (v) {
+ v.reviewState = "published";
+ v.approvedAt = now();
+ await store.putVersion(v);
+ asset.currentVersion = v.version;
+ await store.putAsset(asset);
+ submission.state = "published";
+ await store.putSubmission(submission);
+ }
+ }
+ }
+ return c.json({ submission });
+});
+
+async function findAssetForVersion(store: ReturnType<typeof getStore>, versionId: string): Promise<Asset | undefined> {
+ const { items } = await store.listAssets({});
+ for (const asset of items) {
+ const vs = await store.listVersions(asset.id);
+ if (vs.some((v) => v.id === versionId)) return asset;
+ }
+ return undefined;
+}
+
+export default app;
diff --git a/apps/cloud/src/marketplace/types.ts b/apps/cloud/src/marketplace/types.ts
new file mode 100644
index 00000000..2655b602
--- /dev/null
+++ b/apps/cloud/src/marketplace/types.ts
@@ -0,0 +1,71 @@
+import type {
+ Asset,
+ AssetVersion,
+ Draft,
+ Submission,
+ EarningsEntry,
+ CreatorBalance,
+ Attribution,
+} from "@openreel/fxpkg";
+
+export type Bindings = {
+ TEMPLATES_BUCKET: R2Bucket;
+ SHARES_BUCKET: R2Bucket;
+ /** optional: durable marketplace storage; when absent an in-memory store is used */
+ ASSETS_BUCKET?: R2Bucket;
+ AI: Ai;
+ ENVIRONMENT: string;
+ /** secret used to verify HMAC-sealed marketplace events (§41.5) */
+ EVENT_HMAC_SECRET?: string;
+ /** durable storage for desktop/app crash + error reports (POST /crash) */
+ CRASHES_BUCKET?: R2Bucket;
+ /** bearer token guarding the crash list/read endpoints (GET /crash) */
+ CRASH_ADMIN_TOKEN?: string;
+};
+
+export interface AssetListFilter {
+ kind?: Asset["kind"];
+ category?: string;
+ creatorId?: string;
+ sort?: "trending" | "new" | "installs";
+ q?: string;
+ page?: number;
+ pageSize?: number;
+}
+
+export interface Store {
+ // assets
+ putAsset(a: Asset): Promise<void>;
+ getAsset(id: string): Promise<Asset | undefined>;
+ getAssetBySlug(creatorId: string, slug: string): Promise<Asset | undefined>;
+ listAssets(filter: AssetListFilter): Promise<{ items: Array<Asset & { latest?: AssetVersion }>; total: number }>;
+ // versions
+ putVersion(v: AssetVersion): Promise<void>;
+ getVersion(assetId: string, version: number): Promise<AssetVersion | undefined>;
+ listVersions(assetId: string): Promise<AssetVersion[]>;
+ latestApproved(assetId: string): Promise<AssetVersion | undefined>;
+ // drafts
+ putDraft(d: Draft): Promise<void>;
+ getDraft(id: string): Promise<Draft | undefined>;
+ listDraftsByCreator(creatorId: string): Promise<Draft[]>;
+ deleteDraft(id: string): Promise<void>;
+ pushSnapshot(draftId: string, graph: unknown): Promise<void>;
+ // submissions
+ putSubmission(s: Submission): Promise<void>;
+ getSubmission(id: string): Promise<Submission | undefined>;
+ listSubmissions(state?: string): Promise<Submission[]>;
+ // installs
+ install(userId: string, assetId: string): Promise<void>;
+ isInstalled(userId: string, assetId: string): Promise<boolean>;
+ listInstalls(userId: string): Promise<string[]>;
+ // money
+ addEarning(e: EarningsEntry): Promise<void>;
+ listEarnings(creatorId: string): Promise<EarningsEntry[]>;
+ getBalance(creatorId: string): Promise<CreatorBalance>;
+ setBalance(b: CreatorBalance): Promise<void>;
+ // attribution
+ addAttributions(a: Attribution[]): Promise<void>;
+ // events dedupe
+ seenExport(dedupeKey: string): Promise<boolean>;
+ markExport(dedupeKey: string): Promise<void>;
+}
diff --git a/apps/cloud/tsconfig.json b/apps/cloud/tsconfig.json
new file mode 100644
index 00000000..113eaf65
--- /dev/null
+++ b/apps/cloud/tsconfig.json
@@ -0,0 +1,42 @@
+{
+ "compilerOptions": {
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
+
+ /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
+ "target": "es2024",
+ /* Specify a set of bundled library declaration files that describe the target runtime environment. */
+ "lib": ["es2024"],
+ /* Specify type package names to be included without being referenced in a source file. */
+ "types": ["@cloudflare/workers-types"],
+ /* Specify what JSX code is generated. */
+ "jsx": "react-jsx",
+
+ /* Specify what module code is generated. */
+ "module": "es2022",
+ /* Specify how TypeScript looks up a file from a given module specifier. */
+ "moduleResolution": "node",
+ /* Enable importing .json files */
+ "resolveJsonModule": true,
+
+ /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
+ "allowJs": true,
+ /* Enable error reporting in type-checked JavaScript files. */
+ "checkJs": false,
+
+ /* Disable emitting files from a compilation. */
+ "noEmit": true,
+
+ /* Ensure that each file can be safely transpiled without relying on other imports. */
+ "isolatedModules": true,
+ /* Allow 'import x from y' when a module doesn't have a default export. */
+ "allowSyntheticDefaultImports": true,
+ /* Ensure that casing is correct in imports. */
+ "forceConsistentCasingInFileNames": true,
+
+ /* Enable all strict type-checking options. */
+ "strict": true,
+
+ /* Skip type checking all .d.ts files. */
+ "skipLibCheck": true
+ }
+}
diff --git a/apps/cloud/worker-configuration.d.ts b/apps/cloud/worker-configuration.d.ts
new file mode 100644
index 00000000..ea209442
--- /dev/null
+++ b/apps/cloud/worker-configuration.d.ts
@@ -0,0 +1,7 @@
+// Generated by Wrangler by running `wrangler types`
+
+interface Env {
+ ENVIRONMENT: "production";
+ TEMPLATES_BUCKET: R2Bucket;
+ SHARES_BUCKET: R2Bucket;
+}
diff --git a/apps/cloud/wrangler.jsonc b/apps/cloud/wrangler.jsonc
new file mode 100644
index 00000000..cb18b5ff
--- /dev/null
+++ b/apps/cloud/wrangler.jsonc
@@ -0,0 +1,38 @@
+{
+ "name": "openreel-cloud",
+ "main": "src/index.ts",
+ "compatibility_date": "2024-01-01",
+ "routes": [
+ {
+ "pattern": "api.openreel.video",
+ "custom_domain": true
+ }
+ ],
+ "ai": {
+ "binding": "AI"
+ },
+ "r2_buckets": [
+ {
+ "binding": "TEMPLATES_BUCKET",
+ "bucket_name": "openreel-templates"
+ },
+ {
+ "binding": "SHARES_BUCKET",
+ "bucket_name": "openreel-shares"
+ },
+ {
+ "binding": "ASSETS_BUCKET",
+ "bucket_name": "openreel-assets"
+ },
+ {
+ "binding": "CRASHES_BUCKET",
+ "bucket_name": "openreel-crashes"
+ }
+ ],
+ "vars": {
+ "ENVIRONMENT": "production"
+ },
+ "observability": {
+ "enabled": true
+ }
+}
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 63839d95..cc09a2f3 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -19,12 +19,6 @@ const EditorInterface = lazy(() =>
default: m.EditorInterface,
}))
);
-const MotionCreatorApp = lazy(() =>
- import("./motion/MotionCreatorApp").then((module) => ({
- default: module.MotionCreatorApp,
- }))
-);
-
const LoadingSpinner: React.FC<{ message: string }> = ({ message }) => (
<div className="h-screen w-screen bg-background flex flex-col items-center justify-center">
<div className="w-10 h-10 border-2 border-primary border-t-transparent rounded-full animate-spin mb-3" />
@@ -48,19 +42,12 @@ function App() {
const { route, params, navigate, parsedDimensions, fps } = useRouter();
const hasHandledInitialRoute = useRef(false);
- const isMotionHost =
- typeof window !== "undefined" &&
- window.location.hostname.startsWith("motion.");
- const isMotionSurface = isMotionHost || route === "motion";
-
useKieAIPoller();
useEffect(() => {
if (hasHandledInitialRoute.current) return;
- if (isMotionSurface) {
- hasHandledInitialRoute.current = true;
- } else if (route === "new") {
+ if (route === "new") {
hasHandledInitialRoute.current = true;
let projectName = "New Project";
@@ -107,7 +94,6 @@ function App() {
}
}, [
route,
- isMotionSurface,
params,
parsedDimensions,
fps,
@@ -147,11 +133,7 @@ function App() {
return (
<div className="h-screen w-screen bg-background text-text-primary overflow-hidden">
<MobileBlocker />
- {isMotionSurface ? (
- <Suspense fallback={<LoadingSpinner message="Loading Motion Creator..." />}>
- <MotionCreatorApp />
- </Suspense>
- ) : isSharePage ? (
+ {isSharePage ? (
<SharePage shareId={params.shareId!} />
) : showWelcome ? (
<WelcomeScreen initialTab={initialTab} />
diff --git a/apps/web/src/components/editor/EditorActionRail.tsx b/apps/web/src/components/editor/EditorActionRail.tsx
index df371236..d8318511 100644
--- a/apps/web/src/components/editor/EditorActionRail.tsx
+++ b/apps/web/src/components/editor/EditorActionRail.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback } from "react";
+import React from "react";
import {
ToolcraftDropdownMenu as DropdownMenu,
ToolcraftIconButton as IconButton,
@@ -48,7 +48,7 @@ const RailButton: React.FC<{
);
export const EditorActionRail: React.FC = () => {
- const { undo, redo, createMotionComposition } = useProjectStore();
+ const { undo, redo } = useProjectStore();
const {
openModal,
toggleKeyframeEditor,
@@ -77,13 +77,6 @@ export const EditorActionRail: React.FC = () => {
);
const themeActionLabel = `Theme: ${themeLabel}. Switch to ${nextThemeLabel}`;
- const handleCreateMotionScene = useCallback(async () => {
- const composition = await createMotionComposition("Motion Scene");
- if (composition) {
- navigate("motion", { compositionId: composition.id });
- }
- }, [createMotionComposition, navigate]);
-
return (
<nav
data-tour="toolbar"
@@ -120,11 +113,6 @@ export const EditorActionRail: React.FC = () => {
<div className="my-1.5 h-px w-6 bg-border" />
- <RailButton
- label="Create Motion Scene"
- icon="cube"
- onClick={() => void handleCreateMotionScene()}
- />
<RailButton
label="Action history"
icon="clock"
diff --git a/apps/web/src/components/editor/Toolbar.tsx b/apps/web/src/components/editor/Toolbar.tsx
index 572eadab..0dc9db74 100644
--- a/apps/web/src/components/editor/Toolbar.tsx
+++ b/apps/web/src/components/editor/Toolbar.tsx
@@ -7,7 +7,6 @@ import {
} from "@/icons/lucide-compat";
import { useProjectStore } from "../../stores/project-store";
import { useUIStore } from "../../stores/ui-store";
-import { useRouter } from "../../hooks/use-router";
import {
getExportEngine,
getDeviceProfile,
@@ -26,10 +25,6 @@ import { ScreenRecorder } from "./ScreenRecorder";
import { HistoryPanel } from "./inspector/HistoryPanel";
import { ProjectSwitcher } from "./ProjectSwitcher";
import { SettingsDialog } from "./settings/SettingsDialog";
-import {
- WorkspaceModeTabs,
- type WorkspaceMode,
-} from "../WorkspaceModeTabs";
import { Icon } from "@/icons/Icon";
import { toast } from "../../stores/notification-store";
import { useAnalytics, AnalyticsEvents } from "../../hooks/useAnalytics";
@@ -59,11 +54,9 @@ export const Toolbar: React.FC = () => {
const {
selectedItems,
setExportState: setGlobalExportState,
- setDesktopPage,
activeModal,
closeModal,
} = useUIStore();
- const { navigate } = useRouter();
const [isExportOpen, setIsExportOpen] = useState(false);
const [isExportDialogOpen, setIsExportDialogOpen] = useState(false);
const [isCompressOpen, setIsCompressOpen] = useState(false);
@@ -85,19 +78,6 @@ export const Toolbar: React.FC = () => {
}
}, [projectNameDraft, project.name, renameProject]);
- const handleWorkspaceModeSelect = useCallback(
- (mode: WorkspaceMode) => {
- if (mode === "motion") {
- setDesktopPage("motion");
- navigate("motion");
- return;
- }
- setDesktopPage("edit");
- navigate("editor");
- },
- [navigate, setDesktopPage],
- );
-
// selectedItems drives related UX in the editor (e.g. inspector context).
// Kept on the destructure list so future tweaks don't have to rewire it.
void selectedItems;
@@ -416,13 +396,6 @@ export const Toolbar: React.FC = () => {
return (
<header className="h-[60px] flex items-center gap-[18px] px-[18px] bg-bg-1 border-b border-border shrink-0 z-30 relative">
- {/* ─── Left: mode switch ────────────────────────────────── */}
- <WorkspaceModeTabs
- activeMode="video"
- onSelectMode={handleWorkspaceModeSelect}
- className="shrink-0"
- />
-
{/* ─── Center: project name ─────────────────────────────── */}
<div className="flex flex-1 min-w-0 items-center justify-center gap-1.5">
<ToolcraftTextInputControl
diff --git a/apps/web/src/components/editor/inspector/tabs/AnimateTab.tsx b/apps/web/src/components/editor/inspector/tabs/AnimateTab.tsx
index 8aeda02f..50ff7d92 100644
--- a/apps/web/src/components/editor/inspector/tabs/AnimateTab.tsx
+++ b/apps/web/src/components/editor/inspector/tabs/AnimateTab.tsx
@@ -1,7 +1,4 @@
import React from "react";
-import { ToolcraftClickableCard as ClickableCard } from "@openreel/ui";
-import { ToolcraftText as Text } from "@openreel/ui";
-import { Box, ExternalLink } from "@/icons/lucide-compat";
import {
KeyframesSection,
ClipTransitionSection,
@@ -11,8 +8,6 @@ import {
TextAnimationSection,
} from "../";
import { InspectorSection } from "../shell/InspectorSection";
-import { useRouter } from "../../../../hooks/use-router";
-import { useProjectStore } from "../../../../stores/project-store";
export interface AnimateTabProps {
clipId: string;
@@ -25,44 +20,8 @@ export const AnimateTab: React.FC<AnimateTabProps> = ({
clipType,
showTextSection,
}) => {
- const { navigate } = useRouter();
- const motionCompositionId = useProjectStore((state) => {
- const clip = state.project.timeline.tracks
- .flatMap((track) => track.clips)
- .find((candidate) => candidate.id === clipId);
- return typeof clip?.metadata?.motionCompositionId === "string"
- ? clip.metadata.motionCompositionId
- : null;
- });
- const motionComposition = useProjectStore((state) =>
- motionCompositionId
- ? (state.project.motionCompositions ?? []).find(
- (composition) => composition.id === motionCompositionId,
- )
- : undefined,
- );
-
return (
<>
- {motionCompositionId && motionComposition && (
- <InspectorSection title="Motion Scene" sectionId="motion-scene">
- <ClickableCard
- label={`Open ${motionComposition.name} motion scene`}
- className="flex w-full items-center justify-between rounded-md border border-border bg-bg-2 px-3 py-2 text-left text-sm text-fg hover:bg-hover"
- onClick={() =>
- navigate("motion", { compositionId: motionCompositionId })
- }
- >
- <Text as="span" type="body" className="flex min-w-0 items-center gap-2">
- <Box size={16} className="text-accent" />
- <Text as="span" type="body" className="truncate">
- {motionComposition.name}
- </Text>
- </Text>
- <ExternalLink size={14} className="text-fg-3" />
- </ClickableCard>
- </InspectorSection>
- )}
<InspectorSection title="Keyframes" sectionId="keyframes">
<KeyframesSection clipId={clipId} />
</InspectorSection>
diff --git a/apps/web/src/components/editor/panels/TemplatesTab.tsx b/apps/web/src/components/editor/panels/TemplatesTab.tsx
index fa6988f9..3d34a701 100644
--- a/apps/web/src/components/editor/panels/TemplatesTab.tsx
+++ b/apps/web/src/components/editor/panels/TemplatesTab.tsx
@@ -1,11 +1,10 @@
import React, { useState, useEffect, useCallback, useMemo } from "react";
-import { Box, Search, Layout, Clock } from "@/icons/lucide-compat";
+import { Search, Layout, Clock } from "@/icons/lucide-compat";
import { ToolcraftButton as Button } from "@openreel/ui";
import { ToolcraftSelectableCard as SelectableCard } from "@openreel/ui";
import { ToolcraftTextInputControl } from "@openreel/ui";
import { useEngineStore } from "../../../stores/engine-store";
import { useProjectStore } from "../../../stores/project-store";
-import { useRouter } from "../../../hooks/use-router";
import type {
TemplateSummary,
TemplateCategory,
@@ -21,10 +20,6 @@ export const TemplatesTab: React.FC = () => {
>("all");
const [loading, setLoading] = useState(true);
const [applying, setApplying] = useState<string | null>(null);
- const createMotionComposition = useProjectStore(
- (state) => state.createMotionComposition,
- );
- const { navigate } = useRouter();
useEffect(() => {
let cancelled = false;
@@ -150,33 +145,6 @@ export const TemplatesTab: React.FC = () => {
))}
</div>
- <button
- type="button"
- aria-label="Start a Motion Creator template"
- className="flex min-h-[72px] w-full min-w-0 items-center gap-3 rounded-lg border border-primary/35 bg-primary/10 p-3 text-left transition-colors hover:bg-primary/15"
- onClick={async () => {
- const composition = await createMotionComposition(
- "Motion Template Scene",
- "motion-ad-card",
- );
- if (composition) {
- navigate("motion", { compositionId: composition.id });
- }
- }}
- >
- <span className="grid h-10 w-10 place-items-center rounded-md bg-primary text-white">
- <Box size={18} />
- </span>
- <span className="min-w-0 flex-1 overflow-hidden">
- <span className="block truncate text-xs font-semibold text-text-primary">
- Start a Motion Creator template
- </span>
- <span className="mt-0.5 block overflow-hidden text-ellipsis text-[10px] leading-4 text-text-muted [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:2]">
- Ads, app UI demos, lower thirds, social hooks, logo reveals, and end screens.
- </span>
- </span>
- </button>
-
{filteredTemplates.length === 0 ? (
<div className="text-center py-8 text-text-muted text-xs">
No templates found
diff --git a/apps/web/src/config/features.ts b/apps/web/src/config/features.ts
new file mode 100644
index 00000000..301f4b8b
--- /dev/null
+++ b/apps/web/src/config/features.ts
@@ -0,0 +1,5 @@
+/**
+ * Product-level feature switches. Keep disabled features wired behind these
+ * constants so they can be restored without reviving stale navigation paths.
+ */
+export const MOTION_CREATOR_ENABLED = false;
diff --git a/apps/web/src/desktop/DesktopApp.test.tsx b/apps/web/src/desktop/DesktopApp.test.tsx
index 03118239..48dd5cd6 100644
--- a/apps/web/src/desktop/DesktopApp.test.tsx
+++ b/apps/web/src/desktop/DesktopApp.test.tsx
@@ -23,10 +23,6 @@ vi.mock("./pages/EditPage", () => ({
EditPage: () => null,
}));
-vi.mock("./pages/MotionPage", () => ({
- MotionPage: () => null,
-}));
-
vi.mock("./editor/DesktopExportButton", () => ({
DesktopExportButton: () => <Button label="Video Export" />,
}));
@@ -84,7 +80,7 @@ describe("DesktopApp", () => {
expect(getByTestId("desktop-workspace")).toBeTruthy();
});
- it("shows the video export only while the Video Editing workspace is active", () => {
+ it("keeps video editing actions available for stale motion state", () => {
mockHasProject(true);
const editView = render(<DesktopApp />);
expect(editView.getByRole("button", { name: "Video Export" })).toBeTruthy();
@@ -92,9 +88,8 @@ describe("DesktopApp", () => {
useUIStore.setState({ desktopPage: "motion" });
const motionView = render(<DesktopApp />);
- expect(
- motionView.queryByRole("button", { name: "Video Export" }),
- ).toBeNull();
+ expect(motionView.getByRole("button", { name: "Video Export" })).toBeTruthy();
+ expect(motionView.getByRole("button", { name: "AI Editor" })).toBeTruthy();
});
it("toggles the AI Editor side panel from the desktop title bar", () => {
diff --git a/apps/web/src/desktop/DesktopApp.tsx b/apps/web/src/desktop/DesktopApp.tsx
index 7376019d..9f73d575 100644
--- a/apps/web/src/desktop/DesktopApp.tsx
+++ b/apps/web/src/desktop/DesktopApp.tsx
@@ -29,13 +29,10 @@ function detectPlatform(): string {
export function DesktopApp(): JSX.Element {
const platform = detectPlatform();
const hasProject = useProjectStore((state) => state.hasOpenProject);
- const desktopPage = useUIStore((state) => state.desktopPage);
const agentChatVisible = useUIStore(
(state) => state.panels.agentChat?.visible ?? false,
);
const togglePanel = useUIStore((state) => state.togglePanel);
- const isVideoEditing = desktopPage !== "motion";
-
// Drive native-menu actions into the app: undo/redo hit the project store
// directly; new/open/export are broadcast as events for the relevant UI to
@@ -96,7 +93,7 @@ export function DesktopApp(): JSX.Element {
return (
<div className="openreel-desktop isolate flex h-screen w-screen flex-col overflow-hidden bg-bg text-fg">
<DesktopTitleBar platform={platform}>
- {hasProject && isVideoEditing ? (
+ {hasProject ? (
<Button
label="AI Editor"
variant={agentChatVisible ? "primary" : "secondary"}
@@ -107,7 +104,7 @@ export function DesktopApp(): JSX.Element {
aria-pressed={agentChatVisible}
/>
) : null}
- {hasProject && isVideoEditing ? <DesktopExportButton /> : null}
+ {hasProject ? <DesktopExportButton /> : null}
<Button
label="Settings"
variant="secondary"
diff --git a/apps/web/src/desktop/shell/Workspace.test.tsx b/apps/web/src/desktop/shell/Workspace.test.tsx
index 9200999e..84ec2443 100644
--- a/apps/web/src/desktop/shell/Workspace.test.tsx
+++ b/apps/web/src/desktop/shell/Workspace.test.tsx
@@ -1,6 +1,6 @@
import "../../test/install-local-storage-mock";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { cleanup, render, screen } from "@testing-library/react";
import type React from "react";
import { useUIStore } from "../../stores/ui-store";
@@ -10,10 +10,6 @@ vi.mock("../editor/EditorBootstrapGate", () => ({
vi.mock("../pages/EditPage", () => ({
EditPage: () => <div data-testid="edit-page" />,
}));
-vi.mock("../pages/MotionPage", () => ({
- MotionPage: () => <div data-testid="motion-page" />,
-}));
-
import { Workspace } from "./Workspace";
describe("Workspace", () => {
@@ -26,32 +22,17 @@ describe("Workspace", () => {
window.localStorage.clear();
});
- it("renders two primary workspace tabs above the editor", async () => {
+ it("renders only the video editor workspace", async () => {
render(<Workspace />);
expect(screen.getByTestId("desktop-workspace")).toBeTruthy();
- expect(
- screen.getByRole("tablist", { name: "Desktop workspaces" }),
- ).toBeTruthy();
- expect(
- screen.getByRole("tab", { name: "Video Editing" }),
- ).toHaveAttribute("aria-selected", "true");
- expect(
- screen.getByRole("tab", { name: "Motion Creation" }),
- ).toHaveAttribute("aria-selected", "false");
- expect(screen.queryByRole("tab", { name: "Color" })).toBeNull();
- expect(screen.queryByRole("tab", { name: "Deliver" })).toBeNull();
+ expect(screen.queryByRole("tablist")).toBeNull();
expect(await screen.findByTestId("edit-page")).toBeTruthy();
});
- it("switches between video editing and motion creation", async () => {
+ it("does not render Motion Creator for stale motion state", async () => {
+ useUIStore.setState({ desktopPage: "motion" });
render(<Workspace />);
-
- fireEvent.click(screen.getByRole("tab", { name: "Motion Creation" }));
-
- expect(useUIStore.getState().desktopPage).toBe("motion");
- expect(await screen.findByTestId("motion-page")).toBeTruthy();
- expect(
- screen.getByRole("tab", { name: "Motion Creation" }),
- ).toHaveAttribute("aria-selected", "true");
+ expect(await screen.findByTestId("edit-page")).toBeTruthy();
+ expect(screen.queryByTestId("motion-page")).toBeNull();
});
});
diff --git a/apps/web/src/desktop/shell/Workspace.tsx b/apps/web/src/desktop/shell/Workspace.tsx
index 742b35fc..d968d80f 100644
--- a/apps/web/src/desktop/shell/Workspace.tsx
+++ b/apps/web/src/desktop/shell/Workspace.tsx
@@ -1,48 +1,17 @@
import type { JSX } from "react";
import { lazy, Suspense } from "react";
import { EditorBootstrapGate } from "../editor/EditorBootstrapGate";
-import { useUIStore, type DesktopPage } from "../../stores/ui-store";
-import {
- WorkspaceModeTabs,
- type WorkspaceMode,
-} from "../../components/WorkspaceModeTabs";
const EditPage = lazy(() =>
import("../pages/EditPage").then((module) => ({ default: module.EditPage })),
);
-const MotionPage = lazy(() =>
- import("../pages/MotionPage").then((module) => ({ default: module.MotionPage })),
-);
-
-type PrimaryDesktopPage = Extract<DesktopPage, "edit" | "motion">;
-
export function Workspace(): JSX.Element {
- const desktopPage = useUIStore((state) => state.desktopPage);
- const setDesktopPage = useUIStore((state) => state.setDesktopPage);
- const activePage: PrimaryDesktopPage =
- desktopPage === "motion" ? "motion" : "edit";
- const activeMode: WorkspaceMode =
- activePage === "motion" ? "motion" : "video";
-
return (
<div className="flex h-full min-h-0 flex-col bg-bg text-fg" data-testid="desktop-workspace">
- <div className="flex h-10 shrink-0 items-center justify-center border-b border-border bg-bg-1 px-3">
- <WorkspaceModeTabs
- activeMode={activeMode}
- ariaLabel="Desktop workspaces"
- accessibleLabels={{
- video: "Video Editing",
- motion: "Motion Creation",
- }}
- onSelectMode={(mode) =>
- setDesktopPage(mode === "motion" ? "motion" : "edit")
- }
- />
- </div>
<EditorBootstrapGate>
<Suspense fallback={<div className="grid h-full place-items-center text-sm text-fg-muted">Loading…</div>}>
<div className="min-h-0 flex-1">
- {activePage === "motion" ? <MotionPage /> : <EditPage />}
+ <EditPage />
</div>
</Suspense>
</EditorBootstrapGate>
diff --git a/apps/web/src/desktop/start/DesktopStartScreen.test.tsx b/apps/web/src/desktop/start/DesktopStartScreen.test.tsx
index 326af0e2..46b23b48 100644
--- a/apps/web/src/desktop/start/DesktopStartScreen.test.tsx
+++ b/apps/web/src/desktop/start/DesktopStartScreen.test.tsx
@@ -8,7 +8,6 @@ const actionMocks = vi.hoisted(() => ({
listRecentProjects: vi.fn(),
openRecentProject: vi.fn(),
startNewProject: vi.fn(),
- startNewMotionProject: vi.fn(),
}));
vi.mock("./desktop-project-actions", async () => {
@@ -20,7 +19,6 @@ vi.mock("./desktop-project-actions", async () => {
listRecentProjects: actionMocks.listRecentProjects,
openRecentProject: actionMocks.openRecentProject,
startNewProject: actionMocks.startNewProject,
- startNewMotionProject: actionMocks.startNewMotionProject,
};
});
@@ -33,7 +31,6 @@ describe("DesktopStartScreen", () => {
actionMocks.listRecentProjects.mockResolvedValue([]);
actionMocks.openRecentProject.mockResolvedValue(true);
actionMocks.startNewProject.mockReset();
- actionMocks.startNewMotionProject.mockReset();
useUIStore.setState({ desktopPage: "edit" });
});
@@ -50,19 +47,14 @@ describe("DesktopStartScreen", () => {
fireEvent.click(screen.getByRole("button", { name: /Horizontal/ }));
expect(actionMocks.startNewProject).toHaveBeenCalledWith(DESKTOP_FORMATS[1]);
- expect(actionMocks.startNewMotionProject).not.toHaveBeenCalled();
expect(useUIStore.getState().desktopPage).toBe("edit");
});
- it("starts a Motion Creator project after selecting the motion mode", async () => {
+ it("does not offer a Motion Creator project mode", async () => {
render(<DesktopStartScreen />);
await screen.findByText("No recent projects yet. Start a new project above.");
- fireEvent.click(screen.getByRole("checkbox", { name: /Motion Creator/ }));
- fireEvent.click(screen.getByRole("button", { name: /Square/ }));
-
- expect(actionMocks.startNewMotionProject).toHaveBeenCalledWith(DESKTOP_FORMATS[2]);
- expect(actionMocks.startNewProject).not.toHaveBeenCalled();
- expect(useUIStore.getState().desktopPage).toBe("motion");
+ expect(screen.queryByText("Motion Creator")).toBeNull();
+ expect(screen.queryByRole("checkbox")).toBeNull();
});
});
diff --git a/apps/web/src/desktop/start/DesktopStartScreen.tsx b/apps/web/src/desktop/start/DesktopStartScreen.tsx
index e52ae990..84eaefe5 100644
--- a/apps/web/src/desktop/start/DesktopStartScreen.tsx
+++ b/apps/web/src/desktop/start/DesktopStartScreen.tsx
@@ -4,16 +4,14 @@ import { ToolcraftBadge } from "@openreel/ui";
import { ToolcraftCard as Card } from "@openreel/ui";
import { ToolcraftClickableCard as ClickableCard } from "@openreel/ui";
import { ToolcraftHeading as Heading } from "@openreel/ui";
-import { ToolcraftSelectableCard as SelectableCard } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
-import { Box, Smartphone, Monitor, Square, Film } from "@/icons/lucide-compat";
+import { Smartphone, Monitor, Square, Film } from "@/icons/lucide-compat";
import { OpenReelMark } from "../brand/OpenReelMark";
import { Icon } from "@/icons/Icon";
import {
DESKTOP_FORMATS,
startNewProject,
- startNewMotionProject,
listRecentProjects,
openRecentProject,
type NewProjectFormat,
@@ -40,13 +38,10 @@ function formatSavedAt(savedAt: number): string {
return date.toLocaleDateString();
}
-type ProjectMode = "edit" | "motion";
-
export function DesktopStartScreen(): JSX.Element {
const [recents, setRecents] = useState<RecentEntry[]>([]);
const [loadingRecents, setLoadingRecents] = useState<boolean>(true);
const [openingId, setOpeningId] = useState<string | null>(null);
- const [projectMode, setProjectMode] = useState<ProjectMode>("edit");
const setDesktopPage = useUIStore((state) => state.setDesktopPage);
useEffect(() => {
@@ -77,17 +72,11 @@ export function DesktopStartScreen(): JSX.Element {
}, [setDesktopPage]);
const handleStartProject = useCallback((format: NewProjectFormat) => {
- if (projectMode === "motion") {
- setDesktopPage("motion");
- startNewMotionProject(format);
- return;
- }
-
setDesktopPage("edit");
startNewProject(format);
- }, [projectMode, setDesktopPage]);
+ }, [setDesktopPage]);
- const formatModeLabel = projectMode === "motion" ? "Motion Creator" : "Video Editor";
+ const formatModeLabel = "Video Editor";
return (
<div className="h-full overflow-y-auto bg-bg text-fg">
@@ -98,50 +87,8 @@ export function DesktopStartScreen(): JSX.Element {
<Heading level={1}>New Project</Heading>
</div>
<Text type="supporting" display="block" className="mt-1">
- Choose a workspace and format. You can change this later.
+ Choose a format. You can change this later.
</Text>
- <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2">
- <SelectableCard
- label="Video Editor"
- isSelected={projectMode === "edit"}
- onChange={() => setProjectMode("edit")}
- padding={5}
- >
- <div className="flex items-start gap-4">
- <span className="flex h-11 w-11 items-center justify-center rounded-md bg-accent-soft text-accent">
- <Film size={22} aria-hidden />
- </span>
- <span>
- <Text type="large" weight="bold" display="block">
- Video Editor
- </Text>
- <Text type="supporting" display="block" className="mt-1">
- Cut, trim, caption, color, and export quickly.
- </Text>
- </span>
- </div>
- </SelectableCard>
- <SelectableCard
- label="Motion Creator"
- isSelected={projectMode === "motion"}
- onChange={() => setProjectMode("motion")}
- padding={5}
- >
- <div className="flex items-start gap-4">
- <span className="flex h-11 w-11 items-center justify-center rounded-md bg-accent text-accent-fg">
- <Box size={22} aria-hidden />
- </span>
- <span>
- <Text type="large" weight="bold" display="block">
- Motion Creator
- </Text>
- <Text type="supporting" display="block" className="mt-1">
- Design animated ads, lower thirds, app demos, and scene graphics.
- </Text>
- </span>
- </div>
- </SelectableCard>
- </div>
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
{DESKTOP_FORMATS.map((format) => {
const FormatIcon = FORMAT_ICONS[format.id] ?? Film;
diff --git a/apps/web/src/hooks/use-router.test.tsx b/apps/web/src/hooks/use-router.test.tsx
new file mode 100644
index 00000000..41766678
--- /dev/null
+++ b/apps/web/src/hooks/use-router.test.tsx
@@ -0,0 +1,25 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useRouter } from "./use-router";
+
+afterEach(() => {
+ window.location.hash = "";
+});
+
+describe("useRouter", () => {
+ it("opens stale Motion Creator links in the video editor", () => {
+ window.location.hash = "#/motion?compositionId=comp-1";
+
+ const { result } = renderHook(() => useRouter());
+
+ expect(result.current.route).toBe("editor");
+ });
+
+ it("normalizes Motion Creator navigation to the video editor", () => {
+ const { result } = renderHook(() => useRouter());
+
+ act(() => result.current.navigate("motion", { compositionId: "comp-1" }));
+
+ expect(window.location.hash).toBe("#/editor");
+ });
+});
diff --git a/apps/web/src/hooks/use-router.ts b/apps/web/src/hooks/use-router.ts
index 7cf1141d..95a05488 100644
--- a/apps/web/src/hooks/use-router.ts
+++ b/apps/web/src/hooks/use-router.ts
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useMemo } from "react";
import { shareBaseOrigin } from "../services/share-origin";
+import { MOTION_CREATOR_ENABLED } from "../config/features";
export type AppRoute =
| "welcome"
@@ -54,6 +55,10 @@ function parseHash(hash: string): RouterState {
params.shareId = pathParts[1];
}
+ if (route === "motion" && !MOTION_CREATOR_ENABLED) {
+ route = "editor";
+ }
+
return {
route: validRoutes.includes(route) ? route : "welcome",
params,
@@ -61,6 +66,10 @@ function parseHash(hash: string): RouterState {
}
function buildHash(route: AppRoute, params?: RouteParams): string {
+ if (route === "motion" && !MOTION_CREATOR_ENABLED) {
+ route = "editor";
+ params = undefined;
+ }
let hash = `#/${route}`;
if (params && Object.keys(params).length > 0) {
diff --git a/apps/web/src/services/agent/mcp-listener.test.ts b/apps/web/src/services/agent/mcp-listener.test.ts
index ca31df6c..3fe836f0 100644
--- a/apps/web/src/services/agent/mcp-listener.test.ts
+++ b/apps/web/src/services/agent/mcp-listener.test.ts
@@ -115,7 +115,7 @@ describe("handleMcpBridgeRequest", () => {
expect(res.result).toEqual({ ok: true, summary: "Deleted" });
});
- it("focuses the Motion Creator surface after successful MCP motion edits", async () => {
+ it("keeps the editor focused after successful MCP motion edits", async () => {
h.getTool.mockReturnValue({ domain: "motion" });
h.executeTool.mockResolvedValue({
ok: true,
@@ -136,7 +136,7 @@ describe("handleMcpBridgeRequest", () => {
);
expect(h.motionState.setPlayhead).toHaveBeenCalledWith(1.25);
expect(h.motionState.selectLayer).toHaveBeenCalledWith("layer-scene");
- expect(h.setDesktopPage).toHaveBeenCalledWith("motion");
+ expect(h.setDesktopPage).toHaveBeenCalledWith("edit");
});
it("opens newly activated scene3d compositions on their resolved preview frame", async () => {
@@ -221,7 +221,7 @@ describe("handleMcpBridgeRequest", () => {
);
expect(h.motionState.setPlayhead).toHaveBeenCalledWith(2.5);
expect(h.motionState.selectLayer).toHaveBeenCalledWith("layer-synced-scene");
- expect(h.setDesktopPage).toHaveBeenCalledWith("motion");
+ expect(h.setDesktopPage).toHaveBeenCalledWith("edit");
});
it("focuses the editor after an MCP motion insert", async () => {
diff --git a/apps/web/src/services/agent/mcp-listener.ts b/apps/web/src/services/agent/mcp-listener.ts
index ee5b38f3..b319c495 100644
--- a/apps/web/src/services/agent/mcp-listener.ts
+++ b/apps/web/src/services/agent/mcp-listener.ts
@@ -117,20 +117,6 @@ function getMotionLayerId(result: ToolResult): string | null {
);
}
-function insertedMotionIntoEditor(
- name: string,
- args: Record<string, unknown>,
- result: ToolResult,
-): boolean {
- if (name === "insert_motion_into_editor") return true;
- const data = getResultDataRecord(result);
- return (
- optionalString(data?.insertedInstanceId) !== null ||
- optionalString(data?.insertedClipId) !== null ||
- (args.insertIntoEditor === true && optionalString(data?.instanceId) !== null)
- );
-}
-
function followMcpMotionResult(
name: string,
args: Record<string, unknown>,
@@ -140,9 +126,7 @@ function followMcpMotionResult(
const compositionId = getMotionCompositionId(args, result);
if (!compositionId) return;
- useUIStore
- .getState()
- .setDesktopPage(insertedMotionIntoEditor(name, args, result) ? "edit" : "motion");
+ useUIStore.getState().setDesktopPage("edit");
const motion = useMotionStore.getState();
const activeChanged = motion.activeCompositionId !== compositionId;
diff --git a/apps/web/src/services/share-origin.test.ts b/apps/web/src/services/share-origin.test.ts
index b7a86f98..9e7f4bb6 100644
--- a/apps/web/src/services/share-origin.test.ts
+++ b/apps/web/src/services/share-origin.test.ts
@@ -23,4 +23,11 @@ describe("shareBaseOrigin", () => {
expect(shareBaseOrigin()).toBe(expected);
expect(getSharePageUrl("x")).toBe(`${expected}#/share/x`);
});
+
+ it("redirects disabled Motion Creator links to the video editor", () => {
+ const expected = `${window.location.origin}${window.location.pathname}`;
+ expect(generateShareableLink("motion", { compositionId: "comp-1" })).toBe(
+ `${expected}#/editor`,
+ );
+ });
});
diff --git a/apps/web/src/stores/chat-store.test.ts b/apps/web/src/stores/chat-store.test.ts
index 8186c8ad..2f533e51 100644
--- a/apps/web/src/stores/chat-store.test.ts
+++ b/apps/web/src/stores/chat-store.test.ts
@@ -3,6 +3,9 @@ import type { RunTurnInput, RunTurnResult } from "@openreel/agent";
const h = vi.hoisted(() => ({
runTurn: vi.fn(),
+ toOpenAITools: vi.fn((_names: Iterable<string>) => []),
+ getTool: vi.fn((_name: string): { domain: string } => ({ domain: "read" })),
+ selectToolsForPrompt: vi.fn((_context: string): string[] => []),
getSecret: vi.fn(async () => "test-key"),
isSessionUnlocked: vi.fn(() => true),
makeBYOKClient: vi.fn(() => ({ complete: vi.fn() })),
@@ -22,9 +25,10 @@ const h = vi.hoisted(() => ({
vi.mock("@openreel/agent", () => ({
runTurn: h.runTurn,
toAnthropicTools: () => [],
- toOpenAITools: () => [],
+ toOpenAITools: h.toOpenAITools,
buildSystemPrompt: () => "system",
- selectToolsForPrompt: () => [],
+ getTool: h.getTool,
+ selectToolsForPrompt: h.selectToolsForPrompt,
}));
vi.mock("../services/secure-storage", () => ({
@@ -93,6 +97,8 @@ describe("chat-store", () => {
h.settings.agentAutoConfirm = false;
h.settings.agentDryRun = false;
h.undoStackSize = 0;
+ h.getTool.mockImplementation((_name: string) => ({ domain: "read" }));
+ h.selectToolsForPrompt.mockReturnValue([]);
});
it("refuses to run without an open project", async () => {
@@ -148,6 +154,36 @@ describe("chat-store", () => {
});
});
+ it("does not expose Motion Creator tools while its view is disabled", async () => {
+ h.selectToolsForPrompt.mockReturnValue([
+ "list_clips",
+ "set_clip_transform",
+ "add_motion_layer",
+ ]);
+ h.getTool.mockImplementation((name: string) => ({
+ domain: name === "add_motion_layer" ? "motion" : "read",
+ }));
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "Done!",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("Animate the first clip");
+
+ expect(h.toOpenAITools).toHaveBeenCalledWith([
+ "list_clips",
+ "set_clip_transform",
+ ]);
+ expect(h.runTurn.mock.calls[0]?.[0].system).toContain(
+ "Motion Creator is temporarily disabled",
+ );
+ });
+
it("saves completed conversations and starts a fresh chat", async () => {
h.runTurn.mockImplementation(
impl(async ({ messages }) => ({
diff --git a/apps/web/src/stores/chat-store.ts b/apps/web/src/stores/chat-store.ts
index 76f1de8f..4fdf213e 100644
--- a/apps/web/src/stores/chat-store.ts
+++ b/apps/web/src/stores/chat-store.ts
@@ -4,6 +4,7 @@ import {
toAnthropicTools,
toOpenAITools,
buildSystemPrompt,
+ getTool,
selectToolsForPrompt,
} from "@openreel/agent";
import type {
@@ -23,6 +24,7 @@ import {
} from "./chat-history-store";
import { useSettingsStore } from "./settings-store";
import { useProjectStore } from "./project-store";
+import { MOTION_CREATOR_ENABLED } from "../config/features";
export type ChatStatus = "idle" | "running" | "awaiting_confirm" | "error";
@@ -301,10 +303,13 @@ export const useChatStore = create<ChatState>((set, get) => ({
.slice(-5)
.map((message) => message.content)
.join("\n");
- const selectedToolNames = selectToolsForPrompt(routingContext, {
+ const routedToolNames = selectToolsForPrompt(routingContext, {
maxTools: 120,
priorToolNames,
});
+ const selectedToolNames = MOTION_CREATOR_ENABLED
+ ? routedToolNames
+ : routedToolNames.filter((name) => getTool(name)?.domain !== "motion");
const tools =
provider === "anthropic-compatible"
? toAnthropicTools(selectedToolNames)
@@ -319,7 +324,14 @@ export const useChatStore = create<ChatState>((set, get) => ({
host,
llm,
tools,
- system: buildSystemPrompt(host, selectedToolNames),
+ system: [
+ buildSystemPrompt(host, selectedToolNames),
+ !MOTION_CREATOR_ENABLED
+ ? "Motion Creator is temporarily disabled. Do not suggest opening it or creating standalone Motion compositions. Complete edits with the available main-timeline clip, keyframe, transition, effect, audio, trim, and speed tools."
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n\n"),
messages: get().conversation,
dryRun,
confirmGate: autoConfirm
diff --git a/apps/web/src/stores/ui-store.test.ts b/apps/web/src/stores/ui-store.test.ts
index c54d1fac..6ec4ba5e 100644
--- a/apps/web/src/stores/ui-store.test.ts
+++ b/apps/web/src/stores/ui-store.test.ts
@@ -16,3 +16,14 @@ describe("ui-store inspectorActiveTab", () => {
expect(useUIStore.getState().inspectorActiveTab).toBe("color");
});
});
+
+describe("ui-store desktop page", () => {
+ beforeEach(() => {
+ useUIStore.setState({ desktopPage: "edit" });
+ });
+
+ it("redirects Motion Creator requests to the video editor while disabled", () => {
+ useUIStore.getState().setDesktopPage("motion");
+ expect(useUIStore.getState().desktopPage).toBe("edit");
+ });
+});
diff --git a/apps/web/src/stores/ui-store.ts b/apps/web/src/stores/ui-store.ts
index a6f12876..de03c900 100644
--- a/apps/web/src/stores/ui-store.ts
+++ b/apps/web/src/stores/ui-store.ts
@@ -1,6 +1,7 @@
import { create } from "zustand";
import { subscribeWithSelector, persist } from "zustand/middleware";
import type { PreviewQuality } from "../components/editor/preview/preview-resolution";
+import { MOTION_CREATOR_ENABLED } from "../config/features";
export type PanelId =
| "mediaLibrary"
@@ -577,7 +578,11 @@ export const useUIStore = create<UIState>()(
set({ inspectorActiveTab: tabId });
},
- setDesktopPage: (page) => set({ desktopPage: page }),
+ setDesktopPage: (page) =>
+ set({
+ desktopPage:
+ page === "motion" && !MOTION_CREATOR_ENABLED ? "edit" : page,
+ }),
setShowWelcomeScreen: (show: boolean) => {
set({ showWelcomeScreen: show });
@@ -592,7 +597,7 @@ export const useUIStore = create<UIState>()(
}),
{
name: "openreel-ui-preferences",
- version: 2,
+ version: 3,
migrate: (persisted: unknown, version: number) => {
const state = persisted as Record<string, unknown>;
if (version === 0) {
@@ -605,6 +610,9 @@ export const useUIStore = create<UIState>()(
}
state.panels = panels;
}
+ if (version < 3 && state.desktopPage === "motion") {
+ state.desktopPage = "edit";
+ }
return state;
},
partialize: (state) => ({
diff --git a/apps/web/wrangler.toml b/apps/web/wrangler.toml
index 17d5e1bd..c57a212a 100644
--- a/apps/web/wrangler.toml
+++ b/apps/web/wrangler.toml
@@ -6,7 +6,8 @@ pages_build_output_dir = "dist"
# This app requires special headers for SharedArrayBuffer (used by FFmpeg.wasm)
# Custom domains:
# - app.openreel.video opens the standard video editor flow
-# - motion.openreel.video opens the Motion Creator surface by hostname detection
+# - motion.openreel.video currently falls back to the standard editor while
+# Motion Creator is disabled in the web app feature configuration
[env.production]
name = "openreel"
diff --git a/docs/AGENT-CAPABILITIES.md b/docs/AGENT-CAPABILITIES.md
index d01dd948..0efda36e 100644
--- a/docs/AGENT-CAPABILITIES.md
+++ b/docs/AGENT-CAPABILITIES.md
@@ -2,7 +2,7 @@
# OpenReel Agent — Capability Reference
-The agent exposes **228 tools** spanning read/observe, project, track, clip, transform, effect, color, speed, audio, subtitle, keyframe, transition, marker, text and graphics domains — plus `execute_action` and `batch_actions` escape hatches for any capability without a dedicated tool.
+The agent exposes **303 tools** spanning read/observe, project, track, clip, transform, effect, color, speed, audio, subtitle, keyframe, transition, marker, text and graphics domains — plus `execute_action` and `batch_actions` escape hatches for any capability without a dedicated tool.
## Tools
@@ -59,7 +59,9 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
- **animate_creation_exploded_view** — Create or replace a semantic multi-object exploded-view animation for agent-native product parts or arbitrary creation objects, store per-object exploded-view recipe metadata on the affected assets, dirty generated caches, and sync bound Motion Creator scene3d position keyframes. Select with objectIds, partIds, or tags; omit selection to animate all visible selectable scene objects.
- **apply_creation_cloth_wave** — Add a first-pass procedural cloth/flag wave to a semantic creation object. This stores clothWave recipe metadata on the object's asset, adds a cloth recipe node, dirties generated caches, persists an editable animation clip, and syncs approximate scene3d rotation keyframes when a render binding exists. Use this for flags, fabric panels, ribbons, capes, and other simple cloth motion until a full cloth solver is available.
- **create_motion_composition** — Create a standalone Motion Creator composition with starter layers. Useful for intros, lower thirds, ads, app demos, and reusable scene graphics.
-- **create_creation_3d_scene** — Create a semantic OpenReel creation scene and a renderable Motion Creator scene3d composition in one call. Use this for arbitrary agent-built 3D worlds, product stages, environment layouts, UI-in-3D mockups, props, labels, and cinematic setups that must remain editable. `objects` uses the same fields as add_motion_3d_scene plus optional key, objectId, assetId, assetKind, materialId, materialModel, tags, and parentKey. Set insertIntoEditor=true to immediately place the rendered motion scene on the editor timeline. Returns semantic object ids and render object ids for follow-up set_creation_object_transform, set_creation_object_material, animate_creation_object, and set_creation_camera calls.
+- **delete_motion_composition** (destructive) — Delete a Motion Creator composition by compositionId. Destructive — removes the composition and any editor instances of it. Use to clean up throwaway or superseded comps.
+- **duplicate_motion_composition** — Deep-clone a Motion Creator composition into a new standalone composition with fresh ids for every layer, keyframe, mask, effect, text animator, expression, marker, light, and variable (no shared references); keyframe and expression property references to remapped mask/effect ids are rewritten to match. Optional name (defaults to '<name> Copy'). Returns the new compositionId.
+- **create_creation_3d_scene** — Create a semantic OpenReel creation scene and a renderable Motion Creator scene3d composition in one call. Use this for arbitrary agent-built 3D worlds, product stages, environment layouts, UI-in-3D mockups, props, labels, and cinematic setups that must remain editable. `objects` uses the same fields as add_motion_3d_scene plus optional key, objectId, assetId, assetKind, materialId, materialModel, tags, and parentKey. insertIntoEditor defaults to false so the scene stays in Motion Creator; set it true ONLY when the user explicitly wants the rendered scene placed on the main video-editor timeline. Returns semantic object ids and render object ids for follow-up set_creation_object_transform, set_creation_object_material, animate_creation_object, and set_creation_camera calls.
- **recover_motion_scene3d_to_creation** — Convert an existing multi-object Motion Creator scene3d layer into editable semantic creation assets/objects and a motion-scene3d render binding. Use this for older MCP-created scenes that render in Motion Creator but show no Creation workspace objects. It preserves the existing render object ids and creates creation state in-place; call sync_creation_scene_to_motion afterward only if the render layer later needs rebuilding.
- **sync_creation_scene_to_motion** — Create, repair, or refresh the Motion Creator scene3d composition/layer for a persisted semantic OpenReel creation scene. Use this when a creation scene exists but is not rendering, after project import/load recovery, after stale binding issues, or when agents need to regenerate the native scene3d layer from editable creation assets/objects/cameras/lights. Reuses an existing motion-scene3d render binding unless forceNew=true, and can insert the synced composition into the editor timeline.
- **add_creation_scene_object** — Append one editable semantic object to an existing OpenReel creation scene and sync the bound Motion Creator scene3d layer when a render binding exists. Uses the same object fields as create_creation_3d_scene/add_motion_3d_scene plus optional key, objectId, renderObjectId, assetId, assetKind, materialId, materialModel, tags, parentId, and parentKey. Returns the creation object id and render object id for set_creation_object_transform, set_creation_object_material, and animate_creation_object.
@@ -82,50 +84,106 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
- **add_creation_cutaway_plane** — Add an editable semantic cutaway plane to a creation/product scene and sync it as a translucent scene3d plane marker. The asset recipe stores normal/offset/target part metadata for future native clipping/boolean rendering while current previews show the cut plane visually.
- **add_creation_decal** — Add an editable semantic decal/logo/marking to a creation scene surface and sync it as a scene3d plane or text3d object. Stores decal projection metadata on the asset recipe for future native texture baking while current previews show the decal as an editable render object.
- **add_creation_ui_panel** — Add an editable 3D UI/screen/holographic panel to a creation scene and sync it as a scene3d plane with editable text3d child rows. Use it for device screens, spatial dashboards, product HUDs, and agent-authored interfaces that must remain semantic rather than baked video.
-- **create_product_cinematic_scene** — Create an editable high-detail product cinematic inside Motion Creator: a semantic multi-object 3D product assembly with materials, exploded-view animation, camera zoom/orbit keyframes, lights, room, and editable callout labels. Set insertIntoEditor=true to immediately place the rendered product cinematic on the editor timeline.
+- **create_product_cinematic_scene** — Create an editable high-detail product cinematic inside Motion Creator: a semantic multi-object 3D product assembly with materials, exploded-view animation, camera zoom/orbit keyframes, lights, room, and editable callout labels. insertIntoEditor defaults to false so it stays in Motion Creator; set it true ONLY when the user explicitly wants the rendered product cinematic placed on the main video-editor timeline.
- **add_creation_product_callout** — Add an editable Motion text callout to a semantic product/creation scene and record it in the scene's motion-scene3d render binding. Use this after create_product_cinematic_scene or create_creation_3d_scene to label product parts, internals, materials, UI panels, or hero details. The returned text layer can be restyled or animated with normal Motion text tools.
-- **add_motion_layer** — Add a layer to a Motion Creator composition. layerType is one of text|shape|image|group|null|composition|adjustment|particle. For image pass assetId (a composition asset id) or mediaId (a media library image). For composition pass refCompositionId (the nested comp to embed). Simple fields: name, text, color, width, height, shapeType.
+- **add_motion_layer** — Add a layer to a Motion Creator composition. layerType is one of text|shape|image|group|null|composition|adjustment|particle|scene3d. For image pass assetId (a composition asset id) or mediaId (a media library image). For composition pass refCompositionId (the nested comp to embed). scene3d creates a blank real-3D scene (one rounded-box hero object, studio lighting, default camera) — use set_motion_scene_object / add_motion_3d_object to populate it. For a bezier PEN shape set shapeType:'path' and supply pathData (an SVG path string, e.g. 'M 0 0 C 10 -20 40 -20 50 0') or pathPoints (an array of >=2 {x,y,inX?,inY?,outX?,outY?} vertices in layer-local pixels; in/out are absolute bezier handle coordinates) plus pathClosed (default true). Simple fields: name, text, color, width, height, shapeType.
- **apply_motion_template** — Create a new Motion Creator composition from a built-in motion template/preset.
- **generate_ad_scene** — Create a practical SaaS/product ad motion scene from headline/subheadline/brand color fields.
- **animate_layer** — Author keyframes on a layer property (e.g. transform.opacity, transform.position.x, transform.scale.x, transform.rotation). Either pass from/to/startTime/endTime for a simple two-keyframe tween, or pass a `keyframes` array of { time, value, easing? } (>=2, strictly increasing times). Easing must be one of the known easing names (see get_capabilities motion.easings).
-- **add_motion_keyframe** — Add or update a single keyframe at a time on a motion layer property (the AE 'stopwatch + set value at playhead' action). property is any animatable id (e.g. transform.scale.x, transform.position.y, transform.opacity, shape.cornerRadius, effect.<id>.<param>; see list_motion_animatable_properties). value defaults to the property's current value if omitted. easing is any known easing name. For a graph-editor curve, pass easing='bezier' with bezierIn {x,y} and bezierOut {x,y} normalized control points (0..1). Re-calling at the same time updates that keyframe in place.
+- **add_motion_keyframe** — Add or update a single keyframe at a time on a motion layer property (the AE 'stopwatch + set value at playhead' action). property is any animatable id: transform.* (e.g. transform.scale.x, transform.position.y, transform.opacity), shape.* (e.g. shape.cornerRadius), effect.<effectId>.<param>, mask.<maskId>.<prop> (prop = x|y|width|height|rotation|feather|expansion|opacity — mask bounds/feather keyframes), modifier.<modifierId>.<prop> (shape modifier fields, including repeater transform.position.x/y, transform.scale.x/y, transform.rotation, transform.opacity), and puppet.<pinId>.<prop>. Call list_motion_animatable_properties to enumerate the exact ids (including mask and modifier ids) for a layer. value defaults to the property's current value if omitted. easing is any known easing name. For a graph-editor curve, pass easing='bezier' with bezierIn {x,y} and bezierOut {x,y} normalized control points: bezierIn is P1 and bezierOut is P2 of the OUTGOING segment (this keyframe → the next one), normalized to that segment — x is the time fraction 0..1 across the segment and y is the value fraction of the segment's value delta. y may exceed [0,1] (e.g. y>1 overshoots past the target before settling, y<0 anticipates below the start). Re-calling at the same time updates that keyframe in place. roving (boolean) marks a middle keyframe as roving: its time is then AUTO-DERIVED (dropped from your input) so the property moves at constant speed between the surrounding non-roving anchor keyframes. A property's first and last keyframes can NEVER rove — requesting roving on an endpoint is a no-op. Toggling roving off restores an editable time.
- **move_motion_keyframe** — Retime a single existing keyframe (by keyframeId) to a new time on a motion layer — like dragging a key in the AE timeline. Get keyframeIds from list_motion_animatable_properties. If another keyframe of the same property already sits at the new time, they merge.
- **remove_motion_keyframe** (destructive) — Delete a single keyframe (by keyframeId) from a motion layer, or pass property to clear ALL keyframes on that property (turn the property back into a static value). Get keyframeIds from list_motion_animatable_properties.
-- **sync_motion_to_audio** (expensive) — Sync a motion composition to audio. If a `mediaId` (or audioClipId referencing audio with waveform data) is given, real beat markers are detected from the waveform; otherwise a beat grid is generated from `bpm`. Also adds an intensity variable.
+- **sync_motion_to_audio** (expensive) — Sync a motion composition to audio. If a `mediaId` (or audioClipId referencing audio with waveform data) is given, real beat markers are detected from the waveform; otherwise a beat grid is generated from `bpm`. Optional `sensitivity` (0-1, higher detects more beats) and `startTime` (seconds offset for the grid/detection). Also adds an intensity variable. Returns `markerTimes` (the beat times in seconds) so you can drive follow-up keyframing.
+- **set_motion_beat_markers** — Set the composition's beat markers explicitly from an array of `times` (seconds). Replaces any existing beat markers. Optional `strengths` (parallel array, 0-1; defaults to 1) and `bpm` (recorded on the beat analysis). Use apply_motion_preset_to_beats to animate a layer on these beats. Returns the marker times.
+- **remove_motion_beat_marker** (destructive) — Remove a single beat marker from the composition by its `index` (0-based position in the beat marker list). Remaining markers are re-indexed. Returns the updated marker times.
+- **apply_motion_preset_to_beats** — Apply an animation preset to a layer at every detected beat (run sync_motion_to_audio or set_motion_beat_markers first). presetId is one of the get_capabilities motion.animationPresets (e.g. pulse, scale-pop, fade-in). Optional: duration (per-beat, capped to the gap to the next beat), onlyDownbeats (bool), distance, intensity, startTime, endTime, maxBeats. Fails if the composition has no beat markers.
- **insert_motion_into_editor** — Place a motion composition into the normal video-editor timeline as a reusable rendered scene.
-- **render_motion_frame** (expensive) — Render a Motion Creator composition to a still image at a given time so YOU can SEE the current result and self-correct (layout, z-order, color, text wrap). Inputs: compositionId (required), timeSeconds (default 0), scale (1-2 supersample). Returns the image attached to the result. Expensive — requires confirmation.
+- **render_motion_frame** (expensive) — Render a Motion Creator composition to a still image at a given time so YOU can SEE the current result and self-correct (layout, z-order, color, text wrap). Inputs: compositionId (required), timeSeconds (default 0), scale (1-2 supersample), quality ('draft' = 1x fast, 'final' = 2x supersampled). An explicit scale overrides quality. Returns the image attached to the result. Expensive — requires confirmation.
- **render_creation_preview** (expensive) — Render a still preview image for a semantic OpenReel creation scene by resolving its bound Motion Creator scene3d composition/layer. Use this after create_creation_3d_scene, sync_creation_scene_to_motion, or product cinematic creation to visually inspect agent-native creation work. If the binding/composition/layer is missing, call sync_creation_scene_to_motion first.
-- **set_motion_layer_transform** — Set a layer's static transform without keyframes. Optional: x, y (pixel center), scale (uniform), scaleX, scaleY, rotation (degrees), opacity (0-1), anchorX, anchorY (pixels). Only the fields you pass change.
+- **set_motion_layer_transform** — Set a layer's static transform without keyframes. Optional: x, y (pixel center), z (depth for 3D-enabled layers), scale (uniform), scaleX, scaleY, rotation (degrees, Z axis), rotationX, rotationY, rotationZ (3D Euler degrees), perspective (camera distance in px for the preserve-3d container), opacity (0-1), anchorX, anchorY (pixels). Only the fields you pass change.
+- **set_motion_layer_name** — Rename any layer in a composition. name is the new label shown in the timeline/layer list (must be non-empty).
+- **duplicate_motion_layer** — Duplicate one or more layers (with their keyframes, effects, masks, and expressions). Pass either layerId (single) or layerIds (array). Groups duplicate their descendants too. Copies are offset 32px and named "<name> Copy". Returns duplicatedLayerIds (the new top-level copies, in request order).
+- **set_motion_layer_solo** — Toggle a layer's solo flag. solo=true isolates soloed layers in preview/render (all non-soloed, non-guide layers are hidden). solo=false clears it.
+- **set_motion_layer_guide** — Toggle a layer's guideLayer flag. guideLayer=true marks it a non-rendering reference layer (visible in the editor, excluded from export). guideLayer=false makes it render normally.
+- **set_motion_layer_3d** — Toggle a 2D layer's 3D container mode. preserve3d=true sets transform.transformStyle='preserve-3d' so the layer and its children compose in a shared 3D space (needed for nested 3D rotations/perspective). preserve3d=false resets to 'flat'.
+- **set_motion_layer_timing** — Move a layer on the timeline by setting its startTime and/or duration (seconds). Values snap to the composition frame rate and are clamped to be non-negative; duration and the resulting out point are clamped to the composition duration. Pass at least one of startTime, duration; only the fields you pass change.
+- **trim_motion_layer** — Trim a layer's in or out point to a composition-time (seconds). edge='in' moves startTime to time (holding the out point fixed); edge='out' moves the end to time (holding startTime fixed). Values snap to the frame rate; a minimum duration is enforced.
+- **split_motion_layer** — Split a layer into two at a composition-time (seconds). The original keeps the first half; a new layer covers the second half (with its keyframes shifted). time must fall strictly inside the layer's span. Returns layerIds: [firstHalfId, secondHalfId].
+- **slip_motion_layer** — Slip a layer's source content by delta seconds while holding its timeline startTime and duration fixed (shifts the layer's timeOffset by delta scaled by playbackRate). Only layers with a source time offset (precomp/composition and video layers) can slip; others are rejected.
+- **ripple_delete_motion_layer** (destructive) — Delete a layer and pull every later layer earlier by the deleted layer's duration, closing the gap it left (AE ripple delete). Locked layers are held in place unless includeLocked=true.
+- **ripple_motion_layers** — Shift every layer whose startTime is at or after fromTime (seconds) later or earlier by delta seconds, opening or closing time as a block (AE ripple insert/remove). Positive delta pushes layers later; negative pulls them earlier. Locked layers are held in place unless includeLocked=true; excludeLayerIds pins specific layers regardless. delta must be non-zero.
+- **create_motion_null_controller** — Create a null layer positioned at the average of the given layers and parent all of them to it, so transforming the null drives them together (AE null-object rig). layerIds is required (non-null layers only). Optional: name, guideColor (#hex). Returns controllerLayerId.
+- **add_motion_guide** — Add a ruler guide to the composition canvas. orientation is 'vertical' (a vertical line at x=position) or 'horizontal' (a horizontal line at y=position); position is in pixels. Optional: color (#hex), locked. Returns guideId.
+- **move_motion_guide** — Move an existing composition guide to a new position (pixels along its axis). Clamped to the composition bounds. Locked guides do not move unless includeLocked=true.
+- **remove_motion_guide** (destructive) — Remove a ruler guide from the composition canvas by guideId.
+- **set_motion_scene3d_lighting** — Set lighting + image-based environment on a scene3d layer (EEVEE-class Three.js renderer). Optional: environment (studio|warm|cool|sunset|city|dark|none), environmentUrl (equirect .hdr/.exr/.jpg/.png world map for reflections + lighting), environmentBackground (show the env as the backdrop), groundShadow, ambient, keyIntensity, rimIntensity (0-10), keyColor (#hex). Only the fields you pass change.
- **reorder_motion_layer** — Change a layer's stacking order in the composition. mode is front | back | forward | backward | to-index (with index). Later layers in composition.layers render on top.
- **remove_motion_layer** (destructive) — Delete one or more layers from a composition. Pass `layerId` and/or `layerIds` (array). Child layers parented to a removed layer are removed too, and dangling track-matte references are cleared. Use to clean up starter layers or iterate on a build.
- **update_motion_composition** — Update a composition's top-level settings. Optional: name, width, height, frameRate, duration, backgroundColor. Only the fields you pass change.
- **import_motion_font** — Register a custom font on a composition so text layers can use it. Inputs: family (required), source (required URL or data: URI for a woff2/woff/ttf/otf), weight?, style? (normal|italic). Appends to composition.fonts.
-- **set_motion_text_style** — Set the full visual style of a text layer. Optional: fontFamily, fontSize, fontWeight, color, align (left|center|right), lineHeight, letterSpacing, maxWidth (px, enables word wrap), verticalAlign (top|middle|bottom), fillGradient { type: linear|radial|conic, angle, center {x,y}, stops:[{offset,color,opacity?}] }, shadow { color, blur, offsetX, offsetY, spread?, inset? }, backgroundColor, backgroundPadding, backgroundRadius. Only the fields you pass change.
-- **attach_motion_expression** — Attach an expression to an animatable layer property. expressionType is a preset (sine|wiggle|drift|spring|loop|ping-pong|random|posterize) or 'expression' for a custom JavaScript expression supplied via `code` (available: value, time, wiggle(freq,amp), loopOut(), linear(), ease(), clamp(), random(), Math). Replaces any existing expression on that property.
+- **set_motion_text_style** — Set the full visual style of a text layer. Optional: fontFamily, fontSize, fontWeight, color, align (left|center|right), lineHeight, letterSpacing, maxWidth (px, enables word wrap), verticalAlign (top|middle|bottom), fillGradient { type: linear|radial|conic, angle, center {x,y}, stops:[{offset,color,opacity?}] }, shadow { color, blur, offsetX, offsetY, spread?, inset? }, stroke { color, width, over? } (outline around glyphs; width 0 clears it, over:true paints on top of the fill), backgroundColor, backgroundPadding, backgroundRadius. Only the fields you pass change.
+- **set_motion_text_content** — Replace the source text string of an existing text layer. Only mutates the layer's `.text`; styling, animators, and keyframes are untouched. Pass an empty string to clear the text. The layer referenced by layerId must be a text layer (else INVALID_PARAMS).
+- **attach_motion_expression** — Attach an expression to an animatable layer property. expressionType is a preset (sine|wiggle|drift|spring|loop|ping-pong|random|posterize) or 'expression' for a custom JavaScript expression supplied via `code`. Custom code may be a single expression ('value + 1') OR a multi-line body with an explicit return ('const a = value * 2;\nreturn a + 1;'). Scope: value, time, valueAtTime(t) (this property's pre-expression value at t), thisLayer (.index/.name/.value(propertyId)/.valueAtTime(propertyId,t)), key(n) (1-based -> {index,time,value}), numKeys, nearestKey(t), thisComp (.layer(nameOrIndex)/.numLayers/.duration/.width/.height/.frameRate), layer(nameOrIndex) -> handle whose .value(propertyId)/.valueAtTime(propertyId,t) fully evaluate another layer (its keyframes + its own expressions), effect(name)(paramName) reading an expression-control param, plus wiggle(freq,amp), loopOut() (cycle), linear(), ease(), clamp(), random(), Math. Cross-layer references are cycle-guarded (A<->B loops fall back to pre-expression values, never hang) and depth-capped at 8. On error the value falls back to the property base and the message is surfaced in the editor. For the built-in presets you may tune amplitude, frequency (cycles/sec), phase (offset), seed (random stream), and decay (spring settle) — omitted knobs use the preset's default (e.g. a slow wide wiggle is amplitude 60, frequency 0.5). Replaces any existing expression on that property.
- **remove_motion_expression** (destructive) — Remove an expression from a layer by expressionId.
+- **update_motion_expression** — Patch an existing expression in place (keeps its id, property, and enabled flag). Optional fields — only the ones you pass change: code (custom JavaScript body/expression), amplitude, frequency (cycles/sec), phase (offset), seed (random stream), decay (spring settle). Unlike attach_motion_expression this does NOT regenerate the id or reset untouched knobs, so it is the non-destructive way to tune a wiggle/spring/etc or repair a custom code string.
+- **toggle_motion_expression** — Enable or disable an expression on a layer by expressionId without removing it. When disabled the property falls back to its keyframed/base value and any stored error for that expression is cleared. `enabled` is required and must be a boolean.
+- **list_motion_expression_errors** (read-only) — Evaluate every enabled expression in a composition and return the compile/cycle/runtime errors, one entry per failing expression: { layerId, property, expressionId, error }. Use this to see why an attached custom expression is not driving its property (the value silently falls back to the property base on error). Returns an empty list when every expression evaluates cleanly.
+- **add_motion_expression_control** — Add an expression-control effect (Slider/Checkbox/Angle) to a layer. controlType is 'slider' (finite float, default 0), 'checkbox' (0 or 1, coerced), or 'angle' (degrees float, default 0). These render nothing on their own; they are named knobs an expression reads via effect("<name>")("value"). Optional name (defaults 'Slider Control'/'Checkbox Control'/'Angle Control') is the reference key; optional value sets the initial control value. The 'value' param is keyframable at effect.<id>.value (see list_motion_animatable_properties). Returns { effectId, name }.
+- **list_motion_shaders** (read-only) — Enumerate the built-in GPU shader library for Motion Creator. Returns fill shaders (procedural fills for shape/text layers), effect shaders (post-process effects on any visual layer), and text shaders (per-glyph animator shaders for text layers), each with its parameters (name, label, type, min, max, default, step) and its collection ('Paper' for the Paper Design catalog, null for the original built-ins). Use before set_motion_shader_fill / add_motion_shader_effect / add_motion_text_shader_animator to pick a valid shaderId and know its params. Optional category filter: 'fill', 'effect', or 'text'. Optional collection filter (e.g. 'Paper') narrows to one collection; an unknown collection returns empty lists, not an error.
+- **create_ai_shader** — Register a new AI-authored GPU shader (GLSL + params) into the project's shader library so it can be used like a built-in via set_motion_shader_fill / add_motion_effect / add_motion_text_shader_animator. category is 'fill', 'effect', or 'text'. glsl must be a WebGL2 GLSL ES 3.00 fragment shader following the authoring contract (#version 300 es; in vec2 vUv; uniform vec2 u_resolution; uniform float u_time; out vec4 fragColor; effect/text also declare uniform sampler2D u_input; text also uniform float u_progress; fills must NOT sample u_input). params is an array of { name, label, min, max, default, step, type?, control? }. If the shader fails the contract or GLSL compile, the tool returns INVALID_PARAMS with the error log so you can repair the source and retry. The created shaderId is namespaced 'ai-<slug>-<hash>' and persists with the project.
+- **list_ai_shaders** (read-only) — List the AI-authored (generated) shaders registered in the current project, each with its id, name, category, and parameters. These also appear in list_motion_shaders under their category.
+- **remove_ai_shader** (destructive) — Remove an AI-authored (generated) shader from the project's shader library by its shaderId (as returned by create_ai_shader / list_ai_shaders). Built-in shaders cannot be removed.
+- **set_motion_shader_fill** — Paint a shape or text layer with a procedural GPU fill shader. shaderId must be a fill shader from list_motion_shaders (category 'fill'). Supplied params are clamped to each param's [min,max]; unknown param names are ignored and missing ones use the shader default. Shape layers store it on style.fill; text layers store it on style.fillShader (overriding color).
+- **clear_motion_shader_fill** — Remove a procedural GPU fill shader previously applied with set_motion_shader_fill. For a text layer this strips style.fillShader so the layer falls back to its solid color/gradient. For a shape layer this resets style.fill.type to 'solid' (keeping the existing color and opacity) and drops the shader reference. Succeeds as a no-op if the layer has no shader fill. Applies only to shape or text layers.
- **add_motion_effect** — Add an effect (blur|drop-shadow|glow|color-adjust|invert|grayscale|sepia|levels|sharpen|posterize|directional-blur|noise|radial-blur|displace|backdrop-blur) to a layer with sensible preset defaults (backdrop-blur frosts what is behind the layer, radius ~16). Returns the new effectId.
-- **update_motion_effect** — Update a numeric effect parameter (radius|opacity|blur|offsetX|offsetY|intensity|brightness|contrast|saturation|hue) by effectId.
+- **add_motion_shader_effect** — Add a GPU post-process shader effect to any visual layer. shaderId must be an effect shader from list_motion_shaders (category 'effect'). Supplied params are clamped to each param's [min,max]; unknown param names are ignored and missing ones use the shader default. Returns the new effectId; edit params later with update_motion_effect.
+- **update_motion_effect** — Update a numeric effect parameter (radius|opacity|blur|offsetX|offsetY|intensity|brightness|contrast|saturation|hue|value|...) by effectId. Pass parameter='value' to statically set the control value of an expression-control effect (slider/checkbox/angle) — the same knob add_motion_expression_control seeds and that effect("<name>")("value") reads. Also accepts any parameter of a shader effect, referenced by that shader's param name (as listed by list_motion_shaders).
+- **transfer_motion_effect_stack** — Copy a source layer's complete ordered effect stack, including animated parameters and expressions, to one or more target layers. mode is append (default) or replace. All pasted effects, keyframes, and expressions receive independent identities.
- **remove_motion_effect** (destructive) — Remove an effect from a layer by effectId.
- **toggle_motion_effect** — Enable or disable an effect on a layer by effectId.
-- **add_motion_mask** — Add a rectangle, ellipse, or polygon mask to a layer. Optional: mode (add|subtract), inverted, feather, and for polygon a `points` array of {x,y} normalized [0,1] vertices. Returns the new maskId.
+- **reorder_motion_effect** — Move an effect one slot within a layer's effect stack. direction is 'up' (renders earlier — closer to the top of the stack) or 'down' (renders later). Effect order matters: later effects process the output of earlier ones. Returns INVALID_PARAMS if the effect is already at the top (up) or bottom (down) and cannot move further.
+- **add_motion_mask** — Add a rectangle, ellipse, polygon, or path (bezier) mask to a layer. Optional: mode (add|subtract), inverted, feather, expansion (px grow/shrink of the mask edge; positive grows), opacity (0-1 mask strength); for polygon a `points` array of {x,y} normalized [0,1] vertices; for path a `pathPoints` array of >=3 {x,y,inX?,inY?,outX?,outY?} vertices in layer-local pixel coordinates (handles optional). Returns the new maskId.
+- **transfer_motion_mask_stack** — Copy a source layer's complete mask stack, including animated mask properties, path keyframes, and expressions, to one or more target layers. mode is append (default) or replace. Every pasted mask and animation identity is regenerated.
- **update_motion_mask** — Update a mask's geometry/options by maskId. Optional normalized bounds (x|y|width|height in 0..1), rotation, mode, inverted, feather, expansion, opacity.
- **remove_motion_mask** (destructive) — Remove a mask from a layer by maskId.
-- **set_motion_track_matte** — Set a track matte on a layer, using another layer as the matte source. type is alpha|alpha-inverted|luma|luma-inverted.
+- **set_motion_mask_path** — Replace a path mask's bezier vertices. pathPoints is an array of >=3 {x,y,inX?,inY?,outX?,outY?} vertices in layer-local pixel coordinates (handles optional). The mask must have shape:path.
+- **add_motion_mask_path_keyframe** — Add or replace a mask-path keyframe (rotoscoping) at a time on a path mask. Optional pathPoints (>=3 {x,y,inX?,inY?,outX?,outY?} vertices in layer-local pixel coordinates) default to the mask's current path. The mask must have shape:path. Returns the keyframe id.
+- **set_motion_track_matte** — Set, toggle, or clear a track matte on a layer, using another layer as the matte source. type is alpha|alpha-inverted|luma|luma-inverted. Pass sourceLayerId=null to CLEAR the matte entirely. Pass enabled (bool) to enable/disable an existing matte without changing its source (defaults true when a source is given). When updating an existing matte, sourceLayerId and type are optional and merge onto the current matte.
- **set_motion_layer_blend_mode** — Set a layer's blend mode (see get_capabilities motion.blendModes / blendModes).
- **set_motion_layer_parent** — Parent one layer to another so it inherits the parent's transform. Pass parentId=null (or omit) to unparent. Cyclic parenting is rejected.
- **set_motion_layer_visibility** — Show or hide a motion layer.
- **set_motion_layer_lock** — Lock or unlock a motion layer.
-- **add_motion_shape_modifier** — Add a shape modifier (trim-paths|repeater|zig-zag|round-corners|wiggle-paths) to a shape layer. One modifier per type. Returns the modifierId.
-- **update_motion_shape_modifier** — Update numeric fields on a shape modifier by modifierId (e.g. trim-paths start/end/offset, repeater copies/offset, round-corners radius). Pass a `fields` object of numeric overrides.
+- **add_motion_shape_modifier** — Add a shape modifier (trim-paths|repeater|zig-zag|round-corners|wiggle-paths|offset-paths|pucker-bloat|twist) to a shape layer. One modifier per type. Returns the modifierId.
+- **update_motion_shape_modifier** — Update numeric fields on a shape modifier by modifierId (e.g. trim-paths start/end/offset, repeater copies/offset, round-corners radius). Pass a `fields` object of numeric overrides. Pass enabled (bool) to enable/disable (bypass) the modifier without removing it. At least one of fields or enabled is required.
- **remove_motion_shape_modifier** (destructive) — Remove a shape modifier from a shape layer by modifierId.
-- **add_motion_text_animator** — Add a per-glyph text animator preset (e.g. text-reveal-up, text-type-on) to a text layer. Returns the animatorId.
+- **add_motion_shape_group** — Add an intra-layer shape group to a shape layer's contents tree (the AE "Group (Shift+Cmd+G)" / compound-path container). Pass parentGroupId to nest inside an existing group, else it appends to the layer root. mergeMode is none|union|subtract|intersect|exclude (Merge Paths boolean applied to the group's children). Returns the groupId. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **add_motion_shape_to_group** — Add a path/shape item to a shape layer's contents tree. Pass parentGroupId to place it inside a group, else it appends to the layer root. shapeType is a 2D shape (rectangle|ellipse|path|...). For shapeType 'path' supply pathData (SVG path string) or pathPoints. position {x,y} offsets the item within its parent. Optional style {fill,stroke,...} overrides the inherited group/layer style (omit to inherit). Returns the itemId. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **update_motion_shape_item** — Patch a shape contents item (group or path) by itemId. patch fields: name, visible; groups also accept transform {anchor,position,scale,rotation,opacity} and mergeMode (none|union|subtract|intersect|exclude); path items also accept shapeType (2D only: rectangle|circle|ellipse|triangle|arrow|line|polygon|path|star — mesh-* 3D types are rejected), width, height, position {x,y}, pathData, style. transform/mergeMode on a path item, or width/height/pathData on a group, are rejected (kind-guard). Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **remove_motion_shape_item** (destructive) — Remove a shape contents item (group or path) by itemId from a shape layer, pruning it from wherever it is nested. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **move_motion_shape_item** — Reorder a shape contents item within its parent (direction up|down). Reordering changes both z-order and merge/operator fold order (document order matters for subtract/exclude). Boundary moves are no-ops. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **add_motion_shape_group_operator** — Append an operator to a shape group's ordered operator stack (applied left-to-right after the group's merge). operatorType is any of trim-paths|repeater|zig-zag|round-corners|wiggle-paths|offset-paths|pucker-bloat|twist. Duplicates are allowed. Pass params (numeric field overrides, e.g. { amount: 12 } / { angle: 90 }) to seed the operator. Returns the operatorId. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **update_motion_shape_group_operator** — Update a group operator's numeric fields (e.g. offset-paths.amount, twist.angle, trim-paths start/end) by operatorId. Pass a fields object of numeric overrides and/or enabled (bool) to bypass without removing. At least one of fields or enabled is required. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **remove_motion_shape_group_operator** (destructive) — Remove an operator from a shape group's operator stack by operatorId. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **merge_motion_shape_layers** (destructive) — Collapse >=2 shape layers into one grouped shape layer with a Merge Paths mode (the AE compound-icon workflow). mode is none|union|subtract|intersect|exclude, folded in the given layerIds order. Each source layer becomes a wrapper group whose transform (position, rotation, scale, anchor, opacity) mirrors the source layer so world placement is preserved; a source with its own contents tree keeps those items verbatim. The source layers are removed and one new shape layer holding the merged group is created (single undoable batch). Non-shape source layers (text/image/etc.) are rejected. Returns { layerId, groupId }. Keyframe any group transform, item path, or operator param via add_motion_keyframe with property ids contents.{itemId}.transform.{positionX|positionY|scaleX|scaleY|rotation|opacity}, contents.{itemId}.pathData, and contents.{itemId}.operator.{operatorId}.{param} (offset-paths.amount, pucker-bloat.amount, twist.angle).
+- **add_motion_text_animator** — Add a per-glyph text animator preset (e.g. text-reveal-up, text-type-on) to a text layer. Returns the animatorId. Optional one-call overrides on top of the preset (each field independently merged): name; enabled (start disabled with false); selector { basedOn: characters|words, start (0-100), end (0-100), offset }; timing { startTime, duration, stagger, direction: forward|reverse|center, easing: linear|ease|ease-in|ease-out }; properties { position {x,y}, scale {x,y}, rotation (deg), opacity (0-1) } (these are the from-values glyphs animate from toward the rest state).
+- **update_motion_text_animator** — Update an existing per-glyph text animator on a text layer by animatorId. Each field is optional and merged onto the current animator (unspecified fields are left intact): name; enabled (routes through the enable/disable path); selector { basedOn: characters|words, start (0-100), end (0-100), offset }; timing { startTime, duration, stagger, direction: forward|reverse|center, easing: linear|ease|ease-in|ease-out }; properties { position {x,y}, scale {x,y}, rotation (deg), opacity (0-1) }. Nested selector/timing/properties objects are themselves partially merged, so passing timing:{duration} changes only the duration.
+- **add_motion_text_shader_animator** — Add a per-glyph GPU shader animator (glyph-dissolve|glyph-glow-wave|chromatic-cascade|scanline-materialize) to a text layer. shaderId must be a text shader from list_motion_shaders (category 'text'). Pass shaderId='' (empty string) to CLEAR/detach the shader from the layer's text animator (back to no GPU shader) — returns { cleared: true }. The shader runs per glyph driven by the animator's staggered progress. Supplied params are clamped to each param's [min,max]; unknown names are ignored and missing ones use the shader default. Optional stagger/duration tune the per-glyph timing. Returns the new animatorId.
- **remove_motion_text_animator** (destructive) — Remove a text animator from a text layer by animatorId.
- **set_motion_camera** — Enable and configure the composition camera. Optional: position x/y/z, zoom, rotation (roll), perspective, and depthOfField (enabled, focusDistance, aperture, maxBlur).
-- **add_motion_light** — Add a light (ambient|point|directional) to the composition. Optional: color, intensity, position x/y, angle, radius. Returns the lightId.
+- **add_motion_marker** — Add a composition marker (a labelled timeline cue) at `time` seconds. Optional label (defaults to 'Marker') and color (#rrggbb). Markers annotate the Motion Creator timeline and are used for snapping. Returns the markerId.
+- **update_motion_marker** — Update a composition marker by markerId. Optional label, time (seconds), color (#rrggbb). Only the fields you pass change.
+- **remove_motion_marker** (destructive) — Remove a composition marker by markerId.
+- **animate_motion_camera** — Keyframe the composition camera over time — comp-level push-in, dolly, orbit, or roll. `position` is an array of { time, x?, y?, z?, easing? } (each channel keyframed independently; omit a channel to leave it alone). `zoom`, `rotation`, and `perspective` are arrays of { time, value, easing? }. Optional `depthOfField` { focusDistance?, aperture?, maxBlur? } enables DOF and sets those values. Times in seconds. Enables the camera automatically. Re-calling upserts keyframes at matching times.
+- **animate_motion_light** — Keyframe a composition light property over time by lightId. `property` is one of light.intensity, light.position.x/y/z, light.radius, light.falloff, light.angle, light.shadowOpacity, light.shadowSoftness. `keyframes` is an array of { time, value, easing? }. Times in seconds. Re-calling upserts keyframes at matching times.
+- **set_motion_light_style** — Update a light's non-numeric style by lightId. Optional: color (#rrggbb or rgba()), castsShadow (bool), name, enabled (bool), type (ambient|point|directional — changing the type renormalizes defaults). Only the fields you pass change. Use update_motion_light / animate_motion_light for numeric properties.
+- **set_motion_blur** — Configure composition-wide motion blur. Optional: enabled (bool), shutterAngle (0-720 deg; higher = more blur), shutterPhase (-360..360 deg), samples (2-32 sub-frame samples). Per-layer opt-in is controlled by set_motion_layer_motion_blur. Only the fields you pass change.
+- **set_motion_layer_motion_blur** — Enable or disable motion blur for a single layer by layerId (per-layer opt-in). Composition motion blur must also be enabled via set_motion_blur for the effect to render.
+- **add_motion_light** — Add a light (ambient|point|directional) to the composition. Optional: color, intensity, position x/y/z, angle, radius, falloff (light attenuation exponent), castsShadow (bool), shadowOpacity (0-1), shadowSoftness (px blur). Returns the lightId.
- **update_motion_light** — Update a light's numeric property by lightId. property is one of light.intensity, light.position.x/y/z, light.radius, light.falloff, light.angle, light.shadowOpacity, light.shadowSoftness.
- **remove_motion_light** (destructive) — Remove a light from the composition by lightId.
- **create_motion_variable** — Create a composition variable (text|number|color|boolean|media). Returns the variableId. Variables can be bound to layer targets via bind_motion_variable.
-- **update_motion_variable** — Update a composition variable's name and/or value by variableId.
+- **update_motion_variable** — Update a composition variable by variableId. Optional name, value, and variableType (text|number|color|boolean|media). Changing variableType re-coerces the value to the new type (e.g. number -> text). Only the fields you pass change.
+- **delete_motion_variable** (destructive) — Delete a composition variable by variableId. Any layer bindings referencing it become inert. Use with care — bound layers will fall back to their static values.
- **bind_motion_variable** — Bind a composition variable to a compatible layer target (e.g. text.content, text.color, shape.fill.color, transform.opacity, layer.visible, image.assetId). Use get_motion_composition to find ids.
- **unbind_motion_variable** (destructive) — Remove a variable binding from a layer by bindingId.
- **import_svg_composition** — Import raw SVG markup as a new Motion Creator composition (shapes/text become native motion layers). Returns the new compositionId and layer count.
@@ -142,15 +200,27 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
- **set_motion_group_auto_layout** — Turn a group into a Figma-style auto-layout frame: its children pack into a centered row (horizontal) or column (vertical) with a fixed gap, and re-pack automatically whenever a child's size changes. Pass direction (horizontal|vertical), gap (px, default 24), align (start|center|end, default center). Pass clear:true to remove auto-layout and free the children. Locked or position-keyframed children opt out of the flow and keep their own placement.
- **precompose_motion_layers** — Pull the given layers into a new nested composition (a reusable 'component' / precomp) and replace them in place with a single composition layer that references it. Edit the component once and every instance updates. Use add_motion_component_instance to stamp more instances and set_motion_instance_overrides to vary text/color per instance. Returns the new componentId (nested composition id) and the precomp layerId.
- **add_motion_component_instance** — Stamp another instance of a component: duplicate an existing precomp (composition) layer so it references the same master component. Editing the master updates every instance. The copy lands offset by offsetX/offsetY (default 48,48) and, if the source is inside a group, stays a sibling in that group. Returns the new instance layerId.
+- **set_motion_time_remap** — Time-remap a precomp (composition) layer — retime, freeze, reverse, or hand-key its source time. compositionLayerId must reference a layer with type 'composition'. Exactly one mode: `enable:true` lays down a linear identity remap (start of source -> end of source) so you can then adjust it; `reverse:true` plays the source backwards; `freeze:true` holds a single source frame (optional `freezeTime` seconds, default 0); `disable:true` clears the remap; or pass explicit `keyframes` as an array of { time, value, easing? } where time is the layer-local time and value is the source time (both seconds). Only one of enable/reverse/freeze/disable/keyframes may be provided.
- **set_motion_instance_overrides** — Override text and/or color on individual child layers of a component INSTANCE, without touching the master component or its other instances. Pass overrides as an array of { childLayerId, text?, color? } where childLayerId is a layer id inside the master component. text applies to text children; color applies to text or shape children (a color override flattens a gradient fill to solid). An entry with neither text nor color clears that child's override. Pass clear:true to remove all overrides on this instance.
- **disintegrate_motion_layer** — After-Effects-style disintegration: fade the target layer out while spawning a matching particle burst from its position (colored from its fill/text color), so it appears to crumble into dust. time (composition-absolute seconds, default = layer start) is when it disintegrates; duration (default 0.7s) is the fade length. The original layer is trimmed to end at the disintegration point. Pair with add_motion_cursor_click for a click-then-disintegrate beat. Returns the particle burst layerId.
- **morph_motion_layers** — Morph one whole layer/view INTO another (After-Effects crossfade + transform tween): layer A fades out while layer B fades in starting from A's position/scale/rotation and settling into its own — so B appears where A was and animates into place. Use this to transition between two designed views/screens. Both layers must overlap the morph window (time..time+duration) or it no-ops and returns an error. For morphing a single SHAPE's outline into a different shape, use morph_motion_shape instead. fromLayerId, toLayerId; time (default 0), duration (default 0.6s).
- **add_motion_cursor_click** — Drop an animated mouse cursor that travels to a target layer, click-presses on arrival, and makes the target react (a Click Press pulse) — the classic UI-demo 'a hand clicks the button' beat. The cursor is an image layer backed by a baked SVG pointer. targetLayerId; time (composition-absolute start, default 0), travel (seconds to reach the target, default 0.8), fromX/fromY (optional start point; defaults to up-and-left of the target). Returns the cursor layerId. Follow with disintegrate_motion_layer on the same target for click-then-disintegrate.
-- **import_image_layer** — Add a real image (logo/screenshot/icon) into a composition from a public URL or a data: URI. Downloads it into the media library, registers a composition image asset, and creates an image layer. Optional: name, x, y (pixel center), width, height, fit (contain|cover|fill), cornerRadius (rounded-rect clip — a cheap way to put a photo inside a rounded screen without a track matte). Returns data.layerId and data.assetId.
+- **import_image_layer** — Add a real image (logo/screenshot/icon) into a composition from a public URL or a data: URI. Downloads it into the media library, registers a composition image asset, and creates an image layer. Optional: name, x, y (pixel center), width, height, fit (contain|cover|fill), cornerRadius (rounded-rect clip — a cheap way to put a photo inside a rounded screen without a track matte), startTime (seconds, default 0), duration (seconds, default the composition duration), rotation (degrees), opacity (0-1). Returns data.layerId and data.assetId.
- **add_motion_3d_object** — Add a TRUE 3D object (WebGL/Three.js under the hood) to a composition — it renders with real depth and rotates so every side is visible (unlike the 2.5D layers). `object` is one of box | rounded-box | sphere | cylinder | cone | torus | icosahedron | plane | phone (a full iPhone-style device with screen + camera plateau) | model (load ANY .glb/.gltf via modelUrl — auto-centered and scaled to fit) | text3d (extruded 3D text via `text`, with `extrude` depth). Declarative — you describe it, the engine does the WebGL. Optional: name, x, y (pixel center), width, height (render bounds), size/depth/aspect/cornerRadius (geometry), color, metalness (0..1), roughness (0..1), materialKind (physical|basic), emissive, mapAssetId (an image asset id to texture onto the phone screen, e.g. a wallpaper from import_image_layer), rotationX/Y/Z (initial degrees), fov, cameraDistance, environment (studio|dark|none — studio gives realistic reflections on metal/glass), groundShadow (true drops a soft contact shadow under the object), startTime, duration. Animate the spin with animate_layer property 'transform.rotation.y' (or .x/.z) — e.g. 0→360 over 4s shows the whole device turning in 3D. ZOOM/DOLLY: keyframe 'transform.position.z' — +1 pushes the camera 2x closer (zoom in), +2 = 4x, negative pulls back. Combine a position.z 0→1.5 ramp with a rotation.y tilt for a cinematic push-in.
- **morph_motion_shape** — Animate a shape MORPHING into a different shape (After Effects-style path morph): the outline smoothly transforms, point-by-point, from one form to another. Give the source shape (layerId) and a target — toLayerId (morph into another shape layer's outline), toShapeType (rectangle|circle|ellipse|triangle|polygon|star|arrow|line, built at toWidth×toHeight, defaulting to the source size), or toPath (an explicit SVG path string centered at the origin — supply any custom outline, e.g. a logo or icon). Morph runs fromTime (default 0) → toTime with optional easing. Works between completely different shapes (arc-length resampling). Pair with a 'lift' — animate transform.position.z and transform.scale — to pop a button off a UI surface and then morph it into an icon.
+- **set_motion_shape_path** — Replace the whole outline of a bezier PEN shape layer (shapeType 'path'). points is an array of >=2 finite {x,y,inX?,inY?,outX?,outY?} vertices in layer-local pixel coordinates, where inX/inY and outX/outY are ABSOLUTE bezier control-handle coordinates (in = handle from the previous point, out = handle toward the next point); omit handles for straight corners. closed (default keeps the layer's current pathClosed) marks the path as a closed loop. The layer must have shapeType:'path' — create one via add_motion_layer with shapeType:'path'.
+- **edit_motion_shape_path_point** — Edit a single vertex (by index, 0-based) of a bezier PEN shape layer (shapeType 'path'). Pass x/y to move the anchor (its handles move with it), and/or inX/inY (incoming handle) / outX/outY (outgoing handle) as ABSOLUTE layer-local pixel coordinates. Supply at least one of x/y/inX/inY/outX/outY. Use insert_motion_shape_path_point / remove_motion_shape_path_point to change the point count.
+- **insert_motion_shape_path_point** — Insert a vertex into a bezier PEN shape layer (shapeType 'path') AFTER the given index (0-based). Pass an explicit point {x,y,inX?,inY?,outX?,outY?} (layer-local pixels, absolute handles) or omit it to insert a midpoint on the segment following afterIndex. Increases the point count by one.
+- **remove_motion_shape_path_point** — Remove the vertex at index (0-based) from a bezier PEN shape layer (shapeType 'path'). Refuses (INVALID_PARAMS) when the path is already at its minimum (2 points for an open path, 3 for a closed one).
+- **add_motion_shape_path_keyframe** — Add or replace a shape.pathData keyframe at a time on a bezier PEN shape layer (shapeType 'path') so its outline animates/morphs over time. Supply pathData (an SVG path string) or points (an array of >=2 {x,y,inX?,inY?,outX?,outY?} vertices, layer-local pixels, absolute handles); omit both to snapshot the layer's CURRENT path. easing is any known easing name. Re-calling at the same time replaces that keyframe.
+- **transform_motion_keyframes** — Batch-transform ALL keyframes of one property on a motion layer (the AE graph-editor keyframe ops). op is: 'reverse' (mirror values across the property's own time span), 'scale' (stretch/compress times about the first keyframe by factor scale>0 — 2 doubles the spacing), or 'duplicate' (copy every keyframe shifted by offset seconds, merging onto existing). scale is required for 'scale'; offset (may be negative) is required for 'duplicate'. property is any animatable id (transform.*, shape style properties like shape.width, shape.fill.opacity, effect.<id>.<param>, mask.<id>.<prop>, modifier.<id>.<prop>, ...) — note shape path data is not an animatable id here; animate a PEN path with add_motion_shape_path_keyframe. Use copy_motion_keyframes / paste_motion_keyframes to move keys between different properties. Any roving keyframes on the property keep constant-speed spacing: their times are re-derived from the surrounding anchors after the op, so reverse/scale/duplicate reposition them automatically.
+- **copy_motion_keyframes** (read-only) — Read a motion layer property's keyframes into a portable clipboard payload (relative time offsets, values, and easings) for inspection or for feeding paste_motion_keyframes. Returns data.clipboard plus entryCount, span (seconds), and sourceProperty. NOT_FOUND if the property has no keyframes. The roving flag is not carried in the clipboard — pasted keyframes start non-roving, and on the destination property any existing roving keyframes re-derive their constant-speed times after the merge.
+- **paste_motion_keyframes** — Copy every keyframe from fromProperty and paste them onto toProperty of the SAME layer, preserving relative spacing and easing, shifted so the run starts at (fromProperty's first keyframe time + timeOffset seconds, default 0). Existing keyframes on toProperty are kept (pasted keys merge, replacing any at identical times). Both properties must be valid animatable ids. Pasted keyframes are never roving; any roving keyframes already on toProperty re-derive their constant-speed times after the merge. Use transform_motion_keyframes to reverse/scale/duplicate keys in place on a single property.
- **add_motion_3d_scene** — Create ONE scene3d layer that is a FULL 3D WORLD — many objects sharing a camera, lights, and an optional room — instead of a single object. Declarative: you place objects in 3D and the engine does all the WebGL. This legacy-compatible tool now also creates semantic creation assets/objects plus a motion-scene3d render binding, so the scene remains editable in Motion Creator's Creation workspace. `objects` is an array; each entry: { kind (box|rounded-box|sphere|cylinder|cone|torus|icosahedron|plane|phone|model|text3d|soccer-ball|open-box|room), name, x,y,z (world position), rotationX/Y/Z (deg), scaleX/Y/Z, size, depth, aspect, cornerRadius, modelUrl (for model), text+extrude (for text3d), panelTexts (labels for soccer-ball), lidAngle (open-box, deg), color, metalness, roughness, materialKind, emissive, mapAssetId, opacity, key, objectId, partId, tags }. `camera`: { posX,posY,posZ, targetX,targetY,targetZ, fov, near, far }. `room`: { enabled, size, wallColor, floorColor } (camera flies in from the open +Z front). Optional environment (studio|dark|none), groundShadow. Then keyframe motion with animate_scene_camera + animate_scene_object. Returns layerId + render object ids plus semantic scene/object ids.
- **add_scene_object** — Append one object to an existing scene3d layer (created by add_motion_3d_scene). Same fields as one entry of add_motion_3d_scene's `objects`. When the layer has a semantic creation binding, or can be recovered into one, this also appends an editable creation asset/object and render binding so Motion Creator can inspect and revise it later. Returns the render objectId plus semantic creation ids.
+- **set_motion_scene_object** — Statically edit one object inside a multi-object scene3d layer (created by add_motion_3d_scene). Merge only the fields you pass onto the object matched by objectId. transform: { position?{x,y,z}, rotation?{x,y,z} (deg), scale?{x,y,z} }. material: { color?, metalness?, roughness?, emissive?, emissiveIntensity?, opacity?, transmission? (0..1 glass), ior? (index of refraction), clearcoat? (0..1), clearcoatRoughness? (0..1), materialKind? (physical|basic), mapAssetId?, normalMapAssetId?, roughnessMapAssetId?, metalnessMapAssetId? } (metalness/roughness/opacity/transmission/clearcoat/clearcoatRoughness clamp to 0..1). geometry: { kind?(box|rounded-box|sphere|cylinder|cone|torus|icosahedron|plane|phone|model|text3d|soccer-ball|open-box|room), size?, depth?, cornerRadius?, aspect?, modelUrl? (for kind=model), text? (for kind=text3d), extrude? (text3d extrusion fraction), panelTexts? (string[] for soccer-ball) }. lidAngle? (deg, for kind=open-box) is set at the object level. For animated changes use animate_scene_object instead.
+- **remove_motion_scene_object** (destructive) — Remove one object from a multi-object scene3d layer by objectId. Refuses to remove the last remaining object — delete the scene3d layer instead when you want an empty scene.
+- **set_motion_scene_camera** — Set the static (non-animated) cinematic camera on a scene3d layer. position?{x,y,z}, target?{x,y,z}, fov? (degrees), near? (near clip plane distance), far? (far clip plane distance). Only the fields you pass change. Complements animate_scene_camera, which keyframes the camera over time.
- **animate_scene_camera** — Keyframe the cinematic camera of a scene3d layer — the 'camera at this angle at this time, move this way, orbit this point' control. `position` and `target` are arrays of { time, x, y, z, easing }; `fov` is an array of { time, value, easing }. Times in seconds. Re-calling replaces the camera keyframes. When the layer is bound to an editable creation scene, this also mirrors the camera animation into creation animation state for recovery and later editing. Example fly-in then orbit: position [{time:0,x:0,y:4,z:24},{time:1.4,x:0,y:2,z:9},{time:2.4,x:7,y:2,z:7},{time:6,x:-7,y:2,z:7}], target locked on the subject.
- **set_model_animation** — Bind a GLB/glTF animation clip to a model inside a scene3d layer so Motion Creator renders the rigged model over time instead of as a static pose. Use clipName or clipIndex to choose a clip; omit both to use the first clip. timeOffset shifts the clip start, playbackRate changes speed, and animationLoop=false clamps on the final frame. For multi-object scenes pass objectId; for a legacy single-model scene3d layer omit objectId.
- **animate_scene_object** — Keyframe one object inside a scene3d layer in TRUE 3D over time — shake, spin, lift, open. `position`, `rotation` (degrees), `scale` are arrays of { time, x, y, z, easing }; `opacity` and `lidAngle` (open-box) are arrays of { time, value, easing }. Times in seconds. Re-calling replaces that object's keyframes for the channels you pass. When the layer is bound to an editable creation scene, this also mirrors position/rotation/scale/opacity tracks into creation animation state for recovery and later editing. Example lift: position [{time:1.4,x:0,y:0,z:0},{time:2.4,x:0,y:5,z:0}] + rotation spin [{time:1.4,x:0,y:0,z:0},{time:6,x:0,y:720,z:0}].
@@ -167,6 +237,7 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
## track
- **add_track** — Add a track (video|audio|image|text|graphics).
+- **duplicate_track** — Duplicate a timeline-backed video, image, or audio track with fresh track, clip, and transition identities. Inserts the copy after the source unless position is supplied.
- **remove_track** (destructive) — Remove a track and its clips.
- **rename_track** — Rename a track.
- **reorder_track** — Move a track to a new stacking position (0 = top of the timeline / front-most).
@@ -208,7 +279,7 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
- **set_clip_blend_opacity** — Set a clip's blend opacity (0..1).
## effect
-- **add_video_effect** — Add a video effect to a clip.
+- **add_video_effect** — Add a video effect to a clip. Standard effectType values include brightness, contrast, saturation, blur, sharpen, vignette, grain, temperature, tint, shadow, glow, motion-blur, radial-blur, chromatic-aberration. Set effectType to 'shader' to run a GPU shader effect from the Motion shader library (only category 'effect' shaders, e.g. the Paper Design catalog like paper-halftone-dots or paper-liquid-metal — use list_motion_shaders with category 'effect' to discover ids); for shader effects, params MUST include a valid shaderId plus optional numeric params (name/value pairs from the shader's params) and an optional numeric time. Shader effects no-op gracefully when WebGL2 is unavailable.
- **remove_video_effect** — Remove a clip's video effect.
- **update_video_effect** — Update a video effect's params.
- **toggle_video_effect** — Enable/disable a video effect.
@@ -269,11 +340,13 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
- **batch_actions** (destructive) — Dispatch a sequence of raw actions in order; stops on first failure.
## export
-- **export_video** (expensive) — Render the whole project to a video file (format: mp4|webm|mov, default mp4), upload it to cloud storage, and return a presigned download URL (data.url, valid ~15 min) plus mediaKey/bytes. Expensive — requires confirmation.
-- **export_audio** (expensive) — Render the project audio to a file (format: mp3|wav|aac|flac|ogg, default wav), upload it to cloud storage, and return a presigned download URL (data.url, valid ~15 min). Expensive — requires confirmation.
-
-## ai
-- **transcribe_clip** (expensive) — Transcribe a clip's audio to text/subtitles via the AI service. Expensive — requires confirmation.
+- **export_motion_video** (expensive) — Render a motion composition to a finished video file and return the filename plus width/height/duration/framesRendered and the format actually encoded. format: 'mp4' (H.264, opaque), 'webm-alpha' (VP9 with transparency), or 'mov-prores4444' (ProRes 4444 with transparency); default 'mp4'. On the web build only the desktop app can produce transparent WebM or ProRes — for those formats on web the export normalizes to opaque H.264, so you MUST pass acknowledgeH264Fallback:true to consent (otherwise the export fails with a warning telling you to acknowledge or use desktop). Optional filename overrides the auto-generated name. Inspect data.normalizedToH264 / data.encodedFormat to see what was really written. Expensive — requires confirmation.
+- **queue_motion_render** — Add a motion composition to the render queue for later batch export. format: 'mp4' | 'webm-alpha' | 'mov-prores4444' | 'png-sequence' (default 'mp4'). Optional rangeStart/rangeEnd (seconds, within the composition duration, start<end) render only that span; resolutionScale (1 | 0.5 | 0.25) downscales the output; optional filename overrides the auto name. On the web build transparent WebM and ProRes normalize to opaque H.264 — for those you MUST pass acknowledgeH264Fallback:true to consent (png-sequence is transparent but ZIP-encoded and never needs acknowledgement). Returns data.itemId. Use run_motion_render_queue to render.
+- **run_motion_render_queue** (expensive) — Render every queued (or previously failed) item in the motion render queue sequentially and return per-item outcomes (data.outcomes: itemId, status, encodedFormat, filename, error). Items whose cancel was requested are skipped as 'canceled'. Expensive — requires confirmation.
+- **list_motion_render_queue** (read-only) — List the current motion render queue items (data.items with itemId, compositionId, format, status, progress, and any range/resolutionScale/filename/error).
+- **cancel_motion_render_item** — Cancel a queued or in-progress motion render queue item by itemId. A queued item is canceled immediately; a rendering item stops at the next frame boundary. Returns whether the item was found.
+- **export_video** (expensive) — Render the whole project to a local video file (format: mp4|webm|mov, default mp4) and return its local result metadata. Expensive — requires confirmation.
+- **export_audio** (expensive) — Render the project audio to a local file (format: mp3|wav|aac|flac|ogg, default wav) and return its local result metadata. Expensive — requires confirmation.
## Capability manifest (enums + parameter ranges)
@@ -295,7 +368,9 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"hue",
"saturation",
"color",
- "luminosity"
+ "luminosity",
+ "add",
+ "linear-dodge"
],
"videoFilterTypes": [
"brightness",
@@ -335,7 +410,20 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"circleReveal",
"blur",
"whipPan",
- "radialWipe"
+ "radialWipe",
+ "pixelate",
+ "glitch",
+ "blinds",
+ "diamondReveal",
+ "spin",
+ "flip",
+ "splitReveal",
+ "flash",
+ "filmBurn",
+ "mosaic",
+ "ripple",
+ "pageTurn",
+ "colorSplit"
],
"easings": [
"linear",
@@ -634,6 +722,36 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"name": "Word by Word",
"category": "entrance"
},
+ {
+ "id": "rise",
+ "name": "Rise",
+ "category": "entrance"
+ },
+ {
+ "id": "drop",
+ "name": "Drop",
+ "category": "entrance"
+ },
+ {
+ "id": "elastic",
+ "name": "Elastic",
+ "category": "entrance"
+ },
+ {
+ "id": "swing",
+ "name": "Swing",
+ "category": "entrance"
+ },
+ {
+ "id": "zoom-blur",
+ "name": "Zoom Blur",
+ "category": "entrance"
+ },
+ {
+ "id": "cascade",
+ "name": "Cascade",
+ "category": "entrance"
+ },
{
"id": "wave",
"name": "Wave",
@@ -1518,7 +1636,9 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"hue",
"saturation",
"color",
- "luminosity"
+ "luminosity",
+ "add",
+ "linear-dodge"
],
"effectTypes": [
"blur",
@@ -1535,12 +1655,21 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"noise",
"radial-blur",
"displace",
- "backdrop-blur"
+ "threshold",
+ "mosaic",
+ "chromatic-aberration",
+ "vignette",
+ "backdrop-blur",
+ "shader",
+ "slider-control",
+ "checkbox-control",
+ "angle-control"
],
"maskShapes": [
"rectangle",
"ellipse",
- "polygon"
+ "polygon",
+ "path"
],
"maskModes": [
"add",
@@ -1606,7 +1735,10 @@ The agent exposes **228 tools** spanning read/observe, project, track, clip, tra
"repeater",
"zig-zag",
"round-corners",
- "wiggle-paths"
+ "wiggle-paths",
+ "offset-paths",
+ "pucker-bloat",
+ "twist"
],
"textAnimatorPresets": [
{
diff --git a/docs/AGENT-GUIDE.md b/docs/AGENT-GUIDE.md
index 78334818..cab40a71 100644
--- a/docs/AGENT-GUIDE.md
+++ b/docs/AGENT-GUIDE.md
@@ -8,23 +8,53 @@ three surfaces:
Cline) to the running desktop app.
- **Headless runner** — edit a stored project from a server/CLI with no app open.
-All three drive the same [capability set](./AGENT-CAPABILITIES.md) (72 tools +
-`execute_action`/`batch_actions` escape hatches), so an agent can do anything a
-professional editor can: import media, build the timeline, trim, crop,
-transform, color-grade, add text/shapes, keyframe, manage transitions, and more.
+All three drive the same [capability set](./AGENT-CAPABILITIES.md) (228 tools +
+`execute_action`/`batch_actions` escape hatches), so an agent can perform the
+full set of project-backed edits the web editor exposes: import media, build the
+timeline, trim, crop, transform, color-grade, mix audio, add
+text/shapes/subtitles, keyframe, manage transitions, build Motion Creator
+compositions and editable 3D scenes, and export the result.
## Bring Your Own Key (web & desktop chat)
-1. Open **Settings → API Keys** and add an OpenAI or Anthropic key. On the web,
- keys are encrypted at rest behind a master password; on desktop they live in
- the OS keychain. **Keys are never sent to or stored on OpenReel servers** —
- in production the web app proxies requests same-origin without persisting the
- key; on desktop the request goes through the native keychain.
-2. Open the **AI Editor** panel (the robot icon in the toolbar).
-3. Pick a provider and model in the panel header.
-4. Describe an edit in plain language, e.g.
+1. Open **Settings → API Keys**. In the browser, create a master password and
+ unlock the session; the password is not stored.
+2. Add an **OpenAI** or **Anthropic** API key. Browser keys are encrypted locally
+ with AES-256-GCM; desktop keys use the operating system keychain. OpenReel
+ does not persist keys on its servers. In the hosted web build, the key is
+ forwarded through the same-origin API proxy for that request; in local
+ development the browser calls the provider directly; on desktop the native
+ process reads the key from its secure store.
+3. Open or create a project, then open the **AI Editor** panel (the robot icon
+ in the toolbar).
+4. Use the AI settings button in the panel header to pick a provider and model.
+ Choose a listed model or select **Custom model ID…** and enter any
+ tool-calling model ID enabled for your provider account.
+5. Describe an edit in plain language, e.g.
_"trim the first clip to 5s, add a fade-in, and put a title card at the start."_
+### Any OpenAI-compatible endpoint
+
+Choose **OpenAI-compatible** to use a hosted alternative, self-hosted model, or
+local runtime that implements the OpenAI Chat Completions tool-calling format.
+
+1. Enter its base URL, for example `https://provider.example/v1` or
+ `http://localhost:11434/v1`. Pasting the complete `/chat/completions` URL is
+ also supported.
+2. Enter the exact model ID exposed by that endpoint.
+3. If authentication is required, add the optional **OpenAI-compatible** key in
+ **Settings → API Keys**. Keyless endpoints work without secure-storage setup.
+
+Compatible requests go directly from the browser to the configured endpoint;
+they are never relayed through OpenReel's hosted proxy. The endpoint must allow
+CORS for the OpenReel origin. Use the desktop app for local HTTP endpoints or
+servers that do not expose browser CORS headers—the native process performs the
+request there. URL credentials and query strings are rejected; store bearer
+credentials in the encrypted API-key field instead.
+
+The selected model must support the standard `tools` and `tool_calls` fields.
+A text-only OpenAI-compatible model can chat, but cannot control the editor.
+
### Controls
- **Confirm gate** — destructive or expensive actions (delete, remove, export,
@@ -35,6 +65,26 @@ transform, color-grade, add text/shapes, keyframe, manage transitions, and more.
- **Stop** — aborts the in-flight turn and rolls back any partial edits.
- **Token meter** — shows cumulative input/output tokens for the conversation.
+The chat automatically sends only the relevant portion of OpenReel's complete
+tool registry on each turn. This keeps requests within provider function limits
+while retaining access to every editor domain across requests. Follow-up turns
+also keep tools used earlier in the conversation available.
+
+### Troubleshooting
+
+- **“Unlock secure storage”** — open **Settings → API Keys** and unlock with the
+ master password created on this browser.
+- **“No API key configured”** — add a key for the provider currently selected in
+ the AI settings popover. OpenAI and Anthropic keys are separate.
+- **401 / authentication error** — replace the stored key and confirm it belongs
+ to the selected provider.
+- **Model not found / unavailable** — choose a listed model, or enter the exact
+ model ID enabled for your provider account. Availability can differ by account.
+- **Compatible endpoint cannot be reached** — verify the base URL, ensure the
+ server implements `/chat/completions`, and enable CORS when using the browser.
+- **An edit needs approval** — approve the inline confirmation, or enable the
+ shield toggle only for a project and key you trust.
+
## Connecting external agents (desktop MCP)
The desktop app runs a local Model Context Protocol server so external clients
@@ -70,16 +120,15 @@ useful for batch edits, "apply this recipe to N projects", and scheduled jobs.
openreel-agent \
--project ./reel.json \
--prompt "Add a title that says Welcome for the first 3 seconds" \
- --provider anthropic --model claude-sonnet-4-20250514 \
+ --provider anthropic --model claude-sonnet-5 \
--out ./reel.edited.json
```
- The API key is read from `OPENREEL_API_KEY` (or `ANTHROPIC_API_KEY` /
`OPENAI_API_KEY`) and is used per-request only — never stored or logged.
- `--dry-run` plans without applying mutations.
-- Render/export jobs are delegated to the GPU worker, authorized by the auth
- broker; a built-in export queue can drive multiple exports concurrently
- ("export these N variants").
+- In-app render/export jobs use the local web or desktop export engine. The
+ headless CLI edits project files but does not submit work to a remote GPU.
## Safety & limits
diff --git a/docs/MOBILE-PARITY.md b/docs/MOBILE-PARITY.md
new file mode 100644
index 00000000..8e1b893f
--- /dev/null
+++ b/docs/MOBILE-PARITY.md
@@ -0,0 +1,164 @@
+# Mobile / Cross-Platform Parity Matrix
+
+Scope: the timeline-semantics that were unified across the recent iOS correctness
+work, compared against Android and the web app. This documents where the three
+platforms agree and where they intentionally differ.
+
+Legend: ✅ implemented & matches · ⚠️ intentional difference · ❌ not implemented
+
+| Capability | iOS | Android | Web | Notes |
+|---|---|---|---|---|
+| Primary / base visual track rule | ✅ | ✅ | ✅ | First `video`/`image` track is the always-on base layer (`primaryVisualTrack`); overlays composite above it. |
+| Overlay z-order | ✅ | ✅ | ✅ | Higher tracks render on top of the base frame; deterministic by track order. |
+| Speed-aware split source-time | ✅ | ✅ | ✅ | Source time = `inPoint + localTime * speed`, clamped to `[inPoint, outPoint)`. iOS preview and export share `TimelineSourceMapper`. |
+| Reverse / boomerang playback | ✅ | ✅ | ✅ | Reversed clips sample backward from `outPoint`; boomerang is forward+reverse pairing on the timeline. |
+| Reversed-clip **audio** | ⚠️ muted | ⚠️ reversed | ✅ reversed | iOS mutes reversed source audio (`TimelineAudioDescriptor` zeroes volume keyframes); Android renders true reversed audio via `ReverseAudioProcessor`. |
+| `audioTrackIndex` selection | ✅ | ✅ | ✅ | `nil` = all source audio tracks; an index selects one, clamped to first when out of bounds (`PlaybackCompositionBuilder.selectedAudioTracks`). |
+| Text/track visibility + solo | ✅ | ✅ | ✅ | Hidden tracks exclude their clips; any soloed track restricts visible clips to soloed tracks. iOS preview and export both call `visibleTextClips(at:)`. |
+| Collage / overlay compositing | ✅ | ⚠️ | ✅ | iOS composites overlays via `overlayComposer` over the base frame. Android samples PiP-over-fullframe and demotes overlays fully occluded by an opaque full-frame primary (`LayeredVideoPlacement`). |
+| Time-windowed overlays (text/graphics) | ✅ | ✅ | ✅ | Overlays gate to their `[start, start+duration)` window; outside the window they are not drawn. Android uses `TimedBitmapOverlay` alpha gating. |
+| Local photo tone/detail/denoise | ✅ | ✅ | ✅ | Mobile processing stays on the device; iOS uses Core Image and Android uses the Media3 GL pipeline. |
+| Local portrait blur/person cutout | ✅ Vision | ✅ bundled ML Kit | ✅ browser/local runtime | Mobile subject segmentation does not upload the source. Android writes a new PNG and keeps the original media item. |
+| Cloud GPU photo/generative tools | ❌ retired | ❌ retired | ❌ retired | Unsupported repair, arbitrary upscale, colorize, face reconstruction, object replacement, and outpainting controls are removed rather than left broken. |
+
+## Intentional platform differences
+
+- **Reversed-clip audio.** iOS deliberately mutes audio on reversed clips to avoid
+ artifacts from backward AVFoundation sampling; Android produces genuine reversed
+ audio through a dedicated processor. Web mirrors Android.
+- **Overlay-over-full-frame.** Android's media3 compositor keeps the primary frame
+ always-on-top, so overlays fully occluded by an opaque full-frame primary are
+ demoted (sampled but not promoted to a layer). iOS composites overlays above the
+ base frame with the same z-order rule and does not demote them.
+
+## Photo tools after cloud GPU retirement
+
+The mobile editors expose only tools backed by a shipping local implementation:
+
+- **iOS:** image-aware Photo Tools with measured auto tone, luminance detail,
+ Core Image denoise, gentle face polish, Vision portrait blur, and subject cutout.
+- **Android:** a dedicated Photo inspector with histogram-based auto tone,
+ edge-aware denoise, detail sharpening, and bundled on-device person segmentation
+ for portrait blur and transparent cutout. Portrait operations create a new PNG;
+ the original remains in Project Media and the clip change is undoable.
+
+The old remote Photo Enhancement surfaces and cloud job/auth clients are not part
+of either mobile build. We intentionally do not advertise generative colorization,
+face reconstruction/repair, semantic object erase/replace, reference-image color
+matching, arbitrary neural upscale, or outpainting without a reliable local engine.
+
+## Preview ↔ Export parity (iOS)
+
+The recent iOS work unified the source-of-truth so that on-device **preview** and
+**export** resolve identical state:
+
+- Both build a `TimelineSourceMapper.ClipTiming` from the same clip fields
+ (`inPoint`, `outPoint`, `startTime`, `duration`, `speed`, `reversed`) and call the
+ same `TimelineSourceMapper.sourceTime(...)`, so forward / speed / reversed clips
+ sample the same source frame in preview and export.
+- Both resolve visible text via the single `OpenReelProject.visibleTextClips(at:)`
+ helper, so hidden/solo filtering is identical.
+
+These invariants are locked by `PreviewExportParityTests` and
+`TimelineSourceMapperTests` in the iOS test target.
+
+## Full feature parity audit (2026-05-29)
+
+A complete iOS↔Android feature audit (9 domains, 4 expert lenses, every gap claim
+adversarially verified against source) lives in **`docs/MOBILE-PARITY-AUDIT.md`**.
+This section is the source-verified shortlist; the matrix above stays as the
+timeline-semantics reference.
+
+### Genuinely-implementable gaps (source-verified)
+
+- **iOS missing — Text-to-Speech voiceover** (no `AVSpeechSynthesizer` anywhere;
+ Android has `core/audio/TextToSpeechSynthesizer.kt` + a TTS card). **P0**, Android→iOS.
+- **Both missing — loudness normalization (LUFS)** and **audio-only export
+ (M4A/WAV)**. **P0**, new shared builds.
+- **Both missing — timeline precision:** on-ruler marker rendering + jump-to-marker,
+ frame-step clip nudge, whole-clip copy/paste to playhead, 3-point insert/overwrite,
+ arbitrary clip grouping. **P1**.
+- **Android missing — 3-way color wheels (lift/gamma/gain)** and **Gaussian/2D blur**
+ (Android only has 1D `MotionBlurEffect`). **P1**, iOS→Android.
+
+### Corrections found while source-verifying the audit (audit over-claimed)
+
+- **iOS reversed-clip audio works on export** (`TimelineAudioOfflineRenderer.reverseBuffer`);
+ it is muted **only in live preview, by design** — AVFoundation can't play backward
+ audio cleanly (`PlaybackCompositionBuilder.swift:82`). Not a port; live-preview reverse
+ would require an AVAudioEngine preview path.
+- **iOS voice-effect pitch works on export** (`TimelineAudioOfflineRenderer.voiceEffectSemitones`
+ sets `pitchNode.pitch`: helium/chipmunk +600¢, deep/monster −500¢); residual gap is
+ live preview only.
+- The iOS/Android `OpenReelProject` Clip schemas are **already field-aligned** (both carry
+ `voiceEffect`, `groupID`, `pan`, `speedRamp`, `reversed`, `sourceClipID`, …), so most
+ audit "shared key needed" items are no-ops; Wave 0 is a small delta (`preservePitch`,
+ `targetLufs`, audio-only export-format entries).
+- Many informal "X is iOS-only / Android-only" assumptions were **refuted** on
+ verification (ripple delete, selective HSL, glitch, GIF export engine, project archive,
+ template preview, stereo pan, compressor) — see audit §4.
+
+**Implementation note:** because adversarial verification still produced false-positive
+gap claims (export vs preview path confusion), every backlog item is re-verified against
+source before coding.
+
+## Session log 2026-05-29 — shipped + remaining backlog
+
+Branch `feat/ios-app`. Each feature below was build-verified (iOS `xcodebuild ... -sdk iphonesimulator`; Android `./gradlew :app:compileDebugKotlin`). All use the shared `OpenReelProject` JSON schema so projects round-trip.
+
+### Shipped (build-verified, NOT yet device-tested)
+- **iOS Text-to-Speech voiceover** — `Core/Audio/TextToSpeechSynthesizer.swift` (AVSpeechSynthesizer, 7 voices matching Android's set) + `Features/Audio/TextToSpeechView.swift`, routed through the existing `importAndPlace` path. Closes the one genuinely-absent P0 (iOS had zero `AVSpeechSynthesizer`).
+- **Android Gaussian blur** — `core/effects/GaussianBlurEffect.kt` (separable 2-pass GL) + `GaussianBlurConfig.kt`, shared effect type `"blur"` (`{radius, type:"gaussian", intensity}`) matching iOS `VideoEffectType.blur`. Wired into `ClipEffectPipeline` (preview+export), `AppState.toggleGaussianBlur`, Effects panel.
+- **Android 3-way color wheels** — `core/effects/ColorWheelsEffect.kt` + `ColorWheelsConfig.kt`, ports iOS `VideoEffectRenderer.applyColorWheels` math to GL. Shared type `"colorWheels"`: scalars `shadowsLift`/`midtonesGamma`/`highlightsGain` + per-tone `{r,g,b}` objects `shadows`/`midtones`/`highlights`. Formula `out_c = pow(in_c*(gain+highlights_c*0.18) + (lift*0.08+shadows_c*0.08+midtones_c*0.04), gamma)`. Toggle applies a cinematic teal/orange default; the full per-wheel pad UI is a follow-up (the engine renders any params iOS writes — web already has `ColorWheelsControl.tsx`).
+
+### Corrections confirmed (user's named examples already exist on BOTH)
+- **Detach audio** — iOS `AppState.detachSelectedClipAudio`, Android `AppState.detachAudio`.
+- **Ducking** — iOS `TimelineAudioDuckingConfig` (threshold/reduction/attack/release/hold + trigger role) in `PlaybackCompositionBuilder.duckingRanges`; Android auto-ducks off Dialogue clips (`DuckingAudioProcessor` + `computeDuckWindows`, fixed 0.32 gain, no UI).
+
+### Remaining backlog — precise execution notes for next session
+
+**1. Audio-only export (M4A/WAV) — both. Schema-touching; keep enums aligned.**
+- Shared enum: add `m4a`, `wav` to `ExportCodec` (iOS `OpenReelProject.swift:284`; Android `OpenReelProject.kt:180`) and a matching container (`m4a`/`wav`). Decode-if-present, additive.
+- iOS: `ProjectExportService.export` hard-throws `noVideoTracks` (`:298`, `:505-507`) and `resolveConfiguration` maps only mov/mp4 fileType (`:905`). Add an early audio-only branch BEFORE the video guard: reuse `prepareCompositionForExport` (it already produces `processedAudioURL`/`audioMix`), then export audio with `AVAssetExportSession(preset: AVAssetExportPresetAppleM4A)` → `.m4a`, or for WAV use `AVAssetWriter` with `fileType .wav` + LinearPCM settings. `makeOutputURL` extension must follow the codec.
+- Android: `core/export/ProjectExportService.kt` uses media3 `Transformer`. For audio-only set `Transformer.Builder().setVideoMimeType(null)` / `EditedMediaItem` with `removeVideo=true`, or drop to `MediaMuxer` with only the AAC audio track for `.m4a`. WAV needs a PCM writer (no muxer support) — simplest: render PCM via existing audio path and write a WAV header.
+- UI: add chips in both ExportSheets (iOS `Features/Export/ExportSheet.swift`; Android `ui/editor/ExportSheet.kt`).
+
+**2. LUFS loudness normalization — both. New shared keys `targetLufs`, `loudnessNormalizeEnabled`.**
+- Implement ITU-R BS.1770 integrated loudness: K-weighting pre-filter (two-stage: high-shelf + high-pass) → mean-square per 400ms block (75% overlap) → absolute gate −70 LUFS → relative gate (−10 LU below ungated mean) → integrated loudness → gain = target − measured, applied as a master gain.
+- iOS: measure on the offline-rendered PCM in `TimelineAudioOfflineRenderer` (Accelerate/vDSP for the filters); apply gain in the final mix.
+- Android: offline measure over decoded PCM; apply via a master-gain `AudioProcessor` (mirror `DuckingAudioProcessor` structure) in the export audio chain.
+- Risk: BS.1770 done half-right is worse than none — implement with care + a known-value unit test (a −23 LUFS reference tone should measure ≈ −23).
+
+**3. Lower-risk parity items (build-provable, no DSP):**
+- On-ruler marker rendering + jump-to-next/prev (markers already modeled both: iOS `OpenReelProject.swift:354`, Android `:249`).
+- Frame-step clip nudge (operates on `clip.startTime`; iOS has playhead-step only at `PlaybackController.swift:673`).
+- Surface Android ducking controls (depth/timing) to match iOS's tunable config.
+- Add 4:5 aspect preset to Android crop; arbitrary chroma-key color picker on Android (engine already supports any key color).
+
+### Update — audio-only export: iOS shipped, Android spec'd (not yet built)
+- **iOS audio export SHIPPED** (`ProjectExportService.exportAudioOnly`, commit on this branch) — isolated path, M4A via `AVAssetExportSession`, WAV via PCM rewrap, "Export Audio" row in the Audio panel + share sheet. Zero video-enum changes.
+- **Android audio export — implementation-ready spec (deliberately not built this session: it lives in the 2153-line render-path `core/export/ProjectExportService.kt`, compile-only verifiable, deserves a device-tested session):**
+ 1. Add `suspend fun exportAudioOnly(project, mediaUriResolver, format)` to `ProjectExportService`.
+ 2. Populate the shared `mediaById` field (`project.mediaLibrary.items.associateBy { it.id }`) — `buildAudioSequences`/`exportMediaItemFor` depend on it (class field at line 36, populated in `runExport` at ~148).
+ 3. Build an **audio-only** `Composition` from `buildAudioSequences(project, mediaUriResolver)` (already returns the ducked, multi-track `List<EditedMediaItemSequence>`) — no video sequence.
+ 4. `Transformer.Builder(context).setAudioMimeType(MimeTypes.AUDIO_AAC)` (drop `setVideoMimeType`), `.build()`, `transformer.start(composition, cacheFile.absolutePath)` to an `.m4a` cache file. Reuse the existing `ProgressHolder` polling + `Transformer.Listener` pattern from `runExportOnMain`.
+ 5. Save via a `saveToMediaStore` variant targeting `MediaStore.Audio` (`Environment.DIRECTORY_MUSIC/OpenReel`, MIME `audio/mp4` for m4a), mirror the `IS_PENDING` flow.
+ 6. WAV on Android needs a PCM writer (media3 muxer has no WAV) — render PCM via an audio-only Transformer to raw then prepend a WAV header, OR ship M4A-only first.
+ 7. UI: add an "Export Audio" entry to `ui/editor/panels/AudioTabPanel.kt` mirroring iOS.
+- Keep the file format aligned with iOS (`.m4a`, `.wav`); no `OpenReelProject` schema change needed (export format is a transient choice, not persisted).
+
+### Update 2 — LUFS + audio export status (final this session)
+- **iOS audio-only export + LUFS: COMPLETE & test-verified.** `exportAudioOnly` (M4A/WAV) with a "Normalize loudness" toggle (target −16 LUFS). `LoudnessNormalizer` (BS.1770) verified by `LoudnessNormalizerTests` (5 tests, 0 failures: round-trip measure→gain→re-measure within 0.3 LU, +6dB on amplitude double, monotonicity).
+- **Android audio-only export: COMPLETE** (`exportAudioOnly` → AAC `.m4a` → MediaStore.Audio, "Export Audio" row). Compiles.
+- **Android LUFS: DSP core COMPLETE & test-verified** (`LoudnessNormalizer.kt`, identical math to iOS; `LoudnessNormalizerTest` passes). **Remaining (1 follow-up): wire it into Android audio export.** Android export streams through media3 Transformer to AAC with no intermediate PCM, so auto-normalize needs a two-pass:
+ 1. In `runAudioExport`, after building the audio `Composition`, run a first Transformer pass exporting to a temp file, then decode that to interleaved PCM via `MediaExtractor` + `MediaCodec` (or reuse `WaveformExtractor`'s decode if it exposes full samples).
+ 2. `LoudnessNormalizer.integratedLufs(pcm, channels=2, 48000.0)` → `linearGain(target=-16, measured)`.
+ 3. If `|gain−1| > 0.001`, second pass: apply gain via a master-gain `BaseAudioProcessor` (multiply PCM-16 samples, mirror `DuckingAudioProcessor`'s structure) set on the Composition's `Effects.audioProcessors`, re-encode, then save to MediaStore.Audio.
+ 4. Add a "Normalize loudness" toggle to the Android export UI mirroring iOS.
+ This was deliberately deferred: it is device-untestable here and adds fragile MediaCodec plumbing to the render path — it deserves a device-tested session.
+
+### Update 3 — Android audio export + LUFS COMPLETE (wired)
+- **Android audio-only export is now fully wired** (commit 0f63d34, fixing dead code from 6a39cb9). `exportAudioOnly(project, mediaUriResolver, normalizeToLufs)` → audio-only media3 Transformer (AAC) → `.m4a` → MediaStore.Audio (Music/OpenReel). Surfaced via `AppState.startAudioExport(normalizeLoudness)` and an "Export Audio" row in the Audio panel.
+- **Android LUFS normalization wired into export.** When the "Normalize Loudness" toggle (−16 LUFS) is on, a two-pass runs: render the mix → `decodePcm` (full interleaved PCM via MediaExtractor+MediaCodec, no decimation) → `LoudnessNormalizer.integratedLufs` → `linearGain` → re-encode with a `MasterGainAudioProcessor`. iOS uses the same target and the same BS.1770 math.
+- **Verification:** `gradlew compileDebugKotlin` SUCCESSFUL; `LoudnessNormalizerTest` 5/5 (XML tests=5 failures=0). The two-pass `decodePcm`/`MasterGain` MediaCodec plumbing compiles but is **not device-tested** — needs a real device run (export an M4A with normalize on, confirm it measures ≈ −16 LUFS).
+- **Parity status:** iOS and Android now both have audio-only export + LUFS normalization with identical loudness math. iOS adds WAV output (Android is M4A-only — media3 muxer has no WAV; a PCM+header writer is the only remaining audio-export delta).
diff --git a/docs/android-port/01-app-structure-navigation.md b/docs/android-port/01-app-structure-navigation.md
new file mode 100644
index 00000000..6cead43b
--- /dev/null
+++ b/docs/android-port/01-app-structure-navigation.md
@@ -0,0 +1,614 @@
+# OpenReel Video — Android Port Spec
+## Part 01: App Structure, Navigation, and Top-Level Screens
+
+This document describes the iOS SwiftUI implementation of OpenReel Video's app shell, navigation graph, theme, and the screens the user sees before entering the editor. The Android team should rebuild these 1:1 in Kotlin (Jetpack Compose recommended).
+
+---
+
+## 1. Overview
+
+The app is a mobile video editor. The top-level surface consists of:
+
+- An **App entry point** (`Openreel_VideoApp`) that boots the audio session for playback and injects two app-wide state objects (`AppState`, `PlaybackController`) into the SwiftUI environment.
+- A **Root view** (`RootView`) which is the master switch between three top-level destinations:
+ 1. **Onboarding** (first launch only — gated by `@AppStorage("hasCompletedOnboarding")`)
+ 2. **A loading screen** (shown while the app bootstraps stored projects)
+ 3. **The Library tab shell** (Home + Projects tabs) OR **the Editor**, depending on `appState.activeScreen`.
+- A **modal `NewProjectSheet`** that can be presented from anywhere via `appState.presentNewProjectSheet()`.
+- A **global error alert** driven by `appState.importErrorMessage`.
+
+The Library has two tabs:
+- **Home** — hero/marketing copy, "New Project" call-to-action, horizontal carousel of recent projects, "Quick Start" platform presets, and quick-action grid (Photo Tools, Quick Trim).
+- **Projects** — full grid/list browser of stored projects with storage usage summary and delete actions.
+
+`ContentView` is a thin wrapper around `RootView` and exists only as the boilerplate Xcode template root.
+
+---
+
+## 2. Navigation Graph
+
+```
+Openreel_VideoApp (Scene)
+└── ContentView
+ └── RootView ← decides which top-level destination is shown
+ ├── if !hasCompletedOnboarding → OnboardingView (full screen, no chrome)
+ ├── else if bootstrapping → loadingView (centered ProgressView + label)
+ ├── else if activeScreen == .editor → EditorView (covered in other docs)
+ └── else → LibraryTabView
+ ├── Tab "Home" → NavigationStack { HomeView }
+ │ └── NavigationLink → PhotoEnhancementView (Quick Start grid)
+ └── Tab "Projects" → NavigationStack { ProjectsView }
+
+Modals / overlays presented on top of RootView regardless of the current branch:
+ • Sheet: NewProjectSheet (presentationDetents = .fraction(0.5), drag indicator visible)
+ • Alert: "OpenReel" alert with appState.importErrorMessage (OK / cancel role)
+ • Confirmation dialog: project deletion (shown from ProjectsView)
+```
+
+### Entry & boot sequence
+1. App launches → `Openreel_VideoApp.init()` configures `AVAudioSession` with category `.playback`, mode `.moviePlayback`, and activates it. (Android equivalent: configure `AudioAttributes` for media playback / request audio focus when starting playback.)
+2. `RootView` mounts, runs `.task { await appState.bootstrap() }` — loads stored projects from disk.
+3. While `appState.isBootstrapping && !appState.hasBootstrapped`, the loading view is shown.
+4. After bootstrap, `LibraryTabView` is shown (or onboarding if the flag is unset, but onboarding is checked *first*, before bootstrap state).
+
+### Conditional onboarding gate
+- Persisted in `UserDefaults` via `@AppStorage("hasCompletedOnboarding") Bool = false`.
+- Onboarding is the only thing the user sees until either:
+ - The "Skip" button in the top bar is tapped, **or**
+ - The user reaches the last page and taps "Start Editing".
+- Both paths call `completeOnboarding()`, which fires a medium impact haptic and sets `hasCompletedOnboarding = true`. The app immediately re-renders into the LibraryTabView.
+
+### Tab switching semantics
+The tab `TabView` selection is bound to a derived `Binding<AppState.Screen>` in `LibraryTabView.selection`:
+- `appState.activeScreen` is the source of truth (`.home`, `.projects`, `.editor`).
+- When mapping to a tab tag: `.projects` → `.projects` tab; `.home` and `.editor` both map to the `.home` tab. (So if the user backs out of the editor and the tab bar is re-displayed, the Home tab is selected.)
+- When the user taps a tab, the setter calls `appState.showHome()` or `appState.showProjects()`. Tapping the editor tag — which is not surfaced in the UI — also routes to `showHome()`.
+
+### Sheet presentation
+- `NewProjectSheet` is presented as a bottom sheet with a half-screen detent (`.fraction(0.5)`) and a drag indicator. The sheet is dismissed by `appState.dismissNewProjectSheet()` or by the user dragging it down or tapping "Close".
+
+### Inter-screen transitions (entry points to the sheet)
+- **HomeView** header `+` button → `appState.presentNewProjectSheet()`
+- **HomeView** "New Project" card → `appState.presentNewProjectSheet()`
+- **HomeView** "Quick Trim" card → `appState.presentNewProjectSheet()`
+- **HomeView** Quick Start platform preset card → `appState.quickCreateProject(...)` (creates a project directly, *no* sheet)
+- **HomeView** "Photo Tools" → `NavigationLink` to `PhotoEnhancementView` (inside the Home `NavigationStack`)
+- **ProjectsView** toolbar `+` → `appState.presentNewProjectSheet()`
+- **ProjectsView** empty state "New Project" → `appState.presentNewProjectSheet()`
+- **NewProjectSheet** "Create Project" → `appState.createProject()` (which navigates to the editor by setting `activeScreen = .editor`).
+
+---
+
+## 3. Theme & Design Tokens
+
+All tokens live in `Theme.swift`. Colors are dynamic (separate light/dark hex codes).
+
+### Color tokens (hex codes, exact)
+
+| Token | Light | Dark | Use |
+|--------------------|-------------|-------------|-----|
+| `background` | `#FBFCF8` | `#0D0D0D` | Root window background |
+| `surface` | `#F0F4EE` | `#1A1A1A` | Inset cards/inputs (level 1) |
+| `surfaceElevated` | `#FFFFFF` | `#262626` | Elevated cards, tab bar bg, sheet content (level 2) |
+| `accent` | `#047857` | `#047857` | Primary brand green — buttons, highlights, selection |
+| `accentSecondary` | `#036B3A` | `#036B3A` | Darker brand green (used by project styling) |
+| `textPrimary` | `#101814` | `#FFFFFF` | Primary text |
+| `textSecondary` | `#5F6F67` | `#A3A3A3` | Secondary/caption text |
+| `destructive` | `#DC2626` | `#EF4444` | Destructive actions (delete) |
+
+Implementation detail: `OpenReelTheme.dynamicColor(light:dark:)` wraps `UIColor { traitCollection in ... }` so the colors react to system light/dark mode automatically. On Android, define two `Colors` palettes (light and dark) inside a Material 3 `ColorScheme` and let the system switch by `isSystemInDarkTheme()`.
+
+### Project-card gradient styles (`AppState.ProjectStyle`)
+
+| Style | Start RGB (0–1) | End RGB (0–1) |
+|----------|------------------------------|------------------------------|
+| emerald | (0.08, 0.32, 0.20) | (0.14, 0.79, 0.47) |
+| cobalt | (0.11, 0.18, 0.37) | (0.27, 0.49, 0.98) |
+| amber | (0.32, 0.21, 0.09) | (0.98, 0.73, 0.20) |
+| coral | (0.40, 0.14, 0.17) | (0.97, 0.43, 0.39) |
+
+All gradients use `LinearGradient(startPoint: .topLeading, endPoint: .bottomTrailing)`.
+
+### Typography tokens (`Font` extension)
+
+All use `design: .rounded` unless noted. Map to a rounded sans-serif on Android — recommend **SF Pro Rounded** equivalent: `Nunito`, `Quicksand`, or Google's `Manrope`. For monospaced text use a mono font like `JetBrains Mono` / `Roboto Mono`.
+
+| Token | Size | Weight | Design |
+|---------------|------|-----------|------------|
+| `reelDisplay` | 34 | bold | rounded |
+| `reelSection` | 16 | semibold | rounded |
+| `reelBody` | 15 | medium | rounded |
+| `reelCaption` | 12 | medium | rounded |
+| `reelMono` | 13 | medium | monospaced |
+
+(Use these sizes as `sp` on Android.)
+
+### Inline font usages (not tokens, but recurring)
+- Logo wordmark: 20pt bold rounded (`HomeView` header), 17pt bold rounded (`OnboardingView` top bar)
+- Hero title: 26pt bold rounded
+- Section labels: 15pt bold rounded
+- Body subcaptions: 13–14pt medium rounded
+- Tiny labels (carousel chips): 10–12pt
+- Monospaced counters: 10–13pt monospaced (`reelMono` style)
+
+### Corner radii (used across screens)
+
+| Use | Radius (pt/dp) | Style |
+|----------------------------------|----------------|-------|
+| Small chips/blocks (clip blocks) | 7 | continuous |
+| Small surfaces (track badge, inspector buttons, lane bg) | 10 | continuous |
+| Small action labels (Quick Start row) | 12 | continuous |
+| Mid surfaces (lists, hero card) | 14 | continuous |
+| Cards (New Project card, presets) | 16 | continuous |
+| Empty state, storage card | 18 | continuous |
+| Sheet content / large cards | 18 or 24 | continuous |
+
+iOS `RoundedRectangle(cornerRadius: X, style: .continuous)` ⇢ Android: use `RoundedCornerShape(X.dp)` (Compose lacks a true "continuous corner" curve — closest equivalent is `AbsoluteSmoothCornerShape` from third-party libs, otherwise `RoundedCornerShape` is acceptable).
+
+### Common paddings/spacings (recurring values)
+- Screen edge horizontal padding: `20` (Home), `16` (Projects), `22` (Onboarding)
+- Section vertical gap: `24–28`
+- Card internal padding: `10–16`
+- Inline element spacing: `6, 8, 10, 12, 14, 16`
+
+### Shadows
+The app uses fairly subtle drop shadows. Key examples:
+- Onboarding action button: `.shadow(color: accent.opacity(0.24), radius: 14, y: 8)`
+- Onboarding editor card: `.shadow(color: .black.opacity(0.10), radius: 24, y: 14)`
+- Onboarding inspector pill: `.shadow(color: .black.opacity(0.16), radius: 8, y: 4)`
+- Home hero sun glow: `.shadow(color: accent.opacity(0.32), radius: 12)`
+
+Android: `Modifier.shadow(elevation, shape, ambientColor, spotColor)` — match the y-offset/blur with `elevation` + `RoundedCornerShape`. Use `Modifier.drawBehind` for tinted shadows if needed.
+
+### Animation/motion tokens
+- Card press: `scaleEffect 0.97`, `opacity 0.85` for pressed state, with `.spring(response: 0.25, dampingFraction: 0.7)` — used by `HomeCardButtonStyle`.
+- Home entrance: `withAnimation(.spring(response: 0.7, dampingFraction: 0.8))` setting `appearAnimation = true` on appear (fades elements in, slides hero text from -12px on x).
+- Recent projects staggered entry: per-card delay `0.06 * index` with `.spring(response: 0.6, dampingFraction: 0.8)`.
+- Page-indicator dot expand: `.spring(response: 0.3)`.
+- Onboarding paging: `.spring(response: 0.42, dampingFraction: 0.86)`.
+- Sensory haptic: `sensoryFeedback(.impact(flexibility: .soft), trigger: currentPage)` on each page change, plus a `UIImpactFeedbackGenerator(style: .medium)` on completing onboarding.
+
+---
+
+## 4. Per-Screen Sections
+
+### 4.1 `Openreel_VideoApp` (App Entry)
+
+- **Purpose**: SwiftUI app scene. Boots audio session, creates app-wide state, injects environment.
+- **Layout**: a single `WindowGroup` containing `ContentView()`.
+- **State**:
+ - `@State private var appState = AppState()` — observable model of all app-level state (projects list, active screen, sheet flags, error messages, etc.).
+ - `@State private var playbackController = PlaybackController()` — playback engine (used in the editor and inspector views).
+ - Both injected via `.environment(appState)` / `.environment(playbackController)`.
+- **Side effects**: `configureAudioSession()` runs in `init()`. It sets `AVAudioSession` category to `.playback`, mode `.moviePlayback`, then activates the session. Errors are logged with `print` and otherwise ignored.
+- **Android mapping**: `Application` (or `MainActivity`) initializes a singleton `AppState` (use Hilt / a `ViewModelStoreOwner` at activity scope). Configure audio focus / `AudioAttributes` with `USAGE_MEDIA` + `CONTENT_TYPE_MOVIE` when the editor opens, not at app launch — Android best practice is to request audio focus only while actively playing.
+
+---
+
+### 4.2 `ContentView`
+
+- **Purpose**: Boilerplate Xcode wrapper. Renders `RootView()`.
+- **Android mapping**: not needed — call `RootView`'s Compose equivalent directly from `setContent {}`.
+
+---
+
+### 4.3 `RootView`
+
+- **Purpose**: Top-level router and host for global sheet/alert overlays.
+- **Layout (logical, not visual)**: a single `Group { ... }` whose visible content depends on three conditions in this order:
+ 1. `!hasCompletedOnboarding` → `OnboardingView()`
+ 2. else if `appState.isBootstrapping && !appState.hasBootstrapped` → `loadingView` (centered `VStack(spacing: 16)` with a `ProgressView().tint(accent)` and `Text("Loading projects")` using `.reelBody` + `textSecondary`, filled to `.frame(maxWidth: .infinity, maxHeight: .infinity)`).
+ 3. else if `appState.activeScreen == .editor` → `EditorView()`
+ 4. else → `LibraryTabView()`
+- **Background**: `OpenReelTheme.background.ignoresSafeArea()` behind the entire group.
+- **State**:
+ - `@Environment(AppState.self) private var appState`
+ - `@AppStorage("hasCompletedOnboarding") private var hasCompletedOnboarding = false`
+- **Side effects**:
+ - `.task { await appState.bootstrap() }` runs once when the view appears.
+ - `.sheet(isPresented:)` shows `NewProjectSheet` with `.presentationDetents([.fraction(0.5)])` and `.presentationDragIndicator(.visible)`. Bound to `appState.isShowingNewProjectSheet`; setting it false calls `appState.dismissNewProjectSheet()`.
+ - `.alert("OpenReel", isPresented:)` shows the global error. The presence of `appState.importErrorMessage` is converted to a `Bool` binding. Body has a single OK (`.cancel` role) button which calls `appState.dismissError()`. The message body is `appState.importErrorMessage ?? ""`.
+- **Edge cases**:
+ - If `bootstrap()` is fast, the loading screen may not render at all.
+ - If `hasCompletedOnboarding` flips back to false (e.g., logout/reset), the user is re-onboarded immediately.
+- **Android mapping**:
+ - Use a top-level `@Composable` `RootScreen` with a `when` block over a sealed `AppDestination`.
+ - The "onboarding completed" flag lives in `DataStore<Preferences>` (preferred) or `SharedPreferences`, collected via `collectAsState()`.
+ - Global sheet → `ModalBottomSheet(onDismissRequest = ..., sheetState = ...)` with `skipPartiallyExpanded = false` and a `SheetState` that defaults to half-expanded (Compose's `rememberModalBottomSheetState(skipPartiallyExpanded = false)`; you may need to call `partialExpand()` on first display).
+ - Global error alert → `AlertDialog(...)`.
+ - Loading screen → `Box(contentAlignment = Center) { Column { CircularProgressIndicator(color = accent); Text("Loading projects") } }`.
+
+---
+
+### 4.4 `LibraryTabView` (private inside RootView.swift)
+
+- **Purpose**: The two-tab home shell. Wraps each tab in its own `NavigationStack`.
+- **Layout**:
+ - `TabView(selection: selection) { ... }` — two tabs:
+ - Tab 1 — tag `.home`. `NavigationStack { HomeView() }`. `.tabItem { Label("Home", systemImage: "house.fill") }`.
+ - Tab 2 — tag `.projects`. `NavigationStack { ProjectsView() }`. `.tabItem { Label("Projects", systemImage: "film.stack") }`.
+- **Visual style**:
+ - Tab tint: `OpenReelTheme.accent` (`.tint(...)`).
+ - Tab bar background: `.toolbarBackground(.visible, for: .tabBar)` + `.toolbarBackground(surfaceElevated, for: .tabBar)`.
+- **State**: derived `Binding` (`selection`) mapping `appState.activeScreen` ↔ tab tag (see Navigation Graph for behavior).
+- **Android mapping**: `Scaffold { bottomBar = { NavigationBar { ... } } }` with two `NavigationBarItem`s.
+ - Tab icons: `Icons.Filled.Home` and a custom film/stack icon (or Material Symbol). The iOS icons are SF Symbols `house.fill` and `film.stack`.
+ - Tab content area renders either `HomeScreen()` or `ProjectsScreen()` inside their own `NavHost` so each tab has its own back stack (Compose: separate `NavHost` per tab, or use `rememberNavController()` per tab with `BackHandler`).
+ - Selected tint = accent green; container color = `surfaceElevated`.
+
+---
+
+### 4.5 `OnboardingView`
+
+- **Purpose**: First-launch tutorial showing three illustrated pages selling the editor's features. User can swipe horizontally or tap "Continue" to advance, and finish with "Start Editing" or "Skip".
+
+#### Layout (top to bottom)
+1. **Top bar** (horizontal padding 22, top padding = `max(safeAreaInsets.top, 12)`):
+ - `Image("AppLogo")` 28×28, fit aspect.
+ - 8pt gap.
+ - `Text("OpenReel")` 17pt bold rounded, `textPrimary`.
+ - `Spacer`.
+ - `Button("Skip")` 14pt bold rounded, `textSecondary`. Calls `completeOnboarding()`.
+2. **`TabView`** (page style, no index indicator) containing 3 `OnboardingPageContent` views, each padded `.horizontal, 22`. Page transitions use `.spring(response: 0.42, dampingFraction: 0.86)`.
+3. **Page indicator**: `HStack(spacing: 8)` of three `Capsule()`s.
+ - Active capsule: 24 wide × 8 tall, filled with `accent`.
+ - Inactive capsules: 8×8, filled with `textSecondary.opacity(0.3)`.
+ - Animated with `.spring(response: 0.3)` between states.
+4. **Action button** (horizontal padding 22, bottom padding = `max(safeAreaInsets.bottom, isCompact ? 14 : 24)`):
+ - Full-width pill-button `RoundedRectangle(cornerRadius: 14, style: .continuous)`.
+ - Background `accent`, shadow `accent.opacity(0.24)` radius 14 y 8.
+ - Inside: `HStack(spacing: 8)` of label `Text("Continue")` or `Text("Start Editing")` (16pt bold rounded, white) and an icon `arrow.right` or `checkmark` (14pt bold).
+ - Vertical padding 14, foreground white.
+ - Sensory haptic on page change: `.sensoryFeedback(.impact(flexibility: .soft), trigger: currentPage)`.
+
+Each page (`OnboardingPageContent`):
+- **Stack** (spacing 10 or 14 depending on `isCompact`):
+ - **Animated showcase** (`OnboardingShowcaseView`) — rendered with `TimelineView(.animation(minimumInterval: 1/30))` to drive 30fps animation. Inside, one of three showcases is shown based on `page.kind`:
+ - `.assemble` → fake editor with timeline (animated playhead, scenes appear progressively, a "hand.draw.fill" cursor swings horizontally)
+ - `.style` → glowing color-grade preview with dashed border and floating pill inspector
+ - `.export` → progress ring, export-option list, and share chips
+ - Height: 240 (compact) or 320.
+ - **Pill eyebrow**: `HStack(spacing: 6)` of an `Image(systemName: page.symbol)` (10pt bold) and `Text(page.eyebrow)` (11pt bold rounded). Padding `(.horizontal, 10).(.vertical, 5)`. Background `accent.opacity(0.12)` in a `Capsule`. Foreground `accent`.
+ - **Title** `Text(page.title)` 20pt or 24pt bold rounded, center-aligned, 2-line, `minimumScaleFactor 0.86`, `textPrimary`.
+ - **Description** 13–14pt medium rounded, center-aligned, `lineSpacing 2`, `textSecondary`, `fixedSize(horizontal: false, vertical: true)`.
+
+#### Page content
+| # | eyebrow | symbol | title | description | kind |
+|---|--------------------|--------------------------------|--------------------------------------------------------|------------------------------------------------------------------------------|-------------|
+| 1 | Timeline Builder | `timeline.selection` | "Build edits on a real multi-track timeline." | "Import clips, layer audio and text, trim with handles, and watch the playhead move through the edit." | `.assemble` |
+| 2 | Motion Studio | `sparkles.rectangle.stack.fill`| "Style every frame with motion and effects." | "Animate text, keyframe movement, adjust color, and preview the finished look as you edit." | `.style` |
+| 3 | Premium Export | `square.and.arrow.up.fill` | "Export polished video for every platform." | "Choose quality, resolution, frame rate, and format before sharing a finished cut." | `.export` |
+
+#### Visual style
+- Background = `OpenReelTheme.background.ignoresSafeArea()` with a linear gradient overlay:
+ ```
+ LinearGradient(
+ colors: [ accent.opacity(0.10), background.opacity(0.0), surface.opacity(0.42) ],
+ startPoint: .topLeading, endPoint: .bottomTrailing
+ )
+ ```
+- Showcase card (`OnboardingEditorShell` and `ExportShowcase`): `surfaceElevated` background, corner radius 24, white border 8% opacity, drop shadow (black 10%) radius 24 y 14, internal padding 12.
+- Showcase chrome buttons (`OnboardingChromeButton`): 30×30 circle. `accent` background if primary (white symbol), `surface` otherwise (textSecondary symbol). 11pt bold symbol.
+- Animated playhead (in mini timeline): 10×12 rounded-rect head (radius 2) over a 2×82 vertical line, both `accent`. Shadow `accent.opacity(0.24)` radius 7 y 4.
+- Time label on playhead: 8pt black monospaced white, padding `(.horizontal, 6).(.vertical, 3)`, capsule background `accent`.
+
+#### Interactions
+- **Swipe** horizontally between pages (standard `.page` TabView).
+- **Tap** "Skip" → `completeOnboarding()`.
+- **Tap** primary button → either advances `currentPage` (animated) or completes onboarding on last page.
+- Each page change triggers a soft haptic; completion fires a medium impact haptic.
+
+#### State
+- `@State private var currentPage = 0` — current page index.
+- `@AppStorage("hasCompletedOnboarding") private var hasCompletedOnboarding = false` — persists completion.
+
+#### Edge cases
+- **Compact heights** (`proxy.size.height < 720`): reduced spacings, showcase height 240, smaller title.
+- Safe-area-aware: top/bottom paddings use `max(safeAreaInsets, ...)`.
+
+#### Android mapping
+- `HorizontalPager` (Foundation) for the 3 pages, `PagerState`.
+- `Row` of three pill indicators (animated width via `animateDpAsState`).
+- Bottom button is a `Button` with `RoundedCornerShape(14.dp)` and the same drop shadow (use `Modifier.shadow(8.dp, RoundedCornerShape(14.dp), spotColor = accent.copy(alpha = 0.24f))`).
+- Haptic: `HapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)` from `LocalHapticFeedback.current`.
+- "hasCompletedOnboarding" flag in `DataStore<Preferences>`.
+- The animated showcases are 30fps procedural drawings — recreate with `Canvas` + `withFrameMillis` in a `LaunchedEffect`, or `rememberInfiniteTransition` for looping values, or a Lottie file pre-generated from the same logic.
+
+---
+
+### 4.6 `HomeView`
+
+- **Purpose**: The marketing-y landing tab. Promotes creating new projects, surfaces recent projects, and lists platform presets and tool shortcuts.
+
+#### Layout (vertical scroll, `ScrollView(showsIndicators: false)`)
+Each section's outer padding is given in parentheses.
+
+1. **Header** `homeHeader` (`.padding(.horizontal, 20).padding(.top, 12)`):
+ - `HStack(spacing: 10)`:
+ - `Image("AppLogo")` 26×26, fit aspect.
+ - `Text("OpenReel")` 20pt bold rounded, `textPrimary`.
+ - `Spacer`.
+ - **Plus button**: 32×32 circle, `accent` background, white `plus` SF symbol 14pt bold. Calls `appState.presentNewProjectSheet()`.
+
+2. **Hero** `heroSection` (`.padding(.horizontal, 20).padding(.top, 24)`):
+ - `HStack(alignment: .center, spacing: 16)`:
+ - Left: `VStack(alignment: .leading, spacing: 10)`:
+ - `Text("Create\nsomething great.")` 26pt bold rounded, `textPrimary`, lineSpacing 2.
+ - `Text("Professional video editing, right on your phone.")` 14pt medium rounded, `textSecondary`, lineSpacing 2.
+ - Both fade in from `opacity 0` / `offset(x: -12)` on appear.
+ - Right: `HomeHeroOrbitSystem()` 84×84 — an animated planetary scene (TimelineView at 30fps) with a central sun, orbiting planets, and occasional shooting stars. Scales/fades in on appear.
+
+3. **New Project card** `newProjectAction` (`.padding(.horizontal, 20).padding(.top, 20)`):
+ - Big tappable row:
+ - `HStack(spacing: 14)`:
+ - 42×42 circle, `accent.opacity(0.15)` fill, with `accent` `plus` symbol (16pt bold).
+ - VStack:
+ - `Text("New Project")` 15pt bold rounded, `textPrimary`.
+ - `Text("Set resolution, frame rate, and start editing")` 12pt medium rounded, `textSecondary`.
+ - `Spacer`.
+ - `chevron.right` 12pt bold, `textSecondary.opacity(0.5)`.
+ - Padding 14. Background `surfaceElevated` in `RoundedRectangle(cornerRadius: 16)`. Stroke border `accent.opacity(0.2)` width 1.
+ - Uses `HomeCardButtonStyle` (scale 0.97 on press).
+ - Calls `appState.presentNewProjectSheet()`.
+
+4. **Recent Projects** `recentProjectsSection` (`.padding(.top, 28)`):
+ - Section header row (`.padding(.horizontal, 20)`):
+ - `Text("Recent")` 15pt bold rounded.
+ - `Spacer`.
+ - If `appState.projects` is not empty, "All projects" link → calls `appState.showProjects()`. Label is `HStack(spacing: 4)` of `Text("All projects")` (12pt semibold rounded, `accent`) + `chevron.right` (9pt bold).
+ - If empty: `emptyProjectsState` — a centered card with:
+ - 56×56 circle (`accent.opacity(0.08)`) holding a `film.stack` icon (22pt semibold, `accent`).
+ - `Text("No projects yet")` 15pt bold rounded.
+ - `Text("Your projects will appear here.\nTap + to create your first edit.")` 13pt medium rounded, `textSecondary`, centered, `lineSpacing 2`.
+ - Background `surfaceElevated` in `RoundedRectangle(cornerRadius: 18)`. Border `Color.white.opacity(0.04)` width 1. Padding `(.vertical, 28)`.
+ - Horizontal padding 20.
+ - If non-empty: horizontal `ScrollView` showing `ProjectShowcaseCard(project:, width: 240)` for up to **6** projects (`appState.projects.prefix(6)`). Cards have 12pt spacing, padded `.horizontal, 20`. Each card fades up (`offset(y: 16)` → `0`, `opacity 0 → 1`) with a `.spring(response: 0.6, dampingFraction: 0.8)` staggered by `0.06 * index` seconds. Tap calls `appState.openProject(project)`.
+
+5. **Quick Start** `quickStartSection` (`.padding(.horizontal, 20).padding(.top, 28)`):
+ - `Text("Quick Start")` 15pt bold rounded.
+ - Horizontal `ScrollView`, `HStack(spacing: 10)` of platform preset cards (one per `PlatformPreset.allCases`). Each card:
+ - Width 80, vertical padding 12.
+ - Top icon block: 44×44 rounded rect (radius 8), fill = `preset.accentColor.opacity(0.12)`; centered SF symbol 18pt semibold, `preset.accentColor`.
+ - Label `Text(preset.label)` 12pt bold rounded, `textPrimary`.
+ - Subtitle `Text(preset.subtitle)` 9pt medium rounded, `textSecondary`.
+ - Background `surfaceElevated` in `RoundedRectangle(cornerRadius: 14)`. Border `preset.accentColor.opacity(0.15)` width 1.
+ - On tap: `await appState.quickCreateProject(preset: projectPreset, frameRate:, name:)`.
+ - Presets list (label / subtitle / symbol / accent / canvas / fps):
+ | Label | Subtitle | SF Symbol | Accent RGB | Canvas | FPS |
+ |-------------|----------------|------------------------|-------------------------|----------------|-----|
+ | TikTok | "9:16 · 30fps" | `music.note` | (0.92, 0.20, 0.40) | 1080×1920 | 30 |
+ | YT Short | "9:16 · 30fps" | `play.rectangle.fill` | (1.00, 0.20, 0.20) | 1080×1920 | 30 |
+ | YouTube | "16:9 · 30fps" | `play.rectangle` | (1.00, 0.15, 0.15) | 1920×1080 | 30 |
+ | Instagram | "1:1 · 30fps" | `camera` | (0.85, 0.25, 0.60) | 1080×1080 | 30 |
+ | X / Twitter | "16:9 · 30fps" | `bubble.left` | (0.20, 0.60, 1.00) | 1920×1080 | 30 |
+ | Cinema | "16:9 · 24fps" | `film` | (0.95, 0.70, 0.20) | 1920×1080 | 24 |
+ - 2-column `LazyVGrid` (spacing 10) of two cards below:
+ - **Photo Tools**: `NavigationLink → PhotoEnhancementView`, label `HomeQuickActionLabel(symbol: "photo.artframe", title: "Photo Tools", subtitle: "Enhance & restore")`.
+ - **Quick Trim**: `HomeQuickAction(symbol: "scissors", title: "Quick Trim", subtitle: "Cut a clip")` → presents new-project sheet.
+ - `HomeQuickActionLabel` style: 32×32 icon background `accent.opacity(0.12)` rounded 8, symbol `accent` 14pt semibold. Title 13pt bold rounded `textPrimary`. Subtitle 10pt medium rounded `textSecondary`. Outer padding 10. Background `surfaceElevated` in `RoundedRectangle(cornerRadius: 12)`. Border white 4%.
+
+6. **Bottom spacer**: `Spacer(minLength: 80)` to leave room for the tab bar.
+
+#### Background
+`homeBackground`: ZStack of `OpenReelTheme.background.ignoresSafeArea()` + a linear gradient `[accent.opacity(0.04), background.opacity(0)]` from `.topLeading` to `.center` (ambient green wash).
+
+#### Visual style
+- `.navigationBarHidden(true)` — Home draws its own header.
+- On appear: `withAnimation(.spring(response: 0.7, dampingFraction: 0.8)) { appearAnimation = true }` — drives hero text fade-in (offset -12 → 0, opacity 0 → 1) and hero orbit scale-in (0.8 → 1).
+- Card press style: `HomeCardButtonStyle` — scale 0.97, opacity 0.85 when pressed, `.spring(response: 0.25, dampingFraction: 0.7)`.
+
+#### Interactions
+- **Plus button** in header → present sheet.
+- **New Project** card → present sheet.
+- **All projects** link → switch to Projects tab via `appState.showProjects()`.
+- **Recent project card** → `appState.openProject(project)` (opens editor).
+- **Platform preset card** → `appState.quickCreateProject(...)` (directly creates project & opens editor; no sheet).
+- **Photo Tools** → push `PhotoEnhancementView` onto the Home nav stack.
+- **Quick Trim** → present sheet.
+
+#### State
+- `@Environment(AppState.self) private var appState` — for projects list and actions.
+- `@State private var appearAnimation = false` — local entrance animation flag.
+- Recent project carousel shows at most 6 entries (`appState.projects.prefix(6)`).
+
+#### Side effects
+- Sheet presentation, navigation push, tab switch, project creation (async via `Task`).
+
+#### Edge cases
+- Empty projects → "Recent" section shows the empty-state card; "All projects" link hidden.
+- Long project list → carousel caps at 6; rest accessible only via Projects tab.
+
+#### Android mapping
+- `LazyColumn { ... }` with `item { }` blocks per section, plus a horizontal `LazyRow` for the recent-projects carousel and for the quick-start preset row.
+- The orbit graphic: build with Compose `Canvas` and an `InfiniteTransition`, or render a pre-made Lottie animation (preferred).
+- "New Project" card → `Surface(shape = RoundedCornerShape(16.dp), color = surfaceElevated, border = BorderStroke(1.dp, accent.copy(alpha = 0.2f)), modifier = Modifier.clickable { ... }.padding(14.dp))`.
+- Press animation → `Modifier.pointerInteropFilter` + `animateFloatAsState` or use `Modifier.scale(if (pressed) 0.97f else 1f)` driven by `interactionSource`.
+
+---
+
+### 4.7 `ProjectsView`
+
+- **Purpose**: Full browser of stored projects with storage summary, grid/list toggle, and per-card delete confirmation.
+
+#### Layout
+- Z-stacked `OpenReelTheme.background.ignoresSafeArea()` behind a `ScrollView`.
+- `ScrollView` contents (`.padding(.horizontal, 16).padding(.top, 12).padding(.bottom, 40)`):
+ - If `appState.projects.isEmpty` → `emptyState`.
+ - Else:
+ - **Storage overview card** (`storageOverview`):
+ - `HStack` of:
+ - 46×46 rounded rect (radius 14), fill `accent.opacity(0.14)`, with `internaldrive` symbol 18pt bold `accent`.
+ - `VStack`:
+ - `Text(totalProjectStorageLabel)` 18pt bold rounded `textPrimary` — value computed via `ByteCountFormatter.string(fromByteCount: totalProjectStorageUsage, countStyle: .file)` (e.g. "1.2 GB"). Shows "Calculating…" while storage scan is incomplete (`projectStorageUsageByID.count < projects.count`).
+ - `Text(storageOverviewSubtitle)` 12pt medium rounded `textSecondary` — "1 project stored on this device" / "N projects stored on this device".
+ - `Spacer`.
+ - `Text(count)` 16pt bold monospaced `accent`.
+ - `Text("Use the menu on any card to delete older projects and reclaim storage.")` 12pt medium rounded `textSecondary`.
+ - Outer padding 16. Background `surfaceElevated`, `RoundedRectangle(cornerRadius: 18)`. Stroke border `accent.opacity(0.18)` width 1.
+ - **Either grid or list view** depending on `showsGrid`:
+ - **Grid** (`gridContent`): `LazyVGrid(columns: 2, spacing 12)` of `ProjectBrowserGridCard(project:, storageUsage:, onOpen:, onDelete:)`.
+ - **List** (`listContent`): `LazyVStack(spacing 10)` of `ProjectBrowserRowCard(project:, storageUsage:, onOpen:, onDelete:)`.
+ - Section vertical spacing inside the scroll: 20.
+- `.navigationTitle("Projects")`, `.navigationBarTitleDisplayMode(.large)`.
+- `.toolbarBackground(.visible, for: .navigationBar)` + `.toolbarBackground(background, for: .navigationBar)`.
+
+#### Toolbar (top-bar trailing items, two `ToolbarItem(placement: .topBarTrailing)`)
+1. **Layout-toggle group**: `HStack(spacing: 2)` of two 32×32 buttons:
+ - `square.grid.2x2` symbol (grid view) — calls `showsGrid = true`.
+ - `list.bullet` symbol (list view) — calls `showsGrid = false`.
+ - Each `Image(systemName:)` is 14pt semibold; foreground = `accent` if selected else `textSecondary.opacity(0.4)`.
+2. **Plus button**: same style as Home's header plus button — 32×32 circle, `accent` background, white `plus` 14pt bold. Calls `appState.presentNewProjectSheet()`.
+
+#### Empty state
+- Center-stacked `VStack(spacing: 20)`:
+ - `film.stack` symbol 40pt light, `textSecondary`.
+ - `Text("No projects yet")` 18pt bold rounded.
+ - `Text("Create a project to start editing video.")` 14pt medium rounded `textSecondary`.
+ - Pill button "New Project": 14pt semibold rounded white, padding `.horizontal, 20`/`.vertical, 12`, `Capsule` fill `accent`. Calls `presentNewProjectSheet()`.
+- Vertical padding 60. Filled to max width.
+
+#### Visual style
+- 16pt horizontal screen padding (vs. 20 on Home).
+- Storage card uses a green-tinted border to distinguish from neutral cards.
+
+#### Interactions
+- **Tap card** → `appState.openProject(project)`.
+- **Card menu → Delete** → `pendingProjectDeletion = project`, opens a confirmation dialog.
+- **Toolbar layout toggle** → `showsGrid = true/false`.
+- **Toolbar `+`** → present sheet.
+
+#### Deletion confirmation
+`.confirmationDialog("Delete Project", titleVisibility: .visible)`:
+- Destructive button labeled `"Delete \(project.name)"` → `Task { await appState.deleteProject(project); pendingProjectDeletion = nil }`.
+- Cancel button labeled `"Cancel"`.
+- Message: `"This removes the project, its media, thumbnails, and cached AI results from this device."`.
+
+#### State
+- `@Environment(AppState.self) private var appState`.
+- `@State private var showsGrid = true` — view mode.
+- `@State private var pendingProjectDeletion: OpenReelProject?` — the project the user is about to delete.
+- `projectStorageRefreshSignature` — a string `"id-modifiedAt|id-modifiedAt|..."` recomputed any time projects change; used as `.task(id:)` so storage usage is re-scanned whenever projects or their modified times change.
+
+#### Side effects
+- `.task(id: projectStorageRefreshSignature) { await appState.refreshProjectStorageUsage() }` — scans on-disk storage in the background.
+- Confirmation dialog presentation/dismissal.
+- Async project deletion.
+
+#### Edge cases
+- **Storage still calculating** → `totalProjectStorageLabel` shows "Calculating…" until `projectStorageUsageByID.count >= projects.count`.
+- **Singular / plural** subtitle (1 vs N).
+- **Empty list** → swaps the entire content for the empty state.
+
+#### Android mapping
+- Scaffold with a `LargeTopAppBar(title = { Text("Projects") }, actions = { ... })`.
+- Top-bar actions: a `Row` containing two `IconButton`s for grid/list, then an `IconButton` styled as a 32.dp circle with the accent background for `+`.
+- Body: `LazyVerticalGrid(columns = GridCells.Fixed(2), ...)` or `LazyColumn` based on `showsGrid` state.
+- Storage card: `Surface(shape = RoundedCornerShape(18.dp), color = surfaceElevated, border = BorderStroke(1.dp, accent.copy(alpha = 0.18f)), ...)`.
+- Delete confirmation: `AlertDialog` with destructive button (`MaterialTheme.colorScheme.error`).
+- Storage rescan: launch a `LaunchedEffect(projectsSignature) { viewModel.refreshStorage() }` keyed off the same signature.
+
+---
+
+### 4.8 `NewProjectSheet`
+
+- **Purpose**: Modal sheet to configure a new project (name + resolution + frame rate) and create it.
+
+#### Presentation
+- Presented from `RootView` with `.presentationDetents([.fraction(0.5)])` and `.presentationDragIndicator(.visible)` — half-screen by default, drag indicator visible at top.
+- Hosted in a `NavigationStack` so the toolbar `Close` button can appear in the nav bar.
+
+#### Layout (vertical scroll, `padding(20)` on the inner `VStack(spacing: 24, alignment: .leading)`)
+1. **Header**:
+ - `Text("New Project")` 24pt bold rounded, `textPrimary`.
+ - `Text("Pick a canvas and frame rate for your first edit.")` `.reelBody`, `textSecondary`.
+2. **Project Name section** (VStack spacing 12):
+ - Label: `Text("Project Name")` `.reelSection`, `textPrimary`.
+ - `TextField("Project Name", text: $appState.newProjectConfiguration.name)`:
+ - `.textInputAutocapitalization(.words)`.
+ - `.padding(.horizontal, 16)`.
+ - Height 52. Background `OpenReelTheme.surface` in `RoundedRectangle(cornerRadius: 16)`.
+3. **Resolution section** (VStack spacing 12):
+ - Label: `Text("Resolution")` `.reelSection`.
+ - `LazyVGrid(columns: 2, spacing 12)` of preset buttons (one per `NewProjectConfiguration.presets`):
+ - Each button:
+ - `Text(preset.name)` 15pt semibold rounded.
+ - `Text("\(preset.width) × \(preset.height)")` `.reelCaption`.
+ - Foreground: white if selected, else `textPrimary`.
+ - Background: `accent` (if selected) else `surface`, in `RoundedRectangle(cornerRadius: 16)`.
+ - Min height 76, leading-aligned, padding `.horizontal, 14`.
+4. **Frame Rate section** (VStack spacing 12):
+ - Label: `Text("Frame Rate")` `.reelSection`.
+ - `HStack(spacing: 10)` of pill buttons (one per `NewProjectConfiguration.supportedFrameRates`):
+ - Label `"\(Int(frameRate)) fps"` 13pt semibold rounded.
+ - Foreground white if selected else `textPrimary`.
+ - Background `accent` (selected) or `surfaceElevated` (unselected), in `Capsule()`.
+ - Padding `.horizontal, 14`. Height 42.
+5. **Create button**:
+ - `Text("Create Project")` 16pt bold rounded, white.
+ - Full width, height 54. Background `accent` in `RoundedRectangle(cornerRadius: 18)`.
+ - On tap: `Task { await appState.createProject() }`.
+
+#### Toolbar
+- `ToolbarItem(placement: .topBarTrailing)`: `Button("Close")` with `foregroundStyle(textSecondary)`. Calls `appState.dismissNewProjectSheet()`.
+
+#### Background
+`OpenReelTheme.background.ignoresSafeArea()` inside the `NavigationStack`'s scroll background.
+
+#### Interactions
+- Type in text field — updates `newProjectConfiguration.name`.
+- Tap a resolution preset — sets `newProjectConfiguration.preset`.
+- Tap a frame rate pill — sets `newProjectConfiguration.frameRate`.
+- Tap "Create Project" — creates the project asynchronously; on success, `AppState` navigates to the editor.
+- Tap "Close" or drag down — dismisses the sheet via `dismissNewProjectSheet()`.
+
+#### State
+- `@Environment(AppState.self) private var appState` (`@Bindable` view of it).
+- All edits write through `appState.newProjectConfiguration`. Presets/frame rates come from `NewProjectConfiguration.presets` and `NewProjectConfiguration.supportedFrameRates`.
+
+#### Edge cases
+- Validation is implicit (no inline errors shown here). Creation failures surface via the global `importErrorMessage` alert in `RootView`.
+
+#### Android mapping
+- `ModalBottomSheet` (Material 3) with `skipPartiallyExpanded = false`. Use `sheetState.partialExpand()` if you want the half-detent first.
+- Inner content: a `Column` inside `Modifier.verticalScroll(rememberScrollState())`.
+- Resolution grid: `LazyVerticalGrid(columns = GridCells.Fixed(2), userScrollEnabled = false)` *or* a manual two-column `Row`-of-`Column`s pattern — both work.
+- Frame rate pills: `Row` of `FilterChip`s or custom-styled buttons matching the green capsule.
+- Use `OutlinedTextField` or a custom `BasicTextField` styled to match (no border, rounded 16.dp `surface` background, `capitalization = KeyboardCapitalization.Words`).
+- Bottom "Create Project" button: full-width `Button` with `shape = RoundedCornerShape(18.dp)`.
+
+---
+
+## 5. Android Mapping Summary
+
+| iOS | Android (Compose) |
+|---------------------------------------------|-----------------------------------------------------------------------------------|
+| `@main App` + `@Environment` injection | `Application` + Hilt (or `ViewModelStoreOwner`) for app-scoped state |
+| `RootView` switch-by-state | `RootScreen` with `when (destination) { ... }` |
+| `TabView` (bottom tab bar) | `Scaffold(bottomBar = { NavigationBar { NavigationBarItem(...) } })` |
+| `NavigationStack` | `NavHost` (one per tab) with `rememberNavController()` |
+| `.sheet(detents: [.fraction(0.5)])` | `ModalBottomSheet` with `rememberModalBottomSheetState` |
+| `.alert("...")` | `AlertDialog` |
+| `.confirmationDialog` | `AlertDialog` (destructive button + cancel) or `ModalBottomSheet` |
+| `@AppStorage("hasCompletedOnboarding")` | `DataStore<Preferences>` flow collected with `collectAsState()` |
+| `@Environment(AppState.self)` | `viewModel: AppViewModel = hiltViewModel()` (activity scope) |
+| SF Symbols (e.g. `house.fill`, `plus`) | Material Symbols / `androidx.compose.material.icons.filled.*` (or vector assets) |
+| `RoundedRectangle(cornerRadius:, style: .continuous)` | `RoundedCornerShape(X.dp)` |
+| `LinearGradient` | `Brush.linearGradient(colors, start = Offset.Zero, end = ...)` |
+| `TimelineView(.animation)` | `withFrameMillis { ... }` inside `LaunchedEffect`, or `rememberInfiniteTransition`|
+| `Button(...).buttonStyle(.plain)` + press scale | `Modifier.clickable(interactionSource = ...)` + animated `scale` |
+| `@AppStorage`-backed dark mode dynamic color | Material 3 `lightColorScheme`/`darkColorScheme` |
+| `UIImpactFeedbackGenerator` | `LocalHapticFeedback.current.performHapticFeedback(...)` |
+| `AVAudioSession` setup at app init | Configure `AudioAttributes`/`AudioFocusRequest` lazily when starting playback |
+| `ByteCountFormatter` | `android.text.format.Formatter.formatFileSize(context, bytes)` |
+
+### Naming/imagery the Android team needs
+- App logo image: `AppLogo` (provide as `R.drawable.ic_app_logo`, vector or PNG).
+- SF Symbols used by these screens (find Material Symbol equivalents):
+ - `plus`, `chevron.right`, `house.fill`, `film.stack`, `square.grid.2x2`, `list.bullet`, `internaldrive`, `photo.artframe`, `scissors`, `arrow.right`, `checkmark`, `timeline.selection`, `sparkles.rectangle.stack.fill`, `square.and.arrow.up.fill`, `square.and.arrow.up`, `arrow.uturn.backward`, `play.fill`, `music.note`, `play.rectangle`, `play.rectangle.fill`, `camera`, `bubble.left`, `film`, `photo.fill`, `waveform`, `textformat`, `textformat.size`, `camera.filters`, `diamond.fill`, `slider.horizontal.3`, `square.and.arrow.down`, `video.fill`, `hand.draw.fill`.
+
+### Components used outside this doc (referenced but defined elsewhere)
+- `ProjectShowcaseCard(project:, width: 240)` — used on Home.
+- `ProjectBrowserGridCard` / `ProjectBrowserRowCard` — used on Projects.
+- `EditorView` — editor screen (separate doc).
+- `PhotoEnhancementView` — pushed from Home Quick Start (separate doc).
+- `AppState`, `PlaybackController`, `OpenReelProject`, `NewProjectConfiguration` — app-state types (separate doc).
diff --git a/docs/android-port/02-data-models-and-state.md b/docs/android-port/02-data-models-and-state.md
new file mode 100644
index 00000000..408fe381
--- /dev/null
+++ b/docs/android-port/02-data-models-and-state.md
@@ -0,0 +1,1587 @@
+# 02 — Data Models, Project Format, and Persistence
+
+Source of truth for the Android Kotlin port. Every type below is verbatim from the iOS SwiftUI app.
+
+Primary source files:
+
+- `Openreel Video/Openreel Video/Core/Models/OpenReelProject.swift`
+- `Openreel Video/Openreel Video/Core/Storage/ProjectStore.swift`
+- `Openreel Video/Openreel Video/Core/Timeline/ActionHistory.swift`
+- `Openreel Video/Openreel Video/Core/Timeline/TimelineTransitionResolver.swift`
+- `Openreel Video/Openreel Video/Core/Timeline/TransitionCatalog.swift`
+- `Openreel Video/Openreel Video/AppState.swift`
+
+---
+
+## 1. OpenReelProject schema
+
+### 1.1 Envelope
+
+```swift
+struct OpenReelProjectFile: Codable, Equatable {
+ static let schemaVersion = "1.1.0"
+ var version: String // schema version (currently "1.1.0")
+ var project: OpenReelProject
+}
+```
+
+The persisted JSON is always wrapped in `OpenReelProjectFile { version, project }`. `version` is required when decoding; absence implies the file is corrupt.
+
+A second envelope exists for template packages:
+
+```swift
+struct OpenReelTemplatePackageFile: Codable, Equatable {
+ static let schemaVersion = "1.0.0"
+ var version: String
+ var template: OpenReelProject.TemplatePackage
+}
+```
+
+### 1.2 OpenReelProject (root)
+
+| Field | Type | Default | Notes |
+|--------------------|---------------------------|---------------|-------|
+| `id` | `String` | required | UUID v4 string |
+| `name` | `String` | required | Display name |
+| `createdAt` | `Int` | required | Unix epoch **milliseconds** |
+| `modifiedAt` | `Int` | required | Unix epoch **milliseconds** |
+| `settings` | `ProjectSettings` | required | |
+| `exportPreferences`| `ExportPreferences` | derived from `settings` if missing | added in 1.1 |
+| `mediaLibrary` | `MediaLibrary` | required | |
+| `timeline` | `Timeline` | required | |
+| `textClips` | `[TextClip]` | `[]` | optional in JSON |
+| `graphicsClips` | `[GraphicsClip]` | `[]` | optional in JSON |
+
+Custom Codable on the project allows missing `exportPreferences`, `textClips`, and `graphicsClips` (migration path from older 1.0.x files).
+
+### 1.3 ProjectSettings
+
+```swift
+struct ProjectSettings: Codable, Equatable {
+ var width: Int
+ var height: Int
+ var frameRate: Double // hz, normalized to {24, 30, 60}
+ var sampleRate: Int // typically 48000
+ var channels: Int // typically 2
+}
+```
+
+`NewProjectConfiguration` defaults: `sampleRate = 48_000`, `channels = 2`, `frameRate = 30`, preset = 1080p `1920x1080`. Supported frame rates: `[24, 30, 60]`. Presets: `1080p (1920x1080)`, `Square (1080x1080)`, `Portrait (1080x1920)`, `4K (3840x2160)`.
+
+### 1.4 Export configuration
+
+```swift
+struct ExportPreferences: Codable, Equatable {
+ var preset: ExportPreset // default: .youtube
+ var resolution: ExportResolution
+ var frameRate: Double // snapped to supported rates
+ var format: ExportFormat // default by preset
+ var quality: Double // clamped to [0.2, 1.0]; default 0.85
+}
+
+enum ExportPreset: String, Codable, CaseIterable {
+ case youtube, tiktok, instagramSquare, instagramPortrait, twitter, custom
+}
+
+struct ExportResolution: Codable, Hashable {
+ var width: Int // min 1
+ var height: Int // min 1
+}
+
+struct ExportFormat: Codable, Equatable {
+ var container: ExportContainer
+ var codec: ExportCodec
+ var proResProfile: ProResProfile? // only set when codec == .proRes
+}
+
+enum ExportContainer: String, Codable { case mp4, mov, gif }
+enum ExportCodec: String, Codable { case h264, hevc, proRes, gif }
+enum ProResProfile: String, Codable { case proxy, lt, standard, hq }
+```
+
+Format invariants (enforced in `ExportFormat.init`):
+
+- `codec == .gif` -> `container = .gif`
+- `codec == .proRes` -> `container = .mov`, `proResProfile` defaulted to `.standard` if nil
+- Otherwise `container` honored, `proResProfile = nil`
+
+Preset → default resolution:
+
+| Preset | Resolution | Default codec |
+|--------------------|---------------|----------------|
+| youtube | 1920x1080 | hevc |
+| tiktok | 1080x1920 | h264 |
+| instagramSquare | 1080x1080 | hevc |
+| instagramPortrait | 1080x1350 | h264 |
+| twitter | 1920x1080 | h264 |
+| custom | 1920x1080 | hevc |
+
+### 1.5 Schema version migrations
+
+| From | To | Migration |
+|------|-------|-----------|
+| — | 1.0.0 | initial |
+| 1.0.x| 1.1.0 | `exportPreferences`, `textClips`, `graphicsClips` made optional during decode and default-initialized; `Timeline.beatMarkers`, `Timeline.beatAnalyses` made optional. `Track.audioMix` defaults to `AudioTrackMix()`. `Clip.audioConfiguration` defaults to `AudioConfiguration()`. |
+
+There is no in-place rewrite of files; old documents simply decode with defaults filled in, and the next save writes `version = "1.1.0"`.
+
+---
+
+## 2. Track, Clip, Layer hierarchy
+
+### 2.1 Timeline
+
+```swift
+struct Timeline: Codable, Equatable {
+ var tracks: [Track]
+ var subtitles: [Subtitle]
+ var duration: Double // seconds; optional, default 0
+ var markers: [Marker]
+ var beatMarkers: [BeatMarker] = []
+ var beatAnalyses: [BeatAnalysis] = []
+}
+```
+
+`subtitles`, `markers`, `beatMarkers`, `beatAnalyses` are optional in JSON and default to `[]`.
+
+### 2.2 Track
+
+```swift
+struct Track: Codable, Identifiable, Equatable {
+ var id: String
+ var type: TrackType
+ var name: String
+ var clips: [Clip]
+ var transitions: [Transition]
+ var locked: Bool // default false
+ var hidden: Bool // default false
+ var muted: Bool // default false
+ var solo: Bool // default false
+ var audioMix: AudioTrackMix = AudioTrackMix()
+}
+
+enum TrackType: String, Codable { case video, audio, image, text, graphics }
+
+enum AudioTrackRole: String, Codable, CaseIterable {
+ case general, dialogue, music, effects, ambience
+}
+
+struct AudioTrackMix: Codable, Equatable {
+ var role: AudioTrackRole // default .general
+ var gain: Double // default 1
+ var pan: Double // default 0 (range [-1, 1])
+}
+```
+
+There is no z-order field — order in `tracks[]` is the stacking order. `clips` and `transitions` are optional on decode (default `[]`); `locked/hidden/muted/solo/audioMix` are optional with the defaults above.
+
+### 2.3 Clip (media-backed: video, audio, image)
+
+```swift
+struct Clip: Codable, Identifiable, Equatable {
+ var id: String
+ var mediaId: String // references MediaLibrary.items[].id
+ var trackId: String
+ var startTime: Double // seconds on timeline; default 0
+ var duration: Double // seconds; default 0
+ var inPoint: Double // source in-point; default 0
+ var outPoint: Double // source out-point; default == duration
+ var effects: [Effect] // visual/processing effects; default []
+ var audioEffects: [Effect] // audio effects; default []
+ var transform: Transform
+ var volume: Double // default 1; clamped [0, 2]
+ var keyframes: [Keyframe] // default []
+ var speed: Double? // optional; default nil; clamped [0.25, 4]
+ var reversed: Bool? // optional
+ var audioTrackIndex: Int? // for multi-track media
+ var audioConfiguration: AudioConfiguration = AudioConfiguration()
+ var blendMode: BlendMode? = nil
+ var blendOpacity: Double? = nil
+ var emphasisAnimation: EmphasisAnimation? = nil
+ var metadata: ClipMetadata? = nil
+}
+```
+
+The minimum clip duration (enforced everywhere): `minimumClipDuration = 0.2` seconds.
+
+### 2.4 Transform / Crop / FitMode
+
+```swift
+struct Transform: Codable, Equatable {
+ var position: Point // canvas-space, e.g. (0.5, 0.5) for center
+ var scale: Point // x/y scale, 1 = identity
+ var rotation: Double // radians or degrees per usage site
+ var anchor: Point // anchor point for rotation/scale (0..1 normalized)
+ var opacity: Double // [0, 1]
+ var borderRadius: Double? // px or normalized
+ var fitMode: FitMode? // how source media fits frame
+ var crop: Crop?
+}
+
+struct Point: Codable, Equatable { var x: Double; var y: Double }
+struct Crop: Codable, Equatable { var x, y, width, height: Double }
+
+enum FitMode: String, Codable { case contain, cover, stretch, none }
+```
+
+### 2.5 Blend modes
+
+```swift
+enum BlendMode: String, Codable, CaseIterable {
+ case normal, multiply, screen, overlay, darken, lighten,
+ colorDodge = "color-dodge", colorBurn = "color-burn",
+ hardLight = "hard-light", softLight = "soft-light",
+ difference, exclusion, hue, saturation, color, luminosity
+}
+```
+
+Applied per-clip via `Clip.blendMode` and `Clip.blendOpacity` (in addition to `Transform.opacity`). Text clips and graphics clips have the same two fields.
+
+### 2.6 Effects
+
+```swift
+struct Effect: Codable, Identifiable, Equatable {
+ var id: String
+ var type: String // engine-specific identifier
+ var params: [String: JSONValue] // arbitrary parameter map
+ var enabled: Bool
+}
+```
+
+`Clip.effects` is the visual stack; `Clip.audioEffects` is the audio stack. Order is render order. Effects can be copied across clips via `AppState.copiedEffectStack: [Effect]`.
+
+### 2.7 Keyframes
+
+```swift
+struct Keyframe: Codable, Identifiable, Equatable {
+ var id: String
+ var time: Double // seconds, relative to clip start
+ var property: String // e.g. "transform.position", "opacity"
+ var value: JSONValue
+ var easing: String // see EasingFunctions catalog
+}
+```
+
+Both `Clip` and `TextClip` and `GraphicsClip` carry their own `keyframes: [Keyframe]`. `KeyframeEngine.upserting(_:into:clipDuration:)` is the canonical mutation API.
+
+### 2.8 Audio configuration
+
+```swift
+enum AudioAutomationCurve: String, Codable {
+ case linear, exponential, logarithmic,
+ sCurve = "s-curve", bezier
+}
+
+struct AudioBezierControlPoints: Codable, Equatable {
+ var cp1x, cp1y, cp2x, cp2y: Double
+}
+
+struct AudioFade: Codable, Equatable {
+ var duration: Double
+ var curve: AudioAutomationCurve // default .linear
+ var bezierControlPoints: AudioBezierControlPoints?
+}
+
+struct AudioAutomationPoint: Codable, Identifiable, Equatable {
+ var id: String
+ var time: Double
+ var value: Double
+ var curve: AudioAutomationCurve // default .linear
+ var bezierControlPoints: AudioBezierControlPoints?
+}
+
+struct AudioConfiguration: Codable, Equatable {
+ var pan: Double // [-1, 1]; default 0
+ var fadeIn: AudioFade?
+ var fadeOut: AudioFade?
+ var volumeAutomation: [AudioAutomationPoint] // default []
+ var linkGroupID: String? // links video+detached audio
+ var detachedSourceClipID: String? // back-ref to source clip
+}
+```
+
+### 2.9 Beats and markers
+
+```swift
+struct BeatMarker: Codable, Identifiable, Equatable {
+ var id: String
+ var time: Double
+ var strength: Double
+ var index: Int
+ var isDownbeat: Bool
+ var sourceClipID: String?
+}
+
+struct BeatAnalysis: Codable, Equatable {
+ var sourceClipID: String
+ var bpm: Double
+ var confidence: Double
+ var analyzedAt: Int // unix ms
+}
+
+struct Marker: Codable, Identifiable, Equatable {
+ var id: String
+ var time: Double
+ var label: String
+ var color: String // hex
+}
+```
+
+### 2.10 Subtitles
+
+```swift
+struct Subtitle: Codable, Identifiable, Equatable {
+ var id: String
+ var text: String
+ var startTime: Double
+ var endTime: Double
+ var style: SubtitleStyle? = nil
+ var words: [SubtitleWord]? = nil
+ var animationStyle: CaptionAnimationStyle? = nil
+}
+
+struct SubtitleWord: Codable, Equatable {
+ var text: String
+ var startTime: Double
+ var endTime: Double
+}
+
+struct SubtitleStyle: Codable, Equatable {
+ var fontFamily: String // default "SF Pro"
+ var fontSize: Double // default 24
+ var color: String // default "#FFFFFF"
+ var backgroundColor: String // default "rgba(0,0,0,0.75)"
+ var position: SubtitlePosition // default .bottom
+ var highlightColor: String?
+ var upcomingColor: String?
+}
+
+enum SubtitlePosition: String, Codable, CaseIterable { case top, center, bottom }
+
+enum CaptionAnimationStyle: String, Codable, CaseIterable {
+ case none,
+ wordHighlight = "word-highlight",
+ wordByWord = "word-by-word",
+ karaoke, bounce, typewriter
+}
+```
+
+### 2.11 Text clips
+
+```swift
+struct TextClip: Codable, Identifiable, Equatable {
+ var id: String
+ var trackId: String
+ var startTime: Double
+ var duration: Double
+ var text: String
+ var style: TextStyle
+ var transform: Transform
+ var animation: TextAnimation?
+ var keyframes: [Keyframe]
+ var blendOpacity: Double?
+ var behindSubject: Bool? // SAM-derived render-behind flag
+ var metadata: [String: JSONValue]?
+ var blendMode: BlendMode? = nil
+ var emphasisAnimation: EmphasisAnimation? = nil
+}
+
+struct TextStyle: Codable, Equatable {
+ var fontFamily: String
+ var fontSize: Double
+ var fontWeight: TextFontWeight
+ var fontStyle: String // "normal" | "italic"
+ var color: String // hex
+ var backgroundColor: String?
+ var strokeColor: String?
+ var strokeWidth: Double?
+ var shadowColor: String?
+ var shadowBlur: Double?
+ var shadowOffsetX: Double?
+ var shadowOffsetY: Double?
+ var textAlign: TextAlign // left, center, right, justify
+ var verticalAlign: TextVerticalAlign // top, middle, bottom
+ var lineHeight: Double
+ var letterSpacing: Double
+ var textDecoration: String? // "underline" | "line-through" | nil
+}
+
+enum TextFontWeight: Codable, Equatable {
+ case numeric(Int) // 100..900
+ case named(String) // "bold", "regular", etc.
+}
+
+enum TextAlign: String, Codable, CaseIterable {
+ case left, center, right, justify
+}
+
+enum TextVerticalAlign: String, Codable { case top, middle, bottom }
+
+struct TextAnimation: Codable, Equatable {
+ var preset: TextAnimationPreset
+ var params: [String: JSONValue]
+ var inDuration: Double
+ var outDuration: Double
+ var stagger: Double?
+ var unit: TextAnimationUnit? // character | word | line
+}
+
+enum TextAnimationPreset: String, Codable, CaseIterable {
+ case none, typewriter,
+ wordHighlight = "word-highlight",
+ karaoke, fade,
+ slideLeft = "slide-left", slideRight = "slide-right",
+ slideUp = "slide-up", slideDown = "slide-down",
+ scale, blur, bounce, rotate, wave, shake, pop, glitch, split, flip,
+ wordByWord = "word-by-word", rainbow
+}
+```
+
+### 2.12 Graphics clips
+
+```swift
+struct GraphicsClip: Codable, Identifiable, Equatable {
+ var id: String
+ var trackId: String
+ var startTime: Double
+ var duration: Double
+ var type: GraphicType // shape | image | sticker | emoji
+ var transform: Transform
+ var keyframes: [Keyframe]
+ var blendMode: BlendMode?
+ var blendOpacity: Double?
+ var emphasisAnimation: EmphasisAnimation?
+ var shapeType: ShapeType? // when type == .shape
+ var style: ShapeStyle?
+ var points: [Point]? // for polygon/line
+ var asset: GraphicAsset? // for image/sticker/emoji
+ var metadata: [String: JSONValue]?
+}
+
+enum GraphicType: String, Codable, CaseIterable {
+ case shape, image, sticker, emoji
+}
+
+enum ShapeType: String, Codable, CaseIterable {
+ case rectangle, circle, ellipse, triangle, arrow, line, polygon, star
+}
+
+struct GraphicAsset: Codable, Equatable {
+ var imageURL: String?
+ var localFileName: String?
+ var emoji: String?
+ var symbolName: String? // SF Symbols / Android equivalent
+ var name: String?
+ var category: String?
+}
+
+struct ShapeStyle: Codable, Equatable {
+ var fill: FillStyle
+ var stroke: StrokeStyle
+ var shadow: ShadowStyle?
+ var cornerRadius: Double?
+ var points: Int?
+ var innerRadius: Double? // for star
+}
+
+struct FillStyle: Codable, Equatable {
+ var type: FillKind // solid | gradient | none
+ var color: String?
+ var gradient: GradientStyle?
+ var opacity: Double
+}
+
+enum FillKind: String, Codable { case solid, gradient, none }
+
+struct GradientStyle: Codable, Equatable {
+ var type: GradientKind // linear | radial
+ var angle: Double?
+ var stops: [GradientStop]
+}
+
+enum GradientKind: String, Codable { case linear, radial }
+struct GradientStop: Codable, Equatable { var offset: Double; var color: String }
+
+struct StrokeStyle: Codable, Equatable {
+ var color: String
+ var width: Double
+ var opacity: Double
+ var dashArray: [Double]?
+ var dashOffset: Double?
+ var lineCap: StrokeLineCap? // butt | round | square
+ var lineJoin: StrokeLineJoin? // miter | round | bevel
+}
+
+struct ShadowStyle: Codable, Equatable {
+ var color: String
+ var blur: Double
+ var offsetX: Double
+ var offsetY: Double
+}
+```
+
+### 2.13 Emphasis animation (clip-level "wiggle")
+
+```swift
+struct EmphasisAnimation: Codable, Equatable {
+ var type: EmphasisAnimationType
+ var speed: Double
+ var intensity: Double
+ var loop: Bool
+ var focusPoint: Point?
+ var zoomScale: Double?
+ var holdDuration: Double?
+ var startTime: Double?
+ var animationDuration: Double?
+}
+
+enum EmphasisAnimationType: String, Codable, CaseIterable {
+ case none, pulse, shake, bounce, float, spin, flash, heartbeat,
+ swing, wobble, jello,
+ rubberBand = "rubber-band",
+ tada, vibrate, flicker, glow, breathe, wave, tilt,
+ zoomPulse = "zoom-pulse",
+ focusZoom = "focus-zoom",
+ panLeft = "pan-left", panRight = "pan-right",
+ panUp = "pan-up", panDown = "pan-down",
+ kenBurns = "ken-burns"
+}
+```
+
+### 2.14 Media library
+
+```swift
+struct MediaLibrary: Codable, Equatable { var items: [MediaItem] }
+
+struct MediaItem: Codable, Identifiable, Equatable {
+ var id: String
+ var name: String
+ var type: MediaType // video | audio | image
+ var metadata: MediaMetadata
+ var thumbnailUrl: String? // project-relative path
+ var waveformData: [Float]? // pre-rendered waveform
+ var filmstripThumbnails: [FilmstripThumbnail]?
+ var isPlaceholder: Bool?
+ var originalUrl: String?
+ var sourceFile: SourceFile?
+ var localFileName: String? // file in project's media/ dir
+ var localAssetIdentifier: String? // PHAsset identifier (iOS only)
+}
+
+struct FilmstripThumbnail: Codable, Equatable { var timestamp: Double; var url: String }
+
+struct SourceFile: Codable, Equatable {
+ var name: String
+ var size: Int64
+ var lastModified: Int64
+ var folder: String?
+}
+
+enum MediaType: String, Codable { case video, audio, image }
+
+struct MediaMetadata: Codable, Equatable {
+ var duration: Double
+ var width: Int
+ var height: Int
+ var frameRate: Double
+ var codec: String
+ var sampleRate: Int
+ var channels: Int
+ var fileSize: Int64
+ var audioTrackCount: Int?
+}
+```
+
+### 2.15 Transitions
+
+```swift
+struct Transition: Codable, Identifiable, Equatable {
+ var id: String
+ var clipAId: String
+ var clipBId: String
+ var type: String // see TransitionCatalog.supportedTypes
+ var duration: Double
+ var params: [String: JSONValue]
+}
+```
+
+Transitions live on `Track.transitions` and reference two adjacent clips on the same track.
+
+### 2.16 Templates
+
+Template packages let users save a portion of a project (text + graphics + effects) as a reusable, parameterized asset.
+
+```swift
+struct TemplateSource: Codable {
+ var templateId: String
+ var applicationId: String
+ var ownerClipId: String
+ var ownerTrackId: String?
+ var controlValues: [String: JSONValue]?
+}
+
+enum TemplateTrackType: String, Codable { case text, graphics }
+
+struct AppliedTemplate: Codable, Identifiable {
+ var templateId: String
+ var applicationId: String
+ var name: String
+ var category: String?
+ var appliedAt: Int
+ var controlValues: [String: JSONValue]?
+ var id: String { applicationId }
+}
+
+enum TemplateCategory: String, Codable, CaseIterable {
+ case cinema, glitch, retro, social, branding, color, overlay,
+ textEffects = "text-effects", transitions, custom
+}
+
+enum TemplateTargetType: String, Codable, CaseIterable { case video, image }
+enum TemplateControlType: String, Codable, CaseIterable {
+ case number, color, text, toggle, select
+}
+
+struct TemplateControlOption: Codable { var label: String; var value: JSONValue }
+
+struct TemplateControlDefinition: Codable, Identifiable {
+ var id: String
+ var label: String
+ var type: TemplateControlType
+ var defaultValue: JSONValue
+ var min: Double?
+ var max: Double?
+ var step: Double?
+ var options: [TemplateControlOption]?
+}
+
+struct TemplatePayload: Codable {
+ var duration: Double
+ var textClips: [TextClip]
+ var graphicsClips: [GraphicsClip]
+ var effects: [Effect]
+}
+
+struct TemplatePackageSource: Codable {
+ var projectId: String?
+ var clipId: String?
+ var trackId: String?
+ var createdWithVersion: String?
+}
+
+struct TemplatePackage: Codable, Identifiable {
+ var id: String
+ var name: String
+ var description: String
+ var category: TemplateCategory
+ var createdAt: Int
+ var modifiedAt: Int
+ var tags: [String]
+ var supportedTargets: [TemplateTargetType] // default [.video]
+ var controls: [TemplateControlDefinition]
+ var defaultValues: [String: JSONValue]
+ var previewImageData: Data? // PNG/JPEG bytes
+ var previewImageMimeType: String?
+ var payload: TemplatePayload
+ var source: TemplatePackageSource?
+}
+
+struct ClipMetadata: Codable, Equatable {
+ var templateSource: TemplateSource?
+ var appliedTemplates: [AppliedTemplate]?
+ var templateManaged: Bool?
+ var templateTrackType: TemplateTrackType?
+ var userInfo: [String: JSONValue]?
+}
+```
+
+### 2.17 JSONValue (untyped JSON for params/metadata)
+
+```swift
+enum JSONValue: Codable, Sendable {
+ case string(String)
+ case number(Double)
+ case bool(Bool)
+ case object([String: JSONValue])
+ case array([JSONValue])
+ case null
+}
+```
+
+Used pervasively for `effect.params`, `keyframe.value`, `transition.params`, template control values, and metadata.
+
+---
+
+## 3. ProjectStore — persistence layer
+
+`actor ProjectStore` (Swift actor → serializes file I/O on a private queue).
+
+### 3.1 Directory layout
+
+Base URL: `<ApplicationSupport>/OpenReel/Projects/`. Falls back to `NSTemporaryDirectory()/OpenReel/Projects/` if Application Support is unavailable.
+
+Per project:
+
+```
+<base>/
+ <projectID>/ (one folder per project)
+ project.json (the canonical document; JSON, pretty-printed, sorted keys)
+ media/ (imported media files)
+ <safeFileName>.mp4
+ <safeFileName>.mp3
+ ...
+ thumbnails/ (PNG/JPEG thumbnails)
+ effects/
+ luts/ (.cube LUTs, see LUTAsset below)
+ cache/
+ effects/ (effect render cache)
+ ai/ (AI analysis cache)
+ template-library/ (shared across projects)
+ <templateID>.openreeltemplate (JSON file, OpenReelTemplatePackageFile)
+```
+
+### 3.2 Encoding settings
+
+```swift
+let encoder = JSONEncoder()
+encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+let decoder = JSONDecoder()
+```
+
+No custom date strategy — timestamps are stored as `Int` Unix milliseconds, not ISO strings.
+
+### 3.3 Operations
+
+| Method | Behavior |
+|--------|----------|
+| `loadProjects() throws -> [OpenReelProject]` | Lists every subdirectory of base, decodes `<id>/project.json`, returns sorted by `modifiedAt` descending. Skips non-directories and missing `project.json`. |
+| `loadProject(id:) throws -> OpenReelProject?` | Returns nil if directory or `project.json` missing. |
+| `save(project:) throws` | Creates project dirs, encodes envelope, writes `<id>/project.json` atomically (`.atomic`). |
+| `deleteProject(id:) throws` | Removes the entire `<id>/` directory. Throws `.projectNotFound` if absent. |
+| `projectStorageUsage(for: [String]) throws -> [String: Int64]` | Recursively sums file sizes per project. |
+| `loadTemplatePackages() throws` | Loads all `*.openreeltemplate` from `template-library/`, sorted by modifiedAt desc, name asc tiebreak. |
+| `loadTemplatePackage(id:)` / `saveTemplatePackage(_:)` / `deleteTemplatePackage(id:)` | CRUD for shared template library. |
+| `exportTemplatePackage(id:, to:) throws -> URL` | Writes a template file to a user-supplied destination (adds `.openreeltemplate` if missing). |
+| `importTemplatePackage(from:) throws -> TemplatePackage` | Decodes file and saves to template library. |
+| `persistMedia(projectID:, sourceURL:, preferredFileName:, thumbnailData:, thumbnailFileName:) throws -> (mediaFileName, thumbnailRelativePath?)` | Copies media into `<id>/media/`, optional thumbnail into `<id>/thumbnails/`. Uses unique-name strategy (`name`, `name-1`, `name-2`...). |
+| `persistThumbnail(projectID:, fileName:, data:) throws -> String` | Writes raw thumbnail bytes; returns relative path `thumbnails/<name>`. |
+| `persistEffectLUT(projectID:, sourceURL:, preferredFileName:) throws -> LUTAsset` | Copies a `.cube` LUT into `effects/luts/`, computes **SHA-256** checksum, returns `LUTAsset { relativePath, fileName, checksum, byteCount }`. |
+
+### 3.4 Error type
+
+```swift
+enum StoreError: LocalizedError {
+ case applicationSupportUnavailable
+ case projectNotFound
+ case templatePackageNotFound
+}
+```
+
+### 3.5 File-name sanitization
+
+```swift
+private func sanitizeFileName(_ name: String) -> String {
+ name.trimmingCharacters(in: .whitespacesAndNewlines)
+ .replacingOccurrences(of: "/", with: "-")
+ .replacingOccurrences(of: ":", with: "-")
+}
+```
+
+Empty result is replaced with a UUID. Collisions are resolved by appending `-1`, `-2`, etc. before the extension.
+
+### 3.6 Thumbnail generation
+
+`ProjectStore` does **not** generate thumbnails itself — it only persists bytes given to it. Thumbnail generation lives in `MediaImportService` during import and in the editor's preview compositor when individual frames are needed. The on-disk path is `thumbnails/<sanitized-name>.<ext>` and is referenced from `MediaItem.thumbnailUrl` as a project-relative path.
+
+### 3.7 Autosave cadence
+
+There is **no debounced autosave timer**. Instead, every state-mutating method on `AppState` funnels through:
+
+```swift
+private func replaceCurrentProject(with project: OpenReelProject, captureHistory: Bool) async {
+ if captureHistory, let currentProject {
+ history.capture(currentProject)
+ undoRedoToken += 1
+ }
+ replaceProject(project)
+ do {
+ try await projectStore.save(project: project)
+ lastSavedAt = .now
+ } catch {
+ importErrorMessage = error.localizedDescription
+ }
+}
+```
+
+So: every edit is immediately persisted, and `AppState.lastSavedAt` is updated. The UI surfaces this timestamp. Android should match this “save-on-every-edit” model with a coalescing layer if disk pressure is observed (e.g. debounce 250 ms via `Flow.debounce`), but the iOS app does not coalesce.
+
+---
+
+## 4. ActionHistory — undo / redo
+
+Source: `Core/Timeline/ActionHistory.swift`.
+
+```swift
+@MainActor
+final class ActionHistory {
+ private(set) var undoStack: [OpenReelProject] = []
+ private(set) var redoStack: [OpenReelProject] = []
+ private let limit: Int // default 50
+
+ var canUndo: Bool { !undoStack.isEmpty }
+ var canRedo: Bool { !redoStack.isEmpty }
+
+ func clear()
+ func capture(_ state: OpenReelProject)
+ func undo(current: OpenReelProject) -> OpenReelProject?
+ func redo(current: OpenReelProject) -> OpenReelProject?
+}
+```
+
+Strategy: **whole-project snapshot** — not diff-based. `capture()` pushes the *previous* state onto the undo stack, drops the redo stack, and trims to `limit` entries (default **50**). `undo()` pops the last undo entry and pushes the *current* state onto the redo stack; `redo()` is symmetric.
+
+Because every edit performs a deep copy of `OpenReelProject` (Swift value types), memory pressure is bounded by project size × 50. For Android, see §8 mapping notes — use a Kotlin `data class` tree (immutable, with `copy(...)`) and store full snapshots, or do binary serialization to bound memory.
+
+The `AppState.undoRedoToken: Int` is bumped after every capture/undo/redo so `@Observable` invalidates the UI for the otherwise-non-observed `ActionHistory`.
+
+---
+
+## 5. AppState — global view-model
+
+`@MainActor @Observable final class AppState`. Single source of truth for every editor screen. Holds an `ActionHistory`, a `ProjectStore`, and a `MediaImportService`. Smart-tool services receive local file URLs and run on device.
+
+### 5.1 Nested types
+
+```swift
+enum Screen { case home, projects, editor }
+enum EditorTab: String, CaseIterable {
+ case edit = "Edit", media = "Media", text = "Text", graphics = "Graphics",
+ templates = "Templates", effects = "Effects",
+ subtitles = "Subtitles", audio = "Audio"
+}
+enum AspectRatio: String, CaseIterable {
+ case landscape = "16:9", portrait = "9:16", square = "1:1",
+ vertical = "4:5", standard = "4:3"
+ var value: CGFloat { ... }
+}
+enum ProjectStyle: String, CaseIterable { case emerald, cobalt, amber, coral }
+enum TrimEdge { case leading, trailing }
+enum AudioFadeEdge { case fadeIn, fadeOut }
+```
+
+### 5.2 Observable state — by feature area
+
+(All declared `var` — `@Observable` macro auto-publishes. The Kotlin equivalent is `MutableStateFlow` per field or a single composite `MutableStateFlow<EditorUiState>`.)
+
+**Navigation / shell**
+- `activeScreen: Screen = .home`
+- `editorTab: EditorTab = .edit`
+- `selectedAspectRatio: AspectRatio = .landscape`
+
+**Project list / lifecycle**
+- `projects: [OpenReelProject] = []`
+- `projectStorageUsageByID: [String: Int64] = [:]`
+- `selectedProjectID: String?`
+- `isBootstrapping: Bool = false`
+- `hasBootstrapped: Bool = false`
+- `isShowingNewProjectSheet: Bool = false`
+- `newProjectConfiguration: NewProjectConfiguration = NewProjectConfiguration(name: "Project 1")`
+- `lastSavedAt: Date?`
+- `importErrorMessage: String?`
+
+**Selection (timeline)**
+- `selectedClipID: String?`
+- `selectedClipIDs: Set<String> = []`
+- `selectedTextClipID: String?` (resets `isEditingSubtitleTrack` to false on nil)
+- `selectedTextClipIDs: Set<String> = []`
+- `selectedGraphicsClipID: String?`
+- `selectedGraphicsClipIDs: Set<String> = []`
+- `selectedKeyframeID: String?`
+- `selectedTransitionID: String?`
+- `isEditingSubtitleTrack: Bool = false`
+
+**Media import**
+- `isMediaPickerPresented: Bool = false`
+- `isImportingMedia: Bool = false`
+- `mediaImportStatusText: String = "Importing media"`
+
+**Templates**
+- `templateLibrary: [OpenReelProject.TemplatePackage] = []`
+- `selectedTemplatePackageID: String?`
+
+**Timeline view**
+- `timelineZoom: Double = 48` (pixels per second)
+
+**Undo / clipboard**
+- `undoRedoToken: Int = 0`
+- `copiedEffectStack: [OpenReelProject.Effect] = []`
+
+**Local operations**
+- `localOperationStatusText: String?`
+- Feature-specific running/progress state exists only for active on-device work.
+
+**Non-observed dependencies** (`@ObservationIgnored`)
+- `projectStore: ProjectStore`
+- `mediaImportService: MediaImportService`
+- `history = ActionHistory()` (limit 50)
+- `minimumClipDuration: TimeInterval = 0.2`
+- `subtitleManagedMetadataKey = "subtitleManaged"`
+- `subtitleCueIDMetadataKey = "subtitleCueID"`
+- `subtitleSourceMetadataValue = "timeline-subtitle"`
+
+### 5.3 Computed views
+
+- `currentProject: OpenReelProject?` — returns the project with `selectedProjectID` (or first).
+- `currentProjectDuration: TimeInterval`
+- `totalProjectStorageUsage: Int64`
+- `canUndo: Bool`, `canRedo: Bool` (touches `undoRedoToken` to participate in observation)
+- `hasCopiedEffectStack: Bool`
+- `selectedTemplatePackage: TemplatePackage?`
+- `canSaveCurrentTemplatePackage: Bool`
+- `selectedClip: Clip?`, `selectedMediaItem: MediaItem?`
+- `selectedTextClip: TextClip?`, `selectedGraphicsClip: GraphicsClip?`
+- `selectedKeyframe: Keyframe?`, `selectedTransition: Transition?`
+- `selectedTrack: Track?`
+- `canDetachSelectedClipAudio: Bool`
+- `playbackReloadToken: String` (composite ID for forcing playback reload)
+- `hasMultiSelection: Bool`
+
+### 5.4 Public API — method signatures (purpose in line-comments)
+
+Methods take an optional `PlaybackController?` so they can resync playback after each mutation. All mutating methods end up calling `replaceCurrentProject(with:captureHistory:)`, which persists to disk and (optionally) pushes a snapshot to `ActionHistory`.
+
+#### Project lifecycle
+```swift
+func bootstrap() async // loads projects + templates
+func showHome()
+func showProjects()
+func openProject(_ project: OpenReelProject)
+func closeEditor()
+func presentNewProjectSheet()
+func dismissNewProjectSheet()
+func createProject() async // from newProjectConfiguration
+func quickCreateProject(preset: NewProjectConfiguration.Preset,
+ frameRate: Double, name: String) async
+func refreshProjectStorageUsage() async
+func projectStorageUsage(for project: OpenReelProject) -> Int64
+func deleteProject(_ project: OpenReelProject) async
+```
+
+#### Media library
+```swift
+func presentMediaPicker()
+func dismissMediaPicker()
+func importMedia(_ assets: [ImportedMediaAsset],
+ playbackController: PlaybackController) async
+func importMediaToLibrary(_ assets: [ImportedMediaAsset]) async -> [MediaItem]
+func usedProjectMediaIDs(in project: OpenReelProject? = nil) -> Set<String>
+func availableProjectMedia(in project: OpenReelProject? = nil) -> [MediaItem]
+func mediaItem(for mediaID: String, in project: OpenReelProject? = nil) -> MediaItem?
+func mediaURL(for mediaItem: MediaItem, in project: OpenReelProject? = nil) -> URL?
+func projectDirectoryURL(for project: OpenReelProject? = nil) -> URL?
+func thumbnailURL(for relativePath: String?, in project: OpenReelProject? = nil) -> URL?
+```
+
+#### Selection
+```swift
+func selectClip(_ clip: Clip)
+func selectTextClip(_ textClip: TextClip)
+func selectAllClipsOnTrack(_ trackID: String)
+func applyEffectToSelectedClips(_ effect: Effect,
+ playbackController: PlaybackController?) async
+func applyStyleToSelectedTextClips(_ style: TextStyle,
+ playbackController: PlaybackController?) async
+func clearMultiSelection()
+func selectSubtitleTrackForEditing(_ textClip: TextClip)
+func selectGraphicsClip(_ graphicsClip: GraphicsClip)
+func selectKeyframe(_ keyframeID: String)
+func selectTransition(_ transitionID: String)
+```
+
+#### Keyframes
+```swift
+func addSelectedKeyframe(property: String, value: JSONValue?, easing: String,
+ playbackController: PlaybackController?) async
+func updateSelectedKeyframe(time: Double?, value: JSONValue?, easing: String?,
+ playbackController: PlaybackController?) async
+func removeSelectedKeyframe(playbackController: PlaybackController? = nil) async
+```
+
+#### Transitions
+```swift
+func addTransition(clipID: String? = nil, type: String, duration: TimeInterval,
+ params: [String: JSONValue] = [:],
+ playbackController: PlaybackController? = nil) async
+func updateSelectedTransition(type: String? = nil, duration: TimeInterval? = nil,
+ params: [String: JSONValue]? = nil,
+ playbackController: PlaybackController? = nil) async
+func removeSelectedTransition(playbackController: PlaybackController? = nil) async
+```
+
+#### Clips (media)
+```swift
+func splitSelectedClip(at playheadTime: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func detachSelectedClipAudio(playbackController: PlaybackController? = nil) async
+func deleteSelectedClip(ripple: Bool = false,
+ playbackController: PlaybackController? = nil) async
+func trimClip(_ clipID: String, edge: TrimEdge, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func moveClip(_ clipID: String, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func addMediaItemToTimeline(_ mediaItem: MediaItem,
+ at startTime: TimeInterval? = nil,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedClipSpeed(_ speed: Double, playbackController: PlaybackController? = nil) async
+func updateSelectedImageClipDuration(_ duration: TimeInterval, playbackController: PlaybackController? = nil) async
+func updateSelectedClipTransform(...) async
+func updateSelectedClipCrop(...) async
+func resetSelectedClipCrop(playbackController: PlaybackController? = nil) async
+func resetSelectedClipTransform(playbackController: PlaybackController? = nil) async
+func updateClipBlendMode(clipID: String, blendMode: BlendMode,
+ playbackController: PlaybackController? = nil) async
+func updateClipBlendOpacity(clipID: String, opacity: Double,
+ playbackController: PlaybackController? = nil) async
+```
+
+#### Tracks
+```swift
+func addVideoTrack() async
+func addAudioTrack() async
+func addTextTrack() async
+func addGraphicsTrack() async
+func deleteTrack(_ trackID: String, playbackController: PlaybackController? = nil) async
+func moveTrack(_ trackID: String, direction: TrackMoveDirection,
+ playbackController: PlaybackController? = nil) async
+func updateTrackAudioMix(trackID: String, role: AudioTrackRole?, gain: Double?, pan: Double?,
+ playbackController: PlaybackController? = nil) async
+```
+
+#### Text clips
+```swift
+func addTextClip(from preset: TextPreset, at startTime: TimeInterval? = nil,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedTextClipText(_ text: String,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedTextClipStyle(...) async // font, color, alignment, etc.
+func updateSelectedTextClipTransform(...) async
+func updateSelectedTextClipDuration(_ duration: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedTextClipAnimation(_ animation: TextAnimation?,
+ playbackController: PlaybackController? = nil) async
+func moveTextClip(_ id: String, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func trimTextClip(_ id: String, edge: TrimEdge, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func deleteSelectedTextClip(playbackController: PlaybackController? = nil) async
+```
+
+#### Audio
+```swift
+func updateSelectedClipVolume(_ volume: Double, playbackController: PlaybackController? = nil) async
+func updateSelectedClipPan(_ pan: Double, playbackController: PlaybackController? = nil) async
+func updateSelectedClipFade(edge: AudioFadeEdge, duration: TimeInterval,
+ curve: AudioAutomationCurve = .linear,
+ bezierControlPoints: AudioBezierControlPoints? = nil,
+ playbackController: PlaybackController? = nil) async
+```
+
+#### Effects (clip-level)
+```swift
+func upsertSelectedClipEffect(type: String, params: [String: JSONValue],
+ playbackController: PlaybackController? = nil) async
+func upsertSelectedClipAudioEffect(type: String, params: [String: JSONValue],
+ playbackController: PlaybackController? = nil) async
+func appendSelectedClipEffect(type: String, params: [String: JSONValue],
+ playbackController: PlaybackController? = nil) async
+func updateSelectedClipEffect(id effectID: String, params: [String: JSONValue]? = nil,
+ enabled: Bool? = nil,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedClipAudioEffect(id effectID: String, ...) async
+func toggleSelectedClipEffect(id: String, isEnabled: Bool,
+ playbackController: PlaybackController? = nil) async
+func toggleSelectedClipAudioEffect(id: String, isEnabled: Bool, ...) async
+func removeSelectedClipEffect(id: String, playbackController: PlaybackController? = nil) async
+func removeSelectedClipAudioEffect(id: String, ...) async
+func removeSelectedClipEffect(type: String, ...) async // remove all of type
+func removeSelectedClipAudioEffect(type: String, ...) async
+func reorderSelectedClipEffect(id: String, to: Int, ...) async
+func resetSelectedClipEffects(types: Set<String>, ...) async
+func copySelectedClipEffectStack() -> [Effect]
+func copySelectedClipEffectsToClipboard()
+func pasteEffectStack(_ effects: [Effect], replaceExisting: Bool,
+ playbackController: PlaybackController? = nil) async
+func pasteCopiedEffectStack(replaceExisting: Bool = false,
+ playbackController: PlaybackController? = nil) async
+func applySelectedClipEffectStack(...) async
+func importSelectedClipLUT(sourceURL: URL, name: String,
+ playbackController: PlaybackController? = nil) async
+func mergeSelectedClipEffect(...) async // for stack-merge UI
+```
+
+#### Graphics
+```swift
+func addGraphicsClip(from preset: ShapePreset, at startTime: TimeInterval? = nil,
+ playbackController: PlaybackController? = nil) async
+func addStickerClip(from preset: StickerPreset, at startTime: TimeInterval? = nil,
+ playbackController: PlaybackController? = nil) async
+func addGraphicsImageClip(mediaItem: MediaItem, at startTime: TimeInterval? = nil,
+ duration: TimeInterval? = nil,
+ playbackController: PlaybackController? = nil) async
+func updateSelectedGraphicsClipTransform(...) async
+func moveGraphicsClip(_ id: String, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func trimGraphicsClip(_ id: String, edge: TrimEdge, by delta: TimeInterval,
+ playbackController: PlaybackController? = nil) async
+func deleteSelectedGraphicsClip(playbackController: PlaybackController? = nil) async
+func updateGraphicsClipFill(clipID: String, fillType: FillKind, color: String?,
+ playbackController: PlaybackController? = nil) async
+func updateGraphicsClipStroke(clipID: String, width: Double?, color: String?,
+ playbackController: PlaybackController? = nil) async
+func updateGraphicsClipBlendMode(clipID: String, blendMode: BlendMode,
+ playbackController: PlaybackController? = nil) async
+func updateGraphicsClipOpacity(clipID: String, opacity: Double,
+ playbackController: PlaybackController? = nil) async
+func updateGraphicsClipEmphasis(clipID: String, type: EmphasisAnimationType,
+ playbackController: PlaybackController? = nil) async
+```
+
+#### Subtitles
+```swift
+func importSubtitles(from url: URL, animationStyle: CaptionAnimationStyle,
+ position: SubtitlePosition,
+ playbackController: PlaybackController? = nil) async
+func subtitleTextClips(in project: OpenReelProject? = nil) -> [TextClip]
+func subtitleTrackStyle(in project: OpenReelProject? = nil) -> SubtitleStyle?
+func ensureSubtitleTextClips(playbackController: PlaybackController? = nil) async
+func clearSubtitles(playbackController: PlaybackController? = nil) async
+func updateSubtitleAnimationStyle(_ style: CaptionAnimationStyle, ...) async
+func updateSubtitlePosition(_ position: SubtitlePosition, ...) async
+func updateSubtitleTrackStyle(...) async
+func updateSubtitleCueText(id: String, text: String, ...) async
+```
+
+#### Templates
+```swift
+func refreshTemplateLibrary() async
+func saveCurrentProjectAsTemplatePackage(name: String, description: String,
+ category: TemplateCategory,
+ tags: [String]) async
+func importTemplatePackage(from sourceURL: URL) async -> TemplatePackage?
+func exportTemplatePackage(id: String) async -> URL?
+func deleteTemplatePackage(id: String) async
+func applyTemplatePackage(_ template: TemplatePackage, controlValues: [String: JSONValue],
+ playbackController: PlaybackController? = nil) async
+```
+
+#### On-device smart tools
+```swift
+func generateOnDeviceCaptions(playbackController: PlaybackController?) async
+func generateShorts(...) async
+```
+
+Segmentation, tracking, background effects, captions, and highlight analysis
+operate on project-local media. There is no generic remote-job method or
+result-manifest ingestion path.
+
+#### Undo / Redo / Export
+```swift
+func undo(playbackController: PlaybackController) async
+func redo(playbackController: PlaybackController) async
+func advanceAspectRatio()
+func updateExportPreferences(preset: ExportPreset? = nil,
+ resolution: ExportResolution? = nil,
+ frameRate: Double? = nil,
+ format: ExportFormat? = nil,
+ quality: Double? = nil) async
+func applyExportConfigurationToProject(_ preferences: ExportPreferences,
+ playbackController: PlaybackController? = nil) async
+func applyExportPresetToProject(_ preset: ExportPreset,
+ playbackController: PlaybackController? = nil) async
+```
+
+#### Style / Playback helpers
+```swift
+func style(for project: OpenReelProject) -> ProjectStyle
+func primaryVisualClip(in project: OpenReelProject? = nil) -> Clip?
+func selectedVisualClip(in project: OpenReelProject? = nil) -> Clip?
+func clips(for trackType: TrackType, in project: OpenReelProject? = nil) -> [Clip]
+func syncPlayback(with playbackController: PlaybackController)
+func timelinePlaybackTransitions(in project: OpenReelProject? = nil) -> [PlaybackController.TimelineTransition]
+func timelinePlaybackSources(in project: OpenReelProject? = nil) -> [PlaybackController.TimelineSource]
+func dismissError()
+func snapToGridTime(_ time: TimeInterval, in project: OpenReelProject) -> (time: TimeInterval, didSnap: Bool)
+```
+
+### 5.5 Mutation pipeline
+
+Every method ultimately:
+
+1. Reads `currentProject` (returns early if nil).
+2. Locates the affected item (clip / track / transition) via `clipLocation(...)`.
+3. Builds a mutated `OpenReelProject` value.
+4. Updates `modifiedAt = Int(Date().timeIntervalSince1970 * 1000)`.
+5. Calls `replaceCurrentProject(with:captureHistory:)` which:
+ - pushes prior project to `ActionHistory.undoStack`,
+ - writes the new `project.json` atomically via `ProjectStore.save`,
+ - sets `lastSavedAt = .now`,
+ - bumps `undoRedoToken`.
+6. Calls `playbackController?.applyTimelineEdit(...)` to live-rebuild the playback graph.
+
+---
+
+## 6. Transition system
+
+### 6.1 Catalog
+
+`TransitionCatalog.supportedTypes` (string identifiers):
+
+```
+crossfade, dipToBlack, dipToWhite, wipe, slide, zoom, push,
+blurDissolve, iris, spin, glitch, pixelate, lumaFade
+```
+
+`directions = ["left", "right", "up", "down"]`.
+
+`displayName(for:params:)` maps each type to a UI label (e.g. `wipe` + direction → `"Wipe Left"`). `crossfade` displays as `"Dissolve"`.
+
+### 6.2 Default params per type
+
+| Type | Default `params` |
+|----------------|---------------------------------------------------------------------------------------------------|
+| crossfade | `{ curve: "smoothstep" }` |
+| dipToBlack | `{ holdDuration: 0.1, curve: "smoothstep" }` |
+| dipToWhite | `{ holdDuration: 0.1, curve: "smoothstep" }` |
+| wipe | `{ direction: "left", softness: 0, curve: "smoothstep" }` |
+| slide | `{ direction: "left", pushOut: false, curve: "easeOutCubic" }` |
+| zoom | `{ scale: 2, center: { x: 0.5, y: 0.5 }, curve: "easeInOutCubic" }` |
+| push | `{ direction: "left", curve: "easeOutCubic" }` |
+| blurDissolve | `{ maxRadius: 20, curve: "smoothstep" }` |
+| iris | `{ center: { x: 0.5, y: 0.5 }, softness: 0.02, curve: "easeInOutCubic" }` |
+| spin | `{ rotations: 1, curve: "easeInOutCubic" }` |
+| glitch | `{ intensity: 0.5, slices: 8, curve: "linear" }` |
+| pixelate | `{ maxBlockSize: 40, curve: "easeInOutCubic" }` |
+| lumaFade | `{ invert: false, softness: 0.3, curve: "smoothstep" }` |
+
+### 6.3 Param sanitization (`sanitizedParams`)
+
+- Unknown direction → `"left"`.
+- `softness` clamped to `[0, 1]`.
+- `holdDuration` clamped to `[0, 1]`.
+- `scale` clamped to `[1.01, 6]`.
+- `maxRadius` clamped to `[1, 100]`.
+- `rotations` clamped to `[0.25, 4]`.
+- `intensity` clamped to `[0.1, 1]`.
+- `slices` clamped to `[2, 20]`.
+- `maxBlockSize` clamped to `[4, 100]`.
+- `curve` is rewritten via `EasingFunctions.sanitizedEasing(_:)`.
+
+### 6.4 Validation (`TimelineTransitionEngine`)
+
+```swift
+static let minimumDuration: TimeInterval = 0.1
+static let maximumDuration: TimeInterval = 5
+static let adjacencyTolerance: TimeInterval = 0.001
+```
+
+`validate(clipA:clipB:duration:)`:
+
+1. Both clips must share `trackId`.
+2. They must be adjacent: `abs((clipA.startTime + clipA.duration) - clipB.startTime) <= 0.001`.
+3. `duration` is clamped to `[minimumDuration, min(maximumDuration, max(min(clipA.duration, clipB.duration) * 0.5, minimumDuration))]`.
+
+`transition(clipA:clipB:type:duration:params:id:)` constructs an `OpenReelProject.Transition` with sanitized type/params, or returns nil if validation fails.
+
+`sanitizedTransitions(for: track)` rebuilds the entire transition list filtering invalid pairs and de-duping by `clipA|clipB`. Sorted by `clipA.startTime`, then by `transition.id`.
+
+### 6.5 Runtime resolution
+
+`TimelineTransitionResolver.activeVisualTransition(in: project, at: time)` walks all visible video/image tracks (respecting `solo` and `hidden`), finds the active transition window at `time`, and returns:
+
+```swift
+struct ActiveTimelineTransition: Equatable {
+ var transition: OpenReelProject.Transition
+ var outgoingClip: OpenReelProject.Clip
+ var incomingClip: OpenReelProject.Clip
+ var startTime: TimeInterval // boundary − duration/2
+ var endTime: TimeInterval // boundary + duration/2
+ var progress: Double // (time − startTime) / duration, clamped [0,1]
+ var boundaryTime: TimeInterval // outgoingClip.startTime + outgoingClip.duration
+}
+```
+
+The transition window is **centered on the clip boundary** — half the duration sits on each clip. Ordering is `startTime` ascending, then `transition.id` ascending as a stable tiebreak.
+
+---
+
+## 7. JSON examples
+
+### 7.1 Project document (envelope)
+
+```json
+{
+ "version": "1.1.0",
+ "project": {
+ "id": "B5C7C5A1-1F8B-4B6A-A4F0-2A4D6C1F0E22",
+ "name": "Project 1",
+ "createdAt": 1716100000000,
+ "modifiedAt": 1716100012345,
+ "settings": {
+ "width": 1920,
+ "height": 1080,
+ "frameRate": 30,
+ "sampleRate": 48000,
+ "channels": 2
+ },
+ "exportPreferences": {
+ "preset": "youtube",
+ "resolution": { "width": 1920, "height": 1080 },
+ "frameRate": 30,
+ "format": { "container": "mp4", "codec": "hevc" },
+ "quality": 0.85
+ },
+ "mediaLibrary": {
+ "items": [
+ {
+ "id": "f4f0aabc-...",
+ "name": "IMG_5532.mov",
+ "type": "video",
+ "metadata": {
+ "duration": 12.3,
+ "width": 1920,
+ "height": 1080,
+ "frameRate": 29.97,
+ "codec": "hevc",
+ "sampleRate": 48000,
+ "channels": 2,
+ "fileSize": 11_234_567,
+ "audioTrackCount": 1
+ },
+ "thumbnailUrl": "thumbnails/f4f0aabc.jpg",
+ "localFileName": "IMG_5532.mov"
+ }
+ ]
+ },
+ "timeline": {
+ "tracks": [
+ {
+ "id": "track-video-1",
+ "type": "video",
+ "name": "Video 1",
+ "clips": [/* see 7.2 */],
+ "transitions": [
+ {
+ "id": "t-1",
+ "clipAId": "clip-1",
+ "clipBId": "clip-2",
+ "type": "crossfade",
+ "duration": 0.5,
+ "params": { "curve": "smoothstep" }
+ }
+ ],
+ "locked": false,
+ "hidden": false,
+ "muted": false,
+ "solo": false,
+ "audioMix": { "role": "general", "gain": 1, "pan": 0 }
+ }
+ ],
+ "subtitles": [],
+ "duration": 0,
+ "markers": [],
+ "beatMarkers": [],
+ "beatAnalyses": []
+ },
+ "textClips": [/* see 7.3 */],
+ "graphicsClips": []
+ }
+}
+```
+
+### 7.2 Sample clip
+
+```json
+{
+ "id": "clip-1",
+ "mediaId": "f4f0aabc-...",
+ "trackId": "track-video-1",
+ "startTime": 0,
+ "duration": 5.0,
+ "inPoint": 0,
+ "outPoint": 5.0,
+ "effects": [
+ { "id": "fx-1", "type": "brightness", "params": { "amount": { "$type": "number", "value": 0.2 } }, "enabled": true }
+ ],
+ "audioEffects": [],
+ "transform": {
+ "position": { "x": 0.5, "y": 0.5 },
+ "scale": { "x": 1.0, "y": 1.0 },
+ "rotation": 0,
+ "anchor": { "x": 0.5, "y": 0.5 },
+ "opacity": 1.0,
+ "fitMode": "cover"
+ },
+ "volume": 1,
+ "keyframes": [],
+ "audioConfiguration": {
+ "pan": 0,
+ "volumeAutomation": []
+ }
+}
+```
+
+(Note: `Effect.params` and `Keyframe.value` are `JSONValue`-encoded — `JSONValue` encodes as native JSON, not tagged, so a `number(0.2)` value serialises simply as `0.2`. The `$type` wrapper above is illustrative only.)
+
+### 7.3 Sample text clip
+
+```json
+{
+ "id": "text-1",
+ "trackId": "track-text-1",
+ "startTime": 1.0,
+ "duration": 3.0,
+ "text": "Hello, world",
+ "style": {
+ "fontFamily": "SF Pro Display",
+ "fontSize": 96,
+ "fontWeight": 700,
+ "fontStyle": "normal",
+ "color": "#FFFFFF",
+ "backgroundColor": null,
+ "strokeColor": "#000000",
+ "strokeWidth": 2,
+ "shadowColor": "#000000",
+ "shadowBlur": 6,
+ "shadowOffsetX": 0,
+ "shadowOffsetY": 4,
+ "textAlign": "center",
+ "verticalAlign": "middle",
+ "lineHeight": 1.1,
+ "letterSpacing": 0
+ },
+ "transform": {
+ "position": { "x": 0.5, "y": 0.8 },
+ "scale": { "x": 1, "y": 1 },
+ "rotation": 0,
+ "anchor": { "x": 0.5, "y": 0.5 },
+ "opacity": 1
+ },
+ "animation": {
+ "preset": "slide-up",
+ "params": {},
+ "inDuration": 0.3,
+ "outDuration": 0.3,
+ "stagger": 0.04,
+ "unit": "word"
+ },
+ "keyframes": []
+}
+```
+
+`fontWeight` may also be `"bold"`, `"regular"`, etc. (the `TextFontWeight` enum is single-value Codable, accepts both `Int` and `String`).
+
+---
+
+## 8. Android mapping suggestions
+
+### 8.1 Project document
+
+- Mirror the entire schema as `@Serializable` Kotlin `data class`es (kotlinx.serialization). Use the same JSON wire format and `version = "1.1.0"`.
+- `JSONValue` → `kotlinx.serialization.json.JsonElement` (`JsonPrimitive`, `JsonObject`, `JsonArray`, `JsonNull`) — a 1:1 fit.
+- Make all `?: emptyList()` / nullable fields explicit with `@Serializable` defaults so old documents continue to decode (matches the iOS `decodeIfPresent` pattern). Example:
+
+```kotlin
+@Serializable
+data class OpenReelProjectFile(
+ val version: String = "1.1.0",
+ val project: OpenReelProject,
+)
+
+@Serializable
+data class Track(
+ val id: String,
+ val type: TrackType,
+ val name: String,
+ val clips: List<Clip> = emptyList(),
+ val transitions: List<Transition> = emptyList(),
+ val locked: Boolean = false,
+ val hidden: Boolean = false,
+ val muted: Boolean = false,
+ val solo: Boolean = false,
+ val audioMix: AudioTrackMix = AudioTrackMix(),
+)
+```
+
+- Use the same `Json { prettyPrint = true; encodeDefaults = true; ignoreUnknownKeys = true }` configuration.
+
+### 8.2 Persistence
+
+- Replace `Application Support` with `Context.filesDir/OpenReel/Projects/<projectID>/`. Same `project.json` + `media/` + `thumbnails/` + `effects/luts/` + local render-cache layout.
+- File writes: write to a temp file, then `Files.move(..., ATOMIC_MOVE)` — that mirrors iOS `.atomic`.
+- Filename safety: replicate `sanitizeFileName` (trim, replace `/` and `:` with `-`, fallback to `UUID.randomUUID()`).
+- LUT integrity: SHA-256 via `MessageDigest.getInstance("SHA-256")` → hex string, matches `LUTAsset.checksum`.
+- **Do not use Room for project documents.** The model is a single JSON blob that the editor mutates in-memory; a relational schema would force normalization that the editor doesn't want. Use DataStore (Proto or Preferences) only for app-wide settings such as theme and last-opened project ID.
+- If you want a list view backed by a DB, mirror only the metadata (`id`, `name`, `createdAt`, `modifiedAt`, storage bytes, thumbnail path) in Room and keep `project.json` as the source of truth on disk.
+
+### 8.3 State management
+
+- `AppState` → a single `EditorViewModel` (or top-level `OpenReelStateHolder`) holding `MutableStateFlow<EditorUiState>`.
+- Field-level reactivity (à la `@Observable`) is best achieved by splitting state into multiple `StateFlow`s grouped by feature area (selection, project, media import, local operations, UI), and composing via `combine { ... }` for screens that need cross-cuts.
+- Methods become `suspend fun`s. Replace the `playbackController:` trailing argument with a single injected `PlaybackController` (ExoPlayer wrapper) so callers don't pass it.
+- Funnel every mutator through one helper:
+
+```kotlin
+private suspend fun replaceCurrentProject(
+ new: OpenReelProject,
+ captureHistory: Boolean,
+) {
+ if (captureHistory) currentProject.value?.let { actionHistory.capture(it) }
+ _currentProject.value = new
+ runCatching { projectStore.save(new) }
+ .onSuccess { _lastSavedAt.value = Clock.System.now() }
+ .onFailure { _importError.value = it.message }
+ undoRedoToken.value += 1
+}
+```
+
+### 8.4 Undo/redo
+
+- `ActionHistory` is trivially portable — an `ArrayDeque<OpenReelProject>` with `limit = 50` on each stack. Because Kotlin `data class` has structural copies, snapshots are cheap and identity-correct.
+
+### 8.5 Parcelize / Serialization
+
+- All data classes that may cross a process boundary (e.g. shared via `SavedStateHandle` with the system process) should be `@Parcelize` *in addition to* `@Serializable`. In practice only top-level identifiers (`projectId: String`, `clipId: String`) need to traverse `Bundle`s; the full project tree should live in a single in-memory state holder.
+
+### 8.6 Mapping table
+
+| iOS | Kotlin / Android |
+|----------------------------------|-------------------------------------------------------------|
+| `@Observable` / `@MainActor` | `ViewModel` + `StateFlow`/`MutableStateFlow` on `Main` |
+| `Codable` | `kotlinx.serialization @Serializable` |
+| `JSONValue` | `JsonElement` |
+| `actor ProjectStore` | `class ProjectStore` running on `Dispatchers.IO` |
+| `Application Support` URL | `context.filesDir` |
+| `JSONEncoder(.prettyPrinted, .sortedKeys)` | `Json { prettyPrint = true; useArrayPolymorphism = false }` plus a custom sorted-key serializer if exact byte-equality across platforms is required |
+| `try data.write(to: url, .atomic)` | write to `.tmp` then `Files.move(..., StandardCopyOption.ATOMIC_MOVE)` |
+| `SHA256.hash(data:)` | `MessageDigest.getInstance("SHA-256")` |
+| `UUID().uuidString` | `java.util.UUID.randomUUID().toString()` |
+| `Date().timeIntervalSince1970 * 1000` (Int ms) | `System.currentTimeMillis()` (Long) |
+| Swift value-type `copy on write` | Kotlin `data class .copy(...)` |
+| `ActionHistory` (in-memory stack)| `class ActionHistory` with `ArrayDeque`, limit 50 |
+| `ImportedMediaAsset` (sandbox URL + metadata) | Android `Uri` + `MediaMetadataRetriever` results |
+| `PHAsset.localIdentifier` | `MediaStore` `content://media/external/.../id` URI string |
+
+### 8.7 Things to *not* port
+
+- iOS-only `PHAsset.localAssetIdentifier` should still round-trip in `MediaItem.localAssetIdentifier`; Android can leave it null and use its local `originalUrl`. Keep the field for schema compatibility.
+- `symbolName: String?` on `GraphicAsset` references SF Symbols. Android needs a parallel `iconName: String?` mapped to Material Symbols, but **keep `symbolName` in the schema** so projects are round-trippable.
+- `proResProfile` is irrelevant on Android (no ProRes encoder). Decode it but ignore — never set it on save unless the project came from iOS.
+
+---
+
+## Appendix A — JSON field naming conventions
+
+- Numeric times are seconds (`Double`) **except** `createdAt`, `modifiedAt`, `appliedAt`, `analyzedAt`, `SourceFile.lastModified` which are **milliseconds since 1970** (`Int` / `Int64`).
+- Hex colors are `"#RRGGBB"` or `"#RRGGBBAA"` strings; some defaults (e.g. subtitle background) use `rgba(...)` CSS notation. Both must round-trip.
+- Normalized coordinates (anchor, position, gradient `offset`, `softness`, etc.) live in `[0, 1]` unless otherwise documented.
+- Enum raw values are `camelCase` for simple words, `"kebab-case"` for compound words (e.g. `"hard-light"`, `"word-highlight"`, `"rubber-band"`, `"focus-zoom"`). Match these strings exactly in the Kotlin enums via `@SerialName`.
diff --git a/docs/android-port/03-editor-shell.md b/docs/android-port/03-editor-shell.md
new file mode 100644
index 00000000..258b4b16
--- /dev/null
+++ b/docs/android-port/03-editor-shell.md
@@ -0,0 +1,746 @@
+# 03 — Editor Shell
+
+This document describes the main editing screen of "Openreel Video" so an Android team can rebuild it 1:1 in Kotlin / Jetpack Compose.
+
+The editor is implemented in a single SwiftUI file: `Openreel Video/Openreel Video/EditorView.swift` (~5,488 lines). It is entered when `AppState.activeScreen == .editor` and a project is loaded. The app targets iPhone only (single-orientation portrait — see "Orientation").
+
+Theme tokens used throughout (`OpenReelTheme`, defined in `Openreel Video/Openreel Video/Theme.swift`):
+
+| Token | Light | Dark |
+|---|---|---|
+| `background` | `#FBFCF8` | `#0D0D0D` |
+| `surface` | `#F0F4EE` | `#1A1A1A` |
+| `surfaceElevated` | `#FFFFFF` | `#262626` |
+| `accent` | `#047857` | `#047857` |
+| `accentSecondary` | `#036B3A` | `#036B3A` |
+| `textPrimary` | `#101814` | `#FFFFFF` |
+| `textSecondary` | `#5F6F67` | `#A3A3A3` |
+| `destructive` | `#DC2626` | `#EF4444` |
+
+System font is SF Rounded for UI text, SF Mono for time/numeric values.
+
+---
+
+## 1. Overall layout
+
+The editor is a `VStack(spacing: 0)` that fills the screen vertically. Top-down stack with no gaps (per-section padding only):
+
+```
+VStack(spacing: 0) {
+ topBar (.padding(.top, 4).padding(.bottom, 6))
+ previewStage (maxHeight: 240, .padding(.horizontal, 16))
+ timecodeBar (.padding(.top, 6).padding(.bottom, 4), .padding(.horizontal, 20))
+ transportBar (.padding(.bottom, 6), .padding(.horizontal, 20), .padding(.vertical, 4))
+ timeline (fills remaining vertical space — maxHeight: .infinity, .padding(.horizontal, 12))
+ lowerPanel (height = 56 tabBar + optional 56 contextToolBar)
+}
+.background(OpenReelTheme.background.ignoresSafeArea())
+```
+
+Vertical totals (typical iPhone, portrait):
+
+| Section | Approximate height (pt) |
+|---|---|
+| Top bar | ~70 (44 button + 12+12 padding) |
+| Preview stage | up to 240 (clamped by aspect ratio) |
+| Timecode bar | ~24 |
+| Transport bar | ~52 |
+| Timeline | flex (everything else) |
+| Lower panel — context tool bar | 56 (only when selection panel is active) |
+| Lower panel — tab bar | 56 (always) |
+
+Safe-area: only the root container honours safe area; sheets use `ignoresSafeArea()` for full-screen presentation (`MediaPicker`, the importing-overlay). The top bar sits inside the safe area; the bottom tab bar is part of the layout (not pinned to the bottom safe inset by itself — the system safe inset is provided by the parent).
+
+The top bar, preview, timecode bar, and transport bar are encapsulated in panels with rounded backgrounds; padding is applied as `.padding(.horizontal, 16)` on the outer container while inner elements have their own padding.
+
+### Orientation
+
+The app currently targets iPhone-only and is locked to portrait orientation by Info.plist (the recent commit explicitly switched the target device family to iPhone only). The code has no orientation observers; layout assumes a tall narrow viewport with `maxHeight: 240` for preview and a tall timeline below.
+
+### Empty state
+
+When `appState.currentProject == nil`:
+
+```
+VStack(spacing: 18) {
+ Image("film.stack") size 32, semibold, accent
+ Text("Create a project to start editing") 20pt bold rounded, textPrimary
+ Button("New Project") 14pt semibold rounded, accent text, plain
+}
+.frame(maxWidth: .infinity, maxHeight: .infinity)
+```
+
+---
+
+## 2. Header bar (Top bar)
+
+Implemented in `topBar(project:)` (line 567). It is a `HStack(spacing: 12)` inside a rounded surface card:
+
+- Outer container:
+ - `.padding(.horizontal, 16)` (within row), `.padding(.vertical, 12)`
+ - `.background(OpenReelTheme.surface.opacity(0.96))` with `RoundedRectangle(cornerRadius: 20)`
+ - 1pt overlay border `Color.white.opacity(0.05)`
+ - Outer `.padding(.horizontal, 16)` to inset the card from screen edges.
+
+Children, left to right:
+
+1. **Back button**
+ - 42x42, `RoundedRectangle(cornerRadius: 14)`, `OpenReelTheme.surfaceElevated`
+ - SF Symbol `chevron.left`, size 16, weight `.bold`, color `textPrimary`
+ - Action: `playbackController.pause()`, then `appState.closeEditor()`
+
+2. **Project title block** (`VStack(alignment: .leading, spacing: 4)`, `frame(maxWidth: .infinity, alignment: .leading)`):
+ - Title: `project.name`, 18pt bold rounded, `textPrimary`, single line
+ - Subtitle: `"{width}x{height} · {fps}fps · Saved {time}"`, 11pt medium rounded, `textSecondary`, single line. "Saved …" suffix appears only when `lastSavedAt != nil`.
+
+3. **Right cluster** (`HStack(spacing: 8)`):
+ - **Undo button** (`historyButton(symbol: "arrow.uturn.backward", isEnabled: canUndo)`):
+ - 38x38, RoundedRectangle(14), `surfaceElevated`, icon 15pt semibold. Disabled state dims foreground to `textSecondary.opacity(0.35)`.
+ - **Redo button** (`arrow.uturn.forward`, same style)
+ - **Export button**: 44x44, RoundedRectangle(15), `accent` background, icon `square.and.arrow.up.fill` (16pt bold white). While exporting, replaces icon with `ProgressView(value: exportStatus.fraction)` `.progressViewStyle(.circular)`. Tapping presents the export sheet.
+
+There is no "Settings" cog inside the editor; project-level settings are exposed via the export sheet & the tab panels.
+
+---
+
+## 3. Preview canvas
+
+`previewStage(for:)` (line 639). A `ZStack` containing a black rounded rectangle (`cornerRadius: 12`) clipped to `appState.selectedAspectRatio.value`:
+
+- `aspectRatio(.fit)` — the canvas reserves the aspect ratio of the selected ratio (16:9 / 9:16 / 1:1 / 4:5 / 4:3) and never exceeds height 240.
+- Width: `.frame(maxWidth: .infinity)`, plus `.padding(.horizontal, 16)`.
+- Background: pure black, with a 1pt 8%-white stroke border.
+- `clipShape(RoundedRectangle(cornerRadius: 12))`
+
+### Layer composition (front-to-back is reverse of code order)
+
+Inside a `GeometryReader { previewProxy in … }`:
+
+1. **Video layer** — `MetalVideoView` if a player is loaded, otherwise either:
+ - `placeholderPreview(project:)` — a `ZStack` with the project's gradient + `video.badge.plus` icon and "Import a video from Media" / "Preview activates after first import." (only shown when the timeline has no visual content at all).
+2. **Image overlays** — for every image clip active at `playbackController.currentTime`. Uses `EffectImageView` (still-image renderer that applies the clip's effect stack). Crop is implemented by oversizing the frame and offsetting, fit mode controlled by `previewFitScale`:
+ - `.contain` → 1.0
+ - `.cover` → 1.12
+ - `.stretch` → x=1.12, y=1
+ - `.none` → 0.82
+3. **Graphics overlays** — shapes, emojis, stickers, raster images. Shape rendering switches on `shapeType`:
+ - `circle` / `ellipse` → `Ellipse` filled + optional stroke
+ - `triangle` → custom `TimelineTriangle` shape
+ - `star` → `star.fill` SF symbol
+ - `arrow` → `arrowshape.right.fill`
+ - `line` → `Capsule` of `max(strokeWidth, 3)` height
+ - `polygon` → custom `TimelinePolygon(points: 3..n)`
+ - default → `RoundedRectangle(cornerRadius: style.cornerRadius ?? 8)`
+ - Emoji/sticker → Text rendered at `min(width, height) * 0.82` font size
+ - Image → `UIImage(contentsOfFile:)` resizable scaledToFit
+4. **Text overlays** — applies font (`style.fontFamily`, size scaled by preview-to-project ratio), weight, multiline alignment, line height, background pill, shadow, and animation render state (see Section 5 of `EditorView.swift` for the 19 text-animation presets).
+
+### Selection rendering
+
+Selected clip/image/text/graphics gets a 2pt accent `RoundedRectangle` overlay with corner radius 12. For text the overlay is inset by `-8 * textMetricScale` (a small padding outside the text bounds). Only one item can have selection visible at a time; `stageOverlayHitTesting` disables hit testing for other layers when something is selected, and `stageOverlayZIndex` raises the selected one to z=2 (others z=0).
+
+### Gestures
+
+On the active layer (video clip, image overlay, graphics, text), three gestures are attached:
+
+- `previewDragGesture(for:in:)` — `DragGesture(minimumDistance: 2)` `.onEnded` — translates `transform.position` by `value.translation / previewSize`, clamped to `[-0.5, 1.5]`.
+- `previewScaleGesture(for:)` — `MagnifyGesture()` `.onEnded` — multiplies scale by `value.magnification`. Limits per layer type:
+ - Video / image clip: `[0.25, 4]`
+ - Text: `[0.25, 4]`
+ - Graphics: `[0.02, 2]`
+- `previewRotationGesture(for:)` — `RotationGesture()` `.onEnded` — adds `angle.degrees` to current rotation.
+
+Behaviour notes:
+- Drag/scale/rotate commit only on `.onEnded` (single update at gesture end, not continuous). Gestures use `.gesture` (drag) plus `.simultaneousGesture` (scale & rotation) so they compose.
+- **Double-tap on the video layer** resets the selected clip's transform (position / scale / rotation back to identity).
+- **Double-tap on a text overlay** (highPriorityGesture, count: 2) opens the text editor sheet via `presentTextClipEditor`.
+- Single tap on an image / text / graphics overlay → selects that clip and sets editor tab back to `.edit`.
+
+### MetalVideoView details (`Features/Preview/MetalVideoView.swift`)
+
+`UIViewRepresentable` wrapping a `MTKView`. Highlights for the Android team:
+
+- Uses `MTLCreateSystemDefaultDevice()` + `CIContext(mtlDevice:)`. Pixel format `bgra8Unorm`, clear color black.
+- Pulls frames from `AVPlayer` via `AVPlayerItemVideoOutput` (kCVPixelFormatType_32BGRA, metal-compatible).
+- Frame timing: when paused, uses `currentPlayer.currentTime()`; when playing, uses `videoOutput.itemTime(forHostTime: CACurrentMediaTime())`.
+- Effects are applied through `VideoEffectRenderer` (per-frame CIImage pipeline with `effectContext` for AI-driven effects).
+- Output is aspect-fit centered into the drawable using `aspectFitImage(_:in:)` — calculates `min(boundsWidth/sourceWidth, boundsHeight/sourceHeight)` scale and centers within a black background.
+- Updates color scopes every 8 frames via `ColorScopesEngine.snapshot(cgImage:)`, posted back to the SwiftUI state via the `onScopesUpdate` callback.
+- AI frame context is debounced/keyed by `(clipID|mediaID|frameIndex|descriptorSignature)` so it is recomputed only when descriptors or frame change.
+
+`EffectImageView` (`Features/Preview/EffectImageView.swift`) is the still-image equivalent: renders once per `renderKey` change (path + project dir + effect signatures) using `StillImageEffectRenderer.render(...)` and reports color scopes once.
+
+Android mapping: a `SurfaceView` or `TextureView` with an OpenGL ES/Vulkan / `RenderEffect` pipeline. ExoPlayer with a custom `GLSurfaceView` renderer, and a parallel `Bitmap` pipeline for still images.
+
+---
+
+## 4. Playback controls
+
+### Timecode bar (`timecodeBar(for:)`, line 1686)
+
+`HStack`, `.padding(.horizontal, 20)`:
+
+- Left: current time formatted via `playbackController.currentTime.openReelClock(frameRate:)`, 13pt bold monospaced, `textPrimary`. Format is `HH:MM:SS:FF` (drop-frame aware via `openReelClock`).
+- Right: aspect-ratio `Menu` — label is `HStack(spacing: 4)` of the ratio (`16:9`, `9:16`, `1:1`, `4:5`, `4:3`) at 12pt semibold rounded + `chevron.up.chevron.down` (9pt bold), all `textSecondary`. Menu items show ratio + system symbol (`rectangle.ratio.16.to.9` / `rectangle.portrait` / `square` / `rectangle.portrait.and.arrow.right` / `rectangle`).
+
+### Transport bar (`transportBar(for:)`, line 1722)
+
+`HStack(spacing: 0)`, `.padding(.horizontal, 20)`, `.padding(.vertical, 4)`, evenly spaced with `Spacer()` between buttons:
+
+1. **Prev-frame**: 36x36 circle, `surfaceElevated`, icon `backward.frame.fill` (14pt semibold). Steps `playbackController.step(frames: -1)`.
+2. **Play / Pause**: 44x44 circle, `accent` background, icon `play.fill` / `pause.fill` (16pt bold white). Disabled when no timeline content.
+3. **Next-frame**: 36x36 `forward.frame.fill`, mirror of #1.
+4. **Volume toggle**: 36x36 (no background), icon switches based on `playbackController.volume`:
+ - `0` → `speaker.slash.fill`
+ - `<0.4` → `speaker.wave.1.fill`
+ - else → `speaker.wave.2.fill`
+ Single tap toggles mute/full. **Long press (0.4s)** opens the volume sheet.
+5. **Volume percent text** — 36x36, "`{0..200}%`" at 11pt semibold rounded `textSecondary`. Tap opens the volume sheet.
+
+All transport buttons except play are disabled when `hasTimelineContent == false`. Tapping any of them ensures `appState.syncPlayback(with:)` is called first if the player is nil (lazy-init pattern).
+
+There is no separate "fps display" beyond the project subtitle in the header. There is no zoom-control widget for the preview; preview zoom is implicit (gesture only).
+
+### Volume sheet (`volumeSheet`, line 4233) — half-sheet detent `.fraction(0.5)`
+
+`VStack(spacing: 20)`, `.padding(20)`:
+- Header row: "Volume" (17pt bold rounded) on the left, "`{n}%`" on the right (15pt semibold monospaced accent).
+- Slider row: `speaker.fill` (12pt) — `Slider` tinted accent, range `0...2` — `speaker.wave.3.fill` (12pt). Both icons are `textSecondary`.
+- Preset row of 4 buttons: "Mute", "50%", "100%", "200%". Each `volumePresetButton` is full-width-fluid, 10pt vertical padding, `surfaceElevated` background, 10-radius. The active preset uses `accent.opacity(0.12)` background and accent text color.
+
+---
+
+## 5. Timeline
+
+Implemented in `timeline(for:)` (line 1797) and the four lane composers below it. Wrapper background: `OpenReelTheme.surface.opacity(0.5)`, with a 1pt 4%-white horizontal divider on top.
+
+### Geometry
+
+- `pixelsPerSecond = appState.timelineZoom` (range clamped to `[20, 300]`, default 48)
+- Track badge column: width 48, gap 10 to the lanes
+- Lane widths: `contentWidth = max(duration * zoom + 120, trackAreaWidth)`
+- Lane heights: 56 for video/image/text/graphics; 48 for audio (`timelineLaneHeight(for:)`, line 4440)
+- Ruler height: 34
+- Row spacing between lanes: 8
+- Outer horizontal padding: 12; vertical padding 10 top, 8 bottom
+
+The full timeline is a vertical `ScrollView(.vertical)` whose body is an `HStack(spacing: 10)` containing:
+1. A left column of fixed 48-wide **track badges** (a vertical `VStack(spacing: 8)`):
+ - First item is the **Add-track menu** (`Image("plus")` 14pt bold accent, 48x34, RoundedRectangle(12), `surfaceElevated`). Menu shows: Video, Audio, Text, Graphics — each adds a track via `appState.addXxxTrack()`.
+ - Then one badge per track: `Image(systemName: trackSymbol(for: track.type))` (17pt semibold accent), 48 x `laneHeight`, RoundedRectangle(16) `surfaceElevated`.
+ - Track symbols: `film.stack` (video), `waveform` (audio), `photo.stack` (image), `textformat` (text), `sparkles` (graphics).
+ - Tap on an **audio** badge opens the Track Mix sheet (`activeEditingSheet = .trackMix`).
+ - Long-press / context menu: Move Up, Move Down, Select All, Delete Track (destructive). Audio tracks also get a "Track Mix" item at the top.
+2. A horizontal `ScrollView(.horizontal)` containing the ruler + lanes + playhead.
+
+### Ruler (`timelineRuler`, line 1912)
+
+- Step pixels target ~84 per tick. `rulerStep` returns the smallest of `[0.25, 0.5, 1, 2, 5, 10, 15, 30, 60]` seconds satisfying that target.
+- Each mark is a 11pt medium rounded `textSecondary` label (`mm:ss` short clock) plus a 1pt × 12pt 14%-white tick line.
+- A live timecode pill (capsule, accent fill, 11pt bold mono white, padded 8/4) is overlaid above the playhead position.
+
+### Playhead
+
+Two views stack on top of all lanes:
+
+- `playheadView(x:height:)` (line 2262) — visual only. A 14×18 RoundedRectangle(4) accent flag head, plus a 2×(height-18) accent vertical line. zIndex 10.
+- `playheadGrabHandle(x:duration:)` — a 56×46 transparent hit-test rectangle on top of the ruler. zIndex 20. `DragGesture(minimumDistance: 0)`:
+ - On first touch: pauses playback, captures `playheadDragStartTime`.
+ - During: seeks to `baseTime + translation.x / zoom`, clamped to `[0, duration]`.
+ - On end: clears drag state.
+
+When `isDraggingPlayhead` is true, the horizontal scroll view is `scrollDisabled(true)` to avoid conflicting gestures.
+
+During playback, the horizontal scroll auto-tracks the playhead: `scrollOffset = max(0, targetX - trackAreaWidth * 0.5)` keeping it horizontally centred.
+
+### Lane content
+
+Four lane composers dispatched by `track.type`:
+
+- `visualTrackLane` (video, image) → `TimelineClipBlock`
+- `audioTrackLane` → `TimelineAudioClipBlock`
+- `textTrackLane` → `TimelineTextClipBlock`
+- `graphicsTrackLane` → `TimelineGraphicsClipBlock`
+
+If the lane has no clips, an `emptyTimelineLaneButton` is shown spanning the lane:
+
+- Inset 18 horizontal, `surfaceElevated` background, RoundedRectangle(16)
+- Icon (15pt bold accent) + title (13pt semibold rounded textSecondary)
+- Icons / titles per track type:
+ - video/image → `plus.rectangle.on.folder` / `photo.badge.plus` , "Open Media Sheet"
+ - audio → `waveform.badge.plus`, "Add Audio"
+ - text → `plus.bubble`, "Add Text" — opens `text` tab
+ - graphics → `sparkles.square.filled.on.square`, "Add Graphic" — opens `graphics` tab
+
+### TimelineClipBlock (video / image — line 4594)
+
+- Height 54, width = `max(clip.duration * zoom, 44)`
+- Background: project-style gradient (one of emerald/cobalt/amber/coral linear gradients) with corner radius 12.
+- Selection stroke: 2pt accent when selected, else 1pt 6%-white.
+- Foreground content layered with thumbnails (when `filmstripThumbnails` exists):
+ - Horizontal strip of `AsyncImage` thumbnails. Count = `ceil(clipWidth / 56)`. Each thumbnail is exactly `clipWidth / count` wide, height 54, clipped to a RoundedRectangle(12).
+ - Thumbnails are picked by mapping each strip position to a timestamp in `[clip.inPoint, clip.outPoint]` (reversed if `clip.reversed`) and choosing the nearest source thumbnail.
+- Label (top-left, 14h / 8v padding): two-line VStack(spacing: 3):
+ - Media name, 11pt semibold rounded, white, 1 line.
+ - Duration `clip.duration.shortClock()`, 10pt medium rounded, white opacity 0.82.
+- Trim handles on left & right edges: 12×34 RoundedRectangle(5) accent (opacity 0.95 selected, 0.45 idle), with hit-area expanded by `-8` inset on all sides.
+- Keyframe lane overlay (top-leading) when `clip.keyframes` is non-empty: each keyframe is a `TimelineKeyframeMarker` — a 12×12 yellow square rotated 45° (selected → accent), with a 2×18 vertical pin below it. A dashed yellow line connects multiple markers if ≥2 exist (`strokeBorder(Color.yellow.opacity(0.6), dash: [4,3])`).
+
+#### Clip gestures (all block types)
+
+- **Tap** → `onSelect` (select, seek to clip start, set tab to `.edit`).
+- **Long press (0.25s) → drag** → `moveGesture`. On end, calls `onMove(translation.x / zoom)` and fires `UIImpactFeedbackGenerator(.medium)`. During the drag, the block visually offsets by `moveTranslation`.
+- **Drag on a trim handle** → resizes the block live (`leadingTrimOffset` / `trailingTrimOffset` updated on `.onChanged`). On end commits `onTrim(edge, delta)` and fires `.light` haptic.
+- **Double-tap** is only on text blocks (opens editor).
+
+There is **no built-in snapping** in the iOS code; the user moves clips by raw delta-seconds, and the engine layer (`appState.moveClip`) is responsible for boundary clamping. Multi-select operations exist (`selectAllClipsOnTrack`) but no marquee-drag.
+
+### TimelineAudioClipBlock (line 4813)
+
+- Height 46, background hard-coded brown `Color(red: 0.36, green: 0.24, blue: 0.10)`, corner radius 14.
+- Waveform: `HStack(spacing: 3)` of 28 `Capsule`s, each 4pt wide; height = `max(8, sample * 30)`. Samples come from `mediaItem.waveformData` (downsampled to 28 points) or a synthetic sin-based fallback.
+- 12pt padding inset.
+- Trim handles 12×30 (smaller than visual lane).
+- A small `link` icon (10pt bold accent, padded 8) sits top-trailing when `clip.audioConfiguration.detachedSourceClipID != nil` (i.e., this is detached audio from a video).
+
+### TimelineTextClipBlock (line 4930)
+
+- Height 54, gradient background = `LinearGradient(colors: [textTintColor.opacity(0.32), surfaceElevated], topLeading -> bottomTrailing)`. `textTintColor` is the text clip's foreground color.
+- Content (top: name, bottom: animation hint):
+ - Text content, 12pt bold rounded, color is white-or-black based on luminance of the text style color (`prefersDarkTrackLabels` uses `0.2126 R + 0.7152 G + 0.0722 B > 0.62`).
+ - Animation row: `HStack(spacing: 6)` of an animation-specific SF symbol (10pt bold) + the preset name (10pt medium rounded). Symbols per preset:
+ - `typewriter` → `keyboard`
+ - `fade` → `circle.dashed`
+ - slide* → `arrow.up.left.and.down.right.and.arrow.up.right.and.down.left`
+ - `scale` / `pop` → `sparkle.magnifyingglass`
+ - `bounce` → `arrow.down.circle`
+ - `wave` → `water.waves`
+ - `shake` / `glitch` → `waveform.path`
+ - `rotate` / `flip` → `rotate.right`
+ - `blur` → `camera.filters`
+ - `split` → `arrow.left.and.right`
+ - word-* → `text.word.spacing`
+ - `rainbow` → `paintpalette.fill`
+ - else / none → `textformat`
+- 12pt padding. Trim handles 12×34.
+- **Double-tap → onEdit** (opens the text editor panel).
+
+### TimelineGraphicsClipBlock (line 5136)
+
+- Height 54, gradient `[accent.opacity(0.24), surfaceElevated]`. Corner 14.
+- Left icon (30×30):
+ - emoji/sticker → the emoji itself at 24pt
+ - shape → SF symbol from shape type (`circle.fill`, `oval`, `triangle.fill`, `arrowshape.right.fill`, `minus`, `hexagon.fill`, `star.fill`, default `rectangle.fill`)
+ - image → `photo`
+- Title (12pt bold rounded textPrimary) + duration (10pt medium rounded textSecondary).
+- Trim handles 12×34.
+
+### TimelineTransitionMarker (line 4539)
+
+Floats over the boundary between two clips on a video lane:
+
+- HStack(spacing: 6) — `diamond.fill` (9pt bold) + transition label (10pt bold rounded), 1-line.
+- Height 34, width `max(duration * zoom, 44)`. Capsule background — `accent` when selected else `surfaceElevated`. 1pt stroke (28%-white selected, 8%-white idle). Drop shadow `black.opacity(0.18) radius 5 y=2`.
+- Dragging horizontally retimes the transition duration with min-clamp at `TimelineTransitionEngine.minimumDuration`. Drop fires `.light` haptic.
+
+### Pinch-to-zoom
+
+A `MagnifyGesture()` is attached to the whole timeline:
+
+- On change: `newZoom = startingZoom * magnification`, clamped `[20, 300]`.
+- On end: clears `timelineZoomGestureStart`.
+
+There is no two-finger horizontal pan; horizontal panning is the standard `ScrollView` recognizer.
+
+### Tap on the timeline track area
+
+Tapping (not on a clip) seeks to `location.x / zoom` (clamped) and pauses playback.
+
+---
+
+## 6. Tab bar (bottom)
+
+`tabBar` (line 2370): a single horizontal `ScrollView` with horizontal indicators hidden, `HStack(spacing: 0)`, `.padding(.horizontal, 8)`. The tabs are `AppState.EditorTab.allCases` excluding `.edit` (so `.edit` is the implicit "no tab open" state).
+
+Order, label, icon (each tab is 56pt wide, internal `VStack(spacing: 3)`, 28×28 icon at 15pt semibold, 9pt semibold rounded label, foreground `textSecondary`, vertical padding 4):
+
+| Order | Tab (raw) | Label | Icon (SF Symbol) |
+|---|---|---|---|
+| 1 | `.media` | "Media" | `photo.on.rectangle` |
+| 2 | `.text` | "Text" | `textformat` |
+| 3 | `.graphics` | "Graphics" | `square.on.circle` |
+| 4 | `.templates` | "Templates" | `square.stack.3d.up` |
+| 5 | `.effects` | "Effects" | `wand.and.stars` |
+| 6 | `.subtitles` | "Subtitles" | `captions.bubble` |
+| 7 | `.audio` | "Audio" | `music.note` |
+
+(There is also `.edit` with icon `scissors` but it is never rendered as a bar item — it represents the no-panel-open state.)
+
+Tapping a tab calls `openTabPanel(tab)`:
+1. `tabSheetForceAdd = true`
+2. `activeTabSheet = tab` (presents the tab panel sheet)
+3. `appState.editorTab = tab`
+4. Clears `activeEditingSheet`
+
+Each tab panel is a separate SwiftUI view bound to `OpenReelProject`:
+- `.media` → `MediaTabPanel`
+- `.text` → `TextTabPanel(mode:)` — mode is `.edit` if a text clip is selected or subtitle-track is being edited and `!tabSheetForceAdd`; else `.add`
+- `.graphics` → `GraphicsTabPanel`
+- `.templates` → `TemplatesTabPanel`
+- `.effects` → `EffectsTabPanel(colorScopes:)`
+- `.subtitles` → `SubtitlesTabPanel`
+- `.audio` → `AudioTabPanel`
+
+All tab panels are presented as **sheets** with `presentationDetents([.fraction(0.55)])`, `presentationDragIndicator(.visible)`, `presentationBackground(.ultraThinMaterial)`. When dismissed, `editorTab` is reset to `.edit`.
+
+---
+
+## 7. Inspector panels (presentation model)
+
+There is no persistent side panel. Selection-driven inspectors and tab inspectors are **all bottom sheets** on iOS.
+
+### Sheet types
+
+| `@State` driver | Detent | Background |
+|---|---|---|
+| `isExportSheetPresented` | `.fraction(0.5)` | ultraThinMaterial |
+| `showsMediaLibrarySheet` | system default | system |
+| `isMediaPickerPresented` | `fullScreenCover` | full screen |
+| `showsVolumeControl` | `.fraction(0.5)` | ultraThinMaterial |
+| `activeEditingSheet` (12 cases) | `.fraction(0.5)` | ultraThinMaterial |
+| `activeTabSheet` | `.fraction(0.55)` | ultraThinMaterial |
+| `exportedVideo` | `ShareSheet` | system |
+| `completedExportURL` | `.confirmationDialog` | system |
+| `pendingTrackDeletion` | `.confirmationDialog` | system |
+
+### Editing sheet sizes (declared, but actual sheet uses one detent `.fraction(0.5)` — see `editingSheetHeight(for:)` line 2886 for the design heights):
+
+| Sheet | Height (pt design intent) |
+|---|---|
+| volume, speed, pan | 230 |
+| fade, trackMix | 360 |
+| duration | 250 |
+| opacity | 220 |
+| crop | 420 |
+| keyframe | 440 |
+| transition | 500 |
+| filters | 286 |
+| adjust | 306 |
+| blendMode | 480 |
+
+### Lower panel (context tool bar)
+
+`lowerPanel()` (line 2351) is **not** a sheet — it is the bottom-anchored area composed of:
+
+```
+VStack(spacing: 0) {
+ Divider (1pt, white opacity 0.04)
+ contextToolBar (height 56, only present when lowerPanelContent != nil — animated .move(.top).combined(.opacity), snappy 0.2s)
+ tabBar (height 56)
+}
+.background(OpenReelTheme.surfaceElevated)
+```
+
+`lowerPanelContent` is a `SelectionPanel` enum: `videoEdit` / `imageEdit` / `audioEdit` / `textEdit` / `graphicsEdit`. The bar reacts to selection-change `onChange` handlers.
+
+### Dismissal patterns
+
+- Tab sheets — drag-down or `onBack` callback that calls `dismissLowerPanel()` (resets `lowerPanelContent`, `toolBarLevel`, `editorTab = .edit`, both `activeEditingSheet` and `activeTabSheet` to nil).
+- Edit sheets — system drag indicator; setting `activeEditingSheet = nil`.
+- Confirmation dialogs — system Cancel/role buttons.
+
+---
+
+## 8. Selection & editing model
+
+### What gets selected
+
+Three independent selection slots on `AppState`:
+- `selectedClipID` (and `selectedClipIDs: Set<String>` for multi-select) — video/image/audio clips
+- `selectedTextClipID` / `selectedTextClipIDs`
+- `selectedGraphicsClipID` / `selectedGraphicsClipIDs`
+- Plus: `selectedKeyframeID`, `selectedTransitionID`
+
+Selecting one type clears unrelated panels via the `onChange` chain at the top of `baseEditorView`.
+
+### Tap on a timeline clip
+
+`selectClipForPreview(clip:in:)`:
+1. Pause playback.
+2. `appState.selectClip(clip)`.
+3. Resync playback graph to include the clip.
+4. Seek to `clip.startTime` (clamped to project duration).
+
+`handleSelectedClipChange` then sets the `lowerPanelContent`:
+- image media → `.imageEdit`
+- audio media → `.audioEdit`
+- else → `.videoEdit`
+
+…and resets `toolBarLevel = .tools`, clears any editing sheet, sets tab to `.edit`.
+
+### Double-tap
+
+- Video preview layer → reset selected clip's transform.
+- Text overlay or text timeline block → opens the text editor (via `presentTextClipEditor`, which selects the text clip, sets `activeTabSheet = .text`, and forces edit mode).
+
+### Long-press
+
+- On a clip block (0.25s) → begins **move drag**. Lifts the block visually (offset), commits on release with a `.medium` haptic.
+- On the volume button (0.4s) → opens the volume sheet.
+- On the track badge → context menu (Move Up/Down, Select All, Delete Track, plus Track Mix for audio).
+
+### Context tool bar (selection-driven actions, line 2396)
+
+When `lowerPanelContent` is set, a horizontal scrolling tool strip appears above the tab bar:
+
+- A **close/back button** (36×44) — `xmark` when at `.tools` level, `chevron.left` when in a sub-options level. Light haptic on tap.
+- Optional multi-selection badge — capsule pill `accent`, "`{n} selected`" 10pt bold rounded white, 8h/4v padding.
+- Then either `editActions` (top-level tool strip) or `subOptions(for: toolTitle)` (level 2).
+
+Each `toolStripButton` is 54pt wide, `VStack(spacing: 2)`:
+- 30×30 SF Symbol (15pt semibold)
+- 8pt semibold rounded label (1 line)
+- Foreground:
+ - `Delete` → `OpenReelTheme.destructive`
+ - Enabled → `textSecondary`
+ - Disabled → `textSecondary.opacity(0.35)`
+The tool actions per selection type (`editActions` computed property) — symbols here are SF Symbol names:
+
+**Video clip** (`videoEditActions`):
+Split (`scissors`), Keyframe (`diamond.fill`), Transition (`rectangle.on.rectangle`), Delete (`trash`), Detach (`link.circle`), Volume (`speaker.wave.2`), Pan (`dial.low`), Fade (`waveform.path.ecg`), Speed (`gauge.with.dots.needle.33percent`), Crop (`crop`), Mask (`lasso`), Blend (`square.on.square`), Effects (`wand.and.stars`), Filters (`camera.filters`), Adjust (`slider.horizontal.3`), Adjustment Layer (`square.3.layers.3d`).
+
+**Image clip** (`imageEditActions`):
+Duration (`clock`), Keyframe, Transition, Delete, Crop, Blend, Effects, Filters, Adjust, Adjustment Layer, Opacity (`circle.lefthalf.filled`).
+
+**Audio clip** (`audioEditActions`):
+Split, Delete, Volume, Pan, Fade, Speed.
+
+**Text clip** (`textEditActions`):
+Edit Text (`textformat.size`), Keyframe, Duration, Opacity, Delete.
+
+**Graphics clip** (`graphicsEditActions`):
+Delete only.
+
+#### Sub-options (level 2)
+
+`Adjust` → Brightness, Contrast, Saturation, Temperature, Hue, Sharpen, Vignette.
+`Effects` opens the Effects panel, including its on-device Video Tools.
+`Keyframe` → Opacity, Position, Scale, Rotation.
+`Fade` → Fade In, Fade Out.
+`Blend` → Mode.
+`Crop` → Free, 16:9, 9:16, 4:3, 1:1.
+`Filters` → Cinematic, Vintage, B&W, Cool, Warm.
+`Transition` → Type.
+
+Tools route by `handleToolTap`:
+- Immediate actions (`Split`, `Delete`, `Detach`) execute right away.
+- Single-control tools (`Volume`, `Pan`, `Speed`, `Duration`, `Opacity`, `Edit Text`) directly open their sheet.
+- Multi-option tools (`Adjust`, `Effects`, `Keyframe`, `Fade`, `Blend`, `Crop`, `Filters`) set `toolBarLevel = .subOptions(title)`.
+- Transition opens the transition sheet after adding/selecting one.
+
+### Ripple delete
+
+Long-press / context-menu on the Delete button shows "Ripple Delete" (destructive) which calls `appState.deleteSelectedClip(ripple: true, …)`. Plain Delete is non-ripple.
+
+### Action enablement (`isEditingActionEnabled`)
+
+- `Delete` → enabled if any selection.
+- `Keyframe` → clip or text selected.
+- `Transition` → must have an adjacent clip after the selected one.
+- `Edit Text` → text clip selected.
+- `Duration`/`Opacity` → text or image only.
+- `Detach` → `appState.canDetachSelectedClipAudio`.
+- `Split`/`Volume`/`Speed`/`Crop`/`Effects`/`Filters`/`Adjust`/`Blend` → clip selected.
+- `Pan`/`Fade` → clip with audio (audio media or video with audio tracks).
+
+---
+
+## 9. Keyboard shortcuts (iPad)
+
+**None implemented.** The codebase contains no `.keyboardShortcut`, `.onCommand`, or `UICommand` definitions, and the app is currently iPhone-only (recent commit explicitly switched the target device family). Android port can defer hardware-keyboard support.
+
+---
+
+## 10. Reusable shared components
+
+### From `Shared/Components/EditorPanels/EditorPanelComponents.swift`
+
+#### `EditorPanelContainer<Content>`
+Outer wrapper for all sheet/tab panels.
+
+- `VStack(alignment: .leading, spacing: 16)` filling the area.
+- Holds a `PanelHeader` then arbitrary content.
+- Padding 16. Background `OpenReelTheme.surfaceElevated`.
+- API: `title`, `subtitle`, `symbol` (SF Symbol), optional `onBack`, `@ViewBuilder content`.
+
+#### `PanelHeader`
+- `HStack(spacing: 12)`:
+ - Optional back button — 34×34 circle, `OpenReelTheme.surface`, icon `chevron.left` (15pt bold textPrimary).
+ - Symbol tile — 34×34 RoundedRectangle(10) accent fill, white SF Symbol (16pt bold).
+ - Title (17pt bold rounded textPrimary) + subtitle (12pt medium rounded textSecondary, 1 line).
+ - Trailing `Spacer`.
+
+#### `EditorMenuRow`
+Vertical list row with icon tile, title/subtitle and chevron.
+
+- `HStack(spacing: 12)`, `.padding(12)`, RoundedRectangle(14) `surface`, 1pt 6%-white stroke.
+- Icon tile 36×36 RoundedRectangle(12) `surfaceElevated`, SF Symbol 16pt bold in `accentColor` (or 35% textSecondary when disabled).
+- Two-line title block: 13pt bold rounded + 11pt medium rounded `textSecondary` (2 lines max).
+- Disclosure chevron 12pt bold textSecondary on right (toggleable).
+- Disabled state dims everything to 35%.
+
+#### `PanelActionTile`
+Square tile for grid actions.
+
+- `VStack(alignment: .leading, spacing: 12)`, minHeight 98, padding 12.
+- RoundedRectangle(12) `surface`, 1pt 6%-white stroke.
+- Icon 18pt semibold accent (top), title (13pt bold rounded, 1 line) + subtitle (11pt medium rounded, 2 lines).
+
+#### `PresetGridCard`
+Grid cell with colored icon panel + label/subtitle, supports selection state.
+
+- minHeight 126, padding 10, RoundedRectangle(12).
+- Top — 52pt-tall RoundedRectangle(10) filled with `accentColor.opacity(0.12)` (or `.24` selected), centered icon 20pt semibold.
+- Below — 12pt bold rounded title + 10pt medium rounded subtitle (2 lines).
+- Selected state strokes border with `accent` 2pt; idle 1pt 6%-white.
+
+#### `CompactSliderRow`
+- HStack(spacing: 10), 92-wide left label, slider, 52-wide right value text.
+- Label: 11pt semibold rounded textSecondary.
+- Value: 11pt bold monospaced textSecondary, formatted via `format(value)` (default `"NN%"`).
+- Slider tint `accent`.
+
+#### `SwatchButton`
+- Circle 34×34 fill from a hex color (or `surface` + `slash.circle` 18pt for hex == "none").
+- Selected: 3pt accent stroke; idle: 1pt 12%-white.
+
+`Color.init(hexString:)` extension parses via `OpenReelColorParser.components`.
+
+### From `EditorView.swift` (private helpers used by sheets)
+
+- `sheetHeader(title:value:)` — bold rounded 17pt left + 15pt semibold mono accent right.
+- `sliderRow(label:value:range:onChange:)` — 72-wide label, accent slider, 40-wide percent.
+- `controlSliderRow(label:value:range:valueText:onChange:)` — same but custom value text.
+- `clipPresetButton(label:action:)` — full-width 10v padding, 10-radius `surfaceElevated`, 12pt semibold rounded label.
+- `sheetSliderCard(label:value:range:format:onChange:)` — horizontal-scrollable card 210×72, RoundedRectangle(12) `surfaceElevated`, label (12pt bold rounded) + accent value (11pt bold mono) + accent slider.
+- `easingMenu(selected:onSelect:)` — 44-tall RoundedRectangle(10) `surfaceElevated`, icon `point.topleft.down.curvedto.point.bottomright.up`, "Easing" label, current value mono, chevron `up.chevron.down`.
+- `audioCurveMenu` — variant of easingMenu (options: Linear, Exp, Log, S-Curve, Bezier).
+- `RotaryKnob(label:value:range:format:onChange:)` (private struct, line 5338) — 64pt knob with a 4pt circular track, accent arc (135°→405°), 6pt notch dot, centered formatted value (11pt bold mono). Vertical drag sensitivity = `(range / 120)` per pt. `.light` haptic on grab. `format` is `.percentage` / `.decimal` / `.signed`.
+- `FilterPresetCard(name:symbol:tintColor:isSelected:action:)` — 64×64 RoundedRectangle(14) card, 18pt symbol + 10pt semibold rounded label. Selected: accent foreground + `accent.opacity(0.1)` fill + 2pt accent stroke. 200ms ease-out animation on selection.
+
+### Timeline-only structs
+
+- `TimelineKeyframeMarker` — described above; 32×32 hit area.
+- `TimelineTransitionMarker` — described above.
+- `TimelineClipBlock` / `TimelineAudioClipBlock` / `TimelineTextClipBlock` / `TimelineGraphicsClipBlock` — described above.
+- `TimelineTriangle` (Shape) — equilateral triangle pointing up.
+- `TimelinePolygon(points:)` (Shape) — regular polygon with N vertices.
+- `Arc(startDegrees:endDegrees:)` (Shape) — for the rotary knob arc.
+
+---
+
+## 11. Animation, haptic, sound feedback
+
+### Animations
+
+- Lower panel context tool bar appearance: `.snappy(duration: 0.2)` animation keyed on `lowerPanelContent != nil`. Transition: `.move(edge: .top).combined(with: .opacity)`.
+- `FilterPresetCard` selection: `.easeOut(duration: 0.2)`.
+- Sheet presentations: default SwiftUI sheet animation, with `presentationBackground(.ultraThinMaterial)` for the blurred backdrop.
+- Timeline auto-scroll during playback: implicit (driven by `scrollPosition.scrollTo(x:)`).
+
+There are no explicit Lottie / particle effects. The video player content itself animates per frame.
+
+### Haptics (UIKit `UIImpactFeedbackGenerator`)
+
+- `.light` — tool-strip button taps, sub-option button taps, context bar close, every trim handle end, transition marker drag end, rotary knob grab start, text-editor open.
+- `.medium` — clip move (long-press drag) end.
+
+No notification or warning haptics are used.
+
+### Sound
+
+No custom sound effects. Only the player audio plays (via AVAudioEngine in `TimelineAudioPreviewEngine`).
+
+---
+
+## 12. Android mapping suggestions
+
+### Layout & navigation
+
+- Implement the editor as a single `Activity` with a Compose `Scaffold` (no nav-host needed inside) — the screen never navigates away; sheets and dialogs handle all secondary UI.
+- Lock orientation to portrait in the manifest (`android:screenOrientation="portrait"`).
+- Top bar → `Surface` with `RoundedCornerShape(20.dp)` and `Modifier.padding(horizontal = 16.dp)`. Use `MaterialTheme` colors mapped to the OpenReelTheme tokens.
+- Sheets → `ModalBottomSheet` with `SheetState` and fixed `skipPartiallyExpanded = false` to mimic `.fraction(0.5)`/`.fraction(0.55)` detents. Use `WindowInsets.safeDrawing` for the root scaffold; sheets can ignore them (`scrim` covers).
+- Confirmation dialogs → `AlertDialog` with destructive role on red buttons. Track delete & export complete are the only two.
+- Picker / full screen → use a separate `Activity` for `MediaPicker` (Photo Picker API on Android 13+, `ActivityResultContracts.PickMultipleVisualMedia`).
+
+### Preview canvas
+
+- `SurfaceView` or `TextureView` wrapped in `AndroidView`. Pull frames from ExoPlayer's `VideoFrameMetadataListener` + `GLSurfaceView` to mirror the Metal pipeline. Use `RenderEffect` (API 31+) for blur and color effects; for older devices fall back to OpenGL fragment shaders matching `VideoEffectRenderer`.
+- Overlays (text, graphics, image) → Compose layers on top of the player view, animated via `Animatable` / `graphicsLayer { translationX, translationY, scaleX, scaleY, rotationZ }` for the same parameters as `OpenReelProject.Transform`.
+- Gestures: `Modifier.pointerInput { detectTransformGestures(...) }` covers pinch + rotate + drag in a single recognizer. Commit on `awaitFirstDown … awaitPointerEvent { gesture.changes }` then `.changedToUp` mirrors the `.onEnded`-only commit pattern. Double-tap → `detectTapGestures(onDoubleTap = …)`.
+
+### Timeline
+
+- Use a custom `LazyColumn` for the lanes and a single `HorizontalScrollState` (synchronized between the ruler row and each lane row). Both `LazyColumn` (vertical) and lanes (horizontal) share the same horizontal state so the ruler and tracks scroll together.
+- Pinch-to-zoom: `Modifier.pointerInput` → `detectTransformGestures` with only `zoom` consumed → update `pixelsPerSecond` clamped 20..300.
+- Clip blocks → `Canvas` or `Box` with `Modifier.drawBehind` for thumbnails. Use `Coil` for `AsyncImage` thumbnails. Filmstrip behaviour mirrors `displayThumbnailURLs` (nearest-neighbor selection).
+- Trim handles → `Modifier.draggable` with `Orientation.Horizontal`; update local offset during drag, commit `onDragStopped`.
+- Move-on-long-press → `Modifier.combinedClickable(onLongClick = ...)` to enter "move" mode, then `Modifier.draggable`. Add a `HapticFeedbackType.LongPress` on enter and `TextHandleMove` on commit.
+- Playhead grab handle → `Box` with `Modifier.pointerInput { awaitEachGesture { ... } }` (start gesture immediately, no minimum distance). Disable horizontal scroll while dragging by toggling a `nestedScrollConnection`.
+
+### Selection model
+
+- `EditorViewModel` (single shared) holds: selectedClipId, selectedTextClipId, selectedGraphicsClipId, multiselect sets, selectedKeyframeId, selectedTransitionId. Use `MutableStateFlow` / Compose `mutableStateOf`. Mirror the iOS `onChange` cascades with `LaunchedEffect`s.
+- The 5-way `LowerPanelContent` enum maps to a sealed class. The 12-way `EditingSheet` enum maps to another sealed class. Use `derivedStateOf` to compute `editActions` based on selection.
+
+### Sheets / inspectors
+
+- All editing sheets share a common `BottomSheetContent` composable with: header row (title bold, value mono accent), body slot. Heights from `editingSheetHeight(for:)` map directly to `Modifier.height(…dp)` if you want to mimic per-sheet sizing — or use a uniform 50% detent.
+- Tab sheets get 55% detent (`fraction = 0.55f`). Use `accompanist-flowlayout` or `LazyVerticalGrid` inside for grid layouts.
+
+### Theming
+
+- Map `OpenReelTheme` to a Material 3 `ColorScheme` plus app-specific extras (the gradient projectstyles need custom `Brush.linearGradient` constants).
+- Fonts: substitute `FontFamily.SansSerif` for SF Rounded; use a custom rounded font like `Inter` or `Manrope` for parity. Monospaced uses `FontFamily.Monospace`.
+- Project gradients (emerald / cobalt / amber / coral) — define as constants from the RGB triples in `Theme.swift` lines 43–50.
+
+### Haptics
+
+- Light → `HapticFeedbackType.TextHandleMove`.
+- Medium → `HapticFeedbackType.LongPress`.
+
+### Tab bar / icons
+
+Use `Icons.Default` (Material) or import a parallel set; here is a suggested mapping for the bottom tabs:
+
+| iOS SF Symbol | Material Icon (suggested) |
+|---|---|
+| `photo.on.rectangle` | `PhotoLibrary` |
+| `textformat` | `TextFields` |
+| `square.on.circle` | `Category` |
+| `square.stack.3d.up` | `ViewInAr` / `Layers` |
+| `wand.and.stars` | `AutoAwesome` |
+| `captions.bubble` | `ClosedCaption` |
+| `music.note` | `MusicNote` |
+| `scissors` | `ContentCut` |
+| `arrow.uturn.backward` / `forward` | `Undo` / `Redo` |
+| `square.and.arrow.up.fill` | `IosShare` / `Upload` |
+| `chevron.left` | `ChevronLeft` |
+| `play.fill` / `pause.fill` | `PlayArrow` / `Pause` |
+| `backward.frame.fill` / `forward.frame.fill` | `SkipPrevious` / `SkipNext` |
+| `speaker.*` family | `VolumeOff` / `VolumeMute` / `VolumeDown` / `VolumeUp` |
+
+Reuse a single `ToolAction(title, icon)` data class for the tool strip and feed `editActions` to a `LazyRow`.
+
+### Naming parity files
+
+| iOS file | Suggested Android module |
+|---|---|
+| `EditorView.swift` | `editor/EditorScreen.kt`, `editor/EditorViewModel.kt` (split) |
+| `EditorPanelComponents.swift` | `editor/components/Panels.kt` |
+| `MetalVideoView.swift` | `editor/preview/VideoSurface.kt` (+ GLSL shaders) |
+| `EffectImageView.swift` | `editor/preview/EffectImage.kt` |
+| `PlaybackController.swift` | `editor/playback/PlaybackController.kt` |
+
+Mirror the iOS `@Observable` pattern via `StateFlow` + Compose `collectAsStateWithLifecycle`. Keep the engine layer pure (no Android framework deps) so the action history can be reused on JVM tests.
diff --git a/docs/android-port/04-playback-rendering.md b/docs/android-port/04-playback-rendering.md
new file mode 100644
index 00000000..e7dfe84c
--- /dev/null
+++ b/docs/android-port/04-playback-rendering.md
@@ -0,0 +1,630 @@
+# 04 — Playback, Rendering, and Video/Image Effects Pipeline
+
+Authoritative reference for porting Openreel Video's preview-side playback and effects to Android. Source files cross-referenced inline.
+
+---
+
+## 1. AVFoundation Playback Architecture
+
+The iOS pipeline composes three Apple frameworks. Android port must reproduce each layer.
+
+```
+PlaybackController (@MainActor, @Observable)
+ |
+ +-- AVPlayer
+ | +-- AVPlayerItem
+ | +-- AVMutableComposition (built by PlaybackCompositionBuilder)
+ | +-- AVMutableAudioMix (volume keyframes / ramps)
+ | +-- AVMutableVideoComposition (custom compositor: TransitionVideoCompositor)
+ |
+ +-- TimelineAudioPreviewEngine (AVAudioEngine, used when descriptor.requiresNativePreview)
+ +-- AVPlayerItemVideoOutput -> MetalVideoView (effects pipeline, color scopes)
+```
+
+What's wrapped:
+
+- `AVPlayer` is the master playhead and clock. Owns rate, mute, volume, seeking.
+- `AVMutableComposition` is the time-track database (video tracks A/B + N audio tracks).
+- `AVMutableAudioMix` carries per-track volume automation (`setVolume(_:at:)` and `setVolumeRamp`).
+- `AVMutableVideoComposition` carries instructions per time range; `customVideoCompositorClass = TransitionVideoCompositor` lets Core Image blend two source tracks for transitions.
+- `AVPlayerItemVideoOutput` (32BGRA, Metal-compatible) pulls decoded frames; the Metal view runs the effect chain.
+- `TimelineAudioPreviewEngine` wraps `AVAudioEngine` for advanced audio cases (pan, advanced effects, ducking) — replaces the AVPlayer audio path by muting AVPlayer.
+
+What's exposed (publicly observable):
+- `currentTime: TimeInterval`
+- `duration: TimeInterval`
+- `isPlaying: Bool`
+- `volume: Float` (0–2)
+- `frameRate: Double` (default 30)
+- `loadedMediaURL: URL?`
+- `player: AVPlayer?` (handed to the Metal view)
+
+Internal observers installed on every player swap:
+- Periodic time observer at `1/30 s` (timescale 600), updates `currentTime` only when `rate > 0`.
+- KVO on `player.rate` → mirrors `isPlaying`.
+- KVO on `playerItem.status` → no-op once `.readyToPlay`; used to defer `play()` until the item is ready.
+- `AVPlayerItemDidPlayToEndTime` notification → sets `isPlaying=false`, snaps `currentTime=duration`, pauses audio engine.
+
+Single-clip load path: `loadVideo(url:duration:frameRate:)` — builds `AVURLAsset` + `AVPlayerItem` directly, no composition, no video composition.
+
+Multi-clip / timeline path: `loadTimeline(sources:duration:frameRate:transitions:)` — debounced via a `signature` (string concatenation of all source signatures + transitions); if the signature already matches `loadedTimelineSignature`, the swap is skipped. Otherwise it kicks off a `Task` that calls `PlaybackCompositionBuilder.build(...)` off the main actor and installs the resulting `AVPlayerItem` when done.
+
+Audio mode (`applyPlayerAudioMode`): when native audio preview is active, `player.isMuted = true` and `player.volume = 0`; otherwise volume is clamped to `min(volume, 1)`.
+
+Android mapping: ExoPlayer (`androidx.media3.exoplayer.ExoPlayer`) + `MediaSource` for each clip + `ConcatenatingMediaSource2` / `Composition` API (Media3 Transformer) for the editing graph. Use `Player.Listener.onIsPlayingChanged` / `onPlaybackStateChanged` instead of KVO. For frame access use `SurfaceTexture` or Media3's `Effect` pipeline; for transitions use Media3 `Composition` with `OverlayEffect` or fall back to a custom `GlEffect`. Pull frames into an OpenGL ES 3 / Vulkan compute pipeline for effect post-processing.
+
+---
+
+## 2. PlaybackController Public API
+
+(`PlaybackController.swift` lines 268–715)
+
+| Method | Behavior |
+|---|---|
+| `loadVideo(url: URL?, duration: TimeInterval, frameRate: Double)` | Single-source mode. If `url` already loaded, just refreshes duration/frame rate. Otherwise tears down observers, creates new `AVURLAsset`+`AVPlayerItem`+`AVPlayer`, installs observers. `frameRate` floors to 30 if <=0. Audio engine is reset to empty descriptor. |
+| `loadTimeline(sources:duration:frameRate:transitions:)` | Multi-clip mode. Computes signature; skips if same. Asynchronously builds the AVComposition via `PlaybackCompositionBuilder.build`. Preserves `currentTime` across the swap (clamped to new duration). |
+| `play()` | If the item isn't `.readyToPlay`, sets `isPlaying = true` and installs a one-shot KVO observer that calls `startPlayback()` once ready. If already at `duration - 0.05`, seeks to zero first (loop on tail). Then starts the audio engine if `usesNativeAudioPreview` and sets `player.rate = 1.0`. |
+| `pause()` | Clears any deferred play observer, pauses the audio engine, sets `player.rate = 0`. |
+| `togglePlayback()` | Pauses if `player.rate > 0`, plays otherwise. |
+| `seek(to time: TimeInterval)` | Clamps to `[0, duration]`, updates `currentTime` synchronously, updates audio-engine playhead. If natively previewing audio while playing, pauses the audio engine, calls `player.seek(toleranceBefore: .zero, toleranceAfter: .zero)`, and on completion restarts the audio engine from the new time. CMTime timescale 600. |
+| `step(frames: Int)` | `seek(to: currentTime + frames / frameRate)`. Frame-step uses zero tolerance. |
+| `setVolume(_ value: Float)` | Clamps to `[0, 2]`. Audio engine clamps to `[0, 1]`. AVPlayer volume = `min(volume, 1)` when not using native preview. |
+
+There is no explicit `setRate(_:)` — playback rate is locked at 1.0. Frame-step uses seek, not rate scrubbing. There is no looping flag; end-of-clip pauses (`actionAtItemEnd = .pause`) and a subsequent `play()` rewinds.
+
+Android equivalents:
+- `loadTimeline` → build a `androidx.media3.transformer.Composition` or feed a `ConcatenatingMediaSource2`. Always preserve playhead across swap.
+- `play/pause/seek` → `Player.play()`, `pause()`, `seekTo(positionMs)`. Use `Player.SEEK_PARAMETERS_EXACT` for frame-accurate seeks.
+- `step(frames:)` → `seekTo(currentPosition + frames * 1000 / frameRate)`.
+- `setVolume` → `Player.setVolume` (0–1) plus a separate gain stage in an `AudioProcessor` for 1–2 range.
+- For deferred-play (item not ready yet) listen on `Player.STATE_READY`.
+
+---
+
+## 3. PlaybackCompositionBuilder
+
+(`PlaybackCompositionBuilder.swift` lines 515–873)
+
+Inputs: `[TimelineSource]`, optional `TimelineAudioDescriptor`, `[TimelineTransition]`, `frameRate`.
+Output: `Result { composition, audioMix, videoComposition? }`.
+
+### Video Track Layout (A/B Rule)
+1. Filter sources where `includesVideo == true`, sort by `startTime` ascending.
+2. Always add exactly **two** video tracks (call them A and B).
+3. Iterate sorted sources; assign track by index parity (`insertCount % 2`): clip 0 → A, clip 1 → B, clip 2 → A, etc. This ensures any neighbour pair (and therefore any transition) reads from different tracks, which the custom video compositor requires (it needs both outgoing and incoming pixel buffers simultaneously).
+4. `clipTrackMap: [String: CMPersistentTrackID]` records which physical track holds each clip ID.
+
+For each video source:
+- Load `AVURLAsset` → first video track.
+- `sourceTimeRange(for:asset:)` computes the readable range: `start = clamp(inPoint, 0, assetDuration)`, `duration = clamp(max(outPoint-inPoint, source.duration * speed), source.duration, availableDuration)`.
+- Insert into track at `CMTime(seconds: startTime, timescale: 600)`.
+- Carry the asset's `preferredTransform` (rotation/mirror) onto the composition track.
+- If `sourceDuration != playbackDuration` (i.e. speed != 1), call `scaleTimeRange(_:toDuration:)` for time-stretch.
+- Capture `renderSize` from the first inserted track (with `preferredTransform` applied via `applying(_:)` and `standardized`).
+
+### Audio Tracks
+For each segment in `TimelineAudioDescriptor.segments`:
+- For each `AVAssetTrack` of `.audio` media type, add a new mutable audio track (one composition track per source audio track).
+- Insert time range, scale if speed != 1.
+- Build `AVMutableAudioMixInputParameters(track:)` and pump in the segment's pre-computed volume keyframes (see §3.3) — either as discrete `setVolume(at:)` points or as `setVolumeRamp(from:to:timeRange:)` between consecutive keyframes whose volumes differ.
+
+### AudioMix Volume Keyframes
+`TimelineAudioDescriptor.volumeKeyframes(for:audioEffects:allSources:)` precomputes a piecewise sample plan based on:
+- Base volume `clamp(source.volume * source.trackGain, 0, 2)`
+- Fade-in / fade-out with curve `{linear|exponential|logarithmic|sCurve|bezier}` (subdivided at 6 internal samples for non-linear curves).
+- Volume automation segments (per-source `volumeAutomation: [AudioAutomationPoint]`).
+- Ducking ranges: if effect `.ducking(config)` is present and another source with `trackRole == config.triggerRole` overlaps, attack/hold/release windows are applied with S-curve. `duckedMultiplier = 1 - config.reduction`.
+
+Curve formulas (`curveValue(progress:curve:bezierControlPoints:)`):
+- `linear`: `t`
+- `exponential`: `pow(t, 2.2)`
+- `logarithmic`: `log10(9t + 1)`
+- `sCurve`: `t*t*(3 - 2t)` (smoothstep)
+- `bezier`: cubic bezier evaluation, 14 bisection iterations to invert x→t.
+
+Volume-keyframe simplification: a 3-tap pass drops any sample equal (within ε=0.0001) to both neighbours.
+
+### Video Composition (only if transitions exist)
+Build only when: at least one transition exists, a render size was captured, and `sources.count >= 2`. Otherwise the `videoComposition` is nil and the player just shows track A/B directly.
+
+Render size is downsampled to `1280` on the longest side for preview.
+
+Frame duration: `CMTime(1, max(round(frameRate), 1))`.
+
+Time segments are built as follows:
+1. For every transition, compute boundary = `outgoing.startTime + outgoing.duration`, `transStart = max(boundary - duration/2, 0)`, `transEnd = boundary + duration/2`. Emit a `.transition(outgoingTrackID, incomingTrackID, params)` segment covering that range.
+2. For every video source, compute its full range; subtract every transition range from it (`subtract(_:from:)`), emit remaining sub-ranges as `.passthrough(trackID)`.
+3. Sort all segments by `timeRange.start`.
+
+Two instruction classes implement `AVVideoCompositionInstructionProtocol`:
+- `CompositorPassthroughInstruction` — single source track, `containsTweening = false`, `requiredSourceTrackIDs = [sourceTrackID]`.
+- `TransitionInstruction` — two sources, `containsTweening = true`, carries `transitionType`, `transitionParams`, `renderSize`.
+
+### TransitionVideoCompositor
+Conforms to `AVVideoCompositing`:
+- `sourcePixelBufferAttributes` / `requiredPixelBufferAttributesForRenderContext` = `32BGRA`.
+- Renders on a single serial `DispatchQueue` (QoS userInteractive), software-rendered=false `CIContext`.
+- Passthrough path: return `sourceFrame(byTrackID:)` directly (or a black frame fallback).
+- Transition path: `aspectFit` (uniform scale + center offset) both outgoing and incoming `CIImage`s to `renderSize`, computes progress = `elapsed / duration` clamped to [0,1], delegates to `TransitionCompositor.apply(...)`, renders to a fresh output `CVPixelBuffer` via `CIContext.render(_:to:bounds:colorSpace:)` with `CGColorSpaceCreateDeviceRGB()`.
+
+Android mapping:
+- Use Media3 Transformer's `Composition` for sequencing, or build a `MediaCodec` decode → `SurfaceTexture` → GLES render loop.
+- Two-track A/B parity rule is mandatory for any cross-fade implementation. Implement equivalent of `subtract(_:from:)` to slice passthrough ranges around transition ranges.
+- Volume keyframes → `Renderer` `AudioProcessor` chain that reads a precomputed envelope, OR Media3's `Effects.audioProcessors` with a custom volume-shaping `AudioProcessor`.
+- For per-clip transforms (rotation), apply the source's display transform via OpenGL matrix.
+
+---
+
+## 4. VideoEffectTypes Catalog
+
+(`VideoEffectTypes.swift`) — exhaustive list. Every parameter ranges and default below. `intensity` parameter is universal: it controls the dissolve blend between original and effected (0 = original, 1 = full effect). Each effect's renderer applies the effect at full strength, then `VideoEffectRenderer.blend(original:effected:intensity:)` dissolves between them.
+
+Effect type strings are the enum `rawValue`s (camelCase).
+
+| Effect | Param | Range | Default | Notes |
+|---|---|---|---|---|
+| `brightness` | `value` | −1 … 1 (CIColorControls) | 0 | additive |
+| `brightness` | `intensity` | 0 … 1 | 1 | |
+| `contrast` | `value` | 0.25 … 4 (CI) | 1 | multiplicative |
+| `contrast` | `intensity` | 0 … 1 | 1 | |
+| `saturation` | `value` | 0 … 2 | 1 | |
+| `saturation` | `intensity` | 0 … 1 | 1 | |
+| `temperature` | `value` | −1 … 1 | 0 | mapped onto R/G/B/Bias matrix (see §5) |
+| `temperature` | `intensity` | 0 … 1 | 1 | |
+| `hue` | `rotation` | degrees (no clamp; converted to radians) | 0 | |
+| `hue` | `intensity` | 0 … 1 | 1 | |
+| `blur` | `radius` | ≥ 0, default 0.5 | 0.5 | CIGaussianBlur |
+| `blur` | `type` | "gaussian" | "gaussian" | currently unused branch |
+| `blur` | `intensity` | 0 … 1 | 1 | |
+| `sharpen` | `amount` | ≥ 0 | 0.3 | CISharpenLuminance |
+| `sharpen` | `radius` | unused in renderer | 1 | |
+| `sharpen` | `threshold` | unused | 10 | |
+| `sharpen` | `intensity` | 0 … 1 | 1 | |
+| `vignette` | `amount` | ≥ 0 | 0.25 | scaled by 0.9 (custom) or 2.2 (CIVignette fallback) |
+| `vignette` | `midpoint` | 0.05 … 1 | 0.5 | radius = `min(w,h) * midpoint` |
+| `vignette` | `roundness` | unused | 0.5 | |
+| `vignette` | `feather` | unused | 0.8 | |
+| `vignette` | `intensity` | 0 … 1 | 1 | |
+| `grain` | `amount` | 0 … 1 | 0.15 | |
+| `grain` | `size` | unused | 1.5 | |
+| `grain` | `roughness` | unused | 0.5 | |
+| `grain` | `colored` | unused | false | |
+| `grain` | `intensity` | 0 … 1 | 1 | |
+| `chromaticAberration` | `amount` | 0 … 20 | 3 | passed to kernel scaled by 0.8 |
+| `chromaticAberration` | `intensity` | 0 … 1 | 1 | |
+| `bloom` | `radius` | 0 … 60 | 12 | CIBloom |
+| `bloom` | `amount` | 0 … 2 | 0.65 | CIBloom intensity |
+| `bloom` | `intensity` | 0 … 1 | 1 | |
+| `pixelate` | `scale` | 1 … 80 | 18 | CIPixellate |
+| `pixelate` | `intensity` | 0 … 1 | 1 | |
+| `motionBlur` | `radius` | 0 … 60 | 8 | CIMotionBlur |
+| `motionBlur` | `angle` | degrees → radians | 0 | |
+| `motionBlur` | `intensity` | 0 … 1 | 1 | |
+| `dissolve` | `amount` | 0 … 1 | 0.25 | alpha multiplier `1-amount` |
+| `dissolve` | `intensity` | 0 … 1 | 1 | |
+| `disintegrate` | `amount` | 0 … 1 | 0.35 | CIDisintegrateWithMaskTransition |
+| `disintegrate` | `shadow` | 0 … 1 | 0.2 | scaled by 18 for shadowRadius |
+| `disintegrate` | `intensity` | 0 … 1 | 1 | |
+| `stabilize` | `strength` | 0 … 1 | 0.5 | |
+| `stabilize` | `crop` | 0 … 0.18 | 0.06 | scale = `1 + crop*strength` |
+| `stabilize` | `target` | "subject" | "subject" | |
+| `stabilize` | `confidence` | 0 … 1 | 0.55 | tracking conf threshold |
+| `stabilize` | `smoothing` | 0 … 1 | 0.5 | |
+| `stabilize` | `quality` | "balanced"/"fast"/"high" | "balanced" | |
+| `stabilize` | `intensity` | 0 … 1 | 1 | |
+| `motionTrack` | `mode` | "subject" | "subject" | renderer pass-through (visual no-op; emits tracking path metadata) |
+| `motionTrack` | `confidence` | 0 … 1 | 0.7 | |
+| `motionTrack` | `smoothing` | 0 … 1 | 0.35 | |
+| `motionTrack` | `quality` | string | "balanced" | |
+| `motionTrack` | `intensity` | 0 … 1 | 1 | |
+| `backgroundRemoval` | — | see `BackgroundRemovalSettings.effectParams` | (settings default) | AI mask via Vision; applied through `AIMaskCompositor.applyBackgroundRemoval` |
+| `subjectBlur` | `radius` | ≥ 0 | 16 | gaussian on background, keyed by AI mask |
+| `subjectBlur` | `feather` | ≥ 0 | 4 | mask edge feather |
+| `subjectBlur` | `quality` | string | "balanced" | |
+| `subjectBlur` | `intensity` | 0 … 1 | 1 | |
+| `subjectGlow` | `radius` | ≥ 0 | 18 | |
+| `subjectGlow` | `amount` | ≥ 0 | 0.65 | |
+| `subjectGlow` | `feather` | ≥ 0 | 6 | |
+| `subjectGlow` | `quality` | string | "balanced" | |
+| `subjectGlow` | `intensity` | 0 … 1 | 1 | |
+| `faceBeauty` | — | see `FaceBeautySettings.effectParams`: `intensity`, `smoothing`, `sharpen`, `brighten`, `warmth`, `feather` | settings default | CINoiseReduction + ColorControls + temperature; masked to tracked face rect when available |
+| `faceTrack` | `target`/`confidence`/`smoothing`/`quality`/`intensity` | strings/0–1 | "face"/0.6/0.35/"balanced"/1 | pass-through visual |
+| `objectTrack` | (same shape) | | "object"/0.65/0.35/"balanced"/1 | pass-through |
+| `bodyPose` | (same shape) | | "body"/0.55/0.4/"balanced"/1 | pass-through |
+| `autoReframe` | `target` | "subject" | "subject" | crops & rescales to keep tracked box in frame |
+| `autoReframe` | `padding` | 0 … some | 0.12 | padded box = `box * (1 + padding*2)` |
+| `autoReframe` | `smoothing` | 0 … 1 | 0.5 | |
+| `autoReframe` | `confidence` | 0 … 1 | 0.65 | minimum tracking conf |
+| `autoReframe` | `quality` | string | "balanced" | |
+| `autoReframe` | `intensity` | 0 … 1 | 1 | |
+| `colorWheels` | `shadows`/`midtones`/`highlights` | object `{r,g,b}` each clamped −1 … 1 | `{0,0,0}` | applied as R/G/B bias |
+| `colorWheels` | `shadowsLift` | −1 … 1 | 0 | bias 0.08 |
+| `colorWheels` | `midtonesGamma` | 0.2 … 3 | 1 | CIGammaAdjust |
+| `colorWheels` | `highlightsGain` | 0 … 3 | 1 | RGB vector scale |
+| `colorWheels` | `intensity` | 0 … 1 | 1 | |
+| `curves` | `rgb`,`red`,`green`,`blue` | arrays of `{x,y}` each in 0…1 | `[{0,0},{1,1}]` | baked into 32³ color cube |
+| `curves` | `intensity` | 0 … 1 | 1 | |
+| `hsl` | `hue` | length-8 array; each ∈ −180…180 (degrees) | [0]*8 | 8 hue bands of 45° each |
+| `hsl` | `saturation` | length-8; each ∈ −1…1 | [0]*8 | |
+| `hsl` | `luminance` | length-8; each ∈ −1…1 (scaled ×0.5 inside renderer) | [0]*8 | |
+| `hsl` | `intensity` | 0 … 1 | 1 | |
+| `lut` | `name` | string | "None" | |
+| `lut` | `path` | string, project-relative | "" | |
+| `lut` | `size` | int (LUT 3D size) | 0 | |
+| `lut` | `domainMin` | array[3] −1000…1000 | [0,0,0] | |
+| `lut` | `domainMax` | array[3] −1000…1000 | [1,1,1] | |
+| `lut` | `checksum` | string | "" | used as cache key |
+| `lut` | `intensity` | 0 … 1 | 1 | |
+| `filterPreset` | `name` | string | "Custom" | legacy; reapplies contrast/saturation/temperature |
+| `filterPreset` | `contrast`/`saturation`/`temperature` | as above | inherited | |
+| `colorAdjust` | `name`,`brightness`,`contrast`,`saturation`,`temperature`,`beauty` | see Brightness/Contrast/Sat/Temp + `beauty` 0…1 | "Custom"/0/1/1/0/0 | legacy combined preset |
+| `colorAdjust` | `intensity` | 0 … 1 | 1 | |
+
+The `Effect` struct (`OpenReelProject.Effect`) is the persisted shape: `{ id, type, enabled: Bool, params: [String: JSONValue] }`.
+
+---
+
+## 5. CIFilter / Metal Kernel Mappings
+
+(`VideoEffectRenderer.swift`)
+
+| Effect | Underlying API | Notes |
+|---|---|---|
+| `brightness`,`contrast`,`saturation` | `CIColorControls` (`inputBrightness`/`inputContrast`/`inputSaturation`) | Single instance per effect (one channel at a time). |
+| `temperature` | `CIColorMatrix` | Hand-built matrix: warm = max(t,0), cool = max(-t,0). R = `1 + warm*0.10 - cool*0.10`, G = `1 - warm*0.03 - cool*0.02`, B = `1 - warm*0.16 + cool*0.12`. Bias = `(warm*0.015, 0, cool*0.015, 0)`. |
+| `hue` | `CIHueAdjust` (`inputAngle = rotation * π/180`) | |
+| `blur` | `CIGaussianBlur` (cropped back to extent) | |
+| `sharpen` | `CISharpenLuminance` | |
+| `vignette` | Custom Metal kernel `openreelVignette` (preferred) with `amount*0.9` and `radius = min(w,h)*midpoint`; fallback `CIVignette` with `inputIntensity = amount*2.2`. | |
+| `grain` | Custom Metal kernel `openreelGrain`; fallback = `CIRandomGenerator` + `CIColorMatrix` + `CISoftLightBlendMode`. Seed = `timelineTime * 24`. | |
+| `bloom` | `CIBloom` | |
+| `pixelate` | `CIPixellate` centered on image midpoint | |
+| `motionBlur` | `CIMotionBlur` | |
+| `dissolve` | `CIColorMatrix` with `inputAVector = (0,0,0, 1-amount)` | global alpha |
+| `disintegrate` | `CIDisintegrateWithMaskTransition` (target = transparent, mask = jittered noise) | |
+| `chromaticAberration` | Custom Metal kernel `openreelChromaticAberration` (preferred); fallback = 3 channel-isolated `CIColorMatrix` + translated copies + `CIAdditionCompositing`. | |
+| `colorWheels` | `CIColorMatrix` (lift/gain/bias) + `CIGammaAdjust` | |
+| `curves` | `CIColorCubeWithColorSpace` baked from `EffectCurvePoint` arrays (32³) | linear interpolation between sorted curve points |
+| `hsl` | `CIColorCubeWithColorSpace` baked via HSL conversion (32³) | 8-band hue selection by `floor(hue*360/45)` |
+| `lut` | `CIColorCubeWithColorSpace` from parsed `.cube` file; cached by `path|checksum` | `CGColorSpaceCreateDeviceRGB()` |
+| `stabilize` | Affine transform (uniform scale around image center) + optional XY translation based on tracking box | not Vision-stabilized; this is the *post-tracking* render pass |
+| `autoReframe` | `cropped(to:)` + scale-up affine transform | crop rect computed from tracking box and image aspect |
+| `subjectBlur`/`subjectGlow`/`backgroundRemoval` | `AIMaskCompositor.apply*` (consumes Vision segmentation mask supplied by `FrameEffectContext`) | |
+| `faceBeauty` | `CINoiseReduction` + `CIColorControls` + temperature + `CISharpenLuminance`; mask blend via `CIBlendWithMask` with a feathered rectangular mask of the tracked face box | |
+| `motionTrack`,`faceTrack`,`objectTrack`,`bodyPose` | returns `image` unchanged | These effects only **emit** tracking metadata. Use the resulting `TrackingPath` in dependent effects (stabilize, autoReframe, faceBeauty). |
+| `dissolve` (effect, not transition) | alpha matrix | |
+| `filterPreset` | `CIColorControls` + temperature | legacy |
+| `colorAdjust` | `CIColorControls` + temperature + optional `CINoiseReduction` for `beauty` | legacy |
+
+Final intensity blend: `original.applyingFilter("CIDissolveTransition", inputTargetImage = effected, inputTime = clamp(intensity, 0, 1))`.
+
+Android mapping per effect type:
+- `CIColorControls`/`CIColorMatrix`/`CIHueAdjust` → fragment shader with uniforms (or Media3 `RgbFilter`, `RgbMatrix`, `HslAdjustment`).
+- `CIGaussianBlur` → two-pass separable Gaussian shader; or `RenderEffect.createBlurEffect` on API 31+.
+- `CIBloom` → high-pass + Gaussian + additive blend.
+- `CISharpenLuminance` → unsharp mask (`luma - blur(luma)` added back).
+- `CIPixellate` → quantize UV to block grid in shader.
+- `CIMotionBlur` → directional blur shader (sample N taps along angle).
+- `CIVignette` → radial falloff multiplied with RGB (port the Metal `openreelVignette` kernel below).
+- `CIRandomGenerator`+`CISoftLightBlendMode` (grain fallback) → port the Metal `openreelGrain` kernel directly.
+- `CIDisintegrateWithMaskTransition` → there is no direct Android equivalent; reproduce as alpha-keyed dissolve using a tiled noise texture and a shadow offset.
+- `CIColorCubeWithColorSpace` (32³, RGBA float) → use an OpenGL 3D texture (`GL_TEXTURE_3D`) with `RGBA32F` data and trilinear sampling, OR Media3's `SingleColorLut` / `Hdr10ToHdr10PlusEffect`-style lookup, OR androidx `androidx.media3.effect.SingleColorLut` (when 1D) — for 3D use `androidx.media3.effect.GlEffect` with a custom `GlShaderProgram`.
+
+---
+
+## 6. CustomEffectKernels (Metal)
+
+(`CustomEffectKernels.swift`) — three stitchable Metal kernels compiled at runtime via `CIKernel.kernels(withMetalString:)`. Each `apply` returns nil if the library failed to load, in which case the renderer falls back to a CIFilter equivalent.
+
+### `openreelGrain(sample_t image, float amount, float seed, destination dest) -> float4`
+- `dc = dest.coord()`
+- `monoNoise = (random(dc, seed) - 0.5) * amount * 0.22`
+- `blueNoise = (random(dc.yx, seed + 3.1) - 0.5) * amount * 0.08`
+- Output RGB clamped to `[0,1]`: `image.rgb + (monoNoise, monoNoise*0.9, monoNoise + blueNoise)`.
+- Random function: `fract(sin(dot(coord + float2(seed, seed*1.618), float2(12.9898, 78.233))) * 43758.5453)` — classic hash.
+
+### `openreelVignette(sample_t image, float amount, float radius, float2 center, destination dest) -> float4`
+- `distance = distance(dc, center)`
+- `edge = smoothstep(radius * 0.55, radius, distance)`
+- `mul = 1 - edge*amount`
+- Returns `(image.rgb * mul, image.a)`.
+
+### `openreelChromaticAberration(sampler image, float amount, float2 center, destination dest) -> float4`
+- `delta = dc - center`
+- `direction = normalize(delta)` (or zero at center)
+- `offset = direction * amount`
+- Sample: `red = sample(dc + offset)`, `green = sample(dc)`, `blue = sample(dc - offset)`.
+- Output `float4(red.r, green.g, blue.b, green.a)`.
+- ROI callback insets by `-amount` on both axes (so OpenGL/Vulkan port needs equivalent texture-coordinate padding).
+
+Android port: reimplement each as a GLES 3 fragment shader; the math is platform-agnostic. The hash function works identically in GLSL (use `fract`/`sin`/`dot`). For chromatic aberration, set texture wrap to `GL_CLAMP_TO_EDGE`.
+
+---
+
+## 7. TransitionCompositor
+
+(`TransitionCompositor.swift`)
+
+Public entry: `apply(outgoing:incoming:transition:progress:) -> CIImage`. Progress comes from `TransitionVideoCompositor.transitionProgress(at:in:)` = `(time - timeRange.start) / timeRange.duration`, clamped to [0,1].
+
+Easing: `EasingFunctions.value(for: params["curve"] ?? "linear", progress:)` — the curve string is passed through; concrete curves are defined in `EasingFunctions` (see misc-effects doc for the catalog). Both raw and eased progress are clamped to [0,1].
+
+Type dispatch (`TransitionCatalog.sanitizedType(...)`). Each implementation:
+
+| Type | Math / Behavior | Parameters (defaults) |
+|---|---|---|
+| `crossfade` | `incoming.alpha = p` over `outgoing.alpha = 1-p`, composited. | — |
+| `dipToBlack` | 3-phase: fade `outgoing → black` over `1/(2+hold)`, hold black for `hold/(2+hold)`, fade `black → incoming` over the rest. | `holdDuration: 0.1` |
+| `dipToWhite` | Same as dipToBlack but with white. | `holdDuration: 0.1` |
+| `wipe` | Reveal incoming inside a rectangular sub-region growing from one edge. | `direction: "left"|"right"|"up"|"down"` (default `"left"`) |
+| `slide` | Translate incoming in from a direction; if `pushOut`, outgoing slides out the opposite way. | `direction`, `pushOut: false` |
+| `push` | Same as `slide` with `pushOut: true`. | `direction` |
+| `zoom` | Outgoing scales from 1 to `scale` with alpha 1→0; incoming scales from `1/scale` to 1 with alpha 0→1. Both around `center`. | `scale: 2` (clamped 1.01–6), `center: {x:0.5, y:0.5}` |
+| `blurDissolve` | Both layers gaussian-blurred with sigma `maxRadius * sin(progress*π) * (1-progress)*2` (outgoing) and `* progress*2` (incoming), cross-faded. | `maxRadius: 20` |
+| `iris` | CIRadialGradient mask: `currentRadius = diagonal/2 * progress`, inner = `currentRadius - softness*diagonal/2`. CIBlendWithMask of incoming over outgoing. | `center: {0.5,0.5}`, `softness: 0.02` |
+| `spin` | Two-phase: out spins by `progress*rotations*2π` with scale `1 - 0.3*sin(progress*π)`, alpha `1-progress*2`; after midpoint, in spins from `-(1-progress)*rotations*2π` to 0 with `(progress-0.5)*2` alpha. | `rotations: 1` |
+| `glitch` | Slice screen into `slices` horizontal bands, each translated by `sin(seed*13.7)*cos(seed*5.3) * w*intensity*0.3 * sin(crossProgress*π)`. Source = outgoing for `p<0.5`, incoming for `p>=0.5`. Mid-range (`0.3<p<0.7`) adds RGB-split overlay using three `CIColorMatrix` channel isolations translated by `±maxOffset*0.3*sin(p*2π)`. | `intensity: 0.5`, `slices: 8` |
+| `pixelate` | `pixelSize = maxBlockSize * sin(p*π)`. `p<0.5`: pixellate outgoing. Else: pixellate incoming. | `maxBlockSize: 40` |
+| `lumaFade` | Convert outgoing to mono via `CIPhotoEffectMono`. Build a luminance ramp: `rampVector = (-low/range, 1/range, 0, 0)` where `low = p-softness`, `high = p+softness`, `range = high-low`. CIBlendWithMask incoming over outgoing using ramped (and optionally inverted) mono mask. | `invert: false`, `softness: 0.3` |
+| (default) | falls back to `crossfade` | — |
+
+Duration handling: transition extent in the composition timeline is `[boundary - duration/2, boundary + duration/2]` where `boundary = outgoing.startTime + outgoing.duration`. Practically, transitions consume half their length from each adjoining clip.
+
+Helper geometry:
+- `centerPoint(from:in:)` reads normalized `{x,y}` ∈ [0,1], maps to extent.
+- `opacity(_:alpha:)` is an alpha-only `CIColorMatrix`.
+- `scaleImage(_:scale:center:)` is affine `translate(c) · scale · translate(-c)`.
+
+Android mapping: each transition is a small fragment shader. Slide/push/wipe are texture-coordinate gates. Iris is a smoothstep-based mask. Glitch needs a noise hash and band-row sampling. Pixelate uses `floor(uv * blocks) / blocks`. lumaFade extracts luma `dot(rgb, vec3(0.2126, 0.7152, 0.0722))` then ramps via `smoothstep(low, high, luma)`. Spin needs vertex-shader rotation, or premultiplied matrix in a fullscreen tri.
+
+---
+
+## 8. ColorScopesEngine
+
+(`ColorScopesEngine.swift`)
+
+Purpose: produce a `ColorScopesSnapshot { waveform: [ColorScopePoint], vectorscope: [ColorScopePoint] }` for overlay UI.
+
+Inputs:
+- `snapshot(cgImage:targetWidth:targetHeight:maximumSamples:)` — draws CGImage into a fixed 160×90 RGBA8 bitmap (DeviceRGB), interpolation `.low`, then iterates pixels.
+- `snapshot(pixels:width:height:maximumSamples:)` — direct pixel-array path.
+
+Sampling: stride = `max(1, sqrt(width*height / maximumSamples))` (default `maximumSamples = 1400`). Pixels with `alpha == 0` skipped.
+
+Per pixel:
+- `red, green, blue = byte / 255`
+- `luma = 0.2126R + 0.7152G + 0.0722B` (BT.709)
+- `chromaBlue = (B - luma) * 0.565`
+- `chromaRed = (R - luma) * 0.713`
+
+Outputs:
+- Waveform point: `(x / (w-1), 1 - clamp(luma, 0, 1))` — x is pixel column normalized, y inverted so brightness goes up.
+- Vectorscope point: `(0.5 + chromaBlue, 0.5 - chromaRed)` clamped to [0,1].
+
+The Metal preview view calls `snapshot(cgImage:)` every 8 frames (`frameCounter % 8 == 0`) and dispatches to main via the `scopesUpdate` callback. The still-image renderer calls it once after each render.
+
+No histogram is computed — Openreel currently only has waveform + vectorscope. (RGB histograms can be added by binning luma & per-channel values into 256 buckets.)
+
+Android mapping: identical math; downsample frame to 160×90 via OpenGL FBO or `Bitmap.createScaledBitmap`, read back via `glReadPixels` (or `PixelCopy.request` for a Surface), compute on a worker thread. Use BT.709 coefficients verbatim.
+
+---
+
+## 9. CubeLUTParser
+
+(`CubeLUTParser.swift`)
+
+Format support: Adobe `.cube` 3D LUT text files (UTF-8).
+
+Grammar accepted:
+- Lines starting with `#` or blank are skipped.
+- `TITLE "..."` — optional, quotes stripped.
+- `LUT_3D_SIZE N` — required. N must be in `2...128`.
+- `DOMAIN_MIN r g b` — optional, default `[0,0,0]`.
+- `DOMAIN_MAX r g b` — optional, default `[1,1,1]`.
+- `LUT_1D_*` and any other `LUT_*` directive → throws `unsupportedDimension`.
+- Otherwise: 3 space/tab-separated floats per sample, each in `[0,1]`.
+
+Sample ordering follows the standard cube convention: red varies fastest, then green, then blue:
+```
+for blueIndex in 0..<N:
+ for greenIndex in 0..<N:
+ for redIndex in 0..<N:
+ append sample
+```
+Total samples must equal `N^3` or `invalidSampleCount` is thrown.
+
+Output: `CubeLUT { title, size, domainMin, domainMax, samples: [Sample{r,g,b}] }`.
+
+### Color Grading Pipeline (LUT application)
+1. `applyLUT` reads `EffectLUTReference` from params (`name`, `path`, `size`, `domainMin`, `domainMax`, `checksum`, `intensity`).
+2. Cache key = `"\(path)|\(checksum)"`. Cube data is cached as `(dimension: Int, data: Data)` in `VideoEffectRenderer.cubeCache` under an `NSLock`.
+3. Load file from `projectDirectoryURL.appendingPathComponent(reference.path)`, parse via `CubeLUTParser.parse(data:)`.
+4. Convert samples to `Data` of float-quads (RGBA, alpha = 1): little-endian Float32 stream.
+5. Apply via `CIColorCubeWithColorSpace` with `inputCubeDimension`, `inputCubeData`, `inputColorSpace = CGColorSpaceCreateDeviceRGB()`.
+6. Wrap the resulting image into the global `intensity` dissolve like every other effect.
+
+Note: the iOS code does **not** apply `domainMin`/`domainMax` remapping itself (it relies on CIColorCubeWithColorSpace's default [0,1] domain). If your LUT has a non-default domain, you must pre-remap input colors yourself.
+
+Android mapping:
+- Parse `.cube` with the same grammar (any Kotlin parser will do).
+- Upload as `GL_TEXTURE_3D`, `internalformat = GL_RGB16F` or `GL_RGBA16F`, with `GL_LINEAR` mag/min filter, `GL_CLAMP_TO_EDGE` wraps on all three axes.
+- In fragment shader: `outColor.rgb = texture(uLut, inColor.rgb).rgb;` with a tiny half-texel inset (`(0.5 + idx) / N`) to avoid edge bleed.
+- Cache parsed LUTs by `(path, checksum)` like iOS.
+- Libraries: roll your own (the parser is ~150 lines); alternatively `com.gpuimage:gpuimage-library` has 3D LUT support, or use Media3's effect API to wrap a custom `GlShaderProgram`.
+
+---
+
+## 10. EffectParameterCodec
+
+(`EffectParameterCodec.swift`) — JSON ↔ runtime helpers.
+
+Types:
+- `EffectCurvePoint { x, y: Double }` — both clamped to [0,1].
+- `EffectLUTReference { name, path, size, domainMin, domainMax, checksum, intensity, byteCount }`.
+
+Defaults:
+- `defaultCurvePoints` = `[{0,0}, {1,1}]` (identity).
+- `defaultDomainMin` = `[0,0,0]`, `defaultDomainMax` = `[1,1,1]`.
+
+Encoding helpers (used when building `defaultParams` or persisting):
+- `number(value, lowerBound, upperBound)` — clamp and wrap as `.number`.
+- `numberArray(values, count, fallback, lower, upper)` — pad/truncate to fixed length, clamp each.
+- `colorObject(r,g,b)` — `{"r": …, "g": …, "b": …}`, each clamped −1 … 1.
+- `pointObject(EffectCurvePoint)` — `{"x": …, "y": …}`.
+- `curveArray([Point])` — array of point objects, defaulting to identity.
+- `curvesParams(rgb,red,green,blue)` — full curves payload.
+- `hslParams(hue,saturation,luminance)` — three length-8 arrays. Hue clamped −180 … 180; sat/lum clamped −1 … 1.
+- `lutParams(reference:)` — full LUT payload with `byteCount` becoming `.null` if absent.
+
+Decoding helpers:
+- `curvePoints(from:params, key:)` — extracts an array of `{x,y}` objects; clamps each to [0,1]; falls back to identity if missing/empty; **always returned sorted by `x`**.
+- `lutReference(from:)` — requires `name`, `path`, `checksum`, `size > 1`. Intensity clamped 0…1.
+
+`JSONValue` extensions: `boolValue`, `objectValue`, `arrayValue`, `doubleArrayValue(count:)` (returns nil if length mismatch).
+
+Persistence contract: the renderer reads these via `effect.params["…"]?.doubleValue` etc. All effect params should round-trip through JSON exactly; Android port must serialize numeric arrays as JSON arrays, not delimited strings.
+
+---
+
+## 11. StillImageEffectRenderer
+
+(`StillImageEffectRenderer.swift`, `EffectImageView.swift`)
+
+Image-vs-video differences:
+
+| Concern | Video (MetalVideoView) | Image (StillImageEffectRenderer + EffectImageView) |
+|---|---|---|
+| Source | `AVPlayerItemVideoOutput` → `CVPixelBuffer` → `CIImage` | `CIImage(contentsOf:)`, falling back to `UIImage` → `CGImage` → `CIImage` |
+| Render trigger | MTKView delegate `draw(in:)` ~30 fps | `.task(id: renderKey)` — runs once per parameter change |
+| Effect chain | Same `VideoEffectRenderer.render(_:effects:projectDirectoryURL:timelineTime:effectContext:)` | Same renderer, but `timelineTime = 0` and no `effectContext` (AI not run on stills). |
+| AI context | Background `MediaAnalysisService` task per frame | Not applied (stills don't request `FrameEffectContext`). |
+| Color scopes | Sampled every 8th frame from the rendered CIImage | Sampled once after each render via `ColorScopesEngine.snapshot(cgImage:)` |
+| Output | Drawn directly to MTLDrawable texture | `CIContext.createCGImage` → `UIImage` → SwiftUI `Image.scaledToFit()` |
+| Color space | `CGColorSpaceCreateDeviceRGB()` | `CGColorSpaceCreateDeviceRGB()` (same) |
+| Cache key | derived from clip+frameIndex+effects | `renderKey = imageURL.path | projectDir | sortedEffectsSignature` (recomputes whenever any param changes) |
+
+EffectImageView signature builder: `id#type#enabled#sortedKey=value,sortedKey=value`.
+
+`StillImageEffectRenderer.render` constructs a fresh `CIContext` (Metal-backed if available, else CPU) per call — there is no global cache. Returned tuple includes both the rendered `UIImage?` and a `ColorScopesSnapshot` for the scopes overlay.
+
+Android mapping:
+- Decode source via `BitmapFactory.decodeFile` or `ImageDecoder`.
+- Run the same effect pipeline as video (the GLES context can render to an offscreen FBO, then `glReadPixels` into a `Bitmap`).
+- Skip AI-frame-context effects (background removal, subject blur, face beauty) on stills only if you intentionally want video-only AI; otherwise replicate with `androidx.camera.mlkit` segmentation on the still bitmap.
+- Use `Image.asImageBitmap()` if rendering through Compose.
+
+---
+
+## 12. MetalVideoView
+
+(`MetalVideoView.swift`)
+
+Surface:
+- `MTKView` with `device = MTLCreateSystemDefaultDevice()`, `colorPixelFormat = .bgra8Unorm`, `clearColor = (0,0,0,1)`, `framebufferOnly = false` (required because we render via `CIContext.render(_:to:)`), `enableSetNeedsDisplay = false`, `isPaused = false`, `preferredFramesPerSecond = 30`.
+- Backed by a single `MTLCommandQueue` per view.
+- `CIContext(mtlDevice:)` shared with the `VideoEffectRenderer`.
+- Color space: `CGColorSpaceCreateDeviceRGB()` for both render and scopes.
+- HDR: not handled. Pixel buffer attributes request `kCVPixelFormatType_32BGRA` + `kCVPixelBufferMetalCompatibilityKey: true`. HDR10/HLG sources would be tone-mapped to SDR by the BGRA conversion AVPlayerItemVideoOutput performs. There's no PQ or HLG-aware path.
+
+Frame pump:
+1. `installVideoOutput()` attaches an `AVPlayerItemVideoOutput` to the current item.
+2. `currentFrame()` chooses the time: if paused, use `player.currentTime()`; else `videoOutput.itemTime(forHostTime: CACurrentMediaTime())`. If a new pixel buffer is available, copy it into `lastFrame`. If `lastFrame` is nil, force a copy regardless.
+3. `draw(in:)` runs the effect renderer, applies aspect-fit scale/translate to the drawable's bounds (`aspectFitImage(_:in:)`), renders via `CIContext.render(_:to: drawable.texture, commandBuffer:, bounds:, colorSpace:)`, presents the drawable.
+
+Aspect-fit: uniform scale by `min(bounds.w/extent.w, bounds.h/extent.h)`, centered with letterboxing, composited over a black background sized to bounds. Always crops to bounds before presenting.
+
+AI context cache (for background removal, subject blur/glow, face beauty, etc.):
+- Cache key = `clipID|mediaID|frameIndex|descriptorSignature` where `frameIndex = round(sourceTime * frameRate)`.
+- `aiContextTask` is a `Task(priority: .utility)` that calls `AIFrameContextBuilder.frameContext(...)` with the current `CVPixelBuffer`.
+- On completion (on main actor), if the pending key still matches, store the context and call `metalView.draw()` again to repaint with masks/tracking applied.
+- `setPlayer`, `setClip`, `setEffects` all `resetAIContext()` to drop stale results.
+
+Scopes update: every 8 frames (`frameCounter % 8 == 0`) creates a `CGImage` from the rendered `CIImage` (format `.RGBA8`) and dispatches `ColorScopesEngine.snapshot(cgImage:)` result to the callback on main.
+
+Android mapping:
+- `SurfaceView` or `TextureView` backed by an `EGLContext`/`GLES30`.
+- Pull frames via `MediaCodec` + `SurfaceTexture.updateTexImage()` (`SurfaceTexture.OnFrameAvailableListener`), or for Media3 use a `VideoFrameProcessor`.
+- Apply effect chain in a single FBO ping-pong, then blit aspect-fit to default framebuffer.
+- For HDR support on Android, request `ColorSpace.Named.BT2020_HLG` and use `HardwareBuffer` + `ImageReader` with `HardwareBuffer.YCBCR_P010`; pipe through `androidx.media3.effect.HdrToSdr*` or custom tone-mapping. Out of scope for v1 — match iOS by forcing SDR sRGB.
+
+---
+
+## 13. Android Mapping Summary
+
+### Player Stack
+- **AVPlayer → ExoPlayer** (`androidx.media3.exoplayer.ExoPlayer`).
+- **AVMutableComposition → `androidx.media3.transformer.Composition`** or hand-rolled `ConcatenatingMediaSource2`. Two-track parity rule for transitions must be implemented (`EditedMediaItemSequence` × 2 if using Transformer/Composition).
+- **AVMutableAudioMix → `AudioProcessor` chain** with sample-accurate envelope; or per-`EditedMediaItem` `AudioEffectsProvider`.
+- **AVMutableVideoComposition + custom compositor → `androidx.media3.effect.GlEffect`** chain (overlay/transition shaders), or process the dual-track output with a `OverlaySettings`/`OverlayEffect` per time range.
+
+### Display
+- **MTKView + CIContext → `androidx.media3.ui.PlayerView` with `SurfaceView`** (preview), plus a sibling `GLSurfaceView` that consumes `SurfaceTexture` for effect post-processing. Or use Media3's `VideoFrameProcessor` (single-pipe).
+
+### Effect Implementation
+- All `CIFilter`-based effects can be ported as GLES 3.0 fragment shaders. The shader math is in §5 and §7 above.
+- LUTs: `GL_TEXTURE_3D` + `GL_LINEAR` (see §9). Libraries: avoid; the parser is trivial and 3D textures are well-supported on API 21+.
+- Custom Metal kernels (grain, vignette, chromatic aberration): direct GLSL port — code in §6, math is unchanged.
+- AI-driven effects (`backgroundRemoval`, `subjectBlur`, `subjectGlow`, `faceBeauty`, tracking-based effects): use ML Kit (`com.google.mlkit:segmentation-selfie`, `com.google.mlkit:face-detection`) or MediaPipe. Wrap in the same per-frame cache pattern (debounced by `frameIndex`).
+
+### Per-Effect Library/Approach Choice
+
+| Effect | Suggested Android implementation |
+|---|---|
+| brightness, contrast, saturation | Media3 `RgbAdjustment` / `RgbMatrix` / `HslAdjustment`, or single uniform fragment shader |
+| temperature | Custom shader with the hand-tuned R/G/B/Bias matrix from §5 |
+| hue | `HslAdjustment` (hueAdjustmentDegrees) |
+| blur (gaussian) | Two-pass separable shader; `RenderEffect.createBlurEffect` for static cases |
+| sharpen | Unsharp mask shader |
+| vignette | Port `openreelVignette` GLSL |
+| grain | Port `openreelGrain` GLSL (identical hash function) |
+| chromaticAberration | Port `openreelChromaticAberration` GLSL |
+| bloom | Threshold + Gaussian + additive blend in a 2-pass `GlEffect` |
+| pixelate | UV quantize shader |
+| motionBlur | Directional blur shader (N taps) |
+| dissolve | Alpha multiply in shader |
+| disintegrate | Noise-keyed alpha threshold + shadow; custom shader |
+| stabilize | Affine on GLES vertex; tracking via `MotionDataSource` or precomputed paths |
+| motionTrack/faceTrack/objectTrack/bodyPose | ML Kit feature detectors, exported as `TrackingPath` (no visual effect) |
+| backgroundRemoval | ML Kit Selfie Segmentation |
+| subjectBlur / subjectGlow | Segmentation mask + Gaussian blur composited |
+| faceBeauty | ML Kit face detection + denoise + soft sharpen + temperature; mask blend by face bbox |
+| autoReframe | Tracking + crop matrix on draw |
+| colorWheels | Custom shader: lift+gamma+gain |
+| curves | Bake to 3D texture (32³) the same way iOS does — port the cube data writer |
+| hsl | Bake to 3D texture using identical HSL/RGB conversion |
+| lut | `GL_TEXTURE_3D` with trilinear sampling, cached by `(path,checksum)` |
+| filterPreset / colorAdjust (legacy) | Compound shader = contrast+sat+temperature(+beauty for colorAdjust) |
+| chromaticAberration | (see above) |
+| Transitions: crossfade, dipToBlack/White, wipe, slide, push, zoom, blurDissolve, iris, spin, glitch, pixelate, lumaFade | Per-transition fragment shader; dispatcher mirrors `TransitionCatalog.sanitizedType`. |
+
+### LUT Libraries (Android)
+- Roll-your-own with `GLES30.glTexImage3D` — recommended; it's <100 lines and matches iOS exactly.
+- `jp.co.cyberagent.android:gpuimage:2.x` has `GPUImage3DLookupFilter` (1D atlas LUT; less precise than 3D texture).
+- Avoid bitmap-strip "HALD" LUTs unless you also support them in iOS (Openreel does not).
+
+### Color Space
+- Match iOS exactly: linearize sRGB → operate → encode back to sRGB. Use `GL_FRAMEBUFFER_SRGB` extension or do gamma manually with `pow(rgb, 2.2)` / `pow(rgb, 1/2.2)`.
+- BT.709 luma coefficients (0.2126, 0.7152, 0.0722) are non-negotiable for scopes and luma-keyed transitions.
+- HDR is unsupported on iOS today; do not introduce it on Android without parity work.
+
+### Frame Pump Timing
+- Match iOS's behavior: scopes recomputed every 8 frames; AI context debounced per `frameIndex = round(sourceTime * frameRate)`. Use Kotlin coroutines with `Dispatchers.Default` (utility-priority equivalent) and cancel on parameter changes.
+
+### Project Directory Resolution
+- iOS resolves LUT paths against `projectDirectoryURL`. Android must mirror this: resolve `effect.params["path"]` against the project's app-private storage directory (not the LUT's absolute path).
+
+---
+
+### File Index
+- `Openreel Video/Openreel Video/Core/Playback/PlaybackController.swift`
+- `Openreel Video/Openreel Video/Core/Playback/PlaybackCompositionBuilder.swift`
+- `Openreel Video/Openreel Video/Core/Rendering/VideoEffectRenderer.swift`
+- `Openreel Video/Openreel Video/Core/Rendering/CustomEffectKernels.swift`
+- `Openreel Video/Openreel Video/Core/Rendering/StillImageEffectRenderer.swift`
+- `Openreel Video/Openreel Video/Core/Rendering/TransitionCompositor.swift`
+- `Openreel Video/Openreel Video/Core/Rendering/ColorScopesEngine.swift`
+- `Openreel Video/Openreel Video/Core/Effects/CubeLUTParser.swift`
+- `Openreel Video/Openreel Video/Core/Effects/EffectParameterCodec.swift`
+- `Openreel Video/Openreel Video/Core/Effects/VideoEffectTypes.swift`
+- `Openreel Video/Openreel Video/Features/Preview/MetalVideoView.swift`
+- `Openreel Video/Openreel Video/Features/Preview/EffectImageView.swift`
diff --git a/docs/android-port/05-features-media-text-audio.md b/docs/android-port/05-features-media-text-audio.md
new file mode 100644
index 00000000..c01331d5
--- /dev/null
+++ b/docs/android-port/05-features-media-text-audio.md
@@ -0,0 +1,675 @@
+# 05 — Feature Panels: Media, Text, Audio
+
+> **Offline architecture (2026-08-08):** The retired remote-tool sheets and job client
+> are removed. This document describes only shipping local features.
+
+This document is an exhaustive 1:1 spec of the Media, Text, and Audio editor panels in the iOS app "Openreel Video" so that Android engineers can rebuild it in Kotlin/Compose. Every panel row, sheet, slider range, default, swatch, picker flow, and permission is captured here. Where a number, hex code, range, or text label appears below, it must be reproduced verbatim.
+
+Common visual scaffolding (used by every panel):
+
+- `EditorPanelContainer(title, subtitle, symbol, onBack)` — title/back-button header strip at the top of every panel.
+- `EditorMenuRow(title, subtitle, symbol, accentColor?, showsDisclosure=true, isEnabled=true, action)` — a tappable list row. The default look is an icon tile (~32x32, 10pt corner) + 2-line text + optional chevron.
+- `PanelActionTile(title, subtitle, symbol, action)` — a square card for grid layouts (118pt min height, 12pt padding, 12pt radius, white opacity 0.06 border).
+- `PresetGridCard(title, subtitle, symbol, isSelected, accentColor, action)` — selectable grid card.
+- `CompactSliderRow(label, value, range, format?, onChange)` — horizontal slider with leading label and trailing formatted value.
+- `SwatchButton(hex, isSelected, action)` — color swatch chip.
+- Grid columns everywhere: `[GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)]` — i.e. two equal columns with 10pt spacing.
+- All sheets present at `.fraction(0.5)` detent with a drag indicator and `.ultraThinMaterial` background.
+- Haptics: `UIImpactFeedbackGenerator(style: .light)` on most tappable tiles/rows; `.medium` when starting a run; `UINotificationFeedbackGenerator` `.success`/`.error` on completed local operations.
+
+Theme tokens referenced repeatedly:
+
+- `OpenReelTheme.accent` — accent color used for highlights, active swatches, "Add to Timeline" buttons.
+- `OpenReelTheme.destructive` — red used for delete/cancel actions.
+- `OpenReelTheme.textPrimary`, `OpenReelTheme.textSecondary` — text foreground colors.
+- `OpenReelTheme.background`, `OpenReelTheme.surface`, `OpenReelTheme.surfaceElevated` — backgrounds.
+
+Android mapping (global):
+
+- `EditorPanelContainer` → Compose `Scaffold` with a custom top header row (IconButton back + title/subtitle/symbol).
+- `EditorMenuRow` → `ListItem` with leading icon (24-32dp), title (14sp bold), subtitle (11sp medium), trailing chevron when `showsDisclosure`.
+- `PanelActionTile`/`PresetGridCard` → `Card` (`RoundedCornerShape(12.dp)`, 1dp white 6% border) inside `LazyVerticalGrid(GridCells.Fixed(2), spacing 10.dp)`.
+- `CompactSliderRow` → Material 3 `Slider` with leading `Text` and trailing value text.
+- `SwatchButton` → small circular `Box` tinted via `Color(android.graphics.Color.parseColor(hex))`.
+- Sheets at fraction(0.5) → `ModalBottomSheet` with `skipPartiallyExpanded = false`, half-expanded by default. Background can be the closest analogue to ultraThinMaterial (translucent blur).
+- Haptics → `HapticFeedback.LocalHapticFeedback` for light/medium taps; `Vibrator` for success/error patterns.
+
+---
+
+## 1. Media Panel (`MediaTabPanel`)
+
+### 1.1 Header
+
+- Title: `Media`
+- Subtitle: `Import, preview, and place clips`
+- Symbol: `photo.on.rectangle` (Android: `R.drawable.ic_photo_on_rectangle` or Material `PhotoLibrary`).
+
+### 1.2 Layout (top to bottom, single `ScrollView`, 16pt vertical spacing)
+
+All rows are `EditorMenuRow` instances:
+
+1. **Photos** — symbol `photo.stack`. Subtitle `Import videos and images from Photos`. `showsDisclosure = false`. Tap → opens fullScreen `MediaPicker` (PHPickerViewController).
+2. **Camera** — symbol `camera.fill`. Subtitle `Record or capture new media`. `showsDisclosure = false`. Tap → fullScreen `CameraCaptureView` (UIImagePickerController).
+3. **Files** — symbol `folder.fill`. Subtitle `Import video, image, or audio files`. `showsDisclosure = false`. Tap → sheet `DocumentMediaPicker` (UIDocumentPickerViewController).
+4. **Selected Item** — symbol `target`. Subtitle = name of the currently selected media item, fallback `Preview selection`. `showsDisclosure = false`. Disabled when `appState.selectedMediaItem == nil`. Tap → opens `MediaPreviewSheet` for that item.
+5. **Project Media** — symbol `rectangle.stack`. Subtitle `Browse {N} imported items` where N = `appState.availableProjectMedia(in: project).count`. Tap → Project Media sheet (see 1.6).
+
+Bottom padding: 10pt.
+
+### 1.3 PHPicker Photos flow (`MediaPicker.swift`)
+
+Configuration:
+
+- `PHPickerConfiguration(photoLibrary: .shared())`
+- `filter = .any(of: [.videos, .images, .livePhotos])`
+- `selectionLimit = 0` (unlimited)
+- `preferredAssetRepresentationMode = .current`
+- `selection = .ordered`
+
+Result handling:
+
+- For each `PHPickerResult`, the loader probes UTIs in this priority: `UTType.movie` → `UTType.video` → `UTType.image` → `UTType.audio`.
+- File is loaded via `NSItemProvider.loadFileRepresentation`, then copied into `NSTemporaryDirectory()/<UUID>.<ext>` and wrapped as `ImportedMediaAsset(sourceURL, fileName, assetIdentifier, mediaType)`.
+- File name is taken from `provider.suggestedName`; if missing extension, falls back to source URL extension or `UTType.preferredFilenameExtension`.
+
+Errors:
+
+- `MediaPickerError.unsupportedType` → "The selected file type is not supported." (silent — view falls back to cancel).
+
+Permissions iOS: PhotoKit (`NSPhotoLibraryUsageDescription`).
+
+Android mapping:
+
+- `androidx.activity.result.PickVisualMedia` with `PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo)` for modern photo picker (Android 13+), or `PickMultipleVisualMedia` for unlimited selection.
+- Copy the returned `Uri` content into app cache (`context.cacheDir`) so the editor has a stable file URL.
+- Detect MIME via `ContentResolver.getType(uri)` then dispatch image/video/audio.
+- Permissions: on Android 14+ use the photo picker with no runtime permission; on older use `READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`, `READ_MEDIA_AUDIO` (Android 13) or `READ_EXTERNAL_STORAGE` (Android <=12).
+
+### 1.4 Camera flow (`CameraCaptureView` in `MediaInputViews.swift`)
+
+- Uses `UIImagePickerController` with `sourceType = .camera` (falls back to `.photoLibrary` if camera unavailable).
+- `mediaTypes = [UTType.movie.identifier, UTType.image.identifier]` — captures both photos and videos.
+- `videoQuality = .typeHigh`.
+- Captured video → copied to `NSTemporaryDirectory()/Camera-<unix>.mov` and emitted as `ImportedMediaAsset(mediaType: .video)`.
+- Captured still → JPEG, compression quality 0.9, file `Camera-<unix>.jpg`, emitted as `ImportedMediaAsset(mediaType: .image)`.
+
+Permissions iOS: `NSCameraUsageDescription`, `NSMicrophoneUsageDescription`.
+
+Android mapping:
+
+- For full feature parity (resolution control, both video/photo modes), use **CameraX** (`androidx.camera.*`) with `ImageCapture` + `VideoCapture` use cases. For a simpler flow, use `ActivityResultContracts.TakePicture` and `ActivityResultContracts.CaptureVideo`, but those don't expose quality settings.
+- Permissions: `CAMERA`, `RECORD_AUDIO` (for video).
+
+### 1.5 Document picker (`DocumentMediaPicker`)
+
+- `UIDocumentPickerViewController(forOpeningContentTypes: [.movie, .video, .image, .audio, .mpeg4Movie, .quickTimeMovie, .mp3, .wav, .mpeg4Audio], asCopy: true)`.
+- `allowsMultipleSelection = true`.
+- For each picked URL: calls `startAccessingSecurityScopedResource`, copies to `NSTemporaryDirectory()/<UUID>.<ext>`, infers `ImportedMediaType` from the file extension's `UTType` (audio → audio, image → image, else video).
+
+Android mapping:
+
+- `ActivityResultContracts.OpenMultipleDocuments` with MIME filters `video/*`, `image/*`, `audio/*`.
+- Persist via `ContentResolver.openInputStream` + copy to cache.
+
+### 1.6 On-device smart-tool placement
+
+The Media panel has no generic smart-tool sheet and no job progress UI. Import,
+preview, and project-library actions stay here. Clip-specific on-device Vision,
+tracking, reframe, stabilization, and background tools live in the Effects
+panel. Local highlight/shorts generation lives with export/publishing tools.
+
+### 1.7 Project Media sheet
+
+Header HStack: `Project Media` (14pt bold rounded) on left, count (12pt monospaced bold accent) on right.
+
+Empty state card (when `mediaItems.isEmpty`):
+
+- `rectangle.stack.badge.plus` icon (28pt accent).
+- Text: `Import something to start building the timeline.`
+- 28pt vertical padding, 14pt corner card.
+
+Non-empty: 2-column `LazyVGrid` of `mediaCard` tiles. Each card:
+
+- Aspect ratio thumbnail (16:10, fill, clipped).
+- Top-left circular accent badge (24x24) with media type symbol (video=`film.stack`, audio=`waveform`, image=`photo`).
+- Bottom-right time pill (`mediaItem.metadata.duration.shortClock()`, 10pt monospaced bold white on black 65% capsule).
+- Top-right `In Use` pill (9pt bold rounded white on accent 92% capsule) when the clip is on the timeline.
+- Below thumbnail: name (12pt semibold rounded, 1 line) + detail line (10pt medium):
+ - Audio: `{CODEC} · {sampleRate/1000} kHz`
+ - Video/Image: `{width}x{height} · {CODEC}`
+- For audio items, thumbnail is a waveform: 24 capsules of width 4pt, height `max(8, sample * 44)`, accent 75% color, drawn over `surfaceElevated` rounded rect (10pt corner).
+- Tap → opens `MediaPreviewSheet` for that item.
+
+Android mapping: same layout via `Card { Column { Box(thumb) ... Text(name) Text(detail) } }`. For audio waveform use a `Row { repeat(24) { Box(width=4.dp, height=peakDp) } }`.
+
+### 1.8 MediaPreviewSheet (presented when a media item is tapped)
+
+Container: `EditorPanelContainer(title = mediaItem.name, subtitle = "{duration} · {WxH or Audio} · {CODEC}", symbol per type)`.
+
+Body VStack (16pt spacing):
+
+- Preview surface:
+ - Video: `AVPlayer + VideoPlayer`; aspect ratio = `width/height` (clamped >=1px). Player created `onAppear`, paused/nilled `onDisappear`.
+ - Image: `UIImage(contentsOfFile:)`, resizable, scaledToFit. Falls back to `AsyncImage` of thumbnail URL.
+ - Audio: vertical waveform of `waveformSamples` (48 capsules, width 4pt, height `max(10, sample * 76)`, accent 85%), with a circular accent play/pause button (42x42) below. Toggles `AVPlayer.play/pause`.
+- "Add to Timeline" button — full width, accent background, 14pt corner, height 13pt padding vertical, 15pt bold rounded text, white `plus.circle.fill` icon. Calls `appState.addMediaItemToTimeline(at: playbackController.currentTime)`.
+- For images only: secondary "Add as Graphic Overlay" button — `square.on.square.squareshape.controlhandles` icon, surfaceElevated background. Calls `appState.addGraphicsImageClip(...)`.
+
+Aspect ratio for audio preview surface: 16:5.
+
+Android mapping: `ExoPlayer` (`media3`) for video; `Image` + Coil for stills; custom drawn waveform with `Canvas`.
+
+### 1.9 Import behavior (`MediaImportService`)
+
+- Imports run in an `actor`. Each `ImportedMediaAsset` is processed by `prepareImported{Video|Image|Audio}` which:
+ - **Video**: loads `AVURLAsset`, the first video track, duration, naturalSize, preferredTransform, nominalFrameRate, format descriptions, audio track count. Derives width/height after applying preferredTransform. Frame rate defaults to 30 if unknown. Codec is 4CC of subtype. Generates a JPEG poster (`AVAssetImageGenerator`, max 720x720, quality 0.82) and a filmstrip of `max(4, min(8, ceil(duration)))` evenly spaced frames. Persists media + thumbnails to project store. Volume defaults to 1.0, fitMode `.contain`, position `(0.5,0.5)`, scale `(1,1)`.
+ - **Image**: reads `UIImage`, width/height = `size × scale`. JPEG thumbnail quality 0.82. Default placed `duration = 5.0s`. Volume = 0.
+ - **Audio**: reads `AVAudioFile` for sample rate + channel count (fallback 44100/1 or 48000/2). Codec stored as `"aac"`. Generates 48-sample waveform via PCM peak buckets, normalized + clamped to `[0.08, 1]`. Volume = 1.
+
+- Insertion strategy: appends to the appropriate track (`video`, `image` or fallback to video, `audio`). New clips start at `max(existing clip end times, 0)`. Timeline duration extended accordingly.
+
+Android mapping: use **MediaMetadataRetriever** for duration/codec/dimensions, **MediaExtractor** for codec/sample rate, **MediaPlayer**/Exo for playback. Generate frame thumbnails with `MediaMetadataRetriever.getFrameAtTime(timeUs)` or `MediaCodec`+`ImageReader`. Persist into app's private storage (`Context.filesDir/projects/<id>/media/...`).
+
+### 1.10 Photo tools
+
+The former remote Photo Enhancement screen is not part of the shipping mobile
+UI. Still images use the normal local Effects controls and render path. Do not
+expose restore, object erase, arbitrary upscale, or generative cleanup buttons
+until a fully bundled implementation exists.
+
+---
+
+## 2. Text Panel (`TextTabPanel`)
+
+### 2.1 Modes
+
+The same panel renders in two modes:
+
+- `mode = .add` — when adding text to the timeline.
+- `mode = .edit` — when a text clip is selected. If the selected text clip belongs to the subtitle/caption track (`appState.isEditingSubtitleTrack` and clip is in `appState.subtitleTextClips()`), the panel enters the **caption track editor**. Otherwise it shows the **single text clip editor**.
+
+Title/subtitle/symbol by state:
+
+| State | Title | Subtitle | Symbol |
+|-------|-------|----------|--------|
+| add | `Text` | `Titles, captions, and animated overlays` | `textformat` |
+| edit clip | `Edit Text` | `Style, motion, and timing controls` | `textformat.size` |
+| edit caption track | `Edit Captions` | `Style the whole caption track and edit every cue` | `captions.bubble.fill` |
+
+### 2.2 Add mode
+
+Rows:
+
+1. **Text Presets** — `text.badge.plus`. Subtitle `Choose a title or caption style to place at the playhead`. Tap → presets sheet.
+2. Helper card (when no preset chosen): `text.badge.plus` 30pt accent icon + body `Choose a preset to place editable text at the playhead.`
+
+#### 2.2.1 Preset grid (sheet)
+
+Header: `Text Presets` (14pt bold rounded). 2-column `LazyVGrid` of `PresetGridCard`s. Selection shown when `selectedTextClip.metadata["preset"] == preset.id`.
+
+Catalog (`TextPresetCatalog.presets` — 8 presets total):
+
+| id | Name | Subtitle | Symbol | Default Text | Default Duration | Font | Size | Weight | Color | Background | Align | Shadow | Position (x,y) | Scale | Animation (preset / params / inDur / outDur / stagger / unit) |
+|----|------|----------|--------|--------------|------------------|------|------|--------|-------|-----------|-------|--------|----------------|-------|--------|
+| title-bold | Bold Title | Large centered headline | `textformat.size.larger` | `Your Title` | 4s | SF Pro Display | 76 | bold | #FFFFFF | nil | center | yes | 0.5, 0.42 | 1 | pop / popOvershoot=1.22 / 0.45 / 0.25 / 0.03 / character |
+| subtitle-clean | Subtitle | Readable lower caption | `captions.bubble` | `Add a caption` | 5s | SF Pro Display | 38 | bold | #FFFFFF | #000000 | center | no | 0.5, 0.78 | 1 | fade / fadeOpacity {start:0,end:1} / 0.35 / 0.25 / 0.02 / character |
+| lower-third | Lower Third | Name and detail label | `person.text.rectangle` | `Name / Role` | 5s | Avenir Next | 34 | bold | #111827 | #4ADE80 | left | no | 0.32, 0.72 | 1 | slideRight / slideDistance=0.22 / 0.45 / 0.25 / 0.04 / character |
+| quote-card | Quote | Editorial pull quote | `quote.opening` | `Make the moment count.` | 5s | New York | 52 | 700 | #FFFFFF | nil | center | yes | 0.5, 0.5 | 0.98 | wordByWord / wordDelay=0.16 / 0.9 / 0.35 / 0.12 / word |
+| label-pill | Pill Label | Compact callout badge | `tag.fill` | `NEW` | 3s | SF Pro Display | 30 | bold | #052E16 | #4ADE80 | center | no | 0.78, 0.22 | 0.86 | bounce / bounceHeight=0.09, bounceCount=2 / 0.7 / 0.25 / 0.03 / character |
+| typewriter-note | Type Note | Character reveal caption | `keyboard` | `Typing something true` | 5s | Menlo | 32 | 600 | #E5E7EB | #111827 | left | no | 0.42, 0.62 | 1 | typewriter / {} / 1.0 / 0.25 / 0.045 / character |
+| countdown | Countdown | Bold numeric moment | `timer` | `03` | 3s | SF Pro Display | 118 | bold | #4ADE80 | nil | center | yes | 0.5, 0.48 | 1 | scale / scaleFrom=0.35, scaleTo=1 / 0.35 / 0.2 / 0 / character |
+| cta-button | CTA | Action prompt overlay | `hand.tap.fill` | `Tap to follow` | 4s | Avenir Next | 36 | bold | #FFFFFF | #16A34A | center | yes | 0.5, 0.82 | 0.94 | wave / waveAmplitude=0.025, waveFrequency=2 / 0.3 / 0.2 / 0.04 / character |
+
+Default shadow when `shadow: true` is `{ color: "#000000", blur: 12, offsetX: 0, offsetY: 4 }`.
+Default `lineHeight = 1.2`, `letterSpacing = 0`, `verticalAlign = .middle`, `fontStyle = "normal"`.
+
+Tap a preset card → `appState.addTextClip(from: preset, at: playbackController.currentTime, ...)`.
+
+### 2.3 Edit Text mode (single clip)
+
+Rows in main panel:
+
+1. **Content** — `text.cursor`. Subtitle = trimmed/cleaned text preview, capped at 36 chars + ellipsis. Fallback `Edit the copy inside this text clip`. Tap → content sheet.
+2. **Font & Alignment** — `textformat`. Subtitle `{fontFamily} · {alignment.capitalized}`. Tap → font sheet.
+3. **Size & Opacity** — `textformat.size`. Subtitle `{Int(fontSize)}pt · {Int(opacity*100)}%`. Tap → size sheet.
+4. **Colors** — `paintpalette`. Subtitle `Text, background, and contrast styling`. Tap → color sheet.
+5. **Shadow & Stroke** — `shadow`. Subtitle `{Shadow on/off} · {Stroke on/off}`. Tap → effects sheet.
+6. **Animation** — `sparkles`. Subtitle = animation name (from catalog) or `None`. Tap → animation sheet.
+7. **Delete Text** — `trash`, destructive accent. Subtitle `Remove the selected text clip from the timeline`. `showsDisclosure = false`. Tap → `appState.deleteSelectedTextClip(...)`.
+
+#### Sheets
+
+- **Content sheet**: `SelectAllTextField` (UIKit-backed) with placeholder `Text`. Auto-selects all on focus. 36pt min height, 12pt padding, 12pt rounded surface bg.
+- **Font & Alignment sheet** (combined card, 14pt corners, 14pt padding):
+ - Horizontal scrolling font picker with capsule pills (12pt bold rounded). Active pill: accent bg + black text. Inactive: surfaceElevated + secondary text.
+ - Fonts (`TextPresetCatalog.fonts`): `SF Pro Display`, `Avenir Next`, `New York`, `Helvetica Neue`, `Menlo`, `Georgia`.
+ - Alignment picker — 3 equally wide buttons (left/center/right). Active: accent bg + black icon. Icons: `text.alignleft`, `text.aligncenter`, `text.alignright`. Justify is supported in the model (`text.justify`) but not surfaced in the picker.
+- **Size & Opacity sheet**:
+ - `Size` slider: `18...160`, label format `{Int(value)}pt`.
+ - `Opacity` slider: `0...1`.
+- **Colors sheet**:
+ - `Color` swatch row from `TextPresetCatalog.colorSwatches`: `#FFFFFF, #4ADE80, #FDE047, #38BDF8, #F472B6, #FB7185, #111827`.
+ - `Background` swatch row from `TextPresetCatalog.backgroundSwatches`: `none, #000000, #1A1A1A, #14532D, #1E3A8A, #7F1D1D`. Selecting "none" clears the background.
+- **Shadow & Stroke sheet**: two `PanelActionTile`s arranged as 2 columns:
+ - `Shadow On/Off` (icon `shadow`, subtitle `Readable lift`). Toggles `shadowColor` between `#000000` (with `shadowBlur = 12`) and "none" (`shadowBlur = 0`).
+ - `Stroke On/Off` (icon `pencil.line`, subtitle `Outline text`). Toggles `strokeColor` between `#000000` (with `strokeWidth = 3`) and "none" (`strokeWidth = 0`).
+- **Animation sheet**: 2-column `LazyVGrid` of `PresetGridCard`s from `TextPresetCatalog.animations`. Selection matches when the clip's `animation` equals the choice's animation (or both are nil). Card data:
+
+| id | Name | Subtitle | Symbol | Preset | Params | inDur | outDur | Stagger | Unit |
+|----|------|----------|--------|--------|--------|-------|--------|---------|------|
+| none | None | Static title | `circle.slash` | nil | — | — | — | — | — |
+| typewriter | Typewriter | Character reveal | `keyboard` | typewriter | {} | 1.0 | 0.3 | 0.05 | character |
+| typewriter-fast | Fast Type | Quick character reveal | `text.cursor` | typewriter | {} | 0.55 | 0.2 | 0.025 | character |
+| fade | Fade | Soft opacity in | `circle.dashed` | fade | fadeOpacity {start:0,end:1} | 0.5 | 0.25 | 0.02 | character |
+| fade-slow | Slow Fade | Long smooth fade | `moonphase.first.quarter` | fade | fadeOpacity {start:0,end:1} | 1.1 | 0.45 | 0.04 | character |
+| slide-up | Slide Up | Enter from below | `arrow.up.to.line` | slideUp | slideDistance=0.22 | 0.45 | 0.25 | 0.08 | word |
+| slide-down | Slide Down | Enter from above | `arrow.down.to.line` | slideDown | slideDistance=0.22 | 0.45 | 0.25 | 0.08 | word |
+| slide-left | Slide Left | Enter from right | `arrow.left.to.line` | slideLeft | slideDistance=0.24 | 0.45 | 0.25 | 0.04 | character |
+| slide-right | Slide Right | Enter from left | `arrow.right.to.line` | slideRight | slideDistance=0.24 | 0.45 | 0.25 | 0.04 | character |
+| scale | Scale | Grow into frame | `arrow.up.left.and.arrow.down.right` | scale | scaleFrom=0.25, scaleTo=1 | 0.45 | 0.25 | 0.03 | character |
+| scale-subtle | Subtle Scale | Small lift | `plus.magnifyingglass` | scale | scaleFrom=0.82, scaleTo=1 | 0.4 | 0.2 | 0.02 | character |
+| blur | Blur | Unblur into focus | `camera.filters` | blur | blurAmount=10 | 0.55 | 0.3 | 0.06 | word |
+| bounce | Bounce | Playful entrance | `arrow.down.circle` | bounce | bounceHeight=0.1, bounceCount=3 | 0.8 | 0.3 | 0.05 | character |
+| bounce-soft | Soft Bounce | Gentle hop | `arrow.down.circle.dotted` | bounce | bounceHeight=0.05, bounceCount=2 | 0.65 | 0.25 | 0.04 | character |
+| rotate | Rotate | Spin into place | `rotate.right` | rotate | rotateAngle=180 | 0.6 | 0.25 | 0.04 | character |
+| rotate-small | Tilt In | Small rotation | `rotate.3d` | rotate | rotateAngle=24 | 0.42 | 0.2 | 0.02 | character |
+| wave | Wave | Continuous ripple | `water.waves` | wave | waveAmplitude=0.03, waveFrequency=2 | 0.2 | 0.2 | 0.02 | character |
+| shake | Shake | Energetic motion | `waveform.path` | shake | shakeIntensity=0.018, shakeSpeed=18 | 0.2 | 0.2 | 0 | character |
+| pop | Pop | Overshoot snap | `sparkle.magnifyingglass` | pop | popOvershoot=1.24 | 0.42 | 0.25 | 0.04 | character |
+| glitch | Glitch | Digital jitter | `bolt.horizontal` | glitch | glitchIntensity=0.03, glitchSpeed=12 | 0.2 | 0.2 | 0 | character |
+| split | Split | Letters part outward | `arrow.left.and.right` | split | splitDirection="horizontal" | 0.5 | 0.25 | 0.02 | character |
+| flip | Flip | Card flip reveal | `rectangle.portrait.rotate` | flip | flipAxis="y" | 0.58 | 0.25 | 0.04 | character |
+| word-by-word | Word by Word | Spoken rhythm | `text.word.spacing` | wordByWord | wordDelay=0.16 | 0.95 | 0.35 | 0.14 | word |
+| rainbow | Rainbow | Cycling color | `paintpalette.fill` | rainbow | rainbowSpeed=1 | 0.2 | 0.2 | 0.02 | character |
+
+Text style model fields (full schema for Android):
+
+```
+fontFamily: String
+fontSize: Double // pt
+fontWeight: named(String) | numeric(Int) // e.g. .named("bold") or .numeric(700)
+fontStyle: String // "normal" | "italic"
+color: String // hex "#RRGGBB" or "#RRGGBBAA"
+backgroundColor: String? // hex or nil
+strokeColor: String? // hex or nil
+strokeWidth: Double? // pt
+shadowColor: String? // hex or nil
+shadowBlur: Double? // pt
+shadowOffsetX: Double?
+shadowOffsetY: Double?
+textAlign: .left | .center | .right | .justify
+verticalAlign: .top | .middle | .bottom
+lineHeight: Double // multiplier (default 1.2)
+letterSpacing: Double // px (default 0)
+textDecoration: String? // e.g. "underline" | "line-through"
+```
+
+Transform model fields (text uses the same `Transform` as media): `position(x,y)` in normalized 0..1, `scale(x,y)`, `rotation` (deg), `anchor(x,y)`, `opacity` 0..1, `borderRadius`, `fitMode`, `crop`.
+
+### 2.4 Caption track editor
+
+Triggered when editing a text clip that belongs to the subtitle/caption track.
+
+Rows in main panel:
+
+1. **Track Style** — `captions.bubble.fill`. Subtitle `Font, size, placement, and animation for the whole caption track`. Tap → caption style sheet.
+2. **Caption Text** — `text.quote`. Subtitle `Edit each subtitle cue and review timing`. Tap → caption cues sheet.
+3. **Single Clip** — `text.cursor`. Subtitle either `No managed clip available yet` (disabled) or `Jump back to the first caption clip for per-clip edits`. Tap → selects the first managed caption clip (returns to the single-clip edit view).
+
+#### Track Style sheet
+
+Card (14pt corner, surface bg, 14pt padding) containing:
+
+- `Track Style` headline.
+- Font picker (same horizontal pill list as single-clip mode).
+- `Size` slider `18...160` (`{Int(value)}pt`).
+- Position picker — 3 equal-width buttons for `OpenReelProject.SubtitlePosition` (top / middle / bottom). Active: accent bg + black text.
+- Animation picker — horizontal scroll of 72x56pt rounded tiles. Choices (`subtitleAnimationStyles`):
+
+| Style | Label | Symbol |
+|-------|-------|--------|
+| `.none` | None | `text.alignleft` |
+| `.wordHighlight` | Highlight | `highlighter` |
+| `.wordByWord` | Word Pop | `text.word.spacing` |
+| `.karaoke` | Karaoke | `music.mic` |
+| `.bounce` | Bounce | `arrow.up.and.down` |
+| `.typewriter` | Typewriter | `keyboard` |
+
+- Text Color swatches: same as `TextPresetCatalog.colorSwatches`.
+- Background swatches (`subtitleBackgroundSwatches`): `#000000BF, #000000, #1A1A1A, #14532D, #1E3A8A, #7F1D1D` (note the first is 75% black via the BF alpha byte).
+
+#### Caption Text sheet (cue list)
+
+- Headline `Caption Text`.
+- Empty state: `captions.bubble` icon (28pt accent) + `Import or generate captions to edit the track here.`
+- Otherwise, for each cue (sorted by `startTime` then `id`):
+ - Time range header `MM:SS:FF - MM:SS:FF` where frame is `(time%1)*30` (10pt monospaced bold accent).
+ - Multiline `TextField` (axis: vertical) with placeholder `Caption` (15pt semibold rounded text primary). Each keystroke calls `appState.updateSubtitleCueText(cueID, text)`.
+
+### 2.5 Android mapping (Text)
+
+- Custom text rendering: prefer Compose's `Text` with `TextStyle`. For stroke + shadow, fall back to drawing via `androidx.compose.ui.graphics.drawscope.DrawScope.drawText` or `NativeCanvas.drawText` with `Paint.setShadowLayer(blur, offsetX, offsetY, color)` and `Paint.style = STROKE`.
+- Fonts: ship the iOS-named fonts via `FontFamily(Font(R.font.sf_pro_display))` etc.; map "SF Pro Display" → Roboto Flex / Inter; "New York" → a serif (Source Serif / Roboto Serif); "Menlo" → JetBrains Mono / Roboto Mono.
+- Animations: implement each preset as a Compose `infiniteTransition` or `animateFloatAsState` keyed off the text clip lifetime. For per-character/word staging, split the string into glyphs and animate each with a `delayMillis = stagger * index`.
+- Caption track cue editor: `LazyColumn` of `Card { Column { Text(timecode) ; OutlinedTextField(... multiline) } }`.
+
+---
+
+## 3. Audio Panel (`AudioTabPanel`)
+
+### 3.1 Header
+
+- Title: `Audio`
+- Subtitle: `Music, sound effects, and voiceover`
+- Symbol: `music.note`
+
+### 3.2 Layout (top to bottom rows)
+
+1. **Music Library** — `music.note.list`. Subtitle `Import tracks from the device music library`. `showsDisclosure = false`. Tap → `MusicLibraryPicker` (MPMediaPickerController) sheet.
+2. **Audio Files** — `folder.badge.plus`. Subtitle `Import audio files from storage`. `showsDisclosure = false`. Tap → `DocumentMediaPicker` filtered to audio only on output.
+3. **Selected Clip** — `waveform`. Subtitle = selected media item name, or `Choose a clip with audio to adjust pan, fades, and processing` if none. Enabled only when both `selectedClip` and `selectedMediaItem` exist. Tap → Selected Clip sheet.
+4. **Mixer** — `slider.horizontal.3`. Subtitle `Balance track gain, pan, and roles`. Tap → Mixer sheet.
+5. **Sound Effects** — `speaker.wave.2`. Subtitle `Generate short effects and place them on the timeline`. Tap → Sound Effects sheet.
+6. **Voiceover** — `mic.fill`. Subtitle `Record narration directly into the timeline`. Tap → Voiceover sheet.
+
+### 3.3 Audio sources
+
+#### 3.3.1 Music Library (`MusicLibraryPicker`)
+
+- `MPMediaPickerController(mediaTypes: .music)` with `allowsPickingMultipleItems = true`, `showsCloudItems = false`.
+- For each picked `MPMediaItem`, takes `assetURL`, derives file name from `title` (or URL stem) plus extension (defaults `m4a` if missing).
+- Emitted as `ImportedMediaAsset(mediaType: .audio)`.
+
+Permission iOS: `NSAppleMusicUsageDescription`.
+
+Android mapping: there is **no direct Apple Music equivalent**. Map to:
+
+- **MediaStore Audio**: `ActivityResultContracts.OpenDocument` with MIME `audio/*`, or query `MediaStore.Audio.Media.EXTERNAL_CONTENT_URI` for an in-app track picker UI.
+- Permissions: `READ_MEDIA_AUDIO` on Android 13+, `READ_EXTERNAL_STORAGE` on older.
+
+#### 3.3.2 Audio Files
+
+- Same `DocumentMediaPicker` as the Media panel, but consumed assets are filtered to `mediaType == .audio` only.
+
+Android mapping: `ActivityResultContracts.OpenMultipleDocuments` with `mimeTypes = arrayOf("audio/*")`.
+
+#### 3.3.3 Voiceover Recorder (`VoiceRecordView`)
+
+Layout (inside a 14pt-corner card on surface):
+
+- Header HStack: `Voiceover` label (14pt bold rounded) + elapsed time (12pt monospaced bold, accent when recording, secondary otherwise).
+- Level meter: 22 vertical capsules, equal flex width, height `8 + (index%5)*6` pt. Each capsule is filled accent if `index/22 < level`, else white 10%. `level = clamp((averagePower + 60) / 60, 0, 1)`.
+- Permission denied warning text in destructive red: `Microphone access is required for voice recording.`
+- Two equal-flex 12pt-vertical-padded buttons:
+ - Record/Stop: accent bg (mic.fill, black text) when idle → `Record`; destructive bg (stop.fill, white text) when recording → `Stop`.
+ - Cancel: surfaceElevated bg, secondary text label `Cancel`. Disabled when not recording and there's no recording on disk.
+
+Recording flow:
+
+- iOS 17+ uses `AVAudioApplication.requestRecordPermission`; older uses `AVAudioSession.requestRecordPermission`.
+- On grant: sets session category `.playAndRecord` mode `.spokenAudio` options `[.defaultToSpeaker, .allowBluetoothHFP]`.
+- File: `NSTemporaryDirectory()/Voiceover-<unix>.m4a`. Settings:
+ - format `kAudioFormatMPEG4AAC`
+ - sample rate `44100`
+ - channels `1` (mono)
+ - encoder quality `.high`
+- `recorder.isMeteringEnabled = true`. Metering polled every 80ms via `Timer.publish(every: 0.08)`.
+- On Stop: stops recorder, emits `ImportedMediaAsset(mediaType: .audio)`, restores session to `.playback / .moviePlayback`.
+- On Cancel: stops recorder, deletes the temp file.
+
+Permissions iOS: `NSMicrophoneUsageDescription`.
+
+Android mapping:
+
+- `MediaRecorder` or `AudioRecord` (lower-level). Suggested:
+ - `setAudioSource(MediaRecorder.AudioSource.MIC)`, `setOutputFormat(MPEG_4)`, `setAudioEncoder(AAC)`, `setAudioSamplingRate(44100)`, `setAudioChannels(1)`, `setAudioEncodingBitRate(128000)`.
+ - Output to `context.cacheDir/Voiceover-${timestamp}.m4a`.
+ - Level metering: poll `MediaRecorder.maxAmplitude` every 80ms, map to 0..1 with `clamp(20*log10(amp/32767)/-60 ... , 0, 1)` or use `AudioRecord` directly for accurate dB.
+- Permissions: `RECORD_AUDIO`. Show denial copy verbatim.
+
+#### 3.3.4 Sound Effects (`SoundEffectCatalog`)
+
+A built-in catalog of synthesized short effects (no library download). Each generates a WAV in `NSTemporaryDirectory()`. The synthesizer uses:
+
+- Sample rate: 44100, mono, 16-bit PCM.
+- Per-frame: `frequency(t) = effect.frequency + effect.sweep * t/(N-1)`, envelope `sin(π*t) * (1-t)^0.35`, gain 0.72.
+- WAV header is hand-built (RIFF / WAVE / fmt 16 / PCM 1ch / data).
+
+Catalog entries (`SoundEffectChoice`):
+
+| id | Name | Subtitle | Symbol | Frequency (Hz) | Duration (s) | Sweep (Hz) |
+|----|------|----------|--------|----------------|--------------|------------|
+| tap | Tap | Short UI click | `hand.tap` | 740 | 0.16 | 0 |
+| pop | Pop | Soft impact | `circle.circle` | 420 | 0.22 | -120 |
+| chime | Chime | Bright accent | `bell` | 880 | 0.55 | 180 |
+| success | Success | Positive cue | `checkmark.seal` | 660 | 0.62 | 330 |
+| whoosh | Whoosh | Fast transition | `wind` | 220 | 0.5 | 520 |
+| riser | Riser | Build tension | `arrow.up.forward` | 180 | 0.85 | 700 |
+
+Sound Effects sheet UI: 2-column grid of `PresetGridCard`s (title/subtitle/symbol/accent). Tap → synthesizes the WAV, imports it via `importMediaToLibrary`, then places it on the timeline at the playhead.
+
+Android mapping: synthesize the same WAV programmatically (write RIFF header + 16-bit LE PCM samples) into `cacheDir`. The math is identical. Then enqueue with the editor's import pipeline.
+
+#### 3.3.5 Local Music (Android)
+
+Android exposes **Local Music** / **Create offline**. A prompt selects and tunes
+one of the bundled procedural styles; duration and tempo customize the result.
+MusicLibrary.materialiseGenerated writes a mono PCM WAV into project-local
+storage and places it on the timeline. There is no request, token, progress
+polling, or network fallback.
+
+iOS does not currently expose a matching generator. Keep it absent until an
+on-device implementation is added; the ordinary Music Library, Audio Files,
+Sound Effects, Voiceover, and offline Text to Speech paths remain available.
+
+### 3.4 Selected Clip sheet
+
+Visible only when both a clip is selected and its media item supports audio (`mediaItem.type == .audio` or `video with audioTrackCount > 0`).
+
+Card with: media item name (13pt bold), track name (or `Timeline Clip`, 11pt medium secondary). When `canDetachSelectedClipAudio`: a `Detach` button (32pt high, accent bg, 10pt corner) which calls `appState.detachSelectedClipAudio(...)`.
+
+Sliders:
+
+| Label | Range | Format | Action |
+|-------|-------|--------|--------|
+| Pan | -1...1 | `C` when |v|<0.01; otherwise `L NN` or `R NN` where `NN = int(abs*100)` | `updateSelectedClipPan` |
+| Fade In | 0...max(min(clipDuration, 5), 0.2) | `"%.2fs"` | `updateSelectedClipFade(.fadeIn, ...)` |
+| Fade Out | 0...max(min(clipDuration, 5), 0.2) | `"%.2fs"` | `updateSelectedClipFade(.fadeOut, ...)` |
+
+Below sliders, two side-by-side menu pickers ("In Curve" / "Out Curve"). Choices (`OpenReelProject.AudioAutomationCurve`):
+
+- `linear` → "Linear"
+- `exponential` → "Expo"
+- `logarithmic` → "Log"
+- `sCurve` → "S-Curve"
+- (`bezier` exists in the model but is not surfaced in the picker)
+
+Selecting a curve calls `updateSelectedClipFade(edge, duration, curve)` with the current duration retained.
+
+Empty state (when no eligible clip): card with title `No audio clip selected`, body `Select a clip with audio to adjust pan, fades, and detached audio behavior.`
+
+#### 3.4.1 Audio effects processing rack
+
+Five effect cards stacked vertically inside the selected clip sheet. Each card has:
+
+- Title + subtitle on the left.
+- A `Toggle` on the right (accent tint) that enables/disables the effect. Turning on for the first time inserts a default-params effect via `upsertSelectedClipAudioEffect(type:params:)`.
+- When enabled, controls appear below.
+
+**1) EQ** — Title `EQ`, subtitle `Bass, presence, and air shaping`.
+
+- Default `EQ` is 5 bands; the panel exposes 3 of them via sliders, but persists all 5 internally:
+
+| Index | Type | Frequency (Hz) | Default gain (dB) | Q |
+|-------|------|----------------|-------------------|---|
+| 0 | lowshelf | 60 | 0 | 0.707 |
+| 1 | peaking | 250 | 0 | 1.4 |
+| 2 | peaking | 1000 | 0 | 1.4 |
+| 3 | peaking | 4000 | 0 | 1.4 |
+| 4 | highshelf | 16000 | 0 | 0.707 |
+
+- Surface sliders (range -12...12 dB, format `+/-NN dB`):
+ - `Bass` → band 0 gain
+ - `Presence` → band 2 gain
+ - `Air` → band 4 gain
+- Internally clamped to `-24...24 dB` for gain; frequency `20...20000`; Q `0.1...18`.
+- Filter types supported (`TimelineAudioEQBand.FilterType`): `lowshelf, highshelf, peaking, lowpass, highpass, notch`.
+
+**2) Compressor** — Title `Compressor`, subtitle `Tighten dynamics and add makeup gain`.
+
+| Param | Default | Surface range | Internal clamp | Format |
+|-------|---------|---------------|----------------|--------|
+| threshold | -20 dB | -60...0 | -60...0 | `+/-NN dB` |
+| ratio | 4 | 1...12 | 1...20 | `%.1f:1` |
+| attack | 0.01 s | (not in UI) | 0.001...1 | — |
+| release | 0.1 s | (not in UI) | 0.01...3 | — |
+| knee | 6 dB | (not in UI) | 0...40 | — |
+| makeupGain | 0 dB | 0...12 | -24...24 | `+/-NN dB` |
+
+**3) Reverb** — Title `Reverb`, subtitle `Blend room size with wet mix`.
+
+| Param | Default | Surface range | Internal clamp | Format |
+|-------|---------|---------------|----------------|--------|
+| roomSize | 0.5 | 0...1 | 0...1 | `NN%` |
+| damping | 0.5 | (not in UI) | 0...1 | — |
+| wetLevel | 0.3 | 0...1 | 0...1 | `NN%` |
+| dryLevel | 1.0 | (not in UI) | 0...1 | — |
+| preDelay | 0 | (not in UI) | 0...100 | — |
+
+Internally maps to `AVAudioUnitReverb` presets (smallRoom/mediumRoom/plate/largeRoom/mediumHall/largeHall) based on `roomSize` and `damping`.
+
+**4) Noise Reduction** — Title `Noise Reduction`, subtitle `Reduce hiss and room wash`.
+
+| Param | Default | Surface range | Internal clamp |
+|-------|---------|---------------|----------------|
+| threshold | -40 | — | -80...0 |
+| reduction | 0.5 | 0...1 | 0...1 |
+| attack | 10 ms | — | 0...100 |
+| release | 100 ms | — | 0...500 |
+| focus | `balanced` | (menu) | enum |
+
+Focus menu values: `Balanced` (balanced), `Speech` (speech), `White Noise` (whiteNoise), `Music` (music), `Heavy` (heavy), `Wind` (wind), `Hum` (hum). Each focus selects a different internal EQ band profile applied before a dynamics processor.
+
+**5) Ducking** — Title `Ducking`, subtitle `Pull music under the active role`.
+
+| Param | Default | Surface range | Internal clamp |
+|-------|---------|---------------|----------------|
+| threshold | -60 dB | — | -80...0 |
+| reduction | 0.5 | 0...1 | 0...1 |
+| attack | 0.15 s | — | 0...3 |
+| release | 0.3 s | — | 0...3 |
+| holdTime | 0.1 s | — | 0...3 |
+| triggerRole | `dialogue` | menu | enum |
+
+Trigger role menu values: rawValues from `OpenReelProject.AudioTrackRole` (capitalized): `Music, Dialogue, Effects, Voiceover, Ambient` (whichever the model defines via `allCases`).
+
+Note: Ducking does **not** create a `AVAudioNode` in offline render — it's a control signal handled elsewhere in the timeline. The Compressor maps to `AudioUnit kAudioUnitSubType_DynamicsProcessor` with computed `attackTime`/`releaseTime` (in ms), `headRoom = max(0.1, 18/ratio)`, and `expansionRatio = 1`.
+
+Effect persistence schema (`OpenReelProject.Effect`):
+
+```
+{
+ id: String,
+ type: "eq" | "compressor" | "reverb" | "noiseReduction" | "ducking",
+ enabled: Bool,
+ params: { ... per-effect keys, exact names listed above ... }
+}
+```
+
+EQ params shape:
+
+```
+"params": {
+ "bands": [{ "type": "...", "frequency": Hz, "gain": dB, "q": Q }, ...]
+}
+```
+
+#### 3.4.2 Stem separation
+
+Stem separation is not exposed on mobile because no reliable bundled model is
+currently shipped. The selected-clip sheet contains the local processing rack
+only. Do not add a placeholder action or remote fallback.
+
+### 3.5 Mixer sheet
+
+For each audio track in `currentProject.timeline.tracks` where `type == .audio`:
+
+- Card: track name (13pt bold) + `{N} clips` (11pt medium secondary).
+- Trailing role menu showing `track.audioMix.role.rawValue.capitalized` with chevrons. Tap → choose role from `OpenReelProject.AudioTrackRole.allCases`. Calls `updateTrackAudioMix(trackID, role:)`.
+- `Gain` slider — range `0...2` (so 2x boost is possible). No format string by default (raw slider value), but consumer can show 0..200%.
+- `Pan` slider — range `-1...1`, format `C` / `L NN` / `R NN` (same as clip pan).
+
+Empty state: card with title `No audio tracks yet`, body `Import music, sound effects, or voiceover to start shaping your mix.`
+
+Android mapping: `LazyColumn` of `Card { Column { Row { Text(name) ; Spacer ; DropdownMenu(role) } ; Slider(gain) ; Slider(pan) } }`. Gain >1 should be shown as +N% boost.
+
+### 3.6 Offline render (informational — `TimelineAudioOfflineRenderer`)
+
+For Android export pipeline parity, the offline mixer renders each segment with:
+
+- A `AVAudioPlayerNode → AVAudioUnitTimePitch → effect nodes → mainMixerNode` chain.
+- Time-stretch rate clamped to `[1/32, 32]`.
+- Per-frame volume from automation (fade ramps using the chosen curve), then pan via constant-power-ish `leftGain = pan<=0 ? 1 : 1-pan`, `rightGain = pan>=0 ? 1 : 1+pan`.
+- Output: 32-bit float WAV `.caf` at the timeline sample rate (min 8000 Hz) with stereo channels.
+
+Android mapping: implement with **ExoPlayer audio processors** or **Oboe** + a custom DSP chain. The mixing math (per-sample volume * leftGain/rightGain, summed into a stereo mix buffer, clamped to [-1,1]) is identical. For time-stretch use **Sonic** (open-source) or `androidx.media3.exoplayer.audio.SonicAudioProcessor`. EQ via `android.media.audiofx.Equalizer` (simple) or custom biquad filters. Compressor/limiter via `DynamicsProcessing` (API 28+) or a manual biquad+envelope follower. Reverb via `android.media.audiofx.PresetReverb` / `EnvironmentalReverb`. Noise reduction has no AOSP equivalent — port the EQ-band+expander recipe documented above.
+
+### 3.7 Permissions summary (Audio panel)
+
+| iOS | Android |
+|-----|---------|
+| `NSAppleMusicUsageDescription` (Music Library picker) | `READ_MEDIA_AUDIO` (33+) / `READ_EXTERNAL_STORAGE` (≤32) |
+| `NSMicrophoneUsageDescription` (Voiceover) | `RECORD_AUDIO` |
+| File access via document picker (no extra perm) | Storage Access Framework picker (no perm needed) |
+
+---
+
+## 4. Cross-panel notes for Android
+
+### 4.1 State container
+
+iOS uses two SwiftUI `@Environment` injectables:
+
+- `AppState` — project document model + local actions (`addMediaItemToTimeline`, `addTextClip(from preset:)`, `updateSelectedTextClipStyle(...)`, `updateSubtitleTrackStyle(...)`, `upsertSelectedClipAudioEffect(...)`, etc.). It exposes current project and selection state plus local import/operation status.
+- `PlaybackController` — playhead time (`currentTime`).
+
+Android equivalent: a single `ViewModel` (or per-feature `ViewModel`s) exposing `StateFlow<EditorState>`. Mutations live on the ViewModel and dispatch to a repository/service. Maintain the exact field names so JSON serialization stays compatible.
+
+### 4.2 Sheet detent
+
+All sheets use `presentationDetents([.fraction(0.5)])`. In Compose use `ModalBottomSheet(sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false))` and an initial half-expand state. Drag indicator is always visible.
+
+### 4.3 Loading, empty, and error states (recap)
+
+- **Media empty library**: `rectangle.stack.badge.plus`, copy `Import something to start building the timeline.`
+- **Audio Selected Clip (no audio)**: `No audio clip selected` / `Select a clip with audio to adjust pan, fades, and detached audio behavior.`
+- **Mixer empty**: `No audio tracks yet` / `Import music, sound effects, or voiceover to start shaping your mix.`
+- **Caption track empty**: `captions.bubble` + `Import or generate captions to edit the track here.`
+- **Voiceover permission denied**: `Microphone access is required for voice recording.`
+- **Photo Tools loading text states**: `Loading photo`, `Preparing photo`, `Rendering result`, `Downloading result`, `Import failed`, `Edit failed`, `Cancelled`, and per-tool `<Tool> ready` on success.
+- **Errors**: imports surface via `appState.importErrorMessage`; AI photo edits raise alerts (`Photo Import Failed`, `Reference Load Failed`, `Edit Failed`, `Cancel Failed`, `Save Failed`, `Saved To Photos`).
+
+### 4.4 Permissions consolidated
+
+| Capability | iOS Info.plist key | Android permission |
+|-----------|--------------------|---------------------|
+| Photo library read | `NSPhotoLibraryUsageDescription` | `READ_MEDIA_IMAGES`/`READ_MEDIA_VIDEO` (33+) or PhotoPicker (no perm) |
+| Photo library add (save enhanced) | `NSPhotoLibraryAddUsageDescription` | `WRITE_EXTERNAL_STORAGE` (≤28) / MediaStore (29+) |
+| Camera | `NSCameraUsageDescription` | `CAMERA` |
+| Microphone | `NSMicrophoneUsageDescription` | `RECORD_AUDIO` |
+| Music library | `NSAppleMusicUsageDescription` | `READ_MEDIA_AUDIO` (33+) |
+| Files | (none — Document picker handles) | (none — SAF handles) |
+
+### 4.5 File naming conventions (used when copying into temp)
+
+- Camera photo: `Camera-{unixSeconds}.jpg` (JPEG q=0.9).
+- Camera video: `Camera-{unixSeconds}.mov`.
+- Voiceover: `Voiceover-{unixSeconds}.m4a` (AAC mono 44.1k, high quality).
+- Sound effect: `OpenReel-{effectId}-{unixSeconds}.wav` (16-bit PCM mono 44.1k).
+- Document picker copies: `{UUID}.{originalExt}`.
+
+Reproduce these exactly on Android so logs, telemetry, and any user-facing filenames match.
+
+---
+
+End of MEDIA / TEXT / AUDIO panel specification.
diff --git a/docs/android-port/06-features-effects-graphics-templates-subtitles.md b/docs/android-port/06-features-effects-graphics-templates-subtitles.md
new file mode 100644
index 00000000..f39d73cb
--- /dev/null
+++ b/docs/android-port/06-features-effects-graphics-templates-subtitles.md
@@ -0,0 +1,636 @@
+# Effects, Graphics, Templates & Subtitles — Android Port Spec
+
+Source of truth: `Openreel Video/Features/Effects/*`, `…/Graphics/*`, `…/Templates/*`, `…/Subtitles/*`.
+
+All panels share the same chrome: an `EditorPanelContainer` with title, subtitle, leading symbol, and an optional `onBack`. The body is a vertical `ScrollView` of `EditorMenuRow` items (icon + title + subtitle + chevron). Tapping a row opens a half-height bottom sheet (`presentationDetents([.fraction(0.5)])`, drag indicator, `.ultraThinMaterial` background). Each sheet reuses `EditorPanelContainer` for its own header. Color tokens: `OpenReelTheme.surface` / `surfaceElevated` for backgrounds, `OpenReelTheme.accent` for selection, `OpenReelTheme.destructive` for danger, `OpenReelTheme.textPrimary` / `textSecondary` for typography. Tap haptics use `UIImpactFeedbackGenerator(.light)`.
+
+Android equivalent: a `Scaffold` with a top app bar, a `LazyColumn` of list rows, and a `ModalBottomSheet` at half-screen height (`SheetState` with `partiallyExpanded`) backed by `Surface(tonalElevation = 3.dp)`. Haptics via `HapticFeedbackConstants.CONTEXT_CLICK`.
+
+---
+
+## 1. EFFECTS PANEL (`EffectsTabPanel.swift`)
+
+Title: "Effects". Subtitle: "Video effects, tools, and stack order". Header symbol: `wand.and.stars`.
+
+### 1.1 Empty state
+
+When `appState.selectedClip` is nil OR the selected media type is not video/image, the body renders `emptySelection`:
+- Icon `cursorarrow.click.badge.clock` (size 30, semibold, accent color)
+- Text: "Select a visual clip to apply looks."
+- Vertical padding 32, surface background, corner radius 14.
+
+### 1.2 Top-level row list (when a visual clip is selected)
+
+Each row is an `EditorMenuRow(title, subtitle, symbol)` that opens an `EffectsPanelSheet` via `activeSheet`:
+
+| Row | Symbol | Subtitle | Sheet enum |
+|---|---|---|---|
+| Selected Effect | `slider.horizontal.3` | dynamic — name of selected stack effect, or "Choose an applied effect to tune its parameters" | `.selectedEffect` (disabled if no selection) |
+| Effect Stack | `square.stack.3d.down.right` | "{n} effects and tools applied" | `.stack` |
+| Presets | `camera.filters` | "Cinematic looks and reusable grades" | `.presets` |
+| Core Controls | `slider.horizontal.3` | "Brightness, saturation, blur, sharpen, grain, and more" | `.coreControls` |
+| Color Wheels | `circle.lefthalf.filled` | "Lift, gamma, gain, and offset balance" | `.colorWheels` |
+| HSL | `paintpalette` | "Tune hue, saturation, and luminance per color range" | `.hsl` |
+| Curves | `waveform.path.ecg` | "Shape luminance and color channels precisely" | `.curves` |
+| LUT | `square.3.layers.3d` | "Import a .cube look" (none) / "Manage the applied LUT" | `.lut` |
+| Creative Effects | `sparkles` | "Add animated looks and texture treatments" | `.creativeEffects` |
+| Video Tools | `scope` | "On-device Vision, Metal, and Core Image tools" | `.videoTools` |
+| Scopes | `waveform.path` | "Awaiting frame" / "Waveform and vectorscope" | `.scopes` |
+| Reset All | `trash` (destructive tint) | "Remove every effect and tool from the selected clip" | inline action — calls `appState.resetSelectedClipEffects(types: Set(VideoEffectType.allCases))` |
+
+### 1.3 Effect Stack sheet
+
+Toolbar row (horizontal): **Copy** (`doc.on.doc`, bordered accent), **Paste** (`doc.on.clipboard`, disabled until `appState.hasCopiedEffectStack`), **Add** (`plus.circle`, menu listing every `addableEffects` entry — i.e. all `VideoEffectType` cases except `.filterPreset` and `.colorAdjust`), and **Reset All** (right-aligned, destructive text button).
+
+List body:
+- Header: "Effect Stack" + "{count} total".
+- Empty: "Add effects to build an ordered grade stack for this clip."
+- Each effect: row with symbol, name, enabled toggle, drag/reorder, remove. (See `effectRow` not pasted but inferred — provides up/down/remove.)
+- Selected-effect tail card: "Selected: {name}" with one universal **Intensity** slider (0…1, default 1) that writes `params["intensity"]`.
+
+Container: padding 14, `OpenReelTheme.surface`, corner radius 14.
+
+### 1.4 Presets sheet
+
+Layout:
+1. Horizontal category picker — chips for every `FilterPresetCategory` (`Cinematic`, `Vintage`, `Mood`, `Color`, `Stylized`). Selected chip = filled accent background + black text; unselected = surface background + secondary text.
+2. 2-column `LazyVGrid` (spacing 10) of `PresetGridCard`s filtered by selected category. Each card shows symbol, name (`preset.name`), description (`preset.description`), accent color (`Color(hexString: preset.tintHex)`), selected ring when `activePresetName == preset.name`.
+
+Tap → `applyPreset(preset)` (light haptic). Implementation expands `preset.effectStack` (brightness/contrast/saturation/temperature only emitted if they differ from neutral, plus `finishingEffects` per preset id). Each emitted `OpenReelProject.Effect` carries `params["presetID"]` and `params["presetName"]` for round-tripping.
+
+**Full FilterPresetCatalog enumeration** (id, name, category, description, symbol, tintHex, brightness, saturation, contrast, temperature, plus per-id finishing effects):
+
+| id | name | category | description | symbol | tintHex | bright | sat | contr | temp | extra finishing effects |
+|---|---|---|---|---|---|---|---|---|---|---|
+| cinematic-teal-orange | Teal & Orange | Cinematic | Hollywood contrast | film | #38BDF8 | 0 | 1.10 | 1.15 | -0.08 | vignette amount 0.25, midpoint 0.5, roundness 0.5, feather 0.8 |
+| cinematic-noir | Film Noir | Cinematic | Black and punchy | circle.lefthalf.filled | #E5E7EB | -0.05 | 0 | 1.40 | 0 | vignette amount 0.4 mid 0.4 round 0.5 feather 0.6; grain amount 0.15 size 1.5 rough 0.5 colored false |
+| cinematic-blockbuster | Blockbuster | Cinematic | Bold studio look | sparkles.tv | #F97316 | 0.05 | 1.15 | 1.20 | 0.05 | sharpen amount 0.3 radius 1 threshold 10 |
+| vintage-70s | 70s Retro | Vintage | Warm faded stock | camera | #F59E0B | 0.05 | 0.85 | 0.90 | 0.20 | grain amount 0.2 size 2 rough 0.6 colored true |
+| vintage-polaroid | Polaroid | Vintage | Instant photo lift | photo | #FBBF24 | 0.04 | 0.90 | 1.10 | 0.08 | vignette amount 0.3 mid 0.5 round 0.3 feather 0.85 |
+| vintage-vhs | VHS | Vintage | Tape-era color | videocam | #A78BFA | -0.02 | 0.80 | 1.15 | -0.04 | blur radius 0.5 type gaussian; grain amount 0.25 size 2.5 rough 0.7 colored true |
+| vintage-sepia | Sepia | Vintage | Classic warm tone | sun.dust | #D97706 | 0.10 | 0.30 | 1.05 | 0.28 | — |
+| mood-dreamy | Dreamy | Mood | Soft atmosphere | cloud | #F9A8D4 | 0.10 | 0.85 | 0.90 | 0.04 | blur radius 1 type gaussian |
+| mood-moody | Moody | Mood | Dark and dense | moon | #64748B | -0.15 | 0.75 | 1.25 | -0.06 | vignette amount 0.35 mid 0.4 round 0.5 feather 0.7 |
+| mood-golden-hour | Golden Hour | Mood | Sunset warmth | sun.max | #FBBF24 | 0.10 | 1.20 | 1.05 | 0.24 | — |
+| mood-cold | Cold Blue | Mood | Icy balance | snowflake | #67E8F9 | 0.05 | 0.90 | 1.10 | -0.24 | — |
+| color-vibrant | Vibrant | Color | Saturated color | paintpalette | #4ADE80 | 0.05 | 1.40 | 1.15 | 0 | — |
+| color-muted | Muted | Color | Soft palette | drop | #93C5FD | 0.05 | 0.60 | 0.95 | 0.02 | — |
+| color-bw-classic | B&W Classic | Color | Timeless mono | circle.righthalf.filled | #F8FAFC | 0 | 0 | 1.10 | 0 | — |
+| color-bw-high-contrast | B&W High | Color | Dramatic mono | circle.lefthalf.filled | #CBD5E1 | -0.05 | 0 | 1.50 | 0 | — |
+| stylized-cyberpunk | Cyberpunk | Stylized | Neon contrast | bolt | #C084FC | 0 | 1.30 | 1.30 | -0.12 | vignette amount 0.3 mid 0.45 round 0.5 feather 0.75; chromaticAberration amount 2.5 |
+| stylized-comic | Comic Book | Stylized | Graphic punch | burst | #FDE047 | 0.02 | 1.40 | 1.50 | 0.02 | sharpen amount 0.5 radius 1.5 threshold 5 |
+| stylized-soft-glow | Soft Glow | Stylized | Gentle bright wash | sparkles | #FDA4AF | 0.15 | 0.90 | 0.85 | 0.08 | — |
+| cinematic-documentary | Documentary | Cinematic | Balanced factual tone | camera.aperture | #D1D5DB | 0.03 | 0.92 | 1.08 | -0.01 | — |
+| stylized-prism | Prism | Stylized | Split-channel edge glow | triangle.lefthalf.filled | #7DD3FC | 0.04 | 1.18 | 1.12 | -0.03 | chromaticAberration amount 4 |
+
+`presetEffectTypes` (the set of effect types treated as "preset territory" when round-tripping/clearing): `brightness, contrast, saturation, temperature, blur, sharpen, vignette, grain, chromaticAberration, filterPreset, colorAdjust`.
+
+### 1.5 Core Controls sheet
+
+`CompactSliderRow` list inside a surface card:
+
+| Label | Effect type written | Param key | Range | Default | Format |
+|---|---|---|---|---|---|
+| Brightness | brightness | value | -0.5…0.5 | 0 | signedPercent |
+| Contrast | contrast | value | 0.5…2 | 1 | "%.2f" |
+| Saturation | saturation | value | 0…2 | 1 | signedPercent |
+| Temperature | temperature | value | -1…1 | 0 | signedPercent |
+| Hue | hue | rotation | -180…180 | 0 | "%.0f°" |
+| Blur | blur | radius | 0…8 | 0.5 | "%.1f" |
+| Sharpen | sharpen | amount | 0…1.5 | 0.3 | "%.2f" |
+| Vignette | vignette | amount | 0…1 | 0.25 | signedPercent |
+| Grain | grain | amount | 0…0.6 | 0.15 | signedPercent |
+| Prism | chromaticAberration | amount | 0…8 | 0 | "%.1f" |
+
+Slider edits call `upsertEffectValue` / `upsertEffectParams` which `mergeSelectedClipEffect` and replay through `playbackController`.
+
+### 1.6 Color Wheels sheet
+
+Header "Color Wheels" + "Reset" button (restores `VideoEffectType.colorWheels.defaultParams`). For each `WheelTone` (`.lift`, `.gamma`, `.gain`, `.offset`):
+- Section title (`tone.title`)
+- `ColorWheelPad` — circular pad letting the user drag an RGB offset. Reads `tone.key` param as `{red, green, blue}` JSON object, writes back via `EffectParameterCodec.colorObject(red, green, blue)`.
+- `CompactSliderRow` for the tone's scalar amount (`tone.amountTitle`, key `tone.amountKey`, range `tone.amountRange`, default `tone.defaultAmount`, format `tone.format`).
+
+The four wheels map 1:1 to ASC CDL primary/log/gain/offset on Android — use a custom Canvas with a hue/sat wheel and a separate brightness slider per tone.
+
+### 1.7 HSL sheet
+
+Header "HSL" + Reset. Horizontal channel picker for 8 `HSLChannel` cases (Red, Orange, Yellow, Green, Cyan/Aqua, Blue, Purple, Magenta — `selectedHSLChannel.index` 0…7). Selected chip background = `channel.color`.
+
+Three sliders editing arrays of 8 values stored in `params["hue" | "saturation" | "luminance"]`:
+
+| Slider | Range | Format |
+|---|---|---|
+| Hue | -180…180 | "%.0f°" |
+| Saturation | -1…1 | signedPercent |
+| Lightness | -1…1 | signedPercent |
+
+Writes update the array at `selectedHSLChannel.index` and resave via `updateHSLArray`.
+
+### 1.8 Curves sheet
+
+Header "Curves" + Reset (replaces the selected channel array with `EffectParameterCodec.defaultCurvePoints`). Channel picker for `CurveChannel` cases (`rgb`, `red`, `green`, `blue`, `luma` — each with its own color). Body is `CurveEditor`: 256-step spline editor that reads `EffectParameterCodec.curvePoints(from:, key:)` and writes `EffectParameterCodec.curveArray(nextPoints)`. Editor is touch-draggable with anchor points.
+
+### 1.9 LUT sheet
+
+If no LUT effect on the clip → CTA "Import a .cube file to apply a show LUT and blend it per clip." + "Import .cube" button (right-aligned, accent). Opens a `fileImporter` for `.cube` UTType. On success calls `appState.importSelectedClipLUT(sourceURL:)`.
+
+If a LUT is applied → shows:
+- Reference name (`reference.name`)
+- "{size}x{size}x{size} cube" (e.g. 33x33x33)
+- Intensity slider 0…1, default `reference.intensity`, writes `params["intensity"]`.
+- "Replace" button (re-opens importer) and **Remove LUT** destructive button.
+
+### 1.10 Creative Effects sheet
+
+Horizontal scroll of `effectChoiceCard` (132×184) for each type in `creativeEffects`:
+`[disintegrate, dissolve, bloom, motionBlur, pixelate, chromaticAberration, grain, vignette, blur, sharpen]`.
+
+Card UI: symbol tile, title, subtitle, "Add" / "Added" label. Tap calls `applyEffectChoice` — if effect already exists, just selects it; otherwise upserts with default params.
+
+Subtitles per effect (for both cards and Inspector copy):
+- disintegrate — "Particle-style breakup"
+- dissolve — "Fade the clip layer"
+- bloom — "Soft glow highlights"
+- motionBlur — "Directional streak blur"
+- pixelate — "Blocky digital texture"
+- chromaticAberration — "RGB edge split"
+- grain — "Film texture"
+- vignette — "Darkened edges"
+- blur — "Soft focus"
+- sharpen — "Crisp detail"
+
+### 1.11 Video Tools sheet
+
+Same horizontal-scroll card layout for `videoTools`:
+`[backgroundRemoval, subjectBlur, subjectGlow, faceBeauty, motionTrack, faceTrack, objectTrack, bodyPose, autoReframe, stabilize]`.
+
+Subtitles:
+- stabilize — "Subject-aware smoothing"
+- backgroundRemoval — "Vision subject cutout"
+- subjectBlur — "Blur tracked subject masks"
+- subjectGlow — "Glow tracked subject masks"
+- faceBeauty — "Smooth and brighten faces"
+- motionTrack — "Tracking setup for clip attachments"
+- faceTrack — "Face anchor detection"
+- objectTrack — "Object anchor detection"
+- bodyPose — "Body pose analysis"
+- autoReframe — "Subject-aware crop path"
+
+### 1.12 Selected-effect parameter controls
+
+Resolved by `parameterControls(for:)`. For each `VideoEffectType` the editor renders a stack of `CompactSliderRow`s with these defaults:
+
+| VideoEffectType | Slider label | Param key | Default | Range | Format |
+|---|---|---|---|---|---|
+| disintegrate | Amount | amount | 0.35 | 0…1 | signedPercent |
+| dissolve | Fade | amount | 0.25 | 0…1 | signedPercent |
+| bloom | Glow | amount | 0.65 | 0…2 | "%.2f" |
+| bloom | Radius | radius | 12 | 0…60 | "%.0f" |
+| motionBlur | Blur | radius | 8 | 0…60 | "%.0f" |
+| motionBlur | Angle | angle | 0 | -180…180 | "%.0f°" |
+| pixelate | Block | scale | 18 | 1…80 | "%.0f" |
+| chromaticAberration | Split | amount | 3 | 0…20 | "%.1f" |
+| grain | Amount | amount | 0.15 | 0…0.6 | signedPercent |
+| vignette | Amount | amount | 0.25 | 0…1 | signedPercent |
+| blur | Radius | radius | 0.5 | 0…8 | "%.1f" |
+| sharpen | Amount | amount | 0.3 | 0…1.5 | "%.2f" |
+| stabilize | Strength | strength | 0.5 | 0…1 | signedPercent |
+| stabilize | Crop | crop | 0.06 | 0…0.18 | signedPercent |
+| motionTrack | Confidence | confidence | 0.7 | 0…1 | signedPercent |
+| motionTrack | Smooth | smoothing | 0.35 | 0…1 | signedPercent |
+| backgroundRemoval | Strength | strength | 1 | 0…1 | signedPercent |
+| backgroundRemoval | Blur | blurRadius | 24 | 0…80 | "%.0f" |
+| backgroundRemoval | Feather | feather | 4 | 0…32 | "%.0f" |
+| backgroundRemoval | Edge | edgeExpansion | 0 | -12…12 | "%.0f" |
+| subjectBlur | Radius | radius | 16 | 0…80 | "%.0f" |
+| subjectBlur | Feather | feather | 4 | 0…32 | "%.0f" |
+| subjectGlow | Glow | amount | 0.65 | 0…2 | "%.2f" |
+| subjectGlow | Radius | radius | 18 | 0…80 | "%.0f" |
+| subjectGlow | Feather | feather | 6 | 0…32 | "%.0f" |
+| faceBeauty | Smooth | smoothing | 0.35 | 0…1 | signedPercent |
+| faceBeauty | Bright | brighten | 0.08 | 0…1 | signedPercent |
+| faceBeauty | Warmth | warmth | 0.04 | -1…1 | signedPercent |
+| faceBeauty | Detail | sharpen | 0.18 | 0…1 | signedPercent |
+| faceBeauty | Feather | feather | 14 | 0…48 | "%.0f" |
+| faceTrack | Confidence/Smooth | confidence/smoothing | 0.6 / 0.35 | 0…1 | signedPercent |
+| objectTrack | Confidence/Smooth | confidence/smoothing | 0.65 / 0.35 | 0…1 | signedPercent |
+| bodyPose | Confidence/Smooth | confidence/smoothing | 0.55 / 0.4 | 0…1 | signedPercent |
+| autoReframe | Padding | padding | 0.12 | 0…0.4 | signedPercent |
+| autoReframe | Smooth | smoothing | 0.5 | 0…1 | signedPercent |
+| autoReframe | Confidence | confidence | 0.65 | 0…1 | signedPercent |
+
+### 1.13 Scopes sheet
+
+Two `ScopePlotCard`s rendered from `ColorScopesSnapshot`:
+- **Waveform** — `colorScopes.waveform` points, accent color, grid on.
+- **Vectorscope** — `colorScopes.vectorscope` points, blue accent (`Color(red: 0.38, green: 0.76, blue: 1)`), grid off.
+
+Header shows "Live" if data available, "Awaiting frame" otherwise. Android: use a custom `Canvas` plotting normalized 0…1 points from RenderEffect output (or shader-sampled histograms).
+
+### 1.14 On-device tool execution
+
+Video Tools are local effect-stack entries. iOS builds masks and tracking frame
+context with Vision and renders with Core Image/Metal. Android uses ML Kit
+tracking and its local effects pipeline. Track Subject, Auto Reframe, and
+Stabilize create editor keyframes from local detections. There is no separate
+analysis sheet, job identifier, progress polling, or cancel endpoint.
+
+### 1.15 Blend Mode panel (`BlendModePanel.swift`)
+
+Used from the Text/Graphics inspector when surfacing a clip's blend properties. Layout: header "Blend Mode" + current label, **Opacity** slider 0…1 default 1 (writes `clip.blendOpacity`), then a 3-column `LazyVGrid` of blend mode buttons. Selected = `accent.opacity(0.2)` fill + 2px accent border; unselected = `surfaceElevated` + 1px white-6%.
+
+**Full blend-mode list** (mode enum value, label, description). The iOS engine routes each through Core Image (`CIBlendMode*`) or shader equivalents — math given for Android Compose `BlendMode` / PorterDuff parity:
+
+| OpenReelProject.BlendMode | Label | Description | iOS CIBlendMode | Android Compose `BlendMode` | Math (S=source, D=dest) |
+|---|---|---|---|---|---|
+| normal | Normal | Default layer stacking | (alpha-over default) | `BlendMode.SrcOver` | S over D |
+| multiply | Multiply | Darkens by multiplying colors | `CIMultiplyBlendMode` | `BlendMode.Multiply` | S × D |
+| screen | Screen | Lightens by inverting and multiplying | `CIScreenBlendMode` | `BlendMode.Screen` | 1 − (1−S)(1−D) |
+| overlay | Overlay | Combines multiply and screen | `CIOverlayBlendMode` | `BlendMode.Overlay` | D<0.5 ? 2SD : 1−2(1−S)(1−D) |
+| darken | Darken | Keeps darker pixels | `CIDarkenBlendMode` | `BlendMode.Darken` | min(S,D) |
+| lighten | Lighten | Keeps lighter pixels | `CILightenBlendMode` | `BlendMode.Lighten` | max(S,D) |
+| colorDodge | Color Dodge | Brightens highlights | `CIColorDodgeBlendMode` | `BlendMode.ColorDodge` | D / (1−S) |
+| colorBurn | Color Burn | Deepens shadows | `CIColorBurnBlendMode` | `BlendMode.ColorBurn` | 1 − (1−D)/S |
+| hardLight | Hard Light | Intense overlay | `CIHardLightBlendMode` | `BlendMode.Hardlight` | S<0.5 ? 2SD : 1−2(1−S)(1−D) |
+| softLight | Soft Light | Gentle dodge/burn | `CISoftLightBlendMode` | `BlendMode.Softlight` | Photoshop soft-light formula |
+| difference | Difference | Inverts where layers overlap | `CIDifferenceBlendMode` | `BlendMode.Difference` | |S − D| |
+| exclusion | Exclusion | Softer difference | `CIExclusionBlendMode` | `BlendMode.Exclusion` | S + D − 2SD |
+| hue | Hue | Applies hue only | `CIHueBlendMode` | `BlendMode.Hue` | HSL: H_S, S_D, L_D |
+| saturation | Saturation | Applies saturation only | `CISaturationBlendMode` | `BlendMode.Saturation` | HSL: H_D, S_S, L_D |
+| color | Color | Applies hue + saturation | `CIColorBlendMode` | `BlendMode.Color` | HSL: H_S, S_S, L_D |
+| luminosity | Luminosity | Applies brightness only | `CILuminosityBlendMode` | `BlendMode.Luminosity` | HSL: H_D, S_D, L_S |
+
+`darken`/`lighten` are not surfaced in the Graphics panel's reduced list (see 2.4) but are valid for any `BlendModePanel` usage.
+
+---
+
+## 2. GRAPHICS PANEL (`GraphicsTabPanel.swift`)
+
+Title: "Graphics". Subtitle: "Shapes, stickers, and overlays". Header symbol: `square.on.circle`.
+
+### 2.1 Top-level rows
+
+Always-visible:
+- **Shapes** (`square.on.circle`) — "Place a new shape at the playhead" → sheet `.shapes`.
+- **Stickers** (`face.smiling`) — "Add an emoji or sticker overlay" → sheet `.stickers`.
+
+If `appState.selectedGraphicsClip == nil`: a centered `helperCard` precedes the menu: icon `sparkles.square.filled.on.square`, title "No graphic selected", message "Choose a graphic on the timeline to edit fill, stroke, blend, size, opacity, and animation."
+
+If a graphics clip is selected: the helper card is replaced by the `graphicsMenu`:
+
+| Row | Symbol | Subtitle | Sheet | Notes |
+|---|---|---|---|---|
+| Fill (only if `clip.type == .shape` and style != nil) | `paintpalette.fill` | "No fill applied" or "Choose a fill color" | `.fill` | |
+| Stroke (same gating) | `pencil.line` | "Width {clip.style.stroke.width %.1f}" | `.stroke` | |
+| Blend Mode | `square.on.square` | `(clip.blendMode ?? .normal).rawValue.capitalized` | `.blend` | |
+| Size | `arrow.up.left.and.arrow.down.right` | "%.2fx" of avg(scale.x, scale.y) | `.size` | |
+| Opacity | `circle.lefthalf.filled` | "{int(blendOpacity*100)}%" | `.opacity` | |
+| Animation | `sparkles` | `clip.emphasisAnimation?.type.rawValue.capitalized ?? "None"` | `.animation` | |
+| Delete Graphic | `trash` (destructive) | "Remove the selected graphic from the timeline" | inline | `appState.deleteSelectedGraphicsClip` |
+
+### 2.2 Shapes sheet (`ShapePresetCatalog.shapes`)
+
+2-column `LazyVGrid` (spacing 10). Each card (118×170) renders the SF Symbol then the name. Tap = light haptic + `appState.addGraphicsClip(from: preset, at: playbackController.currentTime)`.
+
+**Color swatch palette** used everywhere: `["#4ADE80", "#FFFFFF", "#FDE047", "#38BDF8", "#F472B6", "#FB7185", "#A855F7", "#111827"]`.
+
+**Full ShapePresetCatalog.shapes enumeration**:
+
+| id | name | subtitle | symbol | shapeType | duration | style | transform |
+|---|---|---|---|---|---|---|---|
+| rectangle-solid | Rectangle | Solid filled rectangle | `rectangle.fill` | rectangle | 4 s | solid #4ADE80, cornerRadius 8 | centered, scale 0.40×0.25 |
+| circle-solid | Circle | Solid filled circle | `circle.fill` | circle | 4 s | solid #38BDF8 | centered, scale 0.30×0.30 |
+| ellipse-outline | Ellipse | Stroked ellipse outline | `oval` | ellipse | 4 s | stroke #4ADE80 width 3, no fill, line round-cap/round-join | centered, scale 0.45×0.28 |
+| triangle-solid | Triangle | Equilateral triangle | `triangle.fill` | triangle | 4 s | solid #FDE047 | centered, scale 0.30×0.30 |
+| arrow-right | Arrow | Directional arrow pointer | `arrowshape.right.fill` | arrow | 3 s | solid #4ADE80 | centered, scale 0.35×0.20 |
+| line-horizontal | Line | Horizontal divider line | `minus` | line | 4 s | stroke #FFFFFF width 3 round caps | centered, scale 0.60×0.01 |
+| polygon-hexagon | Polygon | Six-sided polygon | `hexagon.fill` | polygon | 4 s | fill #A855F7, points=6 | centered, scale 0.30×0.30 |
+| star-five | Star | Five-pointed star | `star.fill` | star | 4 s | fill #FDE047, shadow rgba(253,224,71,0.4) blur 6 offset (0,2), points=5, innerRadius 0.4 | centered, scale 0.30×0.30 |
+
+Default `Transform`: `position (0.5, 0.5)`, `anchor (0.5, 0.5)`, `rotation 0`, `opacity 1`, `fitMode .contain`, no `borderRadius` / `crop`.
+
+### 2.3 Stickers sheet (`ShapePresetCatalog.stickers`)
+
+Same grid format but the card renders the `emoji` glyph at size 28 instead of an SF Symbol. Tap = `appState.addStickerClip(from: preset, at: currentTime)`.
+
+`cornerTransform(x:y:)` template: scale `0.15×0.15` at the given normalized corner, with default anchor/rotation/opacity as above.
+
+| id | name | emoji | category | duration | position (x,y) | emphasis |
+|---|---|---|---|---|---|---|
+| fire | Fire | 🔥 | Reactions | 3 s | (0.82, 0.18) | bounce |
+| heart | Heart | ❤️ | Reactions | 3 s | (0.82, 0.18) | pulse |
+| star-eyes | Star Eyes | 🤩 | Reactions | 3 s | (0.82, 0.18) | bounce |
+| thumbs-up | Thumbs Up | 👍 | Reactions | 3 s | (0.82, 0.18) | bounce |
+| lightning | Lightning | ⚡ | Effects | 2 s | (0.50, 0.30) | flash |
+| sparkles | Sparkles | ✨ | Effects | 3 s | (0.50, 0.30) | pulse |
+| party | Party | 🎉 | Celebrations | 3 s | (0.50, 0.30) | bounce |
+| rocket | Rocket | 🚀 | Actions | 3 s | (0.50, 0.30) | float |
+| check | Checkmark | ✅ | Status | 3 s | (0.82, 0.18) | bounce |
+| arrow-down | Arrow Down | ⬇️ | Arrows | 3 s | (0.50, 0.72) | bounce |
+| question | Question | ❓ | Status | 3 s | (0.82, 0.18) | shake |
+| eyes | Eyes | 👀 | Reactions | 3 s | (0.50, 0.30) | shake |
+
+Emphasis animation prototypes used above:
+- bounce — `(speed 1.2, intensity 0.6, loop true)`
+- pulse — `(speed 1.0, intensity 0.5, loop true)`
+- float — `(speed 0.8, intensity 0.4, loop true)`
+- flash — `(speed 1.5, intensity 0.8, loop false)`
+- shake — `(speed 1.5, intensity 0.4, loop false)`
+
+All emphasis animations have `focusPoint = zoomScale = holdDuration = startTime = animationDuration = nil`.
+
+### 2.4 Fill sheet
+
+Inside a `sheetContainer("Fill", "Choose the graphic fill", "paintpalette.fill")`: section header "Fill", then a horizontal `ScrollView` of swatch buttons. The first swatch is `SwatchButton(hex: "none")` (writes `fillType: .none, color: nil`); the rest iterate `ShapePresetCatalog.colorSwatches` (writes `.solid` with the hex). Selected state when `style.fill.color == hex && style.fill.type == .solid`.
+
+### 2.5 Stroke sheet
+
+Section header "Stroke" + `CompactSliderRow("Width", style.stroke.width, range 0…10, format "%.1f")` writing `appState.updateGraphicsClipStroke(clipID:, width:, color: nil)`. Below: horizontal swatch row (same palette) — selecting one sets color and bumps width to `max(style.stroke.width, 2)`.
+
+### 2.6 Blend Mode sheet (Graphics)
+
+Same `sheetContainer` pattern. Body: horizontal pill row (`Capsule()` background, 10×7 padding). The Graphics blend list is a reduced 9-option subset:
+`[Normal, Multiply, Screen, Overlay, Soft Light, Difference, Exclusion, Dodge (= colorDodge), Burn (= colorBurn)]`.
+
+Selection writes via `appState.updateGraphicsClipBlendMode(clipID:, blendMode:)`.
+
+### 2.7 Size sheet
+
+`CompactSliderRow(label: "Size", value: uniformScale, range 0.02…2, format "%.2fx")`. Uniform scale = `(scale.x + scale.y) / 2`. Updating writes `Point(x: newScale, y: newScale)` to the clip transform — i.e. graphics scale isotropically here even though the model supports separate axes.
+
+### 2.8 Opacity sheet
+
+`CompactSliderRow(label: "Opacity", value: blendOpacity ?? 1, range 0…1)` → `updateGraphicsClipOpacity`.
+
+### 2.9 Animation sheet
+
+Horizontal pill row of `EmphasisAnimationType` options, written via `updateGraphicsClipEmphasis`. Full list (label = type capitalized):
+`[None, Pulse, Bounce, Float, Shake, Spin, Flash, Glow, Breathe]`. Selection swaps `clip.emphasisAnimation.type` only — speed/intensity/loop are not exposed in this sheet (use the catalog defaults or text-clip equivalents).
+
+### 2.10 Android mapping (Graphics)
+
+- Build shapes with `Canvas` / `androidx.compose.foundation.Canvas`. `rectangle` → `drawRoundRect`; `circle/ellipse` → `drawOval`; `triangle/arrow/polygon/star` → custom `Path` (compute regular polygon vertices from `points`, star uses alternating outer/`innerRadius`).
+- Stickers → emoji rendered as `Text(emoji, fontSize = size)`.
+- Blend modes → use `Modifier.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }` plus `drawWithContent { drawContent(blendMode = …) }`, mapping via the table in §1.15.
+- Emphasis animations → `Modifier.graphicsLayer` driven by `rememberInfiniteTransition` or `Animatable` (pulse/breathe = scale 1↔1+intensity; bounce = vertical translation; spin = rotation; flash = alpha; shake = horizontal translation; glow = drop-shadow alpha).
+
+---
+
+## 3. TEMPLATES PANEL (`TemplatesTabPanel.swift` + `BuiltInTemplateCatalog.swift` + `TemplatePreviewView.swift`)
+
+A template is `OpenReelProject.TemplatePackage` — a reusable bundle of:
+- `payload.duration` (seconds)
+- `payload.textClips: [TextClip]`
+- `payload.graphicsClips: [GraphicsClip]`
+- `payload.effects: [Effect]`
+- `controls: [TemplateControlDefinition]` (typed user-editable parameters, e.g. title text / size)
+- `defaultValues: [String: JSONValue]`
+- `supportedTargets: [.video | .image]`
+- `category: TemplateCategory` (`cinema, glitch, social, retro, branding, color, overlay`)
+- `tags: [String]`
+- `createdAt`, `modifiedAt` (epoch ms)
+
+Applying a template injects its `textClips` and `graphicsClips` at the current playhead and (if present) appends its `effects` onto the selected visual clip's stack.
+
+### 3.1 Top-level rows
+
+| Row | Symbol | Subtitle behavior | Enabled when | Action |
+|---|---|---|---|---|
+| Save Current | `square.and.arrow.down` | `captureCountLabel` (e.g. "2 text · 1 graphics · 3 effects") or "Add overlays or select a styled clip" | `appState.canSaveCurrentTemplatePackage` | Opens "Save Template" alert with `TextField` (default `"{projectName} Template"`) + Cancel/Save. Save → `appState.saveCurrentProjectAsTemplatePackage(name:)`. |
+| Import | `square.and.arrow.down.on.square` | "Bring in .openreeltemplate packs" | always | `fileImporter` for UTType `openreeltemplate` (or `data` fallback). On success → `appState.importTemplatePackage(from: url)`. |
+| Apply | `sparkles.rectangle.stack` | selected template name or "Choose a template below" | `canApplySelectedTemplate` | `applySelectedTemplate()` |
+| Export | `square.and.arrow.up` | selected template name or "Select a template to share" | template selected | exports via `appState.exportTemplatePackage(id:)` and presents iOS `ShareSheet` |
+| Current Capture | `tray.full` | `captureCountLabel` | always | sheet `.capture` |
+| Selected Template | `square.stack.3d.up` | `selectedTemplatePackage.name` or "Choose a template from the library" | template selected | sheet `.selectedTemplate` |
+| Template Library | `books.vertical` | "Browse {n} reusable templates" | always | sheet `.library` |
+
+`captureCountLabel` is built from non-zero counts joined by " · " — text count, graphics count, selected-clip effect count. If everything is zero: "Nothing selected".
+
+`canApply(template)` returns true when there is a current project AND (template has any text/graphics OR there is a selected clip to host its effects).
+
+### 3.2 Current Capture sheet
+
+Surface card with title + `captureCountLabel` aligned right (accent monospaced). Description text:
+- if `selectedClipEffectCount > 0` and a media item is selected: "Saving now will capture every text and graphics overlay in this project plus the effect stack from {name}."
+- else: "Saving now captures every text and graphics overlay in this project. Select a visual clip first if you also want to include its effects."
+
+Horizontal stat chips: `Text {n}`, `Graphics {n}`, `Effects {n}`, plus the selected media name (secondary tint).
+
+### 3.3 Library sheet
+
+Header "Template Library" + count. Empty state: icon `square.stack.3d.up.slash`, "Save a project look or import a package to build your reusable template library."
+
+When populated: 2-column `LazyVGrid` (spacing 10) of `templateCard`s — accent-tinted symbol tile, checkmark when selected, name, multi-line subtitle (`{counts} · {targetLabel}`). Tap = select. Context menu items: **Apply** (disabled per `canApply`), **Share**, **Delete** (destructive).
+
+`symbol(for: template)` chooses the tile icon by priority: graphics → `square.stack.3d.up`; else text → `textformat`; else effects → `wand.and.stars`; else `square.stack.3d.up`.
+
+`targetLabel(for:)` joins `supportedTargets.rawValue` with " + " or returns "Any target".
+
+### 3.4 Selected Template sheet
+
+Header (large symbol tile + name + description ("Custom template package" fallback)), `TemplatePreviewView` (16:9, 140pt high — see §3.6), then horizontal stat chips and a button row:
+- **Apply at Playhead** (`sparkles.rectangle.stack`, borderedProminent accent, disabled if `!canApplySelectedTemplate`).
+- **Share** (`square.and.arrow.up`, bordered accent).
+- Right-aligned **Delete** (destructive bordered).
+
+### 3.5 Built-in template catalog (`BuiltInTemplateCatalog.packages`)
+
+Eight curated packages. All `createdAt` and `modifiedAt` are set at load time to `Int(Date().timeIntervalSince1970 * 1000)`. Shared text-style template (`makeStyle`): font/size/weight/color/optional background; `shadow=true` adds shadowColor `rgba(0,0,0,0.6)`, blur 12, offset (0,4); `lineHeight 1.2`, `verticalAlign .middle`, `fontStyle "normal"`. Shared transform (`makeTransform`): position `(x, y)` (x default 0.5), scale (default 1×1), anchor `(0.5,0.5)`, rotation 0, opacity 1, fitMode `.contain`. Shared animation (`makeAnimation`): unit `.character`, configurable preset/params/inDuration/outDuration/stagger.
+
+#### 3.5.1 Cinema Opener (`builtin-cinema-opener`)
+
+- category `.cinema`, tags `["title","cinematic","dramatic"]`, supports `[.video]`
+- controls: `title-text` (text, default "YOUR TITLE"); `title-size` (number, default 72, min 32, max 120, step 2)
+- defaultValues: `{title-text: "YOUR TITLE", title-size: 72}`
+- payload duration 5 s
+- text clip `cinema-title`: text "YOUR TITLE", start 0.5, dur 4, SF Pro Display 72 heavy white, center, shadow, letterSpacing 8, position y=0.48; animation `.fade {fadeOpacity: {start:0,end:1}}`, in 0.8 / out 0.6 / stagger 0.04.
+- effects: `vignette {intensity 0.55, radius 0.7}`.
+
+#### 3.5.2 Glitch Title (`builtin-glitch-title`)
+
+- category `.glitch`, tags `["glitch","digital","modern"]`, supports `[.video, .image]`, no controls.
+- duration 4 s.
+- text clip `glitch-title`: text "GLITCH", start 0.2, dur 3.5, Menlo 64 bold color #4ADE80, center, shadow, letterSpacing 4, stroke #00E676 width 1, position y=0.45; animation `.glitch {glitchIntensity: 0.7}`, in 0.3 / out 0.2 / stagger 0.01.
+- effects: `chromaticAberration {intensity 0.4, offset 3}`.
+
+#### 3.5.3 Social Callout (`builtin-social-callout`)
+
+- category `.social`, tags `["social","callout","bubble"]`, supports `[.video, .image]`, no controls.
+- duration 4 s.
+- text clip `social-callout-text`: text "Follow for more!", start 0.3, dur 3.4, SF Pro Display 36 bold color #111827 on background #4ADE80, center, no shadow, position y=0.72; animation `.pop {popOvershoot: 1.3}`, in 0.4 / out 0.3 / stagger 0.02.
+- graphics clip `social-arrow`: shape `.arrow` solid #4ADE80, transform (0.5, 0.82, scale 0.3×0.3), bounce emphasis (speed 1.5, intensity 0.6, loop true), start 0.5, dur 3.
+
+#### 3.5.4 Retro VHS (`builtin-retro-vhs`)
+
+- category `.retro`, tags `["retro","vhs","90s","vintage"]`, supports `[.video]`, no controls.
+- duration 6 s.
+- text clip `vhs-date`: "REC ● 06.18.1994", start 0, dur 6, Menlo 22 regular white, left aligned, letterSpacing 2, position (0.18, 0.88), blendOpacity 0.85, no animation.
+- effects: `filmGrain {intensity 0.6, size 1.2}`, `scanLines {opacity 0.25, count 120}`, `colorAdjust {saturation 0.7, temperature -15}`.
+
+#### 3.5.5 Brand Lower Third (`builtin-branding-lower-third`)
+
+- category `.branding`, tags `["branding","lower-third","professional"]`, supports `[.video]`
+- controls: `name` (text, "Jane Smith"), `role` (text, "Creative Director")
+- defaultValues `{name: "Jane Smith", role: "Creative Director"}`
+- duration 5 s.
+- text clip `brand-name`: "Jane Smith", start 0.3, dur 4.2, SF Pro Display 38 bold white, left, shadow, letterSpacing 1, position (0.28, 0.78); animation `.slideRight {slideDistance: 0.15}`, in 0.45 / out 0.3 / stagger 0.03.
+- text clip `brand-role`: "Creative Director", start 0.6, dur 3.9, SF Pro Display 22 medium #4ADE80, left, no shadow, letterSpacing 2, position (0.28, 0.84); animation `.slideRight {slideDistance: 0.15}`, in 0.5 / out 0.25 / stagger 0.02.
+- graphics clip `brand-accent-bar`: shape `.rectangle` fill #4ADE80 cornerRadius 4, transform (0.14, 0.81, scale 0.04×0.12), no emphasis, start 0.2, dur 4.5.
+
+#### 3.5.6 Color Wash (`builtin-color-wash`)
+
+- category `.color`, tags `["color","overlay","warm"]`, supports `[.video, .image]`
+- controls: `warmth` (number, default 20, min -50, max 50, step 5)
+- duration 0 (effect-only — applied directly to the host clip).
+- effects: `colorAdjust {temperature 20, saturation 1.15, contrast 1.05}`, `filmGrain {intensity 0.2, size 0.8}`.
+
+#### 3.5.7 Minimal Caption (`builtin-minimal-caption`)
+
+- category `.social`, tags `["caption","minimal","clean"]`, supports `[.video, .image]`, no controls.
+- duration 5 s.
+- text clip `minimal-text`: "Your caption here", start 0, dur 5, SF Pro Display 28 semibold white on background `rgba(0,0,0,0.65)`, center, no shadow, position y=0.85; animation `.fade {}`, in 0.3 / out 0.3 / stagger 0.
+
+#### 3.5.8 Dynamic Zoom (`builtin-dynamic-zoom`)
+
+- category `.overlay`, tags `["zoom","dynamic","attention"]`, supports `[.video]`, no controls.
+- duration 3 s.
+- text clip `zoom-text`: "LOOK HERE", start 0.3, dur 2.4, SF Pro Display 48 heavy white, center, shadow, letterSpacing 3, stroke #4ADE80 width 2, position y=0.5; animation `.pop {popOvershoot: 1.4}`, in 0.25 / out 0.2 / stagger 0.01.
+- graphics clip `zoom-circle`: shape `.circle`, fill none, stroke #4ADE80 width 4 round caps, shadow rgba(74,222,128,0.5) blur 8, transform (0.5, 0.5, scale 0.6×0.6), blendOpacity 0.7, pulse emphasis (speed 2, intensity 0.4, loop true), start 0.1, dur 2.6.
+
+### 3.6 TemplatePreviewView
+
+Static-with-subtle-loop preview used inside the Selected Template sheet. Background black, corner radius 10, hairline overlay. An `animationPhase` (0 → 1, eased, repeating, auto-reverse, 2 s) drives opacity 0.6 → 1.0 and a small scale 1.0 → 1.03 (1.06 for emphasis-animated graphics).
+
+Rendering rules:
+- Graphics are drawn first (z-order: graphics under text).
+- Emoji stickers → `Text(emoji)` sized to `min(boxW, boxH) * 0.7`.
+- Shape preview: `circle/ellipse` → `Ellipse().fill(...).overlay(strokeBorder)`; `triangle` → custom `Triangle` shape; `star` → `Image(systemName: "star.fill").resizable()`; `arrow` → `Image(systemName: "arrowshape.right.fill")`; default → `RoundedRectangle(cornerRadius: style.cornerRadius ?? 4)`.
+- Fill color: solid → `Color(hexString:)`; else fallback `OpenReelTheme.accent`. Stroke uses `style.stroke.color` / `width`.
+- Text preview: `Text(textClip.text)` at `min(style.fontSize * 0.4, height * 0.3)`, weight via `fontWeight()` mapping (named weights and numeric ranges 800/700/600/500 → heavy/bold/semibold/medium, else regular), padded 6×3, with a `backgroundForText` that maps `rgba(...)` to `Color.black.opacity(0.5)` and hex strings via `Color(hexString:)`.
+- If a template has only effects (no text, no graphics): renders the `effectsOnlyPreview` — `wand.and.stars` icon + "{n} effect[s]" caption.
+
+### 3.7 Android mapping (Templates)
+
+- Persist as the same JSON shape (`TemplatePackage`) inside Room or a JSON file; expose `.openreeltemplate` MIME so Storage Access Framework can import/export.
+- Preview screen → custom `Composable` driven by `rememberInfiniteTransition`, mirroring the iOS logic 1:1 (z-order graphics under text).
+- Apply flow → service that copies `payload.textClips`/`graphicsClips` into the project at `playhead` (offset their `startTime` by the playhead time) and appends `payload.effects` onto the host clip stack.
+
+---
+
+## 4. SUBTITLES PANEL (`SubtitlesTabPanel.swift` + `SRTParser.swift`)
+
+Title: "Subtitles". Subtitle: "Import captions and set animation style". Header symbol: `captions.bubble`.
+
+### 4.1 Row list
+
+| Row | Symbol | Subtitle | Enabled | Action |
+|---|---|---|---|---|
+| Import SRT / VTT | doc.text | Bring captions into the project or current cue count | always | opens the local file importer |
+| Auto Captions (Offline), iOS | waveform.badge.mic | Uses the installed on-device speech model, or explains that none is installed | local model available, visual clip selected, not already running | runs OnDeviceCaptionService on the local clip |
+| Edit Transcript | text.word.spacing | Edit text to cut video, remove filler and silences | subtitles exist | opens the local transcript editor |
+| Add Captions to Timeline / Edit Caption Track | text.badge.plus / captions.bubble.fill | Creates or opens timeline text clips | subtitles exist | materializes cues and opens the Text tab |
+| Track Style | paintpalette | Animation and position for all captions | subtitles exist | opens style sheet |
+| Caption Presets | wand.and.stars | One-tap styled looks | subtitles exist | opens presets sheet |
+| Subtitle Cues | text.quote | Reviews current cues | subtitles exist | opens cue list |
+| Clear All | trash | Removes every cue | subtitles exist | calls clearSubtitles |
+
+Android ships SRT/VTT import and full local subtitle editing. Automatic Android
+transcription stays hidden until a speech model is bundled and validated.
+
+### 4.2 Track Style sheet
+
+Two sections:
+
+**Caption Style** — horizontal scroll of 6 chips (72×56, icon + label, accent-tinted when selected with 2px accent border):
+
+| `CaptionAnimationStyle` | Label | Symbol |
+|---|---|---|
+| .none | None | `text.alignleft` |
+| .wordHighlight | Highlight | `highlighter` |
+| .wordByWord | Word Pop | `text.word.spacing` |
+| .karaoke | Karaoke | `music.mic` |
+| .bounce | Bounce | `arrow.up.and.down` |
+| .typewriter | Typewriter | `keyboard` |
+
+Selecting writes immediately via `appState.updateSubtitleAnimationStyle(option.style)` (if cues exist).
+
+**Position** — 3-up `HStack` of full-width buttons for `OpenReelProject.SubtitlePosition.allCases` (`top`, `middle`, `bottom`). Label = `.rawValue.capitalized`. Selected = `accent.opacity(0.18)` background. Writes via `appState.updateSubtitlePosition(position)`.
+
+On first appearance (`task(id: subtitleSettingsSignature)`), `selectedAnimationStyle` and `selectedPosition` are seeded from the first subtitle (`animationStyle ?? .none`, `style?.position ?? .bottom`).
+
+### 4.3 Subtitle Cues sheet
+
+`VStack` listing the first 20 cues. Each row is a button (seeks playback to the cue):
+- Left: start timestamp formatted `%02d:%02d:%02d` where the third group is `frames = (fractional * 30)` — i.e. MM:SS:FF at 30fps.
+- Center: `subtitle.text` (max 2 lines).
+- Right: duration "%.1fs".
+- Padding 12×10, surface background, corner radius 10.
+
+If more than 20 cues exist: trailing "+ {n - 20} more" centered label.
+
+### 4.4 SRT / VTT parsing (`SRTParser.swift`)
+
+`SRTParser.parse(content)` (SRT):
+1. Normalize `\r\n` → `\n`, split by blank lines (`\n\n`).
+2. Each block must have ≥ 3 lines; line 1 = integer index, line 2 = "HH:MM:SS,mmm --> HH:MM:SS,mmm" (commas accepted), lines 3+ = text.
+3. Text is joined with `\n`, trimmed, and HTML-like tags `<[^>]+>` stripped via regex.
+4. Empty-text blocks are skipped.
+5. Returns array sorted by `startTime` ascending.
+
+`SRTParser.parseVTT(content)` (WebVTT):
+1. Normalize `\r\n` → `\n`, drop everything up to and including the first `WEBVTT` line.
+2. Split remaining content by blank lines.
+3. Cue id (optional) on line 0 if it does not contain `-->`; time line at index 0 or 1.
+4. Time line: same parse, allows extra cue-settings after the end time (uses the first space-separated token).
+5. Strip inline HTML/VTT tags via the same regex; skip empty text; auto-increment index.
+6. Sorted ascending by start time.
+
+`parseTimestamp`:
+- Replaces `,` with `.` (SRT uses comma decimal).
+- Splits on `:` — must yield exactly 3 parts (H, M, S.fff).
+- Returns `h*3600 + m*60 + s` as `TimeInterval`, else `nil`.
+
+`SRTParser.toSubtitles(parsed, style, animationStyle)`:
+- Wraps each `ParsedSubtitle` as `OpenReelProject.Subtitle(id: UUID, text, startTime, endTime, style, words: nil, animationStyle)`.
+- `words` is always nil from SRT/VTT; on-device transcription may supply per-word timing.
+
+### 4.5 Per-line vs global formatting
+
+- All `style` properties (font, color, background, alignment, **position**) and the animation style are **global** to the track — the panel only exposes track-wide controls and writes them across every cue.
+- Per-cue editing happens via the "Add Captions to Timeline / Edit Caption Track" button: it materializes each cue as a `TextClip` (via `appState.ensureSubtitleTextClips`) and hands the user off to the Text editor tab (`appState.editorTab = .text`) — which has full per-line styling, animation, and timing control.
+- Word-level timing (`subtitle.words`) is consumed by the karaoke/wordHighlight/wordByWord animation modes when available.
+
+### 4.6 On-device caption integration
+
+On iOS, OnDeviceCaptionService accepts a project-local media URL. The action is
+available only when Speech reports supportsOnDeviceRecognition, and its request
+sets requiresOnDeviceRecognition. Timed words are grouped into subtitle cues,
+then the existing timeline mapper and style flow are reused. Failure never
+falls back to a network recognizer.
+
+### 4.7 Loading / empty / error states
+
+- Empty: row subtitles read "Bring captions into the project" / "No cues available yet"; Track Style and Cues rows are disabled until cues exist.
+- Loading: the iOS offline-caption row shows “Creating Captions…” and is disabled until the local recognizer finishes.
+- Error: parser failures leave the cue list empty; caption-service errors are surfaced through local operation status.
+
+### 4.8 Android mapping (Subtitles)
+
+- Use SAF (`ACTION_OPEN_DOCUMENT`) with MIME filter `application/x-subrip`, `text/vtt`, `text/plain`.
+- Parser: keep a 1:1 Kotlin port of `SRTParser` (regex `Regex("<[^>]+>")`, splitting on `"\n\n"`). For richer WebVTT (cue-settings, styles, regions), consider `org.mozilla:rhino`-free libs like `subtitleConvert` or jsoup-free `webvtt-parser`. Default to the simple port for parity with iOS behavior.
+- ExoPlayer/Media3 already ships `SubtitleParser` for SRT and WebVTT via `androidx.media3:media3-extractor`. For rendering use a custom `SubtitleView` so the global style controls map cleanly.
+- Animation styles → Compose `AnimatedContent` per cue. Karaoke/wordHighlight use word-level timestamps when a local source provides them.
+- Persist `position` (`top/middle/bottom`) as a constraint on the caption Y anchor (0.1, 0.5, 0.9) and let the Text editor override per cue if the user promotes it to a real TextClip.
+
+---
+
+## 5. Cross-panel Android implementation checklist
+
+- `EditorMenuRow` → `ListItem` with leading icon, headline + supporting text, trailing chevron, ripple. Disabled state dims content and skips ripple.
+- `CompactSliderRow` → `Slider` with label + formatted value text aligned on a single row.
+- `LazyVGrid(columns: 2)` with spacing 10 → `LazyVerticalGrid(GridCells.Fixed(2), Arrangement.spacedBy(10.dp))`.
+- Sheet container → `ModalBottomSheet(skipPartiallyExpanded = false)` with the same internal layout (header card + scrollable body).
+- File importers → `rememberLauncherForActivityResult(OpenDocument())`.
+- Light haptic → `LocalHapticFeedback.current.performHapticFeedback(HapticFeedbackType.TextHandleMove)`.
+- All effect/preset/template enums stored as JSON strings should keep the exact iOS rawValue strings (`teal-orange` etc.) so packages move between platforms unchanged.
diff --git a/docs/android-port/07-export.md b/docs/android-port/07-export.md
new file mode 100644
index 00000000..625d4b38
--- /dev/null
+++ b/docs/android-port/07-export.md
@@ -0,0 +1,653 @@
+# 07 - Export (iOS -> Android port spec)
+
+This document describes the iOS export subsystem of "Openreel Video" exactly as implemented, so an Android team can rebuild it 1:1 in Kotlin. All numbers, defaults, formulas and option lists are verbatim from the iOS source.
+
+Source files:
+- `Openreel Video/Features/Export/ExportSheet.swift`
+- `Openreel Video/Features/Export/ExportProgressView.swift`
+- `Openreel Video/Core/Export/ProjectExportService.swift`
+- `Openreel Video/Core/Export/PhotoLibraryExportSaver.swift`
+- `Openreel Video/Shared/Components/ShareSheet.swift`
+
+---
+
+## 1. Export Sheet
+
+The export sheet is a modal full-height `NavigationStack > ScrollView` with a `Close` toolbar button (top-trailing). Vertical layout, padding 20, spacing 24 between sections, themed with `OpenReelTheme` (background/surface/surfaceElevated/accent/accentSecondary/destructive/textPrimary/textSecondary).
+
+The sheet is driven by these inputs/outputs:
+
+| Input | Type | Notes |
+|---|---|---|
+| `project` | `OpenReelProject` | Read-only; provides current canvas (`settings.width/height`) and project frame rate. |
+| `draft` (Binding) | `OpenReelProject.ExportPreferences` | The settings being edited. Mutable. |
+| `estimate` | `ProjectExportService.ExportEstimate` | `{ estimatedFileSize: Int64, estimatedDuration: TimeInterval }` recomputed by parent whenever `draft` changes. |
+| `requiresProjectApply` | `Bool` | True when chosen export resolution implies a different canvas aspect than the project; user must `onApplyToProject` first. |
+| `isExporting` | `Bool` | Disables buttons while an export is running. |
+| `onApplyToProject`, `onExport`, `onClose` | closures | |
+
+### 1.1 Section order (top to bottom)
+
+1. Header — title "Export Settings" (24pt rounded bold) + subtitle "Choose a preset, tune the format, and export with the current project render pipeline." (`reelBody`, secondary).
+2. Presets (horizontal scroll chips)
+3. Canvas (project/export comparison cards + resolution grid)
+4. Frame Rate (chips)
+5. Format (2-column grid of 9 cards)
+6. Quality (slider + help text + "Smaller File" shortcut card)
+7. Estimate (4-row summary card)
+8. (Conditional) "Apply Before Export" requirement card
+9. (Conditional) Apply To Project button (54pt height, `accentSecondary`, rounded 18)
+10. Export button (54pt height, `accent`, rounded 18; label "Export GIF" when codec == .gif else "Export Video"; disabled when `isExporting || requiresProjectApply`, opacity 0.55 when disabled)
+
+### 1.2 Presets section
+
+Horizontal scrolling chips, one per `OpenReelProject.ExportPreset` case. Tapping a preset replaces `draft` via `OpenReelProject.ExportPreferences.recommended(for: preset, currentSettings: project.settings, existing: draft)`. Selected chip uses `OpenReelTheme.accent` with white text; others use `OpenReelTheme.surface` and primary text. Corner radius 16. Padding H14 V12. Spacing 10.
+
+| Preset enum case | Display name | Subtitle |
+|---|---|---|
+| `.youtube` | "YouTube" | "16:9 1080p" |
+| `.tiktok` | "TikTok" | "9:16 vertical" |
+| `.instagramSquare` | "Instagram Square" | "1:1 feed" |
+| `.instagramPortrait` | "Instagram Portrait" | "4:5 feed" |
+| `.twitter` | "Twitter" | "16:9 social" |
+| `.custom` | "Custom" | "Manual settings" |
+
+The preset's job is to pick a recommended resolution + format + quality combo (see `ExportPreferences.recommended` in the project domain layer). The user can subsequently modify any field; doing so should set `draft.preset = .custom` (the "Smaller File" shortcut does this explicitly).
+
+### 1.3 Canvas section
+
+Two cards side by side ("Project" and "Export") each showing `WxH` and an aspect label. Below them, a 2-column `LazyVGrid` of three resolution buttons. The choices adapt to the current draft aspect:
+
+- If aspect is roughly 1:1 (|ratio-1| < 0.02): offers `1080x1080`, `1440x1440`, `2160x2160`.
+- If portrait and aspect label resolves to "4:5": offers `1080x1350`, `1440x1800`, `2160x2700`.
+- Otherwise portrait (e.g. 9:16): `1080x1920`, `1440x2560`, `2160x3840`.
+- Else (landscape): `1280x720`, `1920x1080`, `3840x2160`.
+
+Tapping sets `draft.resolution = resolution`. There is no manual width/height entry — only these three quick choices per aspect.
+
+Aspect labels are computed with `aspectLabel(for:)`:
+- 16:9 if |ratio - 16/9| < 0.02
+- 9:16 if |ratio - 9/16| < 0.02
+- 1:1 if |ratio - 1| < 0.02
+- 4:5 if |ratio - 4/5| < 0.02
+- else `String(format: "%.2f:1", ratio)`
+
+Resolution card style: rounded 16, surface or accent if selected, min height 72, H14 padding, value 14pt semibold + aspect caption.
+
+### 1.4 Frame Rate section
+
+Horizontal capsule chips (height 42, H14 padding) for every value in `NewProjectConfiguration.supportedFrameRates`. Label format: `"\(Int(frameRate)) fps"`. Selected uses `accent`, unselected uses `surfaceElevated`. Tapping sets `draft.frameRate = frameRate` (stored as `Double`).
+
+Allowed frame rates: whatever `NewProjectConfiguration.supportedFrameRates` exposes (see project creation doc). Typically: 24, 25, 30, 50, 60. GIF tops out separately (see section 2). Spacing 10.
+
+### 1.5 Format section
+
+2-column grid of 9 cards. Each card shows the format `label` (14pt semibold rounded) and a one-line `detailLabel`. Selected = accent / white text; unselected = surface / primary text. Min height 82, corner radius 16, H14 padding.
+
+| label | container | codec | proResProfile | detailLabel |
+|---|---|---|---|---|
+| MP4 H.264 | .mp4 | .h264 | nil | "Fast and compatible" |
+| MP4 H.265 | .mp4 | .hevc | nil | "Smaller files" |
+| MOV H.264 | .mov | .h264 | nil | "MOV wrapper" |
+| MOV H.265 | .mov | .hevc | nil | "HEVC in MOV" |
+| Animated GIF | .gif | .gif | nil | "Looping animation" |
+| ProRes Proxy | .mov | .proRes | .proxy | "Light offline master" |
+| ProRes LT | .mov | .proRes | .lt | "Smaller ProRes" |
+| ProRes 422 | .mov | .proRes | .standard | "Editing master" |
+| ProRes HQ | .mov | .proRes | .hq | "Maximum quality" |
+
+`outputSummary` strings (used in estimate row + progress view):
+- h264 -> "MP4 H.264" or "MOV H.264"
+- hevc -> "MP4 H.265" or "MOV H.265"
+- proRes -> "MOV ProRes Proxy/LT/422/HQ"
+- gif -> "Animated GIF"
+
+Setting `draft.format = option.format` is the only side effect.
+
+### 1.6 Quality section
+
+Header row: "Quality" title + a right-aligned current label (caption, secondary text):
+
+| Quality range | Label |
+|---|---|
+| < 0.4 | "Low" |
+| < 0.7 | "Balanced" |
+| < 0.9 | "High" |
+| >= 0.9 | "Maximum" |
+
+Slider: `value: $draft.quality`, range `0.2 ... 1`, step `0.05`, tint `accent`. **Disabled when codec == .proRes** (ProRes profile picks quality directly).
+
+Help text (caption, secondary) varies by codec:
+- `.proRes` -> "ProRes profile controls quality directly."
+- `.gif` -> "Higher values render smoother animated GIFs, up to 15 fps."
+- `.h264 / .hevc` -> "Higher values raise bitrate for H.264 and H.265 exports."
+
+"Smaller File" shortcut (only shown when codec != .proRes): a card with `internaldrive` icon, title "Smaller File", subtitle "Switch to MP4 H.265 and trim the bitrate target for sharing." Tapping it executes:
+```
+draft.preset = .custom
+draft.format = ExportFormat(container: .mp4, codec: .hevc)
+draft.quality = min(draft.quality, 0.45)
+```
+
+### 1.7 Estimate section
+
+Single rounded-18 surface card padded 16 with four rows (spacing 12):
+
+1. **File Size** — `ByteCountFormatter.string(fromByteCount: estimate.estimatedFileSize, countStyle: .file)`.
+2. **Export Time** — `DateComponentsFormatter` abbreviated, hours/min/sec if `>= 3600` else min/sec, drop leading zeros.
+3. **Target Bitrate** — call `ProjectExportService.targetBitRates(for: draft)`. If GIF: `"Animated GIF • up to 15 fps"`. Else: `"<video> video • <audio> audio"` where each bitrate is formatted as `"%.1f Mbps"` if >= 1,000,000 else `"<kbps rounded> kbps"`.
+4. **Output** — `draft.format.outputSummary` (see table above).
+
+### 1.8 "Apply Before Export" requirement card
+
+Shown only when `requiresProjectApply == true`. Surface card rounded 18 with accent-tinted stroke (opacity 0.35). Title "Apply Before Export", body "This export changes the canvas aspect ratio. Apply it to the project first so you can reframe clips with the existing preview crop and transform tools." Followed by the "Apply To Project" button (`accentSecondary`).
+
+### 1.9 Defaults summary
+
+| Field | Default source |
+|---|---|
+| `draft.preset` | Whatever the caller passes in (typically `project.exportPreferences.preset`). |
+| `draft.resolution` | `project.exportPreferences.resolution`; mutated when preset/aspect changes. |
+| `draft.frameRate` | `project.exportPreferences.frameRate` (defaults to project's frame rate). |
+| `draft.format` | `ExportFormat(container: .mp4, codec: .h264)` is the typical default; ExportPreferences may carry a different value. |
+| `draft.quality` | 0.2 ... 1, defaults from `ExportPreferences` (typically ~0.65 - "Balanced"). |
+| Audio sample rate | 48,000 (hard-coded). |
+| Audio channels | 2 (hard-coded). |
+
+### 1.10 Inter-option dependencies
+
+- ProRes -> quality slider disabled; quality help text changes; bitrate fully driven by `proResProfile`.
+- GIF -> audio settings nil; export button label "Export GIF"; `quality` reinterpreted as smoothness up to 15 fps; bitrate row shows "Animated GIF • up to 15 fps".
+- GIF -> file size estimate uses a wholly different formula (see 1.11 / section 2).
+- Changing resolution that flips the aspect ratio relative to the project -> parent sets `requiresProjectApply = true` and shows the apply card + apply button, and disables the export button.
+- "Smaller File" -> forces `format = MP4 H.265`, clamps `quality` to <= 0.45, sets `preset = .custom`.
+
+### 1.11 Estimate formulas (`ProjectExportService.estimate`)
+
+```
+duration = max(project.timeline.duration, 1 / max(frameRate, 1))
+
+if codec == .gif:
+ frameCount = duration * gifFrameRate(prefs) // see section 2
+ pixels = width * height
+ qualityScale = 0.16 + quality * 0.18
+ fileSize = max(frameCount * pixels * qualityScale, 128_000) // bytes, Int64
+else:
+ fileSize = (duration * (videoBitRate + audioBitRate)) / 8 // bytes
+
+megapixels = (width * height) / 1_000_000
+
+baseFactor = { .h264: 0.75, .hevc: 0.9, .proRes: 1.4, .gif: 1.15 }[codec]
+
+estimatedDuration = max(duration * megapixels * baseFactor, 1) // seconds
+```
+
+`videoBitRate` (`estimatedVideoBitRate`) is computed as:
+```
+scale = (width * height * frameRate) / (1920 * 1080 * 30)
+normalizedQuality = (quality - 0.2) / 0.8
+base = lerp(minimumBase, maximumBase, normalizedQuality)
+bitrate = clamp(base * scale, minimum, maximum)
+```
+
+| Codec | minimumBase | maximumBase | minimum | maximum |
+|---|---|---|---|---|
+| h264 | 1,400,000 | 4,200,000 | 900,000 | 28,000,000 |
+| hevc | 900,000 | 2,800,000 | 650,000 | 20,000,000 |
+
+ProRes overrides the formula:
+```
+baseBitRate = { proxy: 45_000_000, lt: 100_000_000, standard: 147_000_000, hq: 220_000_000 }
+bitrate = max(baseBitRate, baseBitRate * scale)
+```
+GIF returns 0.
+
+`audioBitRate` (`estimatedAudioBitRate`):
+- gif: 0
+- proRes: 1,536,000 (16-bit 48 kHz stereo PCM)
+- h264 / hevc: 128,000 (AAC)
+
+---
+
+## 2. GIF export specifics
+
+GIF takes a completely different code path (`writeGIFExport`) that bypasses `AVAssetWriter` and uses `ImageIO` / `CGImageDestination`.
+
+- **File type identifier**: `UTType.gif.identifier`.
+- **Looping**: `kCGImagePropertyGIFLoopCount = 0` (infinite loop) set as destination-level property.
+- **Frame rate**: `gifFrameRate(for: prefs)`:
+ ```
+ qualityFrameRate = 8 + ((clamp(quality, 0.2, 1) - 0.2) / 0.8) * 7 // 8..15
+ return min(max(prefs.frameRate, 1), round(qualityFrameRate))
+ ```
+ So GIF fps is the smaller of (a) the chosen project fps and (b) a quality-driven ramp from 8 fps (quality=0.2) to 15 fps (quality=1.0), rounded.
+- **Frame delay**: `1 / gifFrameRate` set per-frame via `kCGImagePropertyGIFDelayTime` and `kCGImagePropertyGIFUnclampedDelayTime`.
+- **Dimensions**: directly the chosen `resolution.width x resolution.height` (no downscale).
+- **Palette**: implicit — `CGImageDestinationAddImage` writes 8-bit palette GIF; no custom palette is generated.
+- **Audio**: none. `audioSettings` returns `nil` for GIF in `audioSettings(for:bitRate:)`.
+- **Pipeline**: pull pixel buffer from `AVAssetReaderVideoCompositionOutput` (BGRA, Metal compatible), wrap as `CIImage`, render via `CIContext.createCGImage` at `configuration.renderSize`, append to `CGImageDestination`. Frames are time-gated: any sample whose PTS is earlier than `nextFrameTime` is skipped; `nextFrameTime = presentationTime + frameInterval` (where `frameInterval = CMTime(seconds: frameDelay, preferredTimescale: 600)`).
+- **Output extension**: `.gif`.
+- **Progress**: detail "Rendering GIF frame N"; fraction `min(0.92, 0.2 + progressOfDuration * 0.7)`; finalize step "Encoding animated GIF" -> "Wrapping up GIF metadata".
+- **No frames -> error**: `"No GIF frames were rendered."`
+
+---
+
+## 3. ExportProgressView
+
+`ExportProgressView` is a centered modal overlay on top of a black 35% scrim (`ZStack`, `Color.black.opacity(0.35)`).
+
+Inputs:
+- `status: ProjectExportService.ExportProgress { fraction: 0..1, stage, detail }`
+- `remainingTime: TimeInterval?`
+- `preferences: OpenReelProject.ExportPreferences` (only for the summary line)
+- `onCancel: () -> Void`
+
+Layout (centered card on `surfaceElevated`, rounded 20, padded 24, VStack spacing 16):
+
+1. `ProgressView(value: status.fraction)` — linear bar, tinted `accent`, width 220, animated easeInOut 0.2 on fraction change.
+2. Stage title (`reelBody`, white) from `status.stage.title`:
+ - `.preparing` -> "Preparing Export"
+ - `.rendering` -> "Rendering Export"
+ - `.finalizing` -> "Finalizing Export"
+ - `.completed` -> "Export Complete"
+3. Percent label: `"\(Int(status.fraction * 100))%"` (14pt semibold rounded, secondary).
+4. `status.detail` (caption, secondary) — sub-step description, e.g. "Rendering video and audio", "Encoding animated GIF", "Wrapping up metadata".
+5. Summary line: `"<W>x<H> • <format.outputSummary>"` (caption, secondary).
+6. If `remainingTime != nil`: `"About <formattedDuration(remainingTime)> remaining"` (caption, secondary), formatted with `DateComponentsFormatter` (hour/min/sec if >=3600 else min/sec, abbreviated style, dropLeading).
+7. **Cancel button** — "Cancel Export" capsule, 42 high, H18 padded, on `OpenReelTheme.destructive`. Calls `onCancel`.
+
+The view does NOT render a completion success card. When `status.stage == .completed`, the parent screen is responsible for dismissing this overlay and presenting next-step affordances (Save to Photos, Share, Open in...). Those affordances live outside this file; expect the parent to:
+- Show a `ShareSheet` (section 6) with the exported file URL.
+- Offer "Save to Photos" via `PhotoLibraryExportSaver.saveVideo(at:)` or `saveAnimatedImage(at:)`.
+- Surface any thrown `ExportError` via an alert with `error.errorDescription`.
+
+`remainingTime` is computed by the parent from `status.fraction` and elapsed time; this view only formats it.
+
+### Stage -> fraction progression
+
+`ExportProgressBox` (in ProjectExportService) drives the fraction for non-GIF exports:
+- Preparing stages explicitly emit fixed fractions: 0.02 "Analyzing timeline", 0.05 "Building composition", 0.08 "Preparing media and audio", 0.18 "Configuring effects and render pipeline".
+- Rendering: weighted sum: `videoFraction * (hasAudio ? 0.56 : 0.74) + audioFraction * (hasAudio ? 0.18 : 0)`, mapped onto `0.18 + ... + 0.99` band, **monotonically increasing** (`lastProgress = max(lastProgress, ...)`).
+- Finalizing: adds `finalizingFraction * 0.08`, with synthetic emissions 0.96 "Finishing the export file", 0.99 "Wrapping up metadata".
+- Completion: `fraction: 1, stage: .completed, detail: "Export ready"`.
+
+GIF progression: 0.2 "Rendering GIF frames" -> per-frame `min(0.92, 0.2 + frac*0.7)` -> 0.96 "Encoding animated GIF" -> 0.99 "Wrapping up GIF metadata" -> 1 completed.
+
+---
+
+## 4. ProjectExportService (encoding pipeline)
+
+Top-level entry point: `static func export(project, sources, projectDirectoryURL, configuration, progress) async throws -> URL`. Returns the temporary file URL of the produced export.
+
+### 4.1 Pipeline architecture
+
+The service uses a hand-rolled `AVAssetReader` + `AVAssetWriter` pipeline (NOT `AVAssetExportSession` — there is a legacy `legacyExport` helper retained for iOS 16, but the main path is the reader/writer pair). Reason: it needs per-frame CIFilter compositing for effects, text, graphics, overlays, transitions and AI effects, plus full control over progress, cancellation, and codec settings.
+
+High-level steps:
+
+1. **Resolve configuration** (`resolveConfiguration`) -> `ResolvedExportConfiguration { preferences, fileType, renderSize, videoSettings, audioSettings, videoBitRate, audioBitRate }`. `fileType` is `.mp4`, `.mov`, or `nil` (GIF).
+2. **Build playback composition** via `PlaybackCompositionBuilder.build(sources, audioDescriptor)` -> `{ composition: AVMutableComposition, audioMix: AVAudioMix? }`. Throws `.noPlayableTracks` if nil.
+3. **Prepare audio** (`prepareCompositionForExport`):
+ - If `TimelineAudioDescriptor` has any non-zero pan or any enabled audio effect, render audio offline via `TimelineAudioOfflineRenderer.render(descriptor, sampleRate: 48_000, channels: 2)` to a temp file. Replace all audio tracks in the composition with the processed track and clear `audioMix`.
+ - Otherwise keep the live `audioMix` and original audio tracks (no offline render).
+ - The processed temp file is deleted in `defer`.
+4. **Compose video** (`makeFilteringVideoComposition`) — uses `AVMutableVideoComposition.videoComposition(with:applyingCIFiltersWithHandler:)`. For each frame:
+ - Compute `timelineTime = compositionTime.seconds` (clamped >= 0).
+ - Call `composePreviewFrame(sourceImage, ...)` to bake the entire visual stack (transitions, active video clip with effects + keyframe animation, image overlays, graphics clips, text clips) onto a black canvas of `renderSize`.
+ - `request.finish(with: frame, context: context)`.
+ - The CI context is Metal-backed (`MTLCreateSystemDefaultDevice` -> `CIContext(mtlDevice:)`), falling back to a software CIContext.
+ - Set `videoComposition.renderSize = renderSize`, `frameDuration = CMTime(value: 1, timescale: max(round(frameRate), 1))`.
+5. **Read+write** (`writeConfiguredExport` for video, `writeGIFExport` for GIF):
+ - Add `AVAssetReaderVideoCompositionOutput` with pixel format `kCVPixelFormatType_32BGRA`, `kCVPixelBufferMetalCompatibilityKey: true`, `alwaysCopiesSampleData = false`, `.videoComposition = videoComposition`.
+ - Optionally add `AVAssetReaderAudioMixOutput(audioTracks, audioSettings: nil)` with `audioMix` attached.
+ - Add `AVAssetWriterInput(mediaType: .video, outputSettings: configuration.videoSettings)`, `expectsMediaDataInRealTime = false`.
+ - Optionally add `AVAssetWriterInput(mediaType: .audio, outputSettings: configuration.audioSettings)`.
+ - `writer.startWriting()`, `reader.startReading()`, `writer.startSession(atSourceTime: .zero)`.
+ - Drain video and audio in parallel on two `DispatchQueue`s ("openreel.export.video" / "openreel.export.audio") via `requestMediaDataWhenReady`. Each pulls samples from its output with `copyNextSampleBuffer` and appends them to the writer input until exhausted, then `markAsFinished()`. A `DispatchGroup` waits for both.
+ - PTS-based progress: `fraction = clamp(pts.seconds / max(duration, 0.1), 0, 1)`; main-actor dispatched to the progress callback.
+ - At the end: `finishWriting` async; final progress emissions; cleanup.
+
+### 4.2 Video encoder settings (`videoSettings`)
+
+For h264/hevc/proRes (not GIF):
+```
+AVVideoCodecKey = .h264 | .hevc | .proRes422Proxy | .proRes422LT | .proRes422 | .proRes422HQ
+AVVideoWidthKey = preferences.resolution.width
+AVVideoHeightKey = preferences.resolution.height
+
+if codec != .proRes:
+ AVVideoCompressionPropertiesKey = {
+ AVVideoAverageBitRateKey: targetVideoBitRate,
+ AVVideoExpectedSourceFrameRateKey: Int(round(frameRate)),
+ AVVideoMaxKeyFrameIntervalKey: Int(max(round(frameRate) * 2, 1)) // ~ every 2 seconds
+ }
+```
+ProRes intentionally has no bitrate / GOP override (codec is intra-frame, profile picks data rate).
+There is **no HDR / 10-bit color setting**, **no color primaries / transfer function override**, **no profile/level setting**, **no B-frame configuration**, **no entropy mode**. Whatever AVFoundation chooses by default is used.
+
+### 4.3 Audio encoder settings (`audioSettings`)
+
+- GIF -> `nil`.
+- ProRes -> LPCM:
+ ```
+ AVFormatIDKey = kAudioFormatLinearPCM
+ AVSampleRateKey = 48_000
+ AVNumberOfChannelsKey = 2
+ AVLinearPCMBitDepthKey = 16
+ AVLinearPCMIsBigEndianKey = false
+ AVLinearPCMIsFloatKey = false
+ AVLinearPCMIsNonInterleaved = false
+ ```
+- H.264 / HEVC -> AAC:
+ ```
+ AVFormatIDKey = kAudioFormatMPEG4AAC
+ AVSampleRateKey = 48_000
+ AVNumberOfChannelsKey = 2
+ AVEncoderBitRateKey = targetAudioBitRate // 128_000
+ ```
+
+### 4.4 How effects bake in
+
+`composePreviewFrame` runs inside the CIFilter handler for every output frame and:
+1. Starts with a solid black `CIImage` cropped to `renderSize`.
+2. Renders any active visual transition between two clips (`activeTransitionFrame`) via `TransitionCompositor.apply(outgoing, incoming, transition, progress)`. The two clips involved are recorded so they are not drawn again as plain clips.
+3. Renders the active video clip — animated by `KeyframeEngine.animatedClip(clip, at:)` — through `VideoEffectRenderer.render(image, effects, projectDirectoryURL, timelineTime, effectContext)`. AI effects can additionally receive a `FrameEffectContext` resolved synchronously by `AIFrameContextBuilder.frameContextSynchronously(...)` using a `MediaAnalysisService` and a CVPixelBuffer rendered for that frame.
+4. Renders active image overlays the same way (animated + effected + positioned via `presentVisualLayer`).
+5. Renders active graphics clips (`renderGraphicsLayer`).
+6. Renders active text clips (`renderTextLayer`).
+
+Each layer is `composited(over:).cropped(to: canvasRect)`. The final cropped `CIImage` is returned to `request.finish(with:context:)`.
+
+### 4.5 How audio mixes
+
+Two modes (decided by `requiresProcessedAudio(for: descriptor)`):
+
+- **Live mix** — uses the `AVAudioMix` produced by `PlaybackCompositionBuilder`. Tracks remain individual and the reader's `AVAssetReaderAudioMixOutput` applies the mix (volume, fades, etc.) on the fly. Used when no segment has per-clip or per-track pan and no audio effect is enabled.
+- **Offline-rendered processed audio** — when any segment has |trackPan + clipPan| > 0.0001 or any enabled audio effect, the service calls `TimelineAudioOfflineRenderer.render(descriptor, sampleRate: 48_000, channels: 2)`. The resulting file (likely WAV/CAF) is loaded as `AVURLAsset`, its audio track copied into a freshly added composition audio track (after removing all existing audio tracks). `audioMix` is set to `nil`. This pre-bakes panning + audio effects.
+
+Either way the writer receives stereo 48 kHz audio.
+
+### 4.6 Error handling
+
+`ExportError: LocalizedError, Equatable`:
+- `.noPlayableTracks` -> "Add video or audio clips before exporting."
+- `.noVideoTracks` -> "Export currently requires at least one visible video clip."
+- `.sessionCreationFailed` -> "The export session could not be created."
+- `.unsupportedFileType` -> "This device does not support the current export format."
+- `.exportFailed(String)` -> message verbatim.
+
+Specific surfaces:
+- Reader/writer construction failures -> `.sessionCreationFailed`.
+- `fileType == nil` for non-GIF -> `.unsupportedFileType`.
+- `canAdd` fails for inputs/outputs -> `.exportFailed("...could not create...")`.
+- `startWriting` / `startReading` false -> `.exportFailed(writer.error?.localizedDescription ?? ...)`.
+- Sample append failure -> `.exportFailed("The export writer rejected a video/audio frame/sample.")`.
+- Reader status `.failed` -> `.exportFailed(reader.error?.localizedDescription)`.
+- Writer not `.completed` after finishWriting -> `.exportFailed(writer.error?.localizedDescription)`.
+- Cancellation (any source) -> `.exportFailed("The export was cancelled.")`.
+- GIF: destination create failure, frame render failure, no frames, finalize failure all map to `.exportFailed("...")`.
+
+On any throw the temp output file at `outputURL` is deleted (`try? FileManager.default.removeItem(at: outputURL)`). The processed audio temp file is deleted in `defer`.
+
+### 4.7 Cancellation
+
+Cancellation is plumbed through:
+- A `ExportCancellationBox` (NSLock-protected `Bool`) wired to `withTaskCancellationHandler(onCancel: { cancellation.cancel() })`. Swift task cancellation propagates here.
+- The UI cancel button calls a parent closure that cancels the wrapping `Task`.
+- Inside both video and audio drain loops, `exportLoopError` checks `cancellation.isCancelled || Task.isCancelled || writer.status == .cancelled || reader.status == .cancelled`. If true, the loop pushes an `.exportFailed("The export was cancelled.")` into the shared `ExportFailureBox`, marks the input finished, and ends.
+- The catch block calls `reader.cancelReading()` + `writer.cancelWriting()`.
+- For GIF, the per-frame loop also checks cancellation and calls `reader.cancelReading()` before throwing.
+
+### 4.8 Background mode behavior
+
+There is no explicit background task or `UIApplication.beginBackgroundTask` handling in this file. The service runs as a standard Swift task. If the app is backgrounded:
+- AVAssetWriter encoding can continue briefly with default iOS rules (no special audio session); long exports may be suspended.
+- No re-entry / resumption mechanism exists; canceling and restarting is the user's only option.
+- The Android port should explicitly use a foreground service (see section 8) to avoid this fragility.
+
+### 4.9 Output file location
+
+`makeOutputURL`:
+```
+extension = mov | mp4 | gif (from container)
+sanitized = project.name keeping only alphanumeric runs joined by '-' (fallback "OpenReel-Export")
+timestamp = ISO8601 with ':' replaced by '-'
+url = FileManager.default.temporaryDirectory / "<sanitized>-<timestamp>.<ext>"
+```
+The file lives in the app's temp dir. Any existing file at that URL is removed before writing.
+
+### 4.10 ExportProgress.Stage detail strings (verbatim, for parity)
+
+Preparing emissions: "Analyzing timeline", "Building composition", "Preparing media and audio", "Configuring effects and render pipeline".
+Rendering emissions: "Rendering video frames" (no audio) or "Rendering video and audio".
+Finalizing emissions: "Packaging the movie file", "Finishing the export file", "Wrapping up metadata".
+GIF rendering: "Rendering GIF frames" / "Rendering GIF frame <N>"; finalizing: "Encoding animated GIF", "Wrapping up GIF metadata".
+Completed: "Export ready".
+
+---
+
+## 5. PhotoLibraryExportSaver
+
+Tiny `enum` wrapping Photos save logic.
+
+```
+enum SaveError: LocalizedError {
+ case permissionDenied -> "OpenReel needs Photos access to save exports."
+ case creationFailed -> "The export could not be saved to Photos."
+}
+```
+
+Three async functions:
+
+1. `saveVideo(at url: URL)` — saves a video file (mp4/mov):
+ - `await PHPhotoLibrary.requestAuthorization(for: .addOnly)`; only `.authorized` and `.limited` proceed, anything else throws `.permissionDenied`.
+ - `PHPhotoLibrary.shared().performChanges { PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url) }`.
+ - Completion: error -> rethrow; `success == true` -> ok; else `.creationFailed`.
+
+2. `saveAnimatedImage(at url: URL)` — for GIFs:
+ - `let data = try Data(contentsOf: url)`; delegates to `saveImage(data:)`.
+
+3. `saveImage(data: Data)`:
+ - Same auth flow as above.
+ - `PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil)`.
+
+**Notes**:
+- No album creation. The asset goes straight to the "All Photos" / camera roll. No "OpenReel" album is created on iOS today.
+- Permission is requested with `.addOnly` (Photos add-only API; doesn't require full library access).
+- No retries, no progress, no thumbnail generation.
+
+---
+
+## 6. ShareSheet
+
+`ShareSheet` is a one-shot `UIViewControllerRepresentable` over `UIActivityViewController`:
+
+```swift
+struct ShareSheet: UIViewControllerRepresentable {
+ var activityItems: [Any]
+ func makeUIViewController(context:) -> UIActivityViewController {
+ UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
+ }
+}
+```
+
+That's the entire file. There are no `excludedActivityTypes`, no custom `applicationActivities`, no completion callback. The parent screen creates the sheet with `activityItems: [exportedFileURL]` (a single `URL` to the temp file produced by `ProjectExportService`). UIKit infers UTType from the file extension (`.mp4`, `.mov`, `.gif`) and offers the system's standard apps: Messages, Mail, AirDrop, Save to Files, Save Video / Save Image, Copy, plus any installed share extensions (Instagram, TikTok, WhatsApp, etc.).
+
+What's included in the share payload: **only the file URL**. No metadata, no caption text, no preview thumbnail override, no project JSON.
+
+---
+
+## 7. Edge cases
+
+| Scenario | iOS behavior today |
+|---|---|
+| Out of storage during write | `AVAssetWriterInput.append` returns false -> `.exportFailed(writer.error?.localizedDescription)`; partial file is removed in catch. No proactive free-space check before starting. |
+| Phone call / interruption | AVFoundation continues (no `AVAudioSession` is configured by this service); typically unaffected. Audio session collisions are not handled here. |
+| App backgrounded | No `beginBackgroundTask`; iOS will eventually suspend the process and the writer fails. User must restart export. |
+| Very long projects | `duration` derives from `composition.duration`, project timeline, or `0.1` minimum. No special chunking; everything streams through a single reader+writer pass. Memory is bounded by pixel buffer pool size (Metal-compatible BGRA). Estimate time grows linearly with `duration * megapixels * baseFactor`. |
+| Cancelled mid-flight | Both inputs are stopped, partial file deleted, throws `"The export was cancelled."` |
+| No video clips | `.noVideoTracks` -> "Export currently requires at least one visible video clip." |
+| No clips at all | `.noPlayableTracks` -> "Add video or audio clips before exporting." |
+| Unsupported file type | `.unsupportedFileType` -> "This device does not support the current export format." |
+| ProRes on devices without HW encoder | Falls through to whatever AVFoundation reports; surfaces as writer error. No explicit pre-flight check. |
+| Bitrate above device capability | Same; relies on AVFoundation. |
+| Memory pressure (4K @ 60 fps with many effects) | No guards; CIContext is Metal-backed which helps, but no frame-rate throttling or quality fallback. |
+| Empty title sanitization | `"OpenReel-Export"` is used. |
+| Filename collision | Timestamped per-export, so unlikely; pre-write `removeItem` ensures clean slate. |
+| GIF with quality 0.2 and frameRate 60 | Effective GIF fps = min(60, round(8)) = 8 fps. |
+| GIF with quality 1.0 and frameRate 24 | Effective GIF fps = min(24, round(15)) = 15 fps. |
+| Audio with effects + cancellation during offline render | Offline render runs before reader/writer setup; cancelling at that stage is not propagated explicitly (it's synchronous via `TimelineAudioOfflineRenderer.render`). After it completes, the processed file is cleaned up in `defer`. |
+| Photos permission denied | `PhotoLibraryExportSaver.SaveError.permissionDenied` thrown; parent should alert the user. |
+| Photos save fails | `.creationFailed` thrown. |
+
+---
+
+## 8. Android mapping suggestions
+
+Below: a direct 1:1 mapping plan. Names map iOS -> Android.
+
+### 8.1 Data models
+
+Mirror `OpenReelProject.ExportPreferences` in Kotlin as a `@Serializable` data class with the exact same fields: `preset`, `resolution(width,height)`, `frameRate: Double`, `format(container, codec, proResProfile?)`, `quality: Float`. Use sealed classes / enums for `ExportPreset`, `ExportContainer (MP4, MOV, GIF)`, `ExportCodec (H264, HEVC, PRORES, GIF)`, `ProResProfile (PROXY, LT, STANDARD, HQ)`. Note: Android **cannot encode ProRes** natively (no MediaCodec support); either:
+- Hide ProRes options on Android, or
+- Bundle FFmpeg (e.g. `FFmpegKit`) and use it for ProRes only — accepting binary-size cost.
+
+### 8.2 Encoding pipeline
+
+Use **AndroidX Media3 Transformer** (recommended for 1:1 effort) — it provides AVMutableComposition-style composition (`EditedMediaItemSequence`, `EditedMediaItem`, `Composition`), per-frame `Effects` (custom `GlEffect` for the equivalent of CIFilters), audio mixing, progress callbacks, and cancellation. It outputs MP4 (H.264 / H.265).
+
+| iOS construct | Media3 equivalent |
+|---|---|
+| `AVMutableComposition` | `Composition` / `EditedMediaItemSequence` |
+| `AVMutableVideoComposition` + CIFilter handler | `Effects` with custom `GlEffect`s |
+| `AVAudioMix` | `AudioProcessor` chain attached per `EditedMediaItem` |
+| `AVAssetReader` + `AVAssetWriter` | `Transformer` (single class manages both) |
+| `videoSettings`/`audioSettings` | `TransformationRequest` + `Transformer.Builder` (set bitrate/codec/resolution) |
+| `progress` callback | `Transformer.Listener.onTransformationProgressUpdate` + `getProgress(holder)` |
+| Cancellation | `Transformer.cancel()` |
+
+For container = MOV, Media3 supports `.mov` output via `Muxer` configuration; if unavailable for the codec mix you need, remux via MediaMuxer or fall back to FFmpeg.
+
+If Media3 doesn't cover something (e.g. ProRes, GIF), drop to **`MediaCodec` + `MediaMuxer`** directly. Pipeline shape:
+1. Decode each source via `MediaCodec` (async surface decoder) -> GL texture.
+2. Composite on a shared `EGLContext` using shaders mirroring `VideoEffectRenderer`.
+3. Push the composited frame to an encoder `MediaCodec` input surface (CONFIGURE for H264 / HEVC via `MediaFormat.MIMETYPE_VIDEO_AVC / HEVC`, set `KEY_BIT_RATE`, `KEY_FRAME_RATE`, `KEY_I_FRAME_INTERVAL = 2`, `KEY_COLOR_FORMAT = COLOR_FormatSurface`).
+4. Mux video + audio with `MediaMuxer` (`OutputFormat.MUXER_OUTPUT_MPEG_4`).
+
+Keyframe interval mapping: iOS uses ~ `frameRate * 2` frames; Android's `MediaFormat.KEY_I_FRAME_INTERVAL` is in **seconds** -> set to `2`.
+
+Bitrate constants from section 1.11 should be reused verbatim — Android encoders accept the same numeric bitrates.
+
+### 8.3 Audio
+
+Use Media3's `AudioProcessor` chain for pan + audio effects, or pre-render with `AudioTrack`/OpenSL/Oboe + a custom mixer if you need full parity with `TimelineAudioOfflineRenderer`. Encode AAC at 128 kbps (h264/hevc) or LPCM (ProRes path) with `MediaCodec` AAC encoder (`audio/mp4a-latm`, `KEY_AAC_PROFILE = AACObjectLC`, `KEY_SAMPLE_RATE = 48000`, `KEY_CHANNEL_COUNT = 2`, `KEY_BIT_RATE = 128000`).
+
+### 8.4 GIF
+
+There is no built-in GIF encoder on Android. Recommended encoders:
+- **AnimatedImageDrawable + ImageDecoder** (decode-only, can't encode).
+- **`android-gif-encoder`** (small Java GIF encoder library, palette = NeuQuant) — use this for parity with iOS.
+- **`Glide`'s `GifEncoder`** is internal; prefer a standalone library.
+- For best quality, run FFmpeg with `palettegen` + `paletteuse`.
+
+Mirror iOS behavior:
+- `loopCount = 0` (infinite).
+- Frame delay = `1 / gifFps` seconds.
+- `gifFps = min(prefs.frameRate, round(8 + ((clamp(quality,0.2,1)-0.2)/0.8) * 7))`.
+- Dimensions = chosen `resolution`.
+- No audio.
+- Output extension `.gif`.
+
+Pipeline: decode each source frame via Media3 `FrameProcessor` -> Bitmap (or read PBO from GL) at `renderSize`, feed into the GIF encoder one frame at a time, finalize.
+
+### 8.5 Saving to "Photos" (MediaStore)
+
+Replace `PhotoLibraryExportSaver` with **MediaStore**:
+- Video: `MediaStore.Video.Media.EXTERNAL_CONTENT_URI`, ContentValues with `DISPLAY_NAME`, `MIME_TYPE = "video/mp4"` (or `video/quicktime` for .mov), `RELATIVE_PATH = "Movies/OpenReel"` (this creates the "OpenReel" album equivalent), `IS_PENDING = 1` while writing, then set to `0`.
+- GIF: `MediaStore.Images.Media.EXTERNAL_CONTENT_URI`, MIME `image/gif`, `RELATIVE_PATH = "Pictures/OpenReel"`.
+
+Permissions:
+- Android 13+ (`TIRAMISU`): no permission needed for own files via scoped MediaStore.
+- Android <= 12: `WRITE_EXTERNAL_STORAGE` (request at runtime).
+- If you want to read other people's media to import (separate concern), request `READ_MEDIA_VIDEO` / `READ_MEDIA_IMAGES`.
+
+Error mapping:
+- `permissionDenied` -> `SecurityException` from `ContentResolver.insert`.
+- `creationFailed` -> any `IOException` / null URI from insert / OutputStream.
+
+### 8.6 ShareSheet -> Intent.ACTION_SEND
+
+```kotlin
+val uri = FileProvider.getUriForFile(context, "$packageName.fileprovider", exportedFile)
+val mime = when (extension) { "mp4" -> "video/mp4"; "mov" -> "video/quicktime"; "gif" -> "image/gif"; else -> "*/*" }
+val intent = Intent(Intent.ACTION_SEND).apply {
+ type = mime
+ putExtra(Intent.EXTRA_STREAM, uri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+}
+context.startActivity(Intent.createChooser(intent, "Share export"))
+```
+
+Mirror iOS's "include only the file URL" — no caption text. Register a `FileProvider` for the app's cache/files dir to grant temporary read access.
+
+### 8.7 Cancellation + foreground service
+
+Wrap the whole export in a **foreground service** (`Service` with `startForeground(notificationId, notification)`) so the OS doesn't kill it when the app is backgrounded. Use a `CoroutineScope` tied to the service; expose a `cancel()` that maps to `Transformer.cancel()` and propagates `CancellationException`. The notification mirrors `ExportProgressView`: stage title + percent + cancel action.
+
+For Android 14+ declare `foregroundServiceType="mediaProcessing"` (or `dataSync`) in the manifest and request `FOREGROUND_SERVICE_MEDIA_PROCESSING` permission.
+
+### 8.8 UI parity
+
+Reuse the section layout 1:1 in Jetpack Compose:
+- Presets row -> `LazyRow` of `FilterChip`-like cards.
+- Resolution grid -> `LazyVerticalGrid(GridCells.Fixed(2))`.
+- Frame rate chips -> `Row` of toggle chips.
+- Format grid -> `LazyVerticalGrid(GridCells.Fixed(2))` with 9 cards (omit/disable ProRes if not implemented).
+- Quality slider -> `Slider(value, range = 0.2f..1f, steps = 15)` (16 stops for step 0.05).
+- Estimate card -> `Column` with 4 rows; use `android.text.format.Formatter.formatFileSize` for size and a manual `mm:ss` / `hh:mm:ss` formatter for time.
+- Progress overlay -> `Dialog` with `LinearProgressIndicator` and a destructive "Cancel Export" button.
+
+### 8.9 Defaults reference (copy verbatim into Android constants)
+
+```
+AUDIO_SAMPLE_RATE = 48_000
+AUDIO_CHANNELS = 2
+AAC_BITRATE = 128_000
+PRORES_PCM_BITRATE = 1_536_000
+
+H264_MIN_BASE = 1_400_000
+H264_MAX_BASE = 4_200_000
+H264_MIN = 900_000
+H264_MAX = 28_000_000
+
+HEVC_MIN_BASE = 900_000
+HEVC_MAX_BASE = 2_800_000
+HEVC_MIN = 650_000
+HEVC_MAX = 20_000_000
+
+PRORES_PROXY = 45_000_000
+PRORES_LT = 100_000_000
+PRORES_STANDARD = 147_000_000
+PRORES_HQ = 220_000_000
+
+KEYFRAME_INTERVAL_SECONDS = 2
+
+QUALITY_RANGE = 0.2f..1f
+QUALITY_STEP = 0.05f
+
+GIF_MIN_FPS = 8
+GIF_MAX_FPS = 15
+GIF_LOOP = 0 // infinite
+GIF_MIN_SIZE_BYTES = 128_000
+GIF_FILE_SIZE_QUALITY_OFFSET = 0.16
+GIF_FILE_SIZE_QUALITY_SLOPE = 0.18
+
+ESTIMATE_TIME_FACTOR_H264 = 0.75
+ESTIMATE_TIME_FACTOR_HEVC = 0.9
+ESTIMATE_TIME_FACTOR_PRORES = 1.4
+ESTIMATE_TIME_FACTOR_GIF = 1.15
+```
+
+---
+
+End of EXPORT spec.
diff --git a/docs/android-port/08-ai-animation-shared.md b/docs/android-port/08-ai-animation-shared.md
new file mode 100644
index 00000000..11b49c8f
--- /dev/null
+++ b/docs/android-port/08-ai-animation-shared.md
@@ -0,0 +1,137 @@
+# OpenReel Mobile — On-device Smart Tools, Animation, and Shared Helpers
+
+> **Offline contract (2026-08-08):** Both mobile apps operate without an
+> internet connection. Do not add job APIs, uploads, authentication brokers,
+> remote model downloads, or network fallbacks. A feature that cannot work
+> locally must be hidden until a bundled/on-device implementation exists.
+
+This document describes the current mobile architecture. It replaces the
+retired cloud-worker protocol.
+
+## Source of truth
+
+### iOS
+
+- `Core/AI/MediaAnalysisService.swift`
+- `Core/AI/AIFrameContextBuilder.swift`
+- `Core/AI/AIMaskCompositor.swift`
+- `Core/AI/TrackingPathKeyframeAdapter.swift`
+- `Core/Subtitles/OnDeviceCaptionService.swift`
+- `Core/Subtitles/CaptionTimelineMapper.swift`
+- `Core/Export/LocalHighlightAnalyzer.swift`
+- `Core/Animation/KeyframeEngine.swift`
+- `Core/Animation/EasingFunctions.swift`
+
+### Android
+
+- `core/ai/MLKitObjectTracker.kt`
+- `core/ai/TrackingPathKeyframeAdapter.kt`
+- `core/audio/MusicLibrary.kt`
+- `core/export/LocalHighlightAnalyzer.kt`
+- `core/animation/KeyframeEngine.kt`
+- `core/animation/EasingFunctions.kt`
+
+## 1. Offline invariant
+
+- Android removes `INTERNET` and `ACCESS_NETWORK_STATE` from its merged
+ manifest, including permissions introduced by transitive dependencies.
+- Android app backup is disabled so project media and preferences are not
+ copied through a cloud backup service.
+- iOS media pickers set `showsCloudItems = false`.
+- iOS speech recognition is exposed only when an installed recognizer reports
+ `supportsOnDeviceRecognition`; requests set
+ `requiresOnDeviceRecognition = true`.
+- Android text-to-speech selects an installed voice whose
+ `isNetworkConnectionRequired` flag is false.
+- Filter LUTs required by the catalog are bundled with each app and verified
+ by checksum before use.
+- `scripts/check-mobile-offline.mjs` enforces these rules and rejects known
+ network/client symbols in shipping mobile sources.
+
+The device may still use local GPU/NPU/DSP hardware. “No cloud GPU” does not
+mean “software rendering only”; it means no paid remote compute and no upload.
+
+## 2. Current smart-tool mapping
+
+| Feature | iOS | Android | Offline behavior |
+|---|---|---|---|
+| Subject/person segmentation | Vision person segmentation | Local effect/ML Kit path where supported | Produces a local mask; no upload |
+| Object/subject tracking | Vision tracking | ML Kit object tracking | Converts detections into editor keyframes |
+| Background removal / subject effects | Vision + Core Image/Metal | Local effects pipeline | Rendered on device |
+| Auto Reframe | Tracking-derived transform path | Tracking-derived transform path | Centers the tracked subject with keyframes |
+| Stabilize | Local motion/tracking analysis | Counter-motion tracking keyframes | No server fallback |
+| Captions | Installed on-device Speech model | SRT/local caption editing | iOS button is unavailable without a local model |
+| Shorts/highlights | Sampled-frame motion/detail scorer | Sampled-frame motion/detail scorer | Ranks candidate windows locally |
+| Music generation | Local music tools | Prompt-guided procedural WAV synthesis | Creates a project-local audio file |
+| LUT filters | Bundled `.cube` asset | Bundled `.cube` asset | Never downloaded |
+
+Model-heavy features without a credible bundled implementation—such as stem
+separation, arbitrary generative image repair, and general translation—are not
+presented as working actions. Do not restore placeholder buttons for them.
+
+## 3. Tracking to keyframes
+
+Tracking produces normalized points over source time. The adapter converts
+those samples into the shared project keyframe model:
+
+1. Resolve the selected local media file.
+2. Sample frames within the selected clip's source-time window.
+3. Run the platform's on-device detector/tracker.
+4. Normalize the detected center to the editor coordinate system.
+5. Replace the prior generated position path for that mode.
+6. Store position keyframes on the clip and refresh playback.
+
+Track Subject follows the detected point. Auto Reframe turns the path into the
+transform needed to keep the subject near the canvas center. Stabilize applies
+the inverse of estimated motion. Empty or low-confidence analyses fail safely
+without fabricating a successful result.
+
+## 4. On-device captions
+
+The iOS caption service sends a local media URL to Speech and maps timed word
+segments into subtitle groups. The service must reject recognizers that need a
+network connection. Caption creation is therefore capability-gated, not
+silently routed online.
+
+Android currently supports SRT import and complete local subtitle styling and
+editing. Automatic transcription must stay hidden until an Android offline
+speech model is bundled and tested across supported ABIs.
+
+## 5. Local highlight analysis
+
+The highlight analyzer samples downscaled frames, computes motion change and
+edge/detail energy, aggregates scores over target-length windows, and returns
+ranked candidates. Shorts generation combines that content score with the
+existing local virality heuristics. If frames cannot be decoded, the app falls
+back to deterministic timeline windows.
+
+## 6. Keyframe engine
+
+Keyframes are sorted by time. Sampling clamps before the first and after the
+last keyframe, locates the surrounding pair, applies the outgoing keyframe's
+easing function to normalized progress, and interpolates scalar or vector
+values. Supported easing includes linear, ease-in, ease-out, ease-in-out,
+bounce, elastic, and spring variants used by the editor.
+
+Keep generated tracking keyframes in the same project schema as manual
+keyframes so preview, export, undo/redo, and cross-platform project files use a
+single rendering path.
+
+## 7. Implementation checklist
+
+- The feature works in airplane mode on a clean install.
+- No permission, client library, URL, token, credential, or remote model fetch
+ is required.
+- Any model or LUT is bundled and included in size/license review.
+- Capability-gated UI explains why a local model/voice is unavailable.
+- Generated assets are written into project-local storage and survive reopen.
+- Preview and export consume the same project data.
+- `node scripts/check-mobile-offline.mjs` passes.
+- Android compilation/unit tests and iOS simulator tests pass.
+
+## 8. Shared helpers
+
+Color parsing, time formatting, haptics, project cards, and theme tokens remain
+ordinary local utilities. They must not start networking as a side effect.
+Cross-platform project schema changes should be coordinated across iOS,
+Android, web, and desktop when relevant.
diff --git a/docs/android-port/PROGRESS.md b/docs/android-port/PROGRESS.md
new file mode 100644
index 00000000..f06c9297
--- /dev/null
+++ b/docs/android-port/PROGRESS.md
@@ -0,0 +1,296 @@
+# Openreel Android — Progress Log
+
+> **Offline architecture (2026-08-08):** Cloud-GPU, authentication, and
+> networking code has been removed. This log describes the current offline
+> implementation; superseded cloud milestones are intentionally omitted.
+
+This document tracks the phases that have shipped on `feat/ios-app` against the
+iOS port spec in this folder. Each commit on the branch corresponds to a
+feature phase; the list below groups them by surface so it's easy to see
+what's covered.
+
+## 1. Foundations
+- Theme tokens (colors light/dark, typography, radii, spacing) matching iOS Theme.swift
+- Compose-friendly press-scale modifier, haptics helper with global toggle, color parsing, time formatting
+- Edge-to-edge `MainActivity` + splash screen + Manifest permissions
+
+## 2. Data & Persistence
+- Kotlin port of the full `OpenReelProject` schema (v1.1.0) so JSON round-trips with iOS
+- `ProjectStore` with autosave, summaries StateFlow, last-saved timestamp, thumbnail capture
+- `ActionHistory` snapshot-based undo/redo (50 entries)
+- DataStore-backed `UserPreferences` (onboarding, haptics, theme, aspect guides)
+- `.openreelzip` archive import/export via SAF
+
+## 3. Navigation Shell
+- RootScreen routes Onboarding → Loading → Library / Editor with crossfade
+- 3-page onboarding pager with custom indicator + CTA + iOS-style haptics
+- Library Home with hero canvas sun glow, recent carousel, Quick Start, Photo Tools / Quick Trim
+- Library Projects with grid/list toggle, storage card, search bar, archive import
+- Custom bottom tab bar (no Material BottomNavigation)
+- NewProjectSheet (custom bottom sheet, name + resolution + frame rate)
+- About sheet (long-press logo) + reset-onboarding
+
+## 4. Editor Surface
+- Editor shell (header, preview canvas, playback bar, timeline area, tab bar)
+- Header: back, project title (tap to rename), undo/redo, settings, Export
+- Auto-save indicator + project rename dialog
+- Playback bar: prev/next frame, play/pause, monospaced time/duration
+- Ruler scrubbing + beat tick marks + project marker lines
+- Preview pinch zoom + double-tap fit
+
+## 5. Playback & Composition
+- ExoPlayer-backed PlaybackController exposing play/pause/seek/setRate
+- ClippingMediaSource per clip, ConcatenatingMediaSource2 per track
+- MergingMediaSource so multiple audio tracks mix in parallel; honors mute/solo/hidden
+- Live audio fade-in/out + per-clip volume automation ramp during playback
+- AudioFocus request/abandon on play/pause (auto-pause on call)
+- AudioEffects bound to ExoPlayer session: EQ (per-band), reverb, compressor
+
+## 6. Media Pipeline
+- MediaImportService via PhotoPicker + SAF + camera capture; copies into project dir
+- MediaMetadataRetriever for duration/width/height/codec; PCM waveform extraction (200 peaks)
+- Beat detector → BeatMarker entries timestamped to clip startTime
+- Project thumbnail capture on import
+- CameraX video + photo capture screen (front/back switch)
+
+## 7. Timeline Editing
+- Multi-track lanes with track-type icons + waveforms; long-press badge → inspector
+- Clip move/trim/split/delete gestures with beat + playhead snap (with flash indicator)
+- Multi-select clips (long-press to start, batch Duplicate/Delete)
+- Transitions catalog + adjacent-clip picker (9 presets)
+- Text + Graphics overlay lanes (drag/trim/long-press-delete strips)
+- Track inspector (mute/solo/hide/role/rename/move up-down)
+- Timeline ruler scrub gesture + beat/marker ticks
+
+## 8. Text & Graphics
+- Text panel: 8 iOS presets, inspector (text/size/color/background swatches)
+- Custom font picker (SAF .ttf/.otf import) with on-canvas rendering
+- Graphics panel: 8 shape presets + 30 emoji palette
+- PreviewOverlay renders text + graphics + emoji + animation keyframes + blend modes
+
+## 9. Effects & Color
+- 20 filter presets across 5 categories (Cinematic, Vintage, Mood, Color, Stylized)
+- Live FilterOverlay (brightness, saturation, contrast, temperature, tint)
+- BackgroundRemove toggle + Track Subject (AI) + LUT (.cube) picker
+- Per-clip effect chain reorder + remove
+- Color scopes overlay (RGB histogram toggleable from header)
+
+## 10. Audio
+- Audio panel cards: Music library, Voiceover, Sound FX, and prompt-guided procedural Local Music
+- Per-track mixer panel with gain + mute pill
+- Voiceover recording timer
+- Audio fades + volume automation editor
+
+## 11. Subtitles & Captions
+- SRT parser + import via SAF
+- SRT import and a fully local subtitle editing/style workflow
+- Subtitle style editor (size, color, position, animation style)
+- CaptionAnimationStyle render in preview (typewriter/bounce/word-by-word/word-highlight/karaoke)
+
+## 12. Templates
+- 10 built-in templates with apply engine (text + graphics + per-category filter)
+- Long-press for customisation (intensity + duration override)
+- Save current as user template + apply user template
+
+## 13. Export
+- Export sheet with resolution/frame rate/format/preset summary
+- Media3 Transformer pipeline with ProgressHolder polling
+- MediaStore save to Movies/OpenReel + Share intent
+- Foreground-style ongoing notification with completion message
+- Per-clip AudioProcessor hook (placeholder for full volume baking)
+
+## 14. On-device Smart Tools
+- ML Kit object tracking creates editor keyframes without uploads
+- Tracking paths drive Track Subject, Auto Reframe, and Stabilize
+- Local frame sampling ranks highlight/shorts windows by motion and detail
+- Prompt-guided procedural music renders directly to a WAV file
+- Unsupported model-heavy tools are not exposed; there is no network fallback
+
+## 15. Settings & Misc
+- Settings sheet: theme (System/Light/Dark), aspect guides, haptics, audio sample rate, and HDR toggle
+- Project markers manager + frame-rate / resolution change
+- Aspect ratio overlay guides on preview
+
+## 16. Timeline editing parity (shipped 2026-05-24)
+- PlacementResolver snaps clips to neighbor edges (max(0.05, 8/zoom) threshold),
+ prevents same-track overlap, and resolves the nearest legal start when a
+ proposed position collides; falls back to candidate set
+ {0, neighbor.end, neighbor.start − duration}
+- AppState.moveClip routes through the resolver, atomically swaps trackId for
+ cross-track moves, and surfaces snap events for haptic feedback
+- VideoTrackLane / AudioTrackLane drag gestures accumulate vertical delta and
+ map it to a same-media-type sibling track (Video↔Image, Audio↔Audio)
+- splitClip frame-snaps to the project frame rate, seeks the playhead to the
+ cut, and auto-selects the right-hand piece
+- Selected video clips get a scissors mini-button at the playhead for one-tap
+ splitting (visible when the clip is wide enough and the playhead is strictly
+ inside it)
+- TimelineZoomMenu becomes a `[− %% +]` capsule chip; − halves zoom, + grows
+ zoom, label opens the preset dropdown
+- 9 unit tests cover the resolver
+
+## 24. Closing-out round (shipped 2026-05-24)
+- Text Split + Flip per-character bakes complete the per-char preset
+ family (all 22 TextAnimationPresets now render correctly)
+- BlendModeBaker wired into keyframed + per-frame-animated overlay
+ paths — animated text overlays sample the moving background each
+ frame; keyframed overlays single-sample at midpoint
+- Smooth multi-segment speed ramp [1.0, 0.5, 0.25, 0.5, 1.0] for
+ CapCut-style ease-in/out slow-mo in one tap
+- AdjustmentLane on the timeline is fully editable — drag to move,
+ trim handles on either end, long-press to delete
+- Photo enhance auto-imports the saved photo back into the project
+ library when a project is open
+- Variable-control template editor sheet collects user values
+ (toggles, number sliders, select chips) before applying
+- Object tracking creates local keyframes from ML Kit detections
+
+## 23. Final CapCut-parity round (shipped 2026-05-24)
+- Text Split (per-char halves slide apart with alpha fade-in) and Flip
+ (per-char scaleY oscillation with phase offset) per-character bakes
+- BlendModeBaker samples the primary clip's frame at each overlay's
+ midpoint and composites the overlay via android.graphics.BlendMode
+ (API 29+) or PorterDuff fallback — Multiply / Screen / Overlay /
+ Darken / Lighten / ColorDodge / ColorBurn / HardLight / SoftLight /
+ Difference / Exclusion supported for static text + graphics overlays
+- Speed ramp preset chips (Bullet 0.2x / Slow 0.5x / Fast 2x / Hyper
+ 3x) in the Timing inspector
+- AppState.saveClipAsAdjustmentLayer + ClipTool action so users can
+ promote a clip's effects to a project-wide adjustment in one tap
+- PhotoEnhancementScreen.Save now optionally re-imports the saved
+ photo into the project library — enhanced photo lands as a Media
+ Library item ready to drop on the timeline
+- applyUserTemplate accepts a controlValues map and substitutes
+ `{{controlId}}` placeholders in clip text + style.color, merging
+ template controls' defaults + template defaultValues + user input
+
+## 22. Effects, audio, and editing actions round 2 (shipped 2026-05-24)
+- Per-character text presets (Wave / Glitch / Rainbow / Shake) — Glitch
+ renders RGB-channel-split chromatic aberration; Rainbow cycles HSV hue
+ per character and over time
+- ReverseAudioProcessor buffers PCM-16 then emits in reverse frame order
+ on EOS — reversed clips now play with reversed audio (not just muted)
+- MotionBlurEffect (custom GlEffect) with 9-tap directional smear,
+ toggleable horizontal / vertical from Effects panel
+- VignetteEffect + FilmGrainEffect via shared SimpleGlEffectProgram
+- DuckingAudioProcessor with cosine ramp; ProjectExportService
+ computes duck windows from AudioTrackRole.Dialogue clips and applies
+ attenuation to music / SFX automatically
+- ChromaKeySwatchPicker exposes eight common key colours in the
+ inspector
+- ShapeMaskEffect (circle / ellipse / rounded-rect / heart) via implicit
+ GLSL distance fields
+- ColorIsolationEffect — "pop of colour" preserves one colour and
+ desaturates the rest
+- Boomerang action — inserts reversed copy after selected clip
+- Slow-mo highlight — splits clip at playhead and 1s later, sets middle
+ to 0.3x, shifts following clips to preserve alignment
+- detachAudio — extracts video clip's audio onto a dedicated audio
+ track and mutes the original
+- autoCutToBeat — splits the selected clip at every beat marker inside
+ its window
+- smartTrimSilence — scans waveform peaks locally and trims runs of
+ silence (peak < 0.06 for >= 0.4s) without round-tripping to cloud
+- AdjustmentClip data model + export merge — effects on an adjustment
+ apply to every video clip whose timeline overlaps it
+ (saveClipAsAdjustmentLayer / removeAdjustmentLayer helpers in
+ AppState; full UI is a follow-up)
+
+## 21. Direct manipulation parity (shipped 2026-05-24)
+- PreviewManipulation hit-tests overlay video clips (non-primary
+ tracks) in addition to text and graphics — drag / pinch / rotate a
+ PIP window directly on the preview surface
+- PreviewSelectionHandles draws the dashed bounding box and corner
+ handles around the selected PIP video clip in addition to text /
+ graphics
+- ClipInspector AdjustPage gains a Chroma Key card: when no key is
+ active, Green / Blue Screen quick toggles; when a key is active,
+ Threshold and Smoothing sliders + a Remove button so users can tune
+ the mask softness without leaving the inspector
+
+## 20. Reverse + emphasis (shipped 2026-05-24)
+- SampledFrameOverlay gains a reverseTime flag; ProjectExportService
+ emits a reversed-frame overlay for clips with Clip.reversed=true,
+ covering the forward primary video, and sets RemoveAudio on the
+ EditedMediaItem so forward audio doesn't play
+- EmphasisAnimatedOverlay drives per-frame OverlaySettings from
+ EmphasisAnimation presets — Pulse, Breathe, Heartbeat, Bounce,
+ Float, Shake, Vibrate, Wobble, Swing, Spin, Flash, Flicker,
+ RubberBand, Jello, Tada — applies to both GraphicsClip and TextClip
+- Mirrors the per-frame sin math used by PreviewOverlay so preview
+ matches export
+
+## 19. Effects & voice CapCut-parity (shipped 2026-05-24)
+- ChromaKeyEffect: custom GlEffect/BaseGlShaderProgram pair with a
+ GLSL fragment shader that masks alpha via YCbCr chroma distance from
+ the configured key colour, smoothstep edge softening, and per-channel
+ spill suppression so green / blue bleed is removed from the edges
+- ChromaKeyConfig stores per-clip settings on Clip.effects with
+ type="chroma-key" and params { keyColor, threshold, smoothing }
+- Effects panel: one-tap "Green Screen" and "Blue Screen" buttons
+ toggle the effect with sensible defaults
+- VoiceEffectPreset.Echo and .HallReverb add custom-AudioProcessor
+ routes — EchoAudioProcessor implements a circular delay buffer with
+ dry / wet / feedback parameters, mixed back into the PCM-16 stream
+- TextAnimationKeyframes converts Fade / Slide-* / Scale / Pop / Bounce
+ / Rotate / Flip TextAnimation presets into synthetic Keyframes so
+ KeyframedBitmapOverlay can bake them without per-frame bitmaps
+- PreviewSelectionHandles draws a dashed bounding box + corner handles
+ around the selected text / graphics overlay so users see exactly
+ what PreviewManipulation will drag / pinch / rotate
+
+## 18. CapCut-parity features (shipped 2026-05-24)
+- VideoFrameSampler extracts a sparse set of bitmaps from a clip's source
+ via MediaMetadataRetriever, downscaled to a configurable max dimension
+- SampledFrameOverlay (Media3 BitmapOverlay subclass) serves time-varying
+ bitmaps with time-varying alpha; supports overlay anchor, background
+ anchor, scale, and rotation so the same primitive renders cross-fades,
+ wipes, slides, and PIP overlay video
+- Cross-fade / wipe / slide / zoom-blur transitions render real incoming
+ clip frames (no longer a placeholder dim)
+- Multi-video-track PIP — overlay video clips on additional tracks bake
+ in via the overlay primitive, positioned and scaled per the clip's
+ transform; audio from these tracks routes through the audio sequence
+ builder
+- KeyframedBitmapOverlay drives per-frame OverlaySettings from
+ KeyframeEngine so position / scale / rotation / opacity keyframes on
+ TextClip and GraphicsClip animate in the exported file
+- AnimatedFrameSequenceOverlay pre-renders ~15fps animation keyframes
+ for content-changing animations (typewriter, word-by-word, karaoke,
+ word-highlight, bounce, plus the subtitle equivalents) and serves the
+ closest by presentation time
+- PreviewManipulation captures detectTransformGestures on the preview,
+ hit-tests the topmost overlay clip at the playhead, and updates
+ transform.position / scale / rotation live — drag, pinch, twist
+- OverlayVideoPreview renders overlay video tracks as poster frames in
+ the editor preview via Coil videoFrameMillis at the local playhead
+ time; matches the export's PIP layout
+- TransitionPreviewOverlay shows the real incoming clip frame for
+ cross-fade / wipe / slide / zoom-blur with rising alpha
+- VoiceEffectPreset (Helium / Chipmunk / Deep / Monster) stores a pitch
+ effect on the clip and applies it via SonicAudioProcessor in export;
+ ClipInspector Audio page picks the active preset
+
+## 17. Export pipeline coverage (shipped 2026-05-24)
+- OverlayBitmapRenderer rasterises TextClip, GraphicsClip (rectangle, circle /
+ ellipse, triangle, line, arrow, star, polygon, emoji), and image/sticker
+ GraphicAssets into the project's output resolution
+- TimedBitmapOverlay subclasses Media3 BitmapOverlay with time-gated alpha
+ (start, end, optional fade-in / fade-out ramps)
+- Composition-level OverlayEffect wires text, graphics, subtitles, and
+ transition fade overlays into the export
+- Transition family: dip-to-black, dip-to-white, flash render with the
+ expected time-varying alpha; cross-fade / wipe / slide / zoom-blur fall
+ back to a subtle dim until true multi-source compositing is wired
+- TransitionPreviewOverlay shows the same fade in the editor so the preview
+ matches the export for the dip family
+- Multi-track audio: each non-muted Audio track becomes its own
+ EditedMediaItemSequence (gaps via addGap), assembled in Composition for
+ parallel mixing — music, voiceover, and SFX now land in the file
+- Subtitles bake into the export with their configured style and time window
+
+## Status
+CapCut parity complete for the local editing surface — every documented
+gap has shipped. Remaining work would be catalog expansion (more filter
+presets, more transition presets, more fonts) and additional on-device
+models that can be bundled without compromising the offline requirement.
diff --git a/docs/android-port/README.md b/docs/android-port/README.md
new file mode 100644
index 00000000..ef07a11f
--- /dev/null
+++ b/docs/android-port/README.md
@@ -0,0 +1,127 @@
+# Openreel Video — Android Port Guide
+
+> **Offline architecture (2026-08-08):** OpenReel's cloud-GPU worker, auth
+> broker, and network clients are removed. The mobile apps must remain fully
+> usable offline. Smart tools use platform media APIs and on-device ML only.
+
+This directory documents the iOS app **Openreel Video** (SwiftUI, ~77 Swift files, ~50k LOC) in enough detail for an Android team to rebuild it 1:1 in Kotlin.
+
+Goal: **feature-parity and visual parity** with iOS. Every screen, every panel, every parameter, every preset, every gesture is captured here. We build custom views to match iOS pixel-for-pixel — no off-the-shelf "Material Design" shortcuts.
+
+---
+
+## Source of Truth
+
+iOS code lives at: `/Users/augustusotu/Projects/openreel/Openreel Video/Openreel Video/`
+
+When this doc and the Swift source disagree, **the Swift source wins**. Update the doc.
+
+---
+
+## How to Read This Guide
+
+The docs are split into 8 sections. Read them in order if you're new; jump around if you're implementing one feature.
+
+| # | Doc | Covers |
+|---|-----|--------|
+| 01 | [App Structure & Navigation](01-app-structure-navigation.md) | App entry, RootView, HomeView, ProjectsView, Onboarding, NewProjectSheet, Theme tokens |
+| 02 | [Data Models & State](02-data-models-and-state.md) | `OpenReelProject` schema, Track/Clip/Layer, `ProjectStore`, `ActionHistory`, full `AppState` API |
+| 03 | [Editor Shell](03-editor-shell.md) | EditorView layout, header, preview canvas, playback controls, timeline, tab bar, inspector panels, shared editor components |
+| 04 | [Playback & Rendering](04-playback-rendering.md) | AVFoundation/Metal pipeline, effects catalog, transitions, color scopes, LUT parsing, MetalVideoView |
+| 05 | [Media, Text, Audio Features](05-features-media-text-audio.md) | Media import (PHPicker, files, camera), local photo adjustments, Text panel (presets + animations), Audio panel (library, recorder, effects) |
+| 06 | [Effects, Graphics, Templates, Subtitles](06-features-effects-graphics-templates-subtitles.md) | Effects/filters/blend modes, shape catalog, built-in templates, SRT subtitles |
+| 07 | [Export](07-export.md) | Export sheet options, encoder pipeline, GIF export, share sheet, Photos library save |
+| 08 | [On-device Smart Tools, Animation, Shared](08-ai-animation-shared.md) | On-device segmentation/tracking/captions/highlights, keyframe engine + easing, and shared helpers |
+
+---
+
+## Implementation Order (suggested)
+
+We recommend building in this order so each phase has runnable output:
+
+1. **Foundations** (doc 01, 02, parts of 08-shared)
+ - Theme tokens (colors, fonts, spacing, radii)
+ - Color parsing, time formatting, haptics helpers
+ - `OpenReelProject` Kotlin data classes + JSON serializer (kotlinx.serialization)
+ - `ProjectStore` (filesystem + thumbnails)
+ - `ActionHistory` (undo/redo)
+ - Top-level Compose navigation (Onboarding → Home → Editor)
+2. **Editor shell** (doc 03)
+ - EditorView scaffold: header, empty preview, empty timeline, tab bar
+ - Shared editor components (sliders, segmented pickers, color picker, expandable rows)
+3. **Playback** (doc 04)
+ - ExoPlayer-backed `PlaybackController` matching iOS signature
+ - Timeline composition builder (ExoPlayer concatenating + clipping media sources)
+ - MetalVideoView equivalent (SurfaceView + OpenGL/Vulkan or Media3 effects)
+4. **Media import** (doc 05 — Media section)
+ - Android PhotoPicker, file picker, CameraX recorder
+ - Add clip → timeline insertion
+5. **Timeline editing** (doc 03 — Timeline section)
+ - Track rendering, clip thumbnails, drag/trim/split, snapping, multi-select
+6. **Text & graphics** (docs 05-text, 06-graphics)
+7. **Effects, transitions, color** (docs 04, 06-effects)
+ - Port each effect — match parameter ranges and defaults exactly
+ - LUT support via .cube parser
+8. **Audio** (doc 05 — Audio section)
+ - Audio tracks, mixer, EQ/reverb/compressor/ducking
+ - Voiceover recorder
+9. **Templates & subtitles** (doc 06)
+10. **Export** (doc 07)
+ - Media3 Transformer pipeline
+ - GIF encoder
+ - Save to MediaStore, Intent.ACTION_SEND share
+11. **On-device smart tools** (doc 08)
+ - Segmentation and tracking with Vision/ML Kit
+ - Tracking-derived reframe/stabilization keyframes
+ - Local captions, procedural music, and highlight analysis where supported
+
+---
+
+## Non-Negotiable Rules for the Android Build
+
+- **Visual parity**: every color, padding, corner radius, font weight must match iOS. Quote the iOS modifier in code comments only if the value is non-obvious; otherwise just match.
+- **No Material chrome leaking through**: no ripple effects where iOS uses opacity dim; no FABs where iOS uses tab-bar buttons; no Material `TopAppBar` styling. Build custom views.
+- **Custom views, every screen**: don't reach for `BottomNavigation`, `Scaffold` defaults, `ModalBottomSheet` defaults if they look Android-ish. Match iOS sheet detents, drag handles, corner radius, blur backgrounds.
+- **Haptics on every interaction iOS hits** — see doc 08, haptic helpers section, for the full event list.
+- **Identical JSON project format**: Android must read/write the same `.openreel` files that iOS produces. Cross-platform projects are a future requirement; the schema must match exactly today.
+- **No OpenReel GPU API**: smart-tool work must stay on-device; the old Worker protocol in doc 08 is historical only.
+- **Same effect math**: shaders/CIFilter params must produce visually identical output. When in doubt, render the same frame in iOS and Android, side-by-side compare.
+
+---
+
+## Tech Stack (recommended)
+
+| Concern | Android choice | iOS equivalent |
+|---|---|---|
+| UI | Jetpack Compose | SwiftUI |
+| State | `StateFlow` + `ViewModel` per screen + shared `AppRepository` | `AppState` `@Published` |
+| Persistence | filesystem JSON + thumbnails (mirror iOS layout) | `ProjectStore` |
+| Video playback | Media3 ExoPlayer | AVPlayer |
+| Video composition | Media3 Transformer + effects | AVMutableComposition + AVVideoComposition |
+| GPU effects | Media3 GL effects + custom shaders | Metal + CIFilter |
+| Audio | AudioTrack + OpenSL/AAudio + custom DSP, or Oboe | AVAudioEngine |
+| Photo picker | androidx PhotoPicker | PHPickerViewController |
+| Camera | CameraX | AVCaptureSession |
+| ML on-device | MLKit / ONNX Runtime / TFLite | Vision, CoreML |
+| Haptics | `Vibrator` (Android 12+ predefined effects) | UIImpactFeedbackGenerator |
+| Animation | Compose Animation, dynamic-animation | SwiftUI animations |
+| Image loading | Coil | AsyncImage / CIImage |
+
+---
+
+## Open Questions for Product
+
+Things the iOS code does that we should confirm before building on Android:
+
+- Subscription / paywall: iOS has App Store entitlements — does Android use Play Billing with the same SKUs? (Check `AppState` for IAP entry points.)
+- HDR export: iOS captures and exports HDR on supported devices — Android equivalent (HDR10/Dolby Vision via Media3) needs device gating.
+- Confirm each smart tool has an on-device implementation before exposing it.
+- Fonts: iOS uses SF Symbols + custom fonts — we need the custom font files vendored into Android.
+
+---
+
+## Maintenance
+
+- Treat these docs as living. If an iOS feature changes, update the relevant section in the same PR.
+- Each section's "Source files" header lists exactly which Swift files were read to produce it — start there when verifying current behavior.
+- Cross-platform JSON schema lives in doc 02. Any schema change must land on iOS, Android, web, and desktop at the same time when relevant.
diff --git a/docs/superpowers/plans/2026-05-22-ios-timeline-fixes.md b/docs/superpowers/plans/2026-05-22-ios-timeline-fixes.md
new file mode 100644
index 00000000..1950fe06
--- /dev/null
+++ b/docs/superpowers/plans/2026-05-22-ios-timeline-fixes.md
@@ -0,0 +1,2017 @@
+# iOS Timeline Fixes Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship the iOS-timeline fixes from `docs/superpowers/specs/2026-05-22-ios-timeline-fixes-design.md` — zoom chip, dark-preview-after-split fix, snap-and-no-overlap on same track, cross-track moves between same-type tracks, and a small split/move polish layer.
+
+**Architecture:** A new `resolveClipPlacement` in `AppState` centralizes snap-and-collision logic so every move path uses one source of truth. The dark-preview fix is split between `PlaybackCompositionBuilder` (skip custom compositor when no transitions exist) and `MetalVideoView` (nudge by a full frame, not 1.67 ms). UI changes are wrapped around the existing `TimelineClipBlock` family — the move gesture is extracted into a shared helper that handles 2-D translation.
+
+**Tech Stack:** Swift 5.10+, SwiftUI, AVFoundation (`AVMutableComposition`, `AVMutableVideoComposition`, `AVPlayerItemVideoOutput`), MetalKit, Swift Testing (`import Testing`, `@Test`, `#expect`).
+
+**Test runner:** From the repo root:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/<ClassName>" \
+ -quiet
+```
+
+Replace `<ClassName>` with the test class for the task. Drop `-only-testing:` to run the whole suite. Each task lists its expected exit state — use that to confirm a task is done.
+
+**Branch:** Already on `feat/ios-app`. Commit per task with the conventional-commit prefix shown in each step.
+
+---
+
+## File Structure
+
+Files this plan creates or modifies, with the responsibility of each:
+
+| File | Purpose | Status |
+|---|---|---|
+| `Openreel Video/Openreel VideoTests/PlaybackCompositionBuilderTests.swift` | Branch-boundary tests for the custom-compositor branch | **Create** |
+| `Openreel Video/Openreel VideoTests/PlacementResolverTests.swift` | Unit tests for `resolveClipPlacement` and `destinationTrack` | **Create** |
+| `Openreel Video/Openreel Video/Core/Playback/PlaybackCompositionBuilder.swift` | Add `transitions.isEmpty` branch in `buildVideoComposition`, plus `buildPassthroughInstructions` helper | Modify |
+| `Openreel Video/Openreel Video/Features/Preview/MetalVideoView.swift` | Replace nudge magnitude, add `pumpFrameUntilDelivered`, KVO on `currentItem` | Modify |
+| `Openreel Video/Openreel Video/AppState.swift` | New `resolveClipPlacement`, `destinationTrack`, `moveClip` overload; existing `moveClip` becomes a thin wrapper | Modify |
+| `Openreel Video/Openreel Video/EditorView.swift` | New `TimelineZoomChip` subview; new `makeMoveGesture` helper used by all four `Timeline*ClipBlock` types; snap-edge overlay; scissors mini-button; post-split playhead seek | Modify |
+
+All work stays in two existing test files' directory and three existing source directories. No new module, no Xcode project changes (Swift Testing files auto-discover from the test target's directory, matching the existing `FilterEndToEndTests.swift` pattern).
+
+---
+
+## Phase 1 — Dark preview fix (spec §6)
+
+The most user-visible bug. Ship-able independently.
+
+### Task 1: Backstop tests for the custom-compositor branch boundary
+
+**Files:**
+- Create: `Openreel Video/Openreel VideoTests/PlaybackCompositionBuilderTests.swift`
+
+- [ ] **Step 1: Write the failing tests**
+
+Create the file with this content:
+
+```swift
+import AVFoundation
+import Foundation
+import Testing
+@testable import Openreel_Video
+
+@MainActor
+struct PlaybackCompositionBuilderTests {
+ @Test func twoSourcesNoTransitionsDoesNotUseCustomCompositor() async throws {
+ let url = try await Self.makeSampleVideoURL()
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let sourceA = makeSource(id: "a", url: url, startTime: 0, duration: 0.5)
+ let sourceB = makeSource(id: "b", url: url, startTime: 0.5, duration: 0.5)
+
+ let result = await PlaybackCompositionBuilder.build(
+ sources: [sourceA, sourceB],
+ transitions: [],
+ frameRate: 30
+ )
+
+ let composition = try #require(result?.videoComposition)
+ #expect(composition.customVideoCompositorClass == nil)
+ #expect(composition.instructions.count >= 2)
+ }
+
+ @Test func twoSourcesWithTransitionUsesCustomCompositor() async throws {
+ let url = try await Self.makeSampleVideoURL()
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let sourceA = makeSource(id: "a", url: url, startTime: 0, duration: 0.5)
+ let sourceB = makeSource(id: "b", url: url, startTime: 0.5, duration: 0.5)
+ let transition = PlaybackController.TimelineTransition(
+ id: "t1",
+ clipAId: "a",
+ clipBId: "b",
+ type: "crossfade",
+ duration: 0.2,
+ params: [:]
+ )
+
+ let result = await PlaybackCompositionBuilder.build(
+ sources: [sourceA, sourceB],
+ transitions: [transition],
+ frameRate: 30
+ )
+
+ let composition = try #require(result?.videoComposition)
+ #expect(composition.customVideoCompositorClass == TransitionVideoCompositor.self)
+ }
+
+ @Test func singleSourceProducesNoVideoComposition() async throws {
+ let url = try await Self.makeSampleVideoURL()
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let source = makeSource(id: "only", url: url, startTime: 0, duration: 1)
+
+ let result = await PlaybackCompositionBuilder.build(
+ sources: [source],
+ transitions: [],
+ frameRate: 30
+ )
+
+ #expect(result?.videoComposition == nil)
+ }
+
+ private func makeSource(
+ id: String,
+ url: URL,
+ startTime: TimeInterval,
+ duration: TimeInterval
+ ) -> PlaybackController.TimelineSource {
+ PlaybackController.TimelineSource(
+ id: id,
+ url: url,
+ kind: .video,
+ startTime: startTime,
+ duration: duration,
+ inPoint: 0,
+ outPoint: duration,
+ speed: 1,
+ volume: 1,
+ includesVideo: true,
+ includesAudio: false
+ )
+ }
+
+ private static func makeSampleVideoURL() async throws -> URL {
+ let url = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("\(UUID().uuidString).mov")
+
+ let writer = try AVAssetWriter(outputURL: url, fileType: .mov)
+ let settings: [String: Any] = [
+ AVVideoCodecKey: AVVideoCodecType.h264,
+ AVVideoWidthKey: 32,
+ AVVideoHeightKey: 32
+ ]
+ let input = AVAssetWriterInput(mediaType: .video, outputSettings: settings)
+ input.expectsMediaDataInRealTime = false
+ let adaptor = AVAssetWriterInputPixelBufferAdaptor(
+ assetWriterInput: input,
+ sourcePixelBufferAttributes: [
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32ARGB,
+ kCVPixelBufferWidthKey as String: 32,
+ kCVPixelBufferHeightKey as String: 32
+ ]
+ )
+ guard writer.canAdd(input) else {
+ throw NSError(domain: "PlaybackCompositionBuilderTests", code: -1)
+ }
+ writer.add(input)
+ guard writer.startWriting() else {
+ throw writer.error ?? NSError(domain: "PlaybackCompositionBuilderTests", code: -2)
+ }
+ writer.startSession(atSourceTime: .zero)
+
+ var pixelBuffer: CVPixelBuffer?
+ CVPixelBufferCreate(kCFAllocatorDefault, 32, 32, kCVPixelFormatType_32ARGB, nil, &pixelBuffer)
+ guard let buffer = pixelBuffer else {
+ throw NSError(domain: "PlaybackCompositionBuilderTests", code: -3)
+ }
+ CVPixelBufferLockBaseAddress(buffer, [])
+ if let base = CVPixelBufferGetBaseAddress(buffer) {
+ memset(base, 0xFF, CVPixelBufferGetDataSize(buffer))
+ }
+ CVPixelBufferUnlockBaseAddress(buffer, [])
+
+ let frameCount = 30
+ for frameIndex in 0..<frameCount {
+ while !input.isReadyForMoreMediaData {
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ let time = CMTime(value: CMTimeValue(frameIndex), timescale: 30)
+ _ = adaptor.append(buffer, withPresentationTime: time)
+ }
+
+ input.markAsFinished()
+ await writer.finishWriting()
+ return url
+ }
+}
+```
+
+- [ ] **Step 2: Run the tests to verify they fail in the expected way**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlaybackCompositionBuilderTests" \
+ -quiet
+```
+
+Expected: `twoSourcesNoTransitionsDoesNotUseCustomCompositor` FAILS (current code sets `customVideoCompositorClass = TransitionVideoCompositor.self` even with zero transitions). The other two tests should PASS.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add "Openreel Video/Openreel VideoTests/PlaybackCompositionBuilderTests.swift"
+git commit -m "test(ios): branch-boundary tests for PlaybackCompositionBuilder"
+```
+
+---
+
+### Task 2: Skip custom compositor when no transitions exist (B1)
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/Core/Playback/PlaybackCompositionBuilder.swift`
+
+- [ ] **Step 1: Read the existing `buildVideoComposition` function to understand its current shape**
+
+Read `Core/Playback/PlaybackCompositionBuilder.swift` lines 655-717. Notice that `CompositorPassthroughInstruction` is custom-compositor-only — when we skip the custom class we must replace those instructions with stock `AVMutableVideoCompositionInstruction` + `AVMutableVideoCompositionLayerInstruction` pairs.
+
+- [ ] **Step 2: Replace `buildVideoComposition` with the branched version**
+
+Open the file and replace lines 655-717 (the entire `buildVideoComposition` function) with:
+
+```swift
+ private static func buildVideoComposition(
+ composition: AVMutableComposition,
+ transitions: [PlaybackController.TimelineTransition],
+ sources: [PlaybackController.TimelineSource],
+ clipTrackMap: [String: CMPersistentTrackID],
+ renderSize: CGSize?,
+ frameRate: Double
+ ) -> AVMutableVideoComposition? {
+ guard let sourceRenderSize = renderSize,
+ sourceRenderSize.width > 0,
+ sourceRenderSize.height > 0,
+ sources.count >= 2
+ else {
+ return nil
+ }
+
+ let resolvedRenderSize = previewRenderSize(for: sourceRenderSize)
+ let frameDuration = CMTime(value: 1, timescale: CMTimeScale(max(frameRate.rounded(), 1)))
+
+ if transitions.isEmpty {
+ let instructions = buildPassthroughLayerInstructions(
+ composition: composition,
+ sources: sources,
+ clipTrackMap: clipTrackMap,
+ renderSize: resolvedRenderSize
+ )
+ guard !instructions.isEmpty else { return nil }
+
+ let videoComposition = AVMutableVideoComposition()
+ videoComposition.instructions = instructions
+ videoComposition.renderSize = resolvedRenderSize
+ videoComposition.frameDuration = frameDuration
+ return videoComposition
+ }
+
+ let transitionLookup = buildTransitionLookup(transitions: transitions, sources: sources)
+ var segments = buildTimeSegments(sources: sources, transitionLookup: transitionLookup, clipTrackMap: clipTrackMap)
+ segments.sort { $0.timeRange.start < $1.timeRange.start }
+
+ var instructions: [AVVideoCompositionInstructionProtocol] = []
+ for segment in segments {
+ switch segment.kind {
+ case .passthrough(let trackID):
+ let instruction = CompositorPassthroughInstruction(
+ timeRange: segment.timeRange,
+ sourceTrackID: trackID
+ )
+ instructions.append(instruction)
+ case .transition(let outgoingTrackID, let incomingTrackID, let transitionData):
+ let instruction = TransitionInstruction(
+ timeRange: segment.timeRange,
+ outgoingTrackID: outgoingTrackID,
+ incomingTrackID: incomingTrackID,
+ transitionType: transitionData.type,
+ transitionParams: transitionData.params,
+ renderSize: resolvedRenderSize
+ )
+ instructions.append(instruction)
+ }
+ }
+
+ guard !instructions.isEmpty else { return nil }
+
+ let videoComposition = AVMutableVideoComposition()
+ videoComposition.instructions = instructions
+ videoComposition.renderSize = resolvedRenderSize
+ videoComposition.frameDuration = frameDuration
+ videoComposition.customVideoCompositorClass = TransitionVideoCompositor.self
+ return videoComposition
+ }
+
+ private static func buildPassthroughLayerInstructions(
+ composition: AVMutableComposition,
+ sources: [PlaybackController.TimelineSource],
+ clipTrackMap: [String: CMPersistentTrackID],
+ renderSize: CGSize
+ ) -> [AVMutableVideoCompositionInstruction] {
+ let videoTracks = composition.tracks(withMediaType: .video)
+ guard !videoTracks.isEmpty else { return [] }
+ let tracksByID = Dictionary(uniqueKeysWithValues: videoTracks.map { ($0.trackID, $0) })
+
+ var instructions: [AVMutableVideoCompositionInstruction] = []
+ for source in sources {
+ guard let trackID = clipTrackMap[source.id],
+ let activeTrack = tracksByID[trackID]
+ else { continue }
+
+ let startTime = CMTime(seconds: max(source.startTime, 0), preferredTimescale: 600)
+ let duration = CMTime(seconds: max(source.duration, 0), preferredTimescale: 600)
+ guard duration.seconds > 0 else { continue }
+
+ let timeRange = CMTimeRange(start: startTime, duration: duration)
+ let instruction = AVMutableVideoCompositionInstruction()
+ instruction.timeRange = timeRange
+
+ var layerInstructions: [AVVideoCompositionLayerInstruction] = []
+ for track in videoTracks {
+ let layer = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
+ if track.trackID == activeTrack.trackID {
+ layer.setOpacity(1.0, at: timeRange.start)
+ let transform = aspectFitTransform(
+ sourceTransform: activeTrack.preferredTransform,
+ sourceNaturalSize: activeTrack.naturalSize,
+ renderSize: renderSize
+ )
+ layer.setTransform(transform, at: timeRange.start)
+ } else {
+ layer.setOpacity(0.0, at: timeRange.start)
+ }
+ layerInstructions.append(layer)
+ }
+
+ instruction.layerInstructions = layerInstructions
+ instructions.append(instruction)
+ }
+
+ instructions.sort { $0.timeRange.start < $1.timeRange.start }
+ return instructions
+ }
+
+ private static func aspectFitTransform(
+ sourceTransform: CGAffineTransform,
+ sourceNaturalSize: CGSize,
+ renderSize: CGSize
+ ) -> CGAffineTransform {
+ let orientedSize = CGRect(origin: .zero, size: sourceNaturalSize)
+ .applying(sourceTransform)
+ .standardized
+ .size
+ let width = abs(orientedSize.width)
+ let height = abs(orientedSize.height)
+ guard width > 0, height > 0, renderSize.width > 0, renderSize.height > 0 else {
+ return sourceTransform
+ }
+
+ let scaleX = renderSize.width / width
+ let scaleY = renderSize.height / height
+ let scale = min(scaleX, scaleY)
+ let scaledWidth = width * scale
+ let scaledHeight = height * scale
+ let offsetX = (renderSize.width - scaledWidth) / 2
+ let offsetY = (renderSize.height - scaledHeight) / 2
+
+ return sourceTransform
+ .concatenating(CGAffineTransform(scaleX: scale, y: scale))
+ .concatenating(CGAffineTransform(translationX: offsetX, y: offsetY))
+ }
+```
+
+The function header (`private static func buildVideoComposition`) is unchanged so the existing caller `let videoComposition = buildVideoComposition(...)` at line ~603 keeps working.
+
+- [ ] **Step 3: Run the tests to verify they all pass**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlaybackCompositionBuilderTests" \
+ -quiet
+```
+
+Expected: all three tests PASS.
+
+- [ ] **Step 4: Build the app to confirm no compile regressions elsewhere**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Core/Playback/PlaybackCompositionBuilder.swift"
+git commit -m "fix(ios): skip custom compositor when no transitions
+
+Two video sources with no transitions previously forced the path
+through TransitionVideoCompositor, which silently delivered black
+frames when AVPlayer was not actively requesting renders. Use
+standard layer instructions for the passthrough case so AVPlayer's
+built-in compositor handles rendering directly."
+```
+
+---
+
+### Task 3: Reliable paused-frame nudge (B2)
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/Features/Preview/MetalVideoView.swift`
+
+- [ ] **Step 1: Replace `forceCompositorRefresh`**
+
+Open `Features/Preview/MetalVideoView.swift`. Find `forceCompositorRefresh` (lines 226-238) and replace it with:
+
+```swift
+ private func forceCompositorRefresh(on item: AVPlayerItem) {
+ guard let player = currentPlayer, player.currentItem === item else { return }
+ let resolvedFrameRate = max(frameRate, 1)
+ let frameDuration = CMTime(value: 1, timescale: CMTimeScale(resolvedFrameRate.rounded()))
+ let currentTime = player.currentTime()
+ let nudgedTime = CMTimeAdd(currentTime, frameDuration)
+
+ player.seek(to: nudgedTime, toleranceBefore: .zero, toleranceAfter: .zero) { [weak self, weak player] _ in
+ Task { @MainActor [weak self, weak player] in
+ guard let self, let player else { return }
+ player.seek(to: currentTime, toleranceBefore: .zero, toleranceAfter: .zero)
+ self.pumpFrameUntilDelivered(remainingAttempts: 3)
+ }
+ }
+ }
+
+ private func pumpFrameUntilDelivered(remainingAttempts: Int) {
+ metalView.draw()
+ guard remainingAttempts > 0, lastFrame == nil else { return }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.033) { [weak self] in
+ guard let self else { return }
+ self.pumpFrameUntilDelivered(remainingAttempts: remainingAttempts - 1)
+ }
+ }
+```
+
+- [ ] **Step 2: Add KVO on `currentItem` so item swaps re-trigger the nudge**
+
+In the same file, find the private property block near the top of `VideoPlayerUIView` (~line 44-56). Add this property next to `itemReadyObserver`:
+
+```swift
+ private var currentItemObserver: NSKeyValueObservation?
+```
+
+Then update `setPlayer(_:)` (lines 98-106) to install/tear down the observer:
+
+```swift
+ func setPlayer(_ player: AVPlayer?) {
+ guard currentPlayer !== player else { return }
+ detachVideoOutput()
+ currentItemObserver?.invalidate()
+ currentItemObserver = nil
+ currentPlayer = player
+ lastFrame = nil
+ resetAIContext()
+ installVideoOutput()
+ if let player {
+ currentItemObserver = player.observe(\.currentItem, options: [.new]) { [weak self] _, _ in
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.detachVideoOutput()
+ self.lastFrame = nil
+ self.installVideoOutput()
+ self.metalView.draw()
+ }
+ }
+ }
+ metalView.draw()
+ }
+```
+
+- [ ] **Step 3: Build to confirm no regressions**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 4: Run the full test suite to confirm nothing else regressed**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: all tests PASS.
+
+- [ ] **Step 5: Manual smoke test the original bug**
+
+Launch the iOS app in the simulator, open a project with a single video clip, hit the toolbar Split button, then press Play. Expected: video plays, preview shows frames (not black). If you observe black frames anywhere in this flow, stop and re-read Section 6 of the spec — the fix is incomplete.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Preview/MetalVideoView.swift"
+git commit -m "fix(ios): nudge paused frame by one full frame, not 1.67ms
+
+The previous nudge of CMTime(value: 1, timescale: 600) was smaller
+than one frame at 30fps; with toleranceBefore/After: .zero AVPlayer
+rounded back to the same frame and never re-invoked the compositor.
+Nudge by an actual frame, retry up to 3x100ms if no buffer lands,
+and re-install the video output if the AVPlayer's currentItem
+changes underneath us."
+```
+
+---
+
+## Phase 2 — Zoom controller (spec §5)
+
+Small, low-risk, immediately visible win.
+
+### Task 4: Add `TimelineZoomChip` in the top-right of the timeline
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+
+- [ ] **Step 1: Read the current `timeline(for:)` body to find the insertion point**
+
+Read `EditorView.swift` lines 1805-1918. The `timeline(for:)` function ends with `.overlay(alignment: .top) { ... }` (the 1 pt divider line). We will add a sibling overlay at `.topTrailing`.
+
+- [ ] **Step 2: Add the `TimelineZoomChip` private struct**
+
+Locate the bottom of the `EditorView` extension that holds the `timeline(for:)` function (just before the next `private struct` definition — search for `private struct TimelineClipBlock` to find the boundary, ~line 4616). Immediately *before* `private struct TimelineClipBlock: View {`, insert:
+
+```swift
+private struct TimelineZoomChip: View {
+ @Binding var zoom: Double
+ let fitZoom: () -> Double
+
+ private let minZoom: Double = 20
+ private let maxZoom: Double = 300
+ private let defaultZoom: Double = 48
+ private let stepFactor: Double = 1.5
+
+ private static let presets: [(label: String, value: Double?)] = [
+ ("25%", 12),
+ ("50%", 24),
+ ("100%", 48),
+ ("200%", 96),
+ ("400%", 192),
+ ("Fit", nil)
+ ]
+
+ var body: some View {
+ HStack(spacing: 6) {
+ Button {
+ step(direction: -1)
+ } label: {
+ Image(systemName: "minus")
+ .font(.system(size: 12, weight: .bold))
+ .foregroundStyle(.white)
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Zoom out")
+
+ Menu {
+ ForEach(Array(Self.presets.enumerated()), id: \.offset) { _, preset in
+ Button(preset.label) {
+ applyPreset(preset.value)
+ }
+ }
+ } label: {
+ Text(percentLabel)
+ .font(.system(size: 12, weight: .semibold, design: .rounded))
+ .foregroundStyle(.white)
+ .frame(minWidth: 44)
+ .contentShape(Rectangle())
+ }
+ .menuStyle(.borderlessButton)
+ .simultaneousGesture(
+ TapGesture().onEnded {
+ applyPreset(defaultZoom)
+ }
+ )
+ .accessibilityLabel("Zoom presets, current \(percentLabel)")
+
+ Button {
+ step(direction: 1)
+ } label: {
+ Image(systemName: "plus")
+ .font(.system(size: 12, weight: .bold))
+ .foregroundStyle(.white)
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Zoom in")
+ }
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(OpenReelTheme.surfaceElevated, in: Capsule())
+ .overlay(
+ Capsule().strokeBorder(Color.white.opacity(0.08), lineWidth: 1)
+ )
+ }
+
+ private var percentLabel: String {
+ "\(Int((zoom / defaultZoom * 100).rounded()))%"
+ }
+
+ private func step(direction: Int) {
+ let factor = direction > 0 ? stepFactor : 1.0 / stepFactor
+ withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) {
+ zoom = min(max(zoom * factor, minZoom), maxZoom)
+ }
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ }
+
+ private func applyPreset(_ value: Double?) {
+ let target = value ?? fitZoom()
+ withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) {
+ zoom = min(max(target, minZoom), maxZoom)
+ }
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ }
+}
+```
+
+- [ ] **Step 3: Wire the chip into `timeline(for:)`**
+
+In `timeline(for:)` (around line 1911-1917), find the existing `.overlay(alignment: .top)` modifier:
+
+```swift
+ .overlay(alignment: .top) {
+ Rectangle()
+ .fill(Color.white.opacity(0.04))
+ .frame(height: 1)
+ }
+ }
+```
+
+Add a sibling overlay directly above it (so it comes *before* `.overlay(alignment: .top)`):
+
+```swift
+ .overlay(alignment: .topTrailing) {
+ TimelineZoomChip(
+ zoom: Binding(
+ get: { appState.timelineZoom },
+ set: { appState.timelineZoom = $0 }
+ ),
+ fitZoom: {
+ let duration = max(project.timeline.duration, 1)
+ let badgeWidth = 48.0
+ let badgeGap = 10.0
+ let horizontalPadding = 24.0
+ let availableWidth = proxy.size.width - badgeWidth - badgeGap - horizontalPadding
+ return max(20, min(300, availableWidth / duration))
+ }
+ )
+ .padding(.trailing, 12)
+ .padding(.top, 6)
+ }
+```
+
+`proxy` and `project` are both in scope inside the `GeometryReader { proxy in ... }` body of `timeline(for:)`.
+
+- [ ] **Step 4: Build**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 5: Manual UI check**
+
+Launch the simulator. Open any project. Confirm:
+- The chip appears in the top-right of the timeline.
+- `−` reduces zoom, `+` increases it; both clamped at `20`/`300`.
+- Tapping the percent label resets to 100% (48 px/sec).
+- Long-pressing the percent label opens a `Menu` with the six presets.
+- "Fit" makes the entire timeline duration just fit the visible width.
+- Pinch still works on the timeline body.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "feat(ios): timeline zoom chip in top-right"
+```
+
+---
+
+## Phase 3 — Placement resolver (spec §7, state-layer only)
+
+Pure logic. Test-driven. No UI changes here.
+
+### Task 5: Test `resolveClipPlacement` — no-conflict and basic snap
+
+**Files:**
+- Create: `Openreel Video/Openreel VideoTests/PlacementResolverTests.swift`
+
+- [ ] **Step 1: Write the initial failing tests**
+
+Create the file with this content:
+
+```swift
+import Foundation
+import Testing
+@testable import Openreel_Video
+
+@MainActor
+struct PlacementResolverTests {
+ @Test func emptyDestinationTrackReturnsFrameSnappedProposed() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [
+ .init(id: "moving", start: 0, duration: 2)
+ ])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "moving",
+ proposedStart: 3.0,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution?.start == 3.0)
+ #expect(resolution?.trackID == "T1")
+ #expect(resolution?.didSnap == false)
+ }
+
+ @Test func snapsToNeighborTrailingEdgeWhenWithinThreshold() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [
+ .init(id: "moving", start: 5, duration: 2),
+ .init(id: "left", start: 0, duration: 2)
+ ])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "moving",
+ proposedStart: 2.05,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution?.start == 2.0)
+ #expect(resolution?.didSnap == true)
+ }
+
+ @Test func unknownClipReturnsNil() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "ghost",
+ proposedStart: 0,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution == nil)
+ }
+}
+
+// MARK: - Test harness
+
+@MainActor
+private struct Harness {
+ let appState: AppState
+
+ init() {
+ let directory = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("PlacementResolverTests-\(UUID().uuidString)")
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ self.appState = AppState(
+ projectStore: ProjectStore(baseURL: directory),
+ mediaImportService: MediaImportService()
+ )
+ }
+
+ enum TrackBuilder {
+ case video(id: String, clips: [ClipFixture])
+ case audio(id: String, clips: [ClipFixture])
+
+ var trackID: String {
+ switch self {
+ case .video(let id, _), .audio(let id, _): return id
+ }
+ }
+ }
+
+ struct ClipFixture {
+ let id: String
+ let start: TimeInterval
+ let duration: TimeInterval
+ }
+
+ func makeProject(tracks: [TrackBuilder]) -> OpenReelProject {
+ var project = OpenReelProject.blank(
+ configuration: NewProjectConfiguration(
+ name: "PlacementResolverTests",
+ preset: NewProjectConfiguration.presets[0],
+ frameRate: 30
+ )
+ )
+ project.timeline.tracks.removeAll()
+ for trackBuilder in tracks {
+ let type: OpenReelProject.TrackType
+ let clips: [ClipFixture]
+ switch trackBuilder {
+ case .video(_, let c): type = .video; clips = c
+ case .audio(_, let c): type = .audio; clips = c
+ }
+ let track = OpenReelProject.Track(
+ id: trackBuilder.trackID,
+ type: type,
+ name: trackBuilder.trackID,
+ clips: clips.map { fixture in
+ OpenReelProject.Clip(
+ id: fixture.id,
+ mediaId: "media-\(fixture.id)",
+ trackId: trackBuilder.trackID,
+ startTime: fixture.start,
+ duration: fixture.duration,
+ inPoint: 0,
+ outPoint: fixture.duration,
+ effects: [],
+ audioEffects: [],
+ transform: OpenReelProject.Transform(
+ position: OpenReelProject.Point(x: 0.5, y: 0.5),
+ scale: OpenReelProject.Point(x: 1, y: 1),
+ rotation: 0,
+ anchor: OpenReelProject.Point(x: 0.5, y: 0.5),
+ opacity: 1,
+ borderRadius: nil,
+ fitMode: .contain,
+ crop: nil
+ ),
+ volume: 1,
+ keyframes: [],
+ speed: 1,
+ reversed: false,
+ audioTrackIndex: nil
+ )
+ },
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false
+ )
+ project.timeline.tracks.append(track)
+ }
+ return project
+ }
+}
+```
+
+The explicit `Transform(position:scale:rotation:anchor:opacity:borderRadius:fitMode:crop:)` initializer mirrors the pattern used in `Openreel_VideoTests.swift` around line 3014; `audioConfiguration` is omitted so the synthesized memberwise initializer fills in `AudioConfiguration()`.
+
+- [ ] **Step 2: Run the tests — they will fail to compile (no `resolveClipPlacement` exists yet)**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlacementResolverTests" \
+ -quiet
+```
+
+Expected: compile error "value of type 'AppState' has no member 'resolveClipPlacement'". This is the failing-test state for Task 6.
+
+- [ ] **Step 3: Commit the failing tests**
+
+```bash
+git add "Openreel Video/Openreel VideoTests/PlacementResolverTests.swift"
+git commit -m "test(ios): failing tests for placement resolver — no conflict, snap-to-edge, unknown clip"
+```
+
+---
+
+### Task 6: Implement `resolveClipPlacement` for the no-conflict + edge-snap cases
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/AppState.swift`
+
+- [ ] **Step 1: Add the resolution struct and the method**
+
+Open `AppState.swift`. Find the end of the `AppState` class (look for the closing `}` of the class — search for `private extension Collection` near line 5256 and add code immediately before that closing brace of `AppState`, around line 5253).
+
+Add this inside the `AppState` class (so it has access to private helpers):
+
+```swift
+ struct PlacementResolution: Equatable {
+ let start: TimeInterval
+ let trackID: String
+ let didSnap: Bool
+ }
+
+ func resolveClipPlacement(
+ clipID: String,
+ proposedStart: TimeInterval,
+ destinationTrackID: String,
+ in project: OpenReelProject
+ ) -> PlacementResolution? {
+ guard let movingClip = project.allClips.first(where: { $0.id == clipID }) else {
+ return nil
+ }
+ let duration = movingClip.duration
+ let frameRate = max(project.settings.frameRate, 1)
+ let frameDuration = 1.0 / frameRate
+
+ let clampedProposed = max(proposedStart, 0)
+ let frameSnapped = (clampedProposed / frameDuration).rounded() * frameDuration
+
+ let snapEdges = collectSnapEdges(in: project, excludingClipID: clipID)
+ let snapThreshold = max(0.05, 8.0 / max(timelineZoom, 1))
+
+ var edgeSnappedStart = frameSnapped
+ var didEdgeSnap = false
+ for edge in snapEdges {
+ if abs(edge - frameSnapped) < snapThreshold {
+ edgeSnappedStart = edge
+ didEdgeSnap = true
+ break
+ }
+ if abs(edge - (frameSnapped + duration)) < snapThreshold {
+ edgeSnappedStart = max(0, edge - duration)
+ didEdgeSnap = true
+ break
+ }
+ }
+
+ guard let destinationTrack = project.timeline.tracks.first(where: { $0.id == destinationTrackID }) else {
+ return nil
+ }
+ let neighbors = destinationTrack.clips
+ .filter { $0.id != clipID }
+ .map { (start: $0.startTime, end: $0.startTime + $0.duration) }
+ .sorted { $0.start < $1.start }
+
+ if rangesAreFree(start: edgeSnappedStart, duration: duration, neighbors: neighbors) {
+ return PlacementResolution(start: edgeSnappedStart, trackID: destinationTrackID, didSnap: didEdgeSnap)
+ }
+
+ var candidates: Set<Double> = [0]
+ for neighbor in neighbors {
+ candidates.insert(neighbor.end)
+ candidates.insert(max(0, neighbor.start - duration))
+ }
+ let validCandidates = candidates
+ .filter { rangesAreFree(start: $0, duration: duration, neighbors: neighbors) }
+ .sorted { abs($0 - edgeSnappedStart) < abs($1 - edgeSnappedStart) }
+
+ guard let chosen = validCandidates.first else {
+ return nil
+ }
+
+ return PlacementResolution(start: chosen, trackID: destinationTrackID, didSnap: true)
+ }
+
+ private func rangesAreFree(
+ start: TimeInterval,
+ duration: TimeInterval,
+ neighbors: [(start: TimeInterval, end: TimeInterval)]
+ ) -> Bool {
+ let candidateEnd = start + duration
+ for neighbor in neighbors {
+ if start < neighbor.end - 0.0001 && candidateEnd > neighbor.start + 0.0001 {
+ return false
+ }
+ }
+ return true
+ }
+
+ private func collectSnapEdges(
+ in project: OpenReelProject,
+ excludingClipID: String
+ ) -> [TimeInterval] {
+ var edges: Set<Double> = [0]
+ for track in project.timeline.tracks {
+ for clip in track.clips where clip.id != excludingClipID {
+ edges.insert(clip.startTime)
+ edges.insert(clip.startTime + clip.duration)
+ }
+ }
+ for textClip in project.textClips {
+ edges.insert(textClip.startTime)
+ edges.insert(textClip.startTime + textClip.duration)
+ }
+ for graphicsClip in project.graphicsClips {
+ edges.insert(graphicsClip.startTime)
+ edges.insert(graphicsClip.startTime + graphicsClip.duration)
+ }
+ for marker in project.timeline.markers {
+ edges.insert(marker.time)
+ }
+ return edges.sorted()
+ }
+```
+
+- [ ] **Step 2: Run the tests**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlacementResolverTests" \
+ -quiet
+```
+
+Expected: all three tests PASS. If the `OpenReelProject.Transform.identity` / `AudioConfiguration()` symbols don't compile, look up the actual initializers in `Core/Models/OpenReelProject.swift` and fix the test fixture's clip construction; the resolver itself does not depend on those values.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/AppState.swift"
+git commit -m "feat(ios): add resolveClipPlacement for snap + collision
+
+Centralizes frame-snap, edge-snap, and same-track overlap avoidance
+into a single resolver. Move and import paths will route through
+this in subsequent commits."
+```
+
+---
+
+### Task 7: Add collision tests (overlap, sandwiched, no-room)
+
+**Files:**
+- Modify: `Openreel Video/Openreel VideoTests/PlacementResolverTests.swift`
+
+- [ ] **Step 1: Append three more failing tests to the existing file**
+
+Add these methods inside the `PlacementResolverTests` struct, just before the closing `}` of the struct:
+
+```swift
+ @Test func overlapWithLeftNeighborSnapsToTrailingEdge() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [
+ .init(id: "moving", start: 10, duration: 3),
+ .init(id: "left", start: 0, duration: 4)
+ ])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "moving",
+ proposedStart: 2,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution?.start == 4.0)
+ #expect(resolution?.didSnap == true)
+ }
+
+ @Test func overlapBetweenTwoNeighborsWithEnoughRoomTakesGap() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [
+ .init(id: "moving", start: 20, duration: 2),
+ .init(id: "left", start: 0, duration: 3),
+ .init(id: "right", start: 8, duration: 3)
+ ])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "moving",
+ proposedStart: 4,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution?.start == 3.0)
+ #expect(resolution?.didSnap == true)
+ }
+
+ @Test func noRoomAnywhereReturnsNil() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "T1", clips: [
+ .init(id: "moving", start: 0, duration: 5),
+ .init(id: "a", start: 0, duration: 2),
+ .init(id: "b", start: 2, duration: 2),
+ .init(id: "c", start: 4, duration: 2),
+ .init(id: "d", start: 6, duration: 2)
+ ])
+ ])
+
+ let resolution = harness.appState.resolveClipPlacement(
+ clipID: "moving",
+ proposedStart: 1,
+ destinationTrackID: "T1",
+ in: project
+ )
+
+ #expect(resolution == nil)
+ }
+```
+
+- [ ] **Step 2: Run the tests**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlacementResolverTests" \
+ -quiet
+```
+
+Expected: all six tests PASS. They should — the resolver was already written to handle these cases.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add "Openreel Video/Openreel VideoTests/PlacementResolverTests.swift"
+git commit -m "test(ios): collision-resolution tests for placement resolver"
+```
+
+---
+
+### Task 8: `destinationTrack` helper for cross-track resolution
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/AppState.swift`
+- Modify: `Openreel Video/Openreel VideoTests/PlacementResolverTests.swift`
+
+- [ ] **Step 1: Add failing tests for `destinationTrack`**
+
+Append inside `PlacementResolverTests`:
+
+```swift
+ @Test func destinationTrackClampsCrossTypeToSource() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "V1", clips: [
+ .init(id: "moving", start: 0, duration: 2)
+ ]),
+ .audio(id: "A1", clips: [])
+ ])
+
+ let destination = harness.appState.destinationTrack(
+ forClipID: "moving",
+ trackDelta: 1,
+ in: project
+ )
+
+ #expect(destination == "V1")
+ }
+
+ @Test func destinationTrackPicksAdjacentSameTypeTrack() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "V1", clips: [
+ .init(id: "moving", start: 0, duration: 2)
+ ]),
+ .video(id: "V2", clips: [])
+ ])
+
+ let destination = harness.appState.destinationTrack(
+ forClipID: "moving",
+ trackDelta: 1,
+ in: project
+ )
+
+ #expect(destination == "V2")
+ }
+
+ @Test func destinationTrackClampsOutOfRangeDelta() {
+ let harness = Harness()
+ let project = harness.makeProject(tracks: [
+ .video(id: "V1", clips: [
+ .init(id: "moving", start: 0, duration: 2)
+ ]),
+ .video(id: "V2", clips: [])
+ ])
+
+ let destinationDown = harness.appState.destinationTrack(
+ forClipID: "moving",
+ trackDelta: 99,
+ in: project
+ )
+ let destinationUp = harness.appState.destinationTrack(
+ forClipID: "moving",
+ trackDelta: -99,
+ in: project
+ )
+
+ #expect(destinationDown == "V2")
+ #expect(destinationUp == "V1")
+ }
+```
+
+- [ ] **Step 2: Verify they fail to compile**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlacementResolverTests" \
+ -quiet
+```
+
+Expected: compile error "value of type 'AppState' has no member 'destinationTrack'".
+
+- [ ] **Step 3: Add `destinationTrack` to `AppState`**
+
+Inside the `AppState` class, just after `resolveClipPlacement`, add:
+
+```swift
+ func destinationTrack(
+ forClipID clipID: String,
+ trackDelta: Int,
+ in project: OpenReelProject
+ ) -> String? {
+ guard let movingClip = project.allClips.first(where: { $0.id == clipID }),
+ let sourceTrack = project.timeline.tracks.first(where: { $0.id == movingClip.trackId })
+ else {
+ return nil
+ }
+ let candidates = project.timeline.tracks
+ .filter { $0.type == sourceTrack.type }
+ guard let sourceIndex = candidates.firstIndex(where: { $0.id == sourceTrack.id }) else {
+ return movingClip.trackId
+ }
+ let targetIndex = max(0, min(candidates.count - 1, sourceIndex + trackDelta))
+ return candidates[targetIndex].id
+ }
+```
+
+- [ ] **Step 4: Run the tests**
+
+Run:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -only-testing:"Openreel VideoTests/PlacementResolverTests" \
+ -quiet
+```
+
+Expected: all nine tests PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/AppState.swift" "Openreel Video/Openreel VideoTests/PlacementResolverTests.swift"
+git commit -m "feat(ios): destinationTrack helper for cross-track moves"
+```
+
+---
+
+## Phase 4 — Wire resolver into existing move (spec §7, UI half)
+
+### Task 9: Route the existing `moveClip` through the resolver
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/AppState.swift`
+
+- [ ] **Step 1: Add the new overload, refactor the existing `moveClip` to delegate**
+
+Open `AppState.swift`. Find `moveClip(_ clipID: String, by delta: TimeInterval, playbackController: PlaybackController? = nil)` (line 1005). Replace its entire body (lines 1005-1049) with:
+
+```swift
+ func moveClip(_ clipID: String, by delta: TimeInterval, playbackController: PlaybackController? = nil) async {
+ guard let project = currentProject,
+ let clip = project.allClips.first(where: { $0.id == clipID })
+ else {
+ return
+ }
+ await moveClip(
+ clipID,
+ by: delta,
+ destinationTrackID: clip.trackId,
+ playbackController: playbackController
+ )
+ }
+
+ func moveClip(
+ _ clipID: String,
+ by delta: TimeInterval,
+ destinationTrackID: String,
+ playbackController: PlaybackController? = nil
+ ) async {
+ guard var project = currentProject,
+ let movingClip = project.allClips.first(where: { $0.id == clipID }),
+ let sourceLocation = clipLocation(for: clipID, in: project)
+ else {
+ return
+ }
+
+ let proposedStart = max(0, movingClip.startTime + delta)
+ guard let resolution = resolveClipPlacement(
+ clipID: clipID,
+ proposedStart: proposedStart,
+ destinationTrackID: destinationTrackID,
+ in: project
+ ) else {
+ return
+ }
+
+ let actualDelta = resolution.start - movingClip.startTime
+ let movingToSameTrack = movingClip.trackId == resolution.trackID
+
+ if abs(actualDelta) < 0.001, movingToSameTrack {
+ return
+ }
+
+ let linkedLocations = linkedClipLocations(for: movingClip, in: project)
+ var linkedUpdates: [(location: ClipLocation, clip: OpenReelProject.Clip)] = []
+
+ for linkedLocation in linkedLocations {
+ let linkedClip = project.timeline.tracks[linkedLocation.trackIndex].clips[linkedLocation.clipIndex]
+ guard let linkedResolution = resolveClipPlacement(
+ clipID: linkedClip.id,
+ proposedStart: linkedClip.startTime + actualDelta,
+ destinationTrackID: linkedClip.trackId,
+ in: project
+ ) else {
+ return
+ }
+ let expected = linkedClip.startTime + actualDelta
+ guard abs(linkedResolution.start - expected) < 0.001 else {
+ return
+ }
+ var updatedLinked = linkedClip
+ updatedLinked.startTime = max(0, linkedResolution.start)
+ linkedUpdates.append((linkedLocation, updatedLinked))
+ }
+
+ var updatedClip = movingClip
+ updatedClip.startTime = max(0, resolution.start)
+ updatedClip.trackId = resolution.trackID
+
+ if movingToSameTrack {
+ project.timeline.tracks[sourceLocation.trackIndex].clips[sourceLocation.clipIndex] = updatedClip
+ } else {
+ project.timeline.tracks[sourceLocation.trackIndex].clips.remove(at: sourceLocation.clipIndex)
+ guard let destinationIndex = project.timeline.tracks.firstIndex(where: { $0.id == resolution.trackID }) else {
+ return
+ }
+ project.timeline.tracks[destinationIndex].clips.append(updatedClip)
+ }
+
+ for update in linkedUpdates {
+ project.timeline.tracks[update.location.trackIndex].clips[update.location.clipIndex] = update.clip
+ }
+
+ normalizeTimeline(&project)
+ await commitEditedProject(project, selectedClipID: clipID, playbackController: playbackController)
+ }
+```
+
+- [ ] **Step 2: Build to confirm no compile regressions**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 3: Run the full test suite**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: all tests PASS. Existing `moveClip` callers continue to work because the old signature is preserved as a wrapper that uses the clip's current `trackId`.
+
+- [ ] **Step 4: Manual UI check — same-track no-overlap**
+
+Launch the simulator. Open a project with two video clips on the same track. Long-press and drag the second clip leftward toward (and into) the first one. Expected: the dragged clip snaps to a position flush against the first clip's trailing edge; it does not overlap.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/AppState.swift"
+git commit -m "feat(ios): route moveClip through resolveClipPlacement
+
+Same-track overlap is now impossible — moves snap to the nearest
+free position. Linked-audio siblings must mirror the video move
+exactly or the entire move aborts."
+```
+
+---
+
+### Task 10: Snap-edge visual indicator + haptic on `TimelineClipBlock`
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+
+- [ ] **Step 1: Add the snap-edge state and overlay to `TimelineClipBlock`**
+
+In `EditorView.swift`, find `private struct TimelineClipBlock: View` (line 4616). Locate its existing `@State private var moveTranslation: CGFloat = 0` (line 4649). Add directly after it:
+
+```swift
+ @State private var snapEdgeX: CGFloat? = nil
+ @State private var snapClearTask: Task<Void, Never>? = nil
+```
+
+Find the `body: some View { ZStack(alignment: .leading) { ... } }` (line 4653). Inside the existing chain of `.overlay { ... }` modifiers (around line 4710), insert a new overlay *after* the keyframe lane overlay:
+
+```swift
+ .overlay(alignment: .leading) {
+ if let snapEdgeX {
+ Rectangle()
+ .fill(OpenReelTheme.accent)
+ .frame(width: 1, height: 62)
+ .offset(x: snapEdgeX - moveTranslation, y: -4)
+ .opacity(0.9)
+ .animation(.easeOut(duration: 0.15), value: snapEdgeX)
+ .allowsHitTesting(false)
+ }
+ }
+```
+
+- [ ] **Step 2: Add helper that triggers the snap pulse**
+
+Inside `TimelineClipBlock` (just after the existing `private var moveGesture: some Gesture { ... }` block ends, around line 4771), add:
+
+```swift
+ private func flashSnapEdge(at edgeX: CGFloat) {
+ if snapEdgeX != edgeX {
+ UIImpactFeedbackGenerator(style: .soft).impactOccurred()
+ }
+ snapClearTask?.cancel()
+ snapEdgeX = edgeX
+ snapClearTask = Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 200_000_000)
+ guard !Task.isCancelled else { return }
+ snapEdgeX = nil
+ }
+ }
+```
+
+`@State` properties on a SwiftUI `View` struct can be assigned from `@MainActor`-isolated closures because the property wrapper's setter is `nonmutating`. The cancellation token guarantees only the most recent flash decides when to clear.
+
+- [ ] **Step 3: Wire the flash into the move gesture's onChanged path**
+
+Replace `moveGesture` (lines 4751-4771) with:
+
+```swift
+ private var moveGesture: some Gesture {
+ LongPressGesture(minimumDuration: 0.18)
+ .sequenced(before: DragGesture(minimumDistance: 1))
+ .onChanged { value in
+ switch value {
+ case .second(true, let drag?):
+ moveTranslation = drag.translation.width
+ detectSnapDuringDrag(translation: drag.translation)
+ default:
+ break
+ }
+ }
+ .onEnded { value in
+ defer {
+ moveTranslation = 0
+ snapEdgeX = nil
+ snapClearTask?.cancel()
+ }
+ guard case .second(true, let drag?) = value else { return }
+
+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+ onMove(drag.translation.width / max(pixelsPerSecond, 1))
+ }
+ }
+
+ private func detectSnapDuringDrag(translation: CGSize) {
+ let project = appState.currentProject
+ guard let project else { return }
+ let proposedStart = max(0, clip.startTime + translation.width / max(pixelsPerSecond, 1))
+ guard let resolution = appState.resolveClipPlacement(
+ clipID: clip.id,
+ proposedStart: proposedStart,
+ destinationTrackID: clip.trackId,
+ in: project
+ ) else {
+ return
+ }
+ if resolution.didSnap {
+ let edgePx = (resolution.start - clip.startTime) * pixelsPerSecond
+ flashSnapEdge(at: edgePx)
+ } else if snapEdgeX != nil {
+ snapClearTask?.cancel()
+ snapEdgeX = nil
+ }
+ }
+```
+
+- [ ] **Step 4: Build**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 5: Manual UI check**
+
+Launch the simulator. Open a project with two clips on the same track. Long-press the second clip and drag it slowly toward the first. Expected: a 1 pt accent vertical line briefly appears at the snap edge each time the drag enters snap range; a soft haptic fires; line fades after 200 ms.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "feat(ios): snap-edge visual + haptic on clip drag"
+```
+
+---
+
+## Phase 5 — Cross-track gesture (spec §8)
+
+### Task 11: Extend `TimelineClipBlock` move gesture to 2-D and wire to cross-track move
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+
+- [ ] **Step 1: Change the block's `onMove` callback to receive 2-D translation**
+
+In `TimelineClipBlock`, find `let onMove: (TimeInterval) -> Void` (line 4628). Replace it with:
+
+```swift
+ let onMove: (_ timeDelta: TimeInterval, _ trackDelta: Int) -> Void
+ let laneHeight: CGFloat
+ let trackRowSpacing: CGFloat
+```
+
+- [ ] **Step 2: Update the caller in `visualTrackLane(for:track:contentWidth:)`**
+
+Find the `TimelineClipBlock(...)` construction inside `visualTrackLane(...)` (line 2080-2105). Update the `onMove:` argument and add the new params. Replace lines 2080-2105 with:
+
+```swift
+ ForEach(visualClips) { clip in
+ TimelineClipBlock(
+ project: project,
+ clip: clip,
+ pixelsPerSecond: appState.timelineZoom,
+ isSelected: appState.selectedClipID == clip.id,
+ selectedKeyframeID: appState.selectedKeyframeID,
+ onSelect: {
+ playbackController.pause()
+ appState.selectClip(clip)
+ playbackController.seek(to: min(max(clip.startTime, 0), appState.currentProject?.timeline.duration ?? clip.startTime))
+ appState.editorTab = .edit
+ },
+ onTrim: { edge, delta in
+ Task {
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+ }
+ },
+ onMove: { timeDelta, trackDelta in
+ Task {
+ let destinationTrackID: String
+ if trackDelta == 0 {
+ destinationTrackID = clip.trackId
+ } else if let resolved = appState.destinationTrack(forClipID: clip.id, trackDelta: trackDelta, in: project) {
+ destinationTrackID = resolved
+ } else {
+ destinationTrackID = clip.trackId
+ }
+ await appState.moveClip(
+ clip.id,
+ by: timeDelta,
+ destinationTrackID: destinationTrackID,
+ playbackController: playbackController
+ )
+ }
+ },
+ onKeyframeSelect: { keyframeID in
+ appState.selectKeyframe(keyframeID)
+ appState.editorTab = .edit
+ lowerPanelContent = nil
+ activeEditingSheet = .keyframe
+ },
+ laneHeight: timelineLaneHeight(for: track),
+ trackRowSpacing: 8
+ )
+ .offset(x: clip.startTime * appState.timelineZoom)
+ .onTapGesture {
+ selectClipForPreview(clip, in: project)
+ }
+ }
+```
+
+- [ ] **Step 3: Update `moveGesture` to also compute `trackDelta` from vertical translation**
+
+Replace `moveGesture` (just authored in Task 10) with:
+
+```swift
+ private var moveGesture: some Gesture {
+ LongPressGesture(minimumDuration: 0.18)
+ .sequenced(before: DragGesture(minimumDistance: 1))
+ .onChanged { value in
+ switch value {
+ case .second(true, let drag?):
+ moveTranslation = drag.translation.width
+ moveVerticalTranslation = drag.translation.height
+ detectSnapDuringDrag(translation: drag.translation)
+ default:
+ break
+ }
+ }
+ .onEnded { value in
+ defer {
+ moveTranslation = 0
+ moveVerticalTranslation = 0
+ snapEdgeX = nil
+ snapClearTask?.cancel()
+ }
+ guard case .second(true, let drag?) = value else { return }
+
+ let timeDelta = drag.translation.width / max(pixelsPerSecond, 1)
+ let trackDelta = Int(round(drag.translation.height / max(laneHeight + trackRowSpacing, 1)))
+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+ onMove(timeDelta, trackDelta)
+ }
+ }
+```
+
+Add the new `@State` (next to `moveTranslation`, ~line 4649):
+
+```swift
+ @State private var moveVerticalTranslation: CGFloat = 0
+```
+
+- [ ] **Step 4: Apply the live vertical offset and "lifted" affordance**
+
+Find the `.offset(x: moveTranslation)` line (line 4715) and replace it with:
+
+```swift
+ .offset(x: moveTranslation, y: moveVerticalTranslation)
+ .scaleEffect(moveVerticalTranslation == 0 && moveTranslation == 0 ? 1.0 : 1.04)
+ .shadow(color: .black.opacity(moveVerticalTranslation == 0 && moveTranslation == 0 ? 0 : 0.35), radius: 12)
+ .zIndex(moveTranslation == 0 && moveVerticalTranslation == 0 ? 0 : 10)
+```
+
+- [ ] **Step 5: Build**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 6: Manual UI check — cross-track move**
+
+Launch the simulator. Open a project, add a second video track via the `+` menu, then long-press a clip on track 1 and drag it down onto track 2. Expected: clip lifts (scale + shadow), follows finger between rows, on release lands on track 2. Drag it back up — returns to track 1. Drag a video clip downward toward an audio track — clip does *not* switch to the audio track (clamps to source).
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "feat(ios): cross-track moves for video clips (same-type only)"
+```
+
+---
+
+### Task 12: Mirror cross-track move into the other three block types
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+
+Mirror Task 11's changes into `TimelineAudioClipBlock`, `TimelineTextClipBlock`, and `TimelineGraphicsClipBlock`. Each block has the same shape — `moveGesture`, `moveTranslation`, `onMove` callback. The text/graphics blocks deliberately stay restricted to text/graphics tracks via `destinationTrack` (which already filters by `track.type`).
+
+- [ ] **Step 1: Update `TimelineAudioClipBlock` (line 4863)**
+
+Add the same three properties (`moveVerticalTranslation`, `laneHeight`, `trackRowSpacing`), update `onMove` signature to `(TimeInterval, Int)`, and copy the same `moveGesture` and `.offset/.scaleEffect/.shadow/.zIndex` block from Task 11. The body around line 4886 (`.frame(width: liveClipWidth, height: 46, alignment: .leading)`) anchors the change — apply the same modifiers there.
+
+- [ ] **Step 2: Update the audio caller**
+
+In `audioTrackLane(track:contentWidth:)` (line 2154), replace the `TimelineAudioClipBlock(...)` construction at line 2168 with:
+
+```swift
+ TimelineAudioClipBlock(
+ clip: clip,
+ pixelsPerSecond: appState.timelineZoom,
+ isSelected: appState.selectedClipID == clip.id,
+ onSelect: {
+ playbackController.pause()
+ appState.selectClip(clip)
+ playbackController.seek(to: min(max(clip.startTime, 0), appState.currentProject?.timeline.duration ?? clip.startTime))
+ appState.editorTab = .edit
+ },
+ onTrim: { edge, delta in
+ Task {
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+ }
+ },
+ onMove: { timeDelta, trackDelta in
+ Task {
+ let project = appState.currentProject
+ let destinationTrackID: String
+ if trackDelta == 0 || project == nil {
+ destinationTrackID = clip.trackId
+ } else if let resolved = appState.destinationTrack(forClipID: clip.id, trackDelta: trackDelta, in: project!) {
+ destinationTrackID = resolved
+ } else {
+ destinationTrackID = clip.trackId
+ }
+ await appState.moveClip(
+ clip.id,
+ by: timeDelta,
+ destinationTrackID: destinationTrackID,
+ playbackController: playbackController
+ )
+ }
+ },
+ laneHeight: timelineLaneHeight(for: track),
+ trackRowSpacing: 8
+ )
+ .offset(x: clip.startTime * appState.timelineZoom)
+```
+
+- [ ] **Step 3: Update `TimelineTextClipBlock` (line 4980) — gesture parity only**
+
+For text clips, this iteration adopts the same gesture surface (faster long-press, 2-D translation, lifted-state visuals) but keeps moves single-track. Change `TimelineTextClipBlock`'s `onMove` declaration from `(TimeInterval) -> Void` to `(_ timeDelta: TimeInterval, _ trackDelta: Int) -> Void`. Add the `laneHeight`/`trackRowSpacing` properties. Copy the same `moveGesture` and `.offset/.scaleEffect/.shadow/.zIndex` modifiers from Task 11.
+
+In the gesture's `onEnded`, ignore `trackDelta` for text — the spec defers cross-track text moves. Pass it through unused:
+
+```swift
+ onMove(timeDelta, trackDelta)
+```
+
+Update the caller in `textTrackLane(...)` at line 1986 to provide the new params and to ignore `trackDelta`:
+
+```swift
+ onMove: { timeDelta, _ in
+ Task {
+ await appState.moveTextClip(textClip.id, by: timeDelta, playbackController: playbackController)
+ }
+ },
+ laneHeight: timelineLaneHeight(for: track),
+ trackRowSpacing: 8
+```
+
+- [ ] **Step 4: Update `TimelineGraphicsClipBlock` (line 5186) — same pattern as text**
+
+Same change as Step 3, but the existing AppState method is `moveGraphicsClip(_:by:playbackController:)`. Update the caller in `graphicsTrackLane(...)` (around line 2036) the same way: pass `onMove: { timeDelta, _ in ... await appState.moveGraphicsClip(graphicsClip.id, by: timeDelta, playbackController: playbackController) }` plus `laneHeight`/`trackRowSpacing`.
+
+- [ ] **Step 5: Build**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 6: Run the full test suite**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: all tests PASS.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "feat(ios): cross-track moves for audio, gesture parity for text/graphics
+
+Audio clips can now move between audio tracks. Text and graphics
+blocks reuse the 2-D gesture for lifted-state visuals and faster
+long-press, but their vertical translation is ignored at commit
+time (the spec scopes cross-track text/graphics out for now)."
+```
+
+---
+
+## Phase 6 — Polish (spec §9)
+
+### Task 13: Scissors mini-button + post-split playhead seek
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+- Modify: `Openreel Video/Openreel Video/AppState.swift`
+
+- [ ] **Step 1: Modify `splitSelectedClip` to return the split time**
+
+In `AppState.swift`, find `splitSelectedClip(at:playbackController:)` (line 820). Change its signature to return the split time:
+
+```swift
+ @discardableResult
+ func splitSelectedClip(at playheadTime: TimeInterval, playbackController: PlaybackController? = nil) async -> TimeInterval? {
+```
+
+At the end of the function (just before the existing closing `}` at line 886), replace `await commitEditedProject(project, selectedClipID: splitResult.right.id, playbackController: playbackController)` with:
+
+```swift
+ await commitEditedProject(project, selectedClipID: splitResult.right.id, playbackController: playbackController)
+ playbackController?.seek(to: splitTime)
+ return splitTime
+```
+
+Inside the existing `guard splitTime > clipStart, splitTime < clipEnd else { return }` (line 831), change `return` to `return nil`. Similarly, change every other early-return inside `splitSelectedClip` to `return nil`. Final `return` line above stays the explicit `return splitTime`.
+
+- [ ] **Step 2: Add the scissors mini-button to `TimelineClipBlock`**
+
+`PlaybackController` is provided to `EditorView` via `@Environment(PlaybackController.self) private var playbackController` (EditorView.swift line 6) but is **not** on `AppState`. Inject it into `TimelineClipBlock` via the SwiftUI environment so the block doesn't need a new constructor parameter.
+
+In `TimelineClipBlock`, find `@Environment(AppState.self) private var appState` (line 4617) and add immediately after it:
+
+```swift
+ @Environment(PlaybackController.self) private var playbackController
+```
+
+Inside the existing chain of `.overlay { ... }` modifiers in `body` (around line 4710), add:
+
+```swift
+ .overlay(alignment: .topTrailing) {
+ if shouldShowScissors {
+ Button {
+ let playheadTime = playbackController.currentTime
+ Task {
+ await appState.splitSelectedClip(at: playheadTime, playbackController: playbackController)
+ }
+ } label: {
+ Image(systemName: "scissors")
+ .font(.system(size: 13, weight: .bold))
+ .foregroundStyle(.white)
+ .frame(width: 32, height: 32)
+ .background(OpenReelTheme.accent, in: Circle())
+ }
+ .buttonStyle(.plain)
+ .offset(x: -6, y: -18)
+ .accessibilityLabel("Split at playhead")
+ }
+ }
+```
+
+Just below the property declarations (~line 4651, after `@State private var trailingTrimOffset`), add the visibility computed property:
+
+```swift
+ private var shouldShowScissors: Bool {
+ guard isSelected else { return false }
+ guard clipWidth > 80 else { return false }
+ let playheadTime = playbackController.currentTime
+ return playheadTime > clip.startTime + 0.001
+ && playheadTime < clip.startTime + clip.duration - 0.001
+ }
+```
+
+Because `PlaybackController` is an `@Observable`, `playbackController.currentTime` participates in SwiftUI's dependency tracking — the button will appear and disappear as the playhead scrubs in and out of the selected clip without any manual invalidation.
+
+- [ ] **Step 3: Build**
+
+Run:
+
+```bash
+xcodebuild build \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: BUILD SUCCEEDED.
+
+- [ ] **Step 4: Run the full test suite**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 15" \
+ -quiet
+```
+
+Expected: all tests PASS.
+
+- [ ] **Step 5: Manual UI check**
+
+Launch the simulator. Open a project, add a video, scrub the playhead to ~1 s, select the clip. Expected: a small scissor button appears on the upper-right of the clip. Tap it. Expected: clip splits at the playhead, playhead now sits exactly at the split point, the right-half clip becomes selected, preview shows a frame (Phase 1 already proved this).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/AppState.swift" "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "feat(ios): scissors mini-button + post-split playhead seek"
+```
+
+---
+
+## Self-Review
+
+After completing all tasks, verify against the spec:
+
+**Spec coverage check:**
+- §5 Zoom controller → Task 4
+- §6.2 Skip custom compositor → Task 2
+- §6.3 Reliable nudge → Task 3
+- §7 Placement resolver → Tasks 5-8
+- §7.4 Snap visuals + haptic → Task 10
+- §8 Cross-track movement (video, audio) → Tasks 11-12
+- §9.1 Long-press to 0.18 s → Task 11 (gesture rewrite)
+- §9.2 Lifted-state visuals → Task 11
+- §9.3 Scissors mini-button → Task 13
+- §9.4 Post-split playhead seek → Task 13
+- §12.1 Composition tests → Task 1
+- §12.1 Placement resolver tests → Tasks 5, 7, 8
+
+**Known gaps explicitly accepted by this plan:**
+- §8 cross-track movement for *text* and *graphics* clips. Task 12 Step 3-4 documents this — those types require their own `moveClip`-equivalent overloads on `AppState` which are out of scope for the current spec.
+- §13's "no room" red-tint visual indicator on the linked audio block — folded into the snap-edge overlay; the *absence* of snap (and the snap-back on drag end) is the user-visible signal. Acceptable.
+
+**Type consistency:**
+- `PlacementResolution` (Task 6) is used in Tasks 7, 9, 10. Same fields throughout.
+- `resolveClipPlacement(clipID:proposedStart:destinationTrackID:in:)` signature is identical at every call site.
+- `destinationTrack(forClipID:trackDelta:in:)` signature is identical at every call site.
+- `onMove: (TimeInterval, Int) -> Void` signature is consistent across `TimelineClipBlock` and `TimelineAudioClipBlock`. Text/graphics blocks adopt the same signature in Task 12 (with cross-track wiring deferred).
+
+---
+
+## Final Manual Acceptance Checklist
+
+Before opening the PR, run through this list against a real device or simulator:
+
+1. Add one video → split at playhead → press play. Video plays, no dark preview.
+2. Add two videos → drag the second toward the first; the proposed range overlaps the first. The clip snaps flush against the first clip's trailing edge.
+3. With two video tracks, drag a clip from track 1 down to track 2. Clip moves between tracks. Drag back up — returns to track 1.
+4. Drag a video clip onto an audio track. No track switch occurs.
+5. Pinch to zoom in → chip reads correct percentage. Tap chip's `100%` → returns to default. Long-press `100%` → preset menu opens. `Fit` makes the timeline span the visible width.
+6. With a clip selected and playhead inside it, the scissors mini-button is visible. Tap it. Clip splits at playhead, right-half is selected, playhead sits on the cut, preview shows the post-split frame.
+7. After many edits, the editor remains responsive (no obvious jank introduced).
diff --git a/docs/superpowers/plans/2026-05-28-android-trim-and-crop-parity.md b/docs/superpowers/plans/2026-05-28-android-trim-and-crop-parity.md
new file mode 100644
index 00000000..bff74a10
--- /dev/null
+++ b/docs/superpowers/plans/2026-05-28-android-trim-and-crop-parity.md
@@ -0,0 +1,1239 @@
+# Android Trim + Crop Parity Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Bring Android trim + crop UX to par with the iOS work shipping on the same branch (`feat/ios-app`). See spec at `docs/superpowers/specs/2026-05-28-android-trim-and-crop-parity-design.md`.
+
+**Architecture:** Two workstreams, distinct files, each task = one commit. Workstream A overhauls the trim gestures across `Timeline.kt` and adds two AppState methods. Workstream B extends the existing `CropResizeScreen.kt` with locked-aspect drag math, flip/fit chips, and pinch-with-centroid.
+
+**Tech Stack:** Kotlin, Jetpack Compose (Material 3 + Foundation), `detectDragGestures`, `detectTransformGestures`, `awaitEachGesture`, kotlinx StateFlow for AppState observation.
+
+**Build / test runner:** From `Openreel Video Android/`:
+
+```bash
+./gradlew assembleDebug
+./gradlew testDebugUnitTest
+```
+
+The repo currently builds and ships APKs; the existing test suite must stay green.
+
+**Branch:** Already on `feat/ios-app`. Commit per task with conventional-commit prefix shown in each step.
+
+---
+
+## File Structure
+
+| File | Purpose | Status |
+|---|---|---|
+| `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt` | Snapshot drag pattern in video/audio/text/graphics/adjustment trim handles; new leading-edge video trim; new audio trim gestures; snap indicator overlay | Modify |
+| `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/state/AppState.kt` | `trimVideoClipStart(trackId, clipId, deltaSeconds)`, `trimAudioClipStart`, `trimAudioClipEnd` | Modify |
+| `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt` | `lockedAspect` state + parameter on `resizeCrop`; Flip H/V chips; Fit mode chip row; pinch-to-zoom with centroid math on the backdrop | Modify |
+
+No new files. The work stays in three existing files.
+
+---
+
+# Workstream A — Trim polish
+
+## Task A1: Snapshot drag pattern for video clip trailing trim
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt` (trailing trim handle around line 1019, `ClipBlock` signature where applicable)
+
+- [ ] **Step 1: Locate the video clip block**
+
+```bash
+grep -n "private fun VideoClipBlock\|private fun ClipBlock\|fun VideoTrackLane" "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt"
+```
+
+Find the block that contains the trailing trim handle at line ~1019–1031 (the `Box .align(Alignment.CenterEnd).fillMaxHeight().pointerInput(...) { detectDragGestures { _, dragAmount -> onTrimEnd(...) } }` pattern). Confirm its enclosing composable name.
+
+- [ ] **Step 2: Replace the trailing trim handle's pointerInput with snapshot-based drag**
+
+Find:
+
+```kotlin
+Box(
+ modifier = Modifier
+ .align(Alignment.CenterEnd)
+ .fillMaxHeight()
+ .pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ onTrimEnd(clip, (deltaDp / pixelsPerSecond).toDouble())
+ }
+ },
+) {
+ TrimHandle(modifier = Modifier.fillMaxHeight(), color = colors.accent)
+}
+```
+
+Replace with:
+
+```kotlin
+var trailingAccumulatedDp by remember(clip.id, pixelsPerSecond) { mutableFloatStateOf(0f) }
+Box(
+ modifier = Modifier
+ .align(Alignment.CenterEnd)
+ .fillMaxHeight()
+ .pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures(
+ onDragStart = {
+ trailingAccumulatedDp = 0f
+ onDragInteraction(true)
+ },
+ onDragEnd = {
+ val deltaSeconds = (trailingAccumulatedDp / pixelsPerSecond).toDouble()
+ if (kotlin.math.abs(deltaSeconds) > 0.001) {
+ onTrimEnd(clip, deltaSeconds)
+ }
+ trailingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ onDragCancel = {
+ trailingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ ) { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ trailingAccumulatedDp += deltaDp
+ }
+ },
+) {
+ TrimHandle(modifier = Modifier.fillMaxHeight(), color = colors.accent)
+}
+```
+
+`trailingAccumulatedDp` lives in the composable's scope (above the `Box`). Its `remember(clip.id, pixelsPerSecond)` key resets when either changes — including after the drag commits and the clip's duration changes.
+
+- [ ] **Step 3: Apply the accumulated delta to the visual width**
+
+Find where the clip block's width is computed. There will be something like:
+
+```kotlin
+val widthDp = (clip.duration * pixelsPerSecond).toFloat().coerceAtLeast(32f)
+```
+
+Add the in-progress visual width below it:
+
+```kotlin
+val widthDp = (clip.duration * pixelsPerSecond).toFloat().coerceAtLeast(32f)
+val visualWidthDp = (widthDp + trailingAccumulatedDp).coerceAtLeast(32f)
+```
+
+Replace the `Box(modifier = Modifier.width(widthDp.dp)...)` with `.width(visualWidthDp.dp)`. There's typically ONE such width on the outer Box of the clip block; check the surrounding code carefully.
+
+If `widthDp` is used in multiple places (e.g., scissors button positioning, child sizing), only the OUTER clip-frame Box's width should use `visualWidthDp`. Interior elements that calculate positions from the clip duration should still use `widthDp`.
+
+- [ ] **Step 4: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt"
+git commit -m "feat(android): snapshot-based drag for video clip trailing trim
+
+Replace per-event onTrimEnd with onDragStart/onDrag/onDragEnd pattern:
+accumulate cumulative dp delta locally during the gesture, apply it
+to the visual frame width so the user sees the result live, and
+commit ONCE on release. Single undo entry per drag instead of 20+."
+```
+
+## Task A2: Add leading-edge trim to video clips
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt`
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/state/AppState.kt`
+
+- [ ] **Step 1: Add `trimVideoClipStart` to AppState**
+
+In `AppState.kt`, find a related method (e.g., `mutateClip` around line 2186 or `trimGraphicsOverlayStart` around line 4573 for a reference). Add a new method near the existing trim methods:
+
+```kotlin
+fun trimVideoClipStart(trackId: String, clipId: String, deltaSeconds: Double) {
+ mutateClip(trackId, clipId, "Trim Clip Start") { clip ->
+ val newStartTime = (clip.startTime + deltaSeconds).coerceAtLeast(0.0)
+ val actualDelta = newStartTime - clip.startTime
+ val newDuration = (clip.duration - actualDelta).coerceAtLeast(0.05)
+ val newInPoint = (clip.inPoint + actualDelta).coerceAtLeast(0.0)
+ clip.copy(
+ startTime = newStartTime,
+ duration = newDuration,
+ inPoint = newInPoint,
+ )
+ }
+}
+```
+
+This shifts the clip's leading edge right by `deltaSeconds`, advancing `inPoint` so the same source frame appears at the new leading edge. The clip's `outPoint` stays put — we're trimming material off the front.
+
+- [ ] **Step 2: Wire the gesture to the leading TrimHandle in the video clip block**
+
+In `Timeline.kt`, find the current leading handle around line 1018:
+
+```kotlin
+TrimHandle(modifier = Modifier.align(Alignment.CenterStart), color = colors.accent)
+```
+
+Replace with:
+
+```kotlin
+var leadingAccumulatedDp by remember(clip.id, pixelsPerSecond) { mutableFloatStateOf(0f) }
+Box(
+ modifier = Modifier
+ .align(Alignment.CenterStart)
+ .fillMaxHeight()
+ .pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures(
+ onDragStart = {
+ leadingAccumulatedDp = 0f
+ onDragInteraction(true)
+ },
+ onDragEnd = {
+ val deltaSeconds = (leadingAccumulatedDp / pixelsPerSecond).toDouble()
+ if (kotlin.math.abs(deltaSeconds) > 0.001) {
+ onTrimStart(clip, deltaSeconds)
+ }
+ leadingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ onDragCancel = {
+ leadingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ ) { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ leadingAccumulatedDp += deltaDp
+ }
+ },
+) {
+ TrimHandle(modifier = Modifier.fillMaxHeight(), color = colors.accent)
+}
+```
+
+You'll need a new `onTrimStart: (Clip, Double) -> Unit` parameter on the video clip block composable. Find its signature (search for `onTrimEnd: (Clip, Double) -> Unit` in the same file) and add `onTrimStart` next to it.
+
+- [ ] **Step 3: Apply accumulated leading-edge offset visually**
+
+The outer Box of the clip block uses `.offset(x = xOffset.dp)` and `.width(visualWidthDp.dp)`. With a leading trim:
+- The visible LEFT edge should move right by `leadingAccumulatedDp` (so the user's finger drags the edge).
+- The visible RIGHT edge should stay put.
+
+Compute:
+
+```kotlin
+val xOffset = (clip.startTime * pixelsPerSecond).toFloat()
+val widthDp = (clip.duration * pixelsPerSecond).toFloat().coerceAtLeast(32f)
+val visualXOffset = (xOffset + leadingAccumulatedDp).coerceAtLeast(0f)
+val visualWidthDp = (widthDp + trailingAccumulatedDp - leadingAccumulatedDp).coerceAtLeast(32f)
+```
+
+Use `visualXOffset.dp` and `visualWidthDp.dp` in the outer Box.
+
+- [ ] **Step 4: Pass `onTrimStart` from the parent**
+
+In `VideoTrackLane` (or wherever the video clip block is instantiated), find the `onTrimEnd = { clip, delta -> appState.mutateClip(...) }` block (around line 363). Add a sibling:
+
+```kotlin
+onTrimStart = { clip, delta ->
+ appState.trimVideoClipStart(videoTrack.id, clip.id, delta)
+},
+```
+
+- [ ] **Step 5: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt" \
+ "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/state/AppState.kt"
+git commit -m "feat(android): leading-edge trim for video clips
+
+New AppState.trimVideoClipStart adjusts startTime + inPoint by the
+delta and clamps to non-negative duration. Wire it from a new
+Box+pointerInput on the leading TrimHandle, mirroring the trailing
+handle's snapshot drag pattern. Leading edge follows the finger
+during drag; right edge stays put."
+```
+
+## Task A3: Add trim gestures to audio clips
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt` (`AudioTrackLane` around line 1132)
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/state/AppState.kt`
+
+- [ ] **Step 1: Add audio trim methods to AppState**
+
+In `AppState.kt`, near `trimVideoClipStart`:
+
+```kotlin
+fun trimAudioClipStart(trackId: String, clipId: String, deltaSeconds: Double) {
+ mutateClip(trackId, clipId, "Trim Audio Start") { clip ->
+ val newStartTime = (clip.startTime + deltaSeconds).coerceAtLeast(0.0)
+ val actualDelta = newStartTime - clip.startTime
+ val newDuration = (clip.duration - actualDelta).coerceAtLeast(0.05)
+ val newInPoint = (clip.inPoint + actualDelta).coerceAtLeast(0.0)
+ clip.copy(
+ startTime = newStartTime,
+ duration = newDuration,
+ inPoint = newInPoint,
+ )
+ }
+}
+
+fun trimAudioClipEnd(trackId: String, clipId: String, deltaSeconds: Double) {
+ mutateClip(trackId, clipId, "Trim Audio End") { clip ->
+ val newDuration = (clip.duration + deltaSeconds).coerceAtLeast(0.05)
+ val snappedEnd = snapEdit(clip.startTime + newDuration)
+ val finalDuration = (snappedEnd - clip.startTime).coerceAtLeast(0.05)
+ clip.copy(duration = finalDuration, outPoint = clip.inPoint + finalDuration)
+ }
+}
+```
+
+- [ ] **Step 2: Replace the decorative audio TrimHandle calls with gesture-bearing wrappers**
+
+In `Timeline.kt` line 1193–1195:
+
+```kotlin
+if (isSelected) {
+ TrimHandle(modifier = Modifier.align(Alignment.CenterStart), color = colors.accent)
+ TrimHandle(modifier = Modifier.align(Alignment.CenterEnd), color = colors.accent)
+}
+```
+
+Replace the entire block with:
+
+```kotlin
+if (isSelected) {
+ var audioLeadingAccumulatedDp by remember(clip.id, pixelsPerSecond) { mutableFloatStateOf(0f) }
+ var audioTrailingAccumulatedDp by remember(clip.id, pixelsPerSecond) { mutableFloatStateOf(0f) }
+
+ Box(
+ modifier = Modifier
+ .align(Alignment.CenterStart)
+ .fillMaxHeight()
+ .pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures(
+ onDragStart = {
+ audioLeadingAccumulatedDp = 0f
+ onDragInteraction(true)
+ },
+ onDragEnd = {
+ val deltaSeconds = (audioLeadingAccumulatedDp / pixelsPerSecond).toDouble()
+ if (kotlin.math.abs(deltaSeconds) > 0.001) {
+ onTrimStart(clip, deltaSeconds)
+ }
+ audioLeadingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ onDragCancel = {
+ audioLeadingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ ) { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ audioLeadingAccumulatedDp += deltaDp
+ }
+ },
+ ) {
+ TrimHandle(modifier = Modifier.fillMaxHeight(), color = colors.accent)
+ }
+
+ Box(
+ modifier = Modifier
+ .align(Alignment.CenterEnd)
+ .fillMaxHeight()
+ .pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures(
+ onDragStart = {
+ audioTrailingAccumulatedDp = 0f
+ onDragInteraction(true)
+ },
+ onDragEnd = {
+ val deltaSeconds = (audioTrailingAccumulatedDp / pixelsPerSecond).toDouble()
+ if (kotlin.math.abs(deltaSeconds) > 0.001) {
+ onTrimEnd(clip, deltaSeconds)
+ }
+ audioTrailingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ onDragCancel = {
+ audioTrailingAccumulatedDp = 0f
+ onDragInteraction(false)
+ },
+ ) { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ audioTrailingAccumulatedDp += deltaDp
+ }
+ },
+ ) {
+ TrimHandle(modifier = Modifier.fillMaxHeight(), color = colors.accent)
+ }
+}
+```
+
+Also update the outer audio clip Box's `xOffset` and `widthDp` calculations the same way as video clips:
+
+```kotlin
+val xOffset = (clip.startTime * pixelsPerSecond).toFloat()
+val widthDp = (clip.duration * pixelsPerSecond).toFloat().coerceAtLeast(32f)
+val visualXOffset = (xOffset + audioLeadingAccumulatedDp).coerceAtLeast(0f)
+val visualWidthDp = (widthDp + audioTrailingAccumulatedDp - audioLeadingAccumulatedDp).coerceAtLeast(32f)
+```
+
+Note: the audio accumulator State must be hoisted ABOVE the Box that uses it, so the modifier chain sees the values. Move the `remember` declarations above the outer `Box(modifier = ...)` line.
+
+- [ ] **Step 3: Add `onTrimStart` and `onTrimEnd` parameters to `AudioTrackLane`**
+
+In the `AudioTrackLane` composable's signature (line 1132), add two new optional callbacks:
+
+```kotlin
+onTrimStart: (Clip, Double) -> Unit = { _, _ -> },
+onTrimEnd: (Clip, Double) -> Unit = { _, _ -> },
+```
+
+Default no-ops keep existing call sites compiling.
+
+- [ ] **Step 4: Wire the new callbacks from the parent**
+
+In the `AudioTrackLane` call site (around line 379), add:
+
+```kotlin
+onTrimStart = { clip, delta ->
+ appState.trimAudioClipStart(audioTrack.id, clip.id, delta)
+},
+onTrimEnd = { clip, delta ->
+ appState.trimAudioClipEnd(audioTrack.id, clip.id, delta)
+},
+```
+
+- [ ] **Step 5: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt" \
+ "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/state/AppState.kt"
+git commit -m "feat(android): trim handles for audio clips
+
+Audio clips had decorative TrimHandle composables with no
+gestures. Wire both edges with the same snapshot drag pattern as
+video clips. New AppState.trimAudioClipStart adjusts
+startTime + inPoint; trimAudioClipEnd resizes duration with snap."
+```
+
+## Task A4: Convert text + graphics + adjustment trim to snapshot drag
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt`
+
+- [ ] **Step 1: Find each of the three lane composables**
+
+```bash
+grep -n "private fun TextLane\|private fun GraphicsLane\|private fun AdjustmentLane" "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt"
+```
+
+You should see three matches. Note their line numbers.
+
+- [ ] **Step 2: Convert each lane's leading + trailing trim to snapshot drag**
+
+For EACH of the three lanes (TextLane, GraphicsLane, AdjustmentLane):
+- Find the leading trim handle's `pointerInput { detectDragGestures { _, dragAmount -> onTrimStart(...) } }` and replace with the snapshot pattern (accumulate locally, commit on release).
+- Same for the trailing trim handle's `onTrimEnd` block.
+- Hoist the accumulator `remember` State above the Box that needs it.
+- Update the outer clip Box's `xOffset` / `widthDp` to use `visualXOffset` / `visualWidthDp` based on the accumulators.
+
+The mechanical pattern is identical to Task A1 (trailing) and Task A2 (leading) for video clips. Use those as the reference. Each lane composable typically takes `onTrimStart: (String, Double) -> Unit` / `onTrimEnd: (String, Double) -> Unit` callbacks where the `String` is the clip ID — preserve those.
+
+- [ ] **Step 3: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt"
+git commit -m "feat(android): snapshot drag for text/graphics/adjustment trim
+
+Convert the per-event commit pattern in TextLane, GraphicsLane, and
+AdjustmentLane to accumulate locally and commit once on release.
+Single undo entry per drag, smooth visual feedback during the gesture.
+Completes Workstream A — all trim drags across all clip types now
+use the snapshot pattern."
+```
+
+## Task A5: Snap indicator + haptic
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt`
+
+- [ ] **Step 1: Add light haptic on snap during commit**
+
+In each of the 5 commit paths added in Tasks A1–A4 (video trailing, video leading, audio leading, audio trailing, text/graphics/adjustment), find the `onDragEnd` block where the commit happens. Add a haptic when the snapped result differs noticeably from the proposed result.
+
+The video trailing handle's `onTrimEnd` is the cleanest illustration. In `VideoTrackLane`'s call site, the existing block already runs `snapEdit`:
+
+```kotlin
+onTrimEnd = { clip, delta ->
+ appState.mutateClip(videoTrack.id, clip.id, "Trim Clip") {
+ val newDuration = (it.duration + delta).coerceAtLeast(0.05)
+ val snappedEnd = appState.snapEdit(it.startTime + newDuration)
+ val finalDuration = (snappedEnd - it.startTime).coerceAtLeast(0.05)
+ it.copy(duration = finalDuration, outPoint = it.inPoint + finalDuration)
+ }
+},
+```
+
+Change to:
+
+```kotlin
+onTrimEnd = { clip, delta ->
+ val proposedEnd = clip.startTime + clip.duration + delta
+ val snappedEnd = appState.snapEdit(proposedEnd)
+ if (kotlin.math.abs(snappedEnd - proposedEnd) > 0.001) {
+ haptics.perform(HapticEvent.Light)
+ }
+ appState.mutateClip(videoTrack.id, clip.id, "Trim Clip") {
+ val newDuration = (it.duration + delta).coerceAtLeast(0.05)
+ val finalDuration = (snappedEnd - it.startTime).coerceAtLeast(0.05)
+ it.copy(duration = finalDuration, outPoint = it.inPoint + finalDuration)
+ }
+},
+```
+
+Use the existing `haptics` (`val haptics = rememberHaptics()` is already in scope in the editor screen). Apply the same pattern at every other trim commit site:
+- `trimVideoClipStart` call site
+- `trimAudioClipStart` and `trimAudioClipEnd` call sites
+- `trimGraphicsOverlayStart` and `trimGraphicsOverlayEnd` call sites
+- `trimAdjustmentLayer(..., fromEnd = true/false)` call sites
+- `resizeTextOverlay` paths
+
+Define a small helper at the top of `EditorScreen.kt` (or as a Composable extension) to keep the boilerplate down:
+
+```kotlin
+private fun emitSnapHapticIfSnapped(haptics: AppHaptics, raw: Double, snapped: Double) {
+ if (kotlin.math.abs(snapped - raw) > 0.001) {
+ haptics.perform(HapticEvent.Light)
+ }
+}
+```
+
+- [ ] **Step 2: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/Timeline.kt" \
+ "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/EditorScreen.kt"
+git commit -m "feat(android): snap haptic on trim release
+
+Fire a light haptic on the trim commit when snapEdit moved the
+target by more than 1ms. Matches the iOS snap-feedback pattern.
+A visible snap indicator overlay during the drag is left as a
+follow-up (would require continuous snapEdit polling)."
+```
+
+## Task A6: Workstream A verification
+
+**Files:** none (verification only).
+
+- [ ] **Step 1: Run the unit test suite**
+
+```bash
+cd "Openreel Video Android"
+./gradlew testDebugUnitTest
+```
+
+Expected: same pass/fail state as before Workstream A — no regressions.
+
+- [ ] **Step 2: Smoke checklist for the user**
+
+Print the manual smoke checklist for trim:
+- For each clip type (video, audio, text, graphics, adjustment) × each edge (leading, trailing):
+ - Drag slowly — visual updates smoothly during the drag, no per-frame state churn.
+ - Drag and release — single undo step lands in history.
+ - Drag near a neighbor's edge — feel a light haptic when snap engages.
+
+---
+
+# Workstream B — Crop editor parity
+
+## Task B1: Aspect-lock during handle drag
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt`
+
+- [ ] **Step 1: Add `lockedAspect` state to `CropResizeScreen`**
+
+Find the existing `var draftCrop by remember(clip.id) { mutableStateOf(...) }` line (around line 107). Below it, add:
+
+```kotlin
+var lockedAspect by remember(clip.id) { mutableStateOf<Float?>(null) }
+```
+
+- [ ] **Step 2: Update aspect chip taps to set the lock**
+
+In the `AspectRatioOption` row (around line 229–246), modify:
+
+```kotlin
+AspectRatioOption(
+ ratio = null,
+ label = "Custom",
+ selected = false,
+ onClick = {
+ draftCrop = Crop(0.0, 0.0, 1.0, 1.0)
+ },
+)
+ASPECT_OPTIONS.forEach { opt ->
+ AspectRatioOption(
+ ratio = opt.ratio,
+ label = opt.label,
+ selected = aspectRatioMatches(draftCrop, opt.ratio),
+ onClick = {
+ draftCrop = cropForAspect(opt.ratio)
+ },
+ )
+}
+```
+
+To:
+
+```kotlin
+AspectRatioOption(
+ ratio = null,
+ label = "Custom",
+ selected = lockedAspect == null,
+ onClick = {
+ lockedAspect = null
+ },
+)
+ASPECT_OPTIONS.forEach { opt ->
+ AspectRatioOption(
+ ratio = opt.ratio,
+ label = opt.label,
+ selected = lockedAspect == opt.ratio,
+ onClick = {
+ lockedAspect = opt.ratio
+ draftCrop = snapCropToAspect(draftCrop, opt.ratio)
+ },
+ )
+}
+```
+
+The "Custom" chip clears the lock. Aspect chips set the lock AND immediately re-snap the current draftCrop to that ratio.
+
+- [ ] **Step 3: Add `snapCropToAspect` helper**
+
+Near the existing `cropForAspect` helper, add:
+
+```kotlin
+private fun snapCropToAspect(crop: Crop, aspect: Float): Crop {
+ val centerX = crop.x + crop.width / 2.0
+ val centerY = crop.y + crop.height / 2.0
+ var width = crop.width
+ var height = (width / aspect).coerceIn(0.10, 1.0)
+ if (height > crop.height) {
+ height = crop.height
+ width = (height * aspect).coerceIn(0.10, 1.0)
+ }
+ val newX = (centerX - width / 2.0).coerceIn(0.0, 1.0 - width)
+ val newY = (centerY - height / 2.0).coerceIn(0.0, 1.0 - height)
+ return Crop(newX, newY, width, height)
+}
+```
+
+- [ ] **Step 4: Pass `lockedAspect` into `CropOverlay` and `resizeCrop`**
+
+Change the `CropOverlay` signature (line 364) to accept `lockedAspect: Float?`:
+
+```kotlin
+@Composable
+private fun CropOverlay(
+ crop: Crop,
+ lockedAspect: Float?,
+ onCropChange: (Crop) -> Unit,
+) {
+```
+
+Pass it from `CropPreview`:
+
+```kotlin
+CropOverlay(crop = crop, lockedAspect = lockedAspect, onCropChange = onCropChange)
+```
+
+And `CropPreview` itself accepts a `lockedAspect` param, passed from `CropResizeScreen`'s body.
+
+Inside `CropOverlay`'s `onDrag`, modify the resize call:
+
+```kotlin
+val next = activeDrag?.let { handle ->
+ resizeCrop(gestureCrop, handle, deltaX, deltaY, lockedAspect)
+} ?: moveCrop(gestureCrop, deltaX, deltaY)
+```
+
+- [ ] **Step 5: Update `resizeCrop` to respect lockedAspect**
+
+Change the signature:
+
+```kotlin
+private fun resizeCrop(crop: Crop, handle: ResizeHandle, dx: Double, dy: Double, lockedAspect: Float? = null): Crop {
+```
+
+When `lockedAspect != null`, derive the perpendicular axis from the dragged axis to preserve the ratio. Add at the END of `resizeCrop`, before the `return`:
+
+```kotlin
+val ratioApplied = if (lockedAspect != null) {
+ val aspect = lockedAspect.toDouble()
+ when (handle) {
+ ResizeHandle.TopLeft, ResizeHandle.TopRight, ResizeHandle.BottomLeft, ResizeHandle.BottomRight -> {
+ // Width-driven; recompute height, anchor opposite corner
+ val newWidth = updated.width
+ val newHeight = (newWidth / aspect).coerceAtLeast(0.10)
+ when (handle) {
+ ResizeHandle.TopLeft -> updated.copy(
+ y = (crop.y + crop.height - newHeight).coerceAtLeast(0.0),
+ height = newHeight.coerceAtMost(crop.y + crop.height),
+ )
+ ResizeHandle.TopRight -> updated.copy(
+ y = (crop.y + crop.height - newHeight).coerceAtLeast(0.0),
+ height = newHeight.coerceAtMost(crop.y + crop.height),
+ )
+ ResizeHandle.BottomLeft -> updated.copy(
+ height = newHeight.coerceAtMost(1.0 - updated.y),
+ )
+ ResizeHandle.BottomRight -> updated.copy(
+ height = newHeight.coerceAtMost(1.0 - updated.y),
+ )
+ else -> updated
+ }
+ }
+ ResizeHandle.Top, ResizeHandle.Bottom -> {
+ val newHeight = updated.height
+ val newWidth = (newHeight * aspect).coerceAtLeast(0.10)
+ val centerX = crop.x + crop.width / 2.0
+ updated.copy(
+ x = (centerX - newWidth / 2.0).coerceIn(0.0, 1.0 - newWidth),
+ width = newWidth.coerceAtMost(1.0),
+ )
+ }
+ ResizeHandle.Left, ResizeHandle.Right -> {
+ val newWidth = updated.width
+ val newHeight = (newWidth / aspect).coerceAtLeast(0.10)
+ val centerY = crop.y + crop.height / 2.0
+ updated.copy(
+ y = (centerY - newHeight / 2.0).coerceIn(0.0, 1.0 - newHeight),
+ height = newHeight.coerceAtMost(1.0),
+ )
+ }
+ }
+} else {
+ updated
+}
+return ratioApplied
+```
+
+Replace the final `return updated` with `return ratioApplied`.
+
+- [ ] **Step 6: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt"
+git commit -m "feat(android): aspect-lock during crop handle drag
+
+Tapping an aspect chip now snaps AND locks subsequent handle drags
+to that ratio. Tap Custom to unlock. resizeCrop gains an optional
+lockedAspect parameter that constrains the perpendicular axis based
+on the handle type. Matches the iOS CropFrameGeometry.resize math."
+```
+
+## Task B2: Flip H / Flip V chips
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt`
+
+- [ ] **Step 1: Add flip draft state**
+
+After `draftCrop`, add:
+
+```kotlin
+var draftFlipH by remember(clip.id) { mutableStateOf(clip.transform.flipHorizontal) }
+var draftFlipV by remember(clip.id) { mutableStateOf(clip.transform.flipVertical) }
+```
+
+(`clip.transform.flipHorizontal` and `flipVertical` are existing `Boolean` fields on the Android model — verify with `grep -n "flipHorizontal\|flipVertical" "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/core/model"`.)
+
+- [ ] **Step 2: Apply flip to the preview backdrop**
+
+In the `CropPreview`'s inner rotation Box (around line 322-327), the existing code is:
+
+```kotlin
+Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .graphicsLayer { rotationZ = rotationDeg },
+) {
+```
+
+Extend with flip:
+
+```kotlin
+Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .graphicsLayer {
+ rotationZ = rotationDeg
+ scaleX = if (flipH) -1f else 1f
+ scaleY = if (flipV) -1f else 1f
+ },
+) {
+```
+
+Pass `flipH: Boolean` and `flipV: Boolean` from `CropPreview`'s callers (default `false` if existing call sites don't yet pass them — but in `CropResizeScreen` they come from `draftFlipH/V`).
+
+- [ ] **Step 3: Add the Flip chips row to the body**
+
+Find the existing "Aspect ratio" Text label and the chips row (around line 220-247). Above the "Aspect ratio" label, add:
+
+```kotlin
+Text(
+ text = "Flip",
+ style = OpenReelTypographyAccess.subcaption.copy(fontWeight = FontWeight.Bold),
+ color = colors.textPrimary,
+)
+Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ FlipChip(label = "Flip H", active = draftFlipH) { draftFlipH = !draftFlipH }
+ FlipChip(label = "Flip V", active = draftFlipV) { draftFlipV = !draftFlipV }
+}
+```
+
+And add the `FlipChip` composable near `AspectRatioOption`:
+
+```kotlin
+@Composable
+private fun FlipChip(label: String, active: Boolean, onClick: () -> Unit) {
+ val colors = OpenReelTheme.colors
+ Box(
+ modifier = Modifier
+ .clip(RoundedCornerShape(20.dp))
+ .background(if (active) colors.accent else colors.surface)
+ .clickable { onClick() }
+ .padding(horizontal = 14.dp, vertical = 8.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ text = label,
+ style = OpenReelTypographyAccess.tiny.copy(fontWeight = FontWeight.Bold, fontSize = 12.sp),
+ color = if (active) Color.Black else colors.textPrimary,
+ )
+ }
+}
+```
+
+If `FlipChip` already exists elsewhere in this file or another shared component file (likely from `ClipInspectorSheet.kt`), reuse the existing one and just adapt the call site.
+
+- [ ] **Step 4: Persist on Apply**
+
+Find the `CropTopBar(onApply = { ... })` block (around line 138-145):
+
+```kotlin
+onApply = {
+ appState.mutateClip(trackId, clip.id, "Crop") {
+ it.copy(transform = it.transform.copy(crop = cropOrNull(draftCrop), rotation = draftRotation.toDouble()))
+ }
+ onDismiss()
+},
+```
+
+Extend the transform update to include flip:
+
+```kotlin
+onApply = {
+ appState.mutateClip(trackId, clip.id, "Crop") {
+ it.copy(
+ transform = it.transform.copy(
+ crop = cropOrNull(draftCrop),
+ rotation = draftRotation.toDouble(),
+ flipHorizontal = draftFlipH,
+ flipVertical = draftFlipV,
+ ),
+ )
+ }
+ onDismiss()
+},
+```
+
+- [ ] **Step 5: Reset clears flips**
+
+Find the Reset button onClick (around line 255-258):
+
+```kotlin
+.clickable {
+ draftCrop = Crop(0.0, 0.0, 1.0, 1.0)
+ draftRotation = 0f
+}
+```
+
+Extend:
+
+```kotlin
+.clickable {
+ draftCrop = Crop(0.0, 0.0, 1.0, 1.0)
+ draftRotation = 0f
+ draftFlipH = false
+ draftFlipV = false
+}
+```
+
+- [ ] **Step 6: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt"
+git commit -m "feat(android): Flip H/V chips in CropResizeScreen
+
+New Flip section above Aspect ratio with two toggle chips.
+Initialized from clip.transform.flip* and persisted on Apply via
+the existing mutateClip path. Reset clears flips. Preview mirror is
+applied via graphicsLayer.scaleX/Y on the existing rotation Box."
+```
+
+## Task B3: Fit mode chips
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt`
+
+- [ ] **Step 1: Add fitMode draft state**
+
+After the flip state:
+
+```kotlin
+var draftFitMode by remember(clip.id) {
+ mutableStateOf(clip.transform.fitMode ?: com.pythonxi.openreelvideo.core.model.FitMode.Contain)
+}
+```
+
+- [ ] **Step 2: Add the Fit chip row**
+
+Above the Flip section (added in Task B2), add:
+
+```kotlin
+Text(
+ text = "Fit",
+ style = OpenReelTypographyAccess.subcaption.copy(fontWeight = FontWeight.Bold),
+ color = colors.textPrimary,
+)
+Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ FitChip("Contain", draftFitMode == com.pythonxi.openreelvideo.core.model.FitMode.Contain) {
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.Contain
+ }
+ FitChip("Cover", draftFitMode == com.pythonxi.openreelvideo.core.model.FitMode.Cover) {
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.Cover
+ }
+ FitChip("Stretch", draftFitMode == com.pythonxi.openreelvideo.core.model.FitMode.Stretch) {
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.Stretch
+ }
+ FitChip("None", draftFitMode == com.pythonxi.openreelvideo.core.model.FitMode.None) {
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.None
+ }
+}
+```
+
+And add a `FitChip` composable identical in shape to `FlipChip`:
+
+```kotlin
+@Composable
+private fun FitChip(label: String, active: Boolean, onClick: () -> Unit) {
+ val colors = OpenReelTheme.colors
+ Box(
+ modifier = Modifier
+ .clip(RoundedCornerShape(20.dp))
+ .background(if (active) colors.accent else colors.surface)
+ .clickable { onClick() }
+ .padding(horizontal = 12.dp, vertical = 6.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ text = label,
+ style = OpenReelTypographyAccess.tiny.copy(fontWeight = FontWeight.Bold, fontSize = 11.sp),
+ color = if (active) Color.Black else colors.textPrimary,
+ )
+ }
+}
+```
+
+If the `FitMode` enum cases differ from `Contain`/`Cover`/`Stretch`/`None` (e.g., they might be `CONTAIN` / `COVER` / etc.), check the model file:
+
+```bash
+grep -n "enum class FitMode\|case fitMode\|Contain\|Cover\|Stretch" "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/core/model"
+```
+
+Adjust the references to the actual enum cases.
+
+- [ ] **Step 3: Persist on Apply**
+
+Extend the `onApply` transform copy to include `fitMode = draftFitMode`:
+
+```kotlin
+onApply = {
+ appState.mutateClip(trackId, clip.id, "Crop") {
+ it.copy(
+ transform = it.transform.copy(
+ crop = cropOrNull(draftCrop),
+ rotation = draftRotation.toDouble(),
+ flipHorizontal = draftFlipH,
+ flipVertical = draftFlipV,
+ fitMode = draftFitMode,
+ ),
+ )
+ }
+ onDismiss()
+},
+```
+
+- [ ] **Step 4: Reset clears fitMode**
+
+Extend the Reset onClick:
+
+```kotlin
+.clickable {
+ draftCrop = Crop(0.0, 0.0, 1.0, 1.0)
+ draftRotation = 0f
+ draftFlipH = false
+ draftFlipV = false
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.Contain
+}
+```
+
+- [ ] **Step 5: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt"
+git commit -m "feat(android): Fit mode chips in CropResizeScreen
+
+New Fit section above Flip with four chips (Contain / Cover /
+Stretch / None). Initialized from clip.transform.fitMode and
+persisted via the existing mutateClip Apply path. Reset returns
+to Contain (default)."
+```
+
+## Task B4: Pinch-to-zoom with centroid
+
+**Files:**
+- Modify: `Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt`
+
+- [ ] **Step 1: Add zoom state**
+
+After the fit state:
+
+```kotlin
+var mediaScale by remember(clip.id) { mutableFloatStateOf(1f) }
+var mediaOffset by remember(clip.id) { mutableStateOf(Offset.Zero) }
+```
+
+- [ ] **Step 2: Wire pinch on `CropPreview`'s backdrop**
+
+In `CropPreview`'s outer Box (line 302–360), the rotation `Box(modifier = Modifier.fillMaxSize().graphicsLayer { ... })` wraps the backdrop. Add the pinch gesture to that Box's modifier chain, AND extend `graphicsLayer` to apply both scale + offset:
+
+```kotlin
+Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .pointerInput(crop) {
+ var pinchStartScale = 1f
+ var pinchStartOffset = Offset.Zero
+ var pinchStartCentroid: Offset? = null
+ var viewSize: androidx.compose.ui.geometry.Size = androidx.compose.ui.geometry.Size.Zero
+
+ awaitEachGesture {
+ pinchStartCentroid = null
+ awaitFirstDown(requireUnconsumed = false)
+ do {
+ val event = awaitPointerEvent()
+ if (event.changes.size >= 2) {
+ val zoom = event.calculateZoom()
+ val centroid = event.calculateCentroid()
+ if (pinchStartCentroid == null) {
+ pinchStartScale = mediaScale
+ pinchStartOffset = mediaOffset
+ pinchStartCentroid = centroid
+ }
+ val newScale = (pinchStartScale * zoom).coerceIn(1f, 6f)
+ val center = Offset(viewSize.width / 2f, viewSize.height / 2f)
+ val startCentroid = pinchStartCentroid ?: centroid
+ val dV = Offset(startCentroid.x - center.x, startCentroid.y - center.y)
+ val m = newScale / pinchStartScale
+ mediaScale = newScale
+ mediaOffset = Offset(
+ dV.x * (1 - m) + pinchStartOffset.x * m,
+ dV.y * (1 - m) + pinchStartOffset.y * m,
+ )
+ event.changes.forEach { it.consume() }
+ } else {
+ pinchStartCentroid = null
+ }
+ } while (event.changes.any { it.pressed })
+ }
+ }
+ .onSizeChanged { viewSize = androidx.compose.ui.geometry.Size(it.width.toFloat(), it.height.toFloat()) }
+ .graphicsLayer {
+ rotationZ = rotationDeg
+ scaleX = (if (flipH) -1f else 1f) * mediaScale
+ scaleY = (if (flipV) -1f else 1f) * mediaScale
+ translationX = mediaOffset.x
+ translationY = mediaOffset.y
+ },
+) {
+ // ... existing video / image / black backdrop content
+}
+```
+
+`viewSize` is a `MutableState<Size>` declared with `var viewSize by remember { mutableStateOf(androidx.compose.ui.geometry.Size.Zero) }` outside the lambda — hoist it appropriately.
+
+Compose imports needed:
+```kotlin
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.gestures.calculateCentroid
+import androidx.compose.foundation.gestures.calculateZoom
+```
+
+`onSizeChanged` is already imported.
+
+- [ ] **Step 3: Reset clears zoom**
+
+Extend the Reset onClick:
+
+```kotlin
+.clickable {
+ draftCrop = Crop(0.0, 0.0, 1.0, 1.0)
+ draftRotation = 0f
+ draftFlipH = false
+ draftFlipV = false
+ draftFitMode = com.pythonxi.openreelvideo.core.model.FitMode.Contain
+ mediaScale = 1f
+ mediaOffset = Offset.Zero
+}
+```
+
+- [ ] **Step 4: Pass `mediaScale` / `mediaOffset` / `flipH` / `flipV` into `CropPreview`**
+
+`CropPreview`'s signature is at line 292. It currently takes `controller, mediaPath, isVideo, aspectRatio, crop, rotationDeg, onCropChange`. Add `flipH: Boolean`, `flipV: Boolean`, `mediaScale: Float`, `mediaOffset: Offset` parameters. Pass them from `CropResizeScreen`'s body at line 156–164.
+
+- [ ] **Step 5: Build**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+```
+
+Expected: `BUILD SUCCESSFUL`.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video Android/app/src/main/java/com/pythonxi/openreelvideo/ui/editor/CropResizeScreen.kt"
+git commit -m "feat(android): pinch-to-zoom with centroid in CropResizeScreen
+
+Two-finger pinch on the crop preview backdrop now zooms 1x to 6x
+with the pinch point staying anchored under the user's fingers.
+Math matches iOS:
+ O = dV * (1 - m) + O0 * m
+where dV = pinchStartCentroid - viewCenter, m = currentScale /
+startScale. Reset clears scale + offset."
+```
+
+## Task B5: Workstream B verification
+
+- [ ] **Step 1: Build + unit tests**
+
+```bash
+cd "Openreel Video Android"
+./gradlew assembleDebug
+./gradlew testDebugUnitTest
+```
+
+Expected: BUILD SUCCESSFUL + tests in same state as before Workstream B.
+
+- [ ] **Step 2: Smoke checklist for the user**
+
+For each photo + video clip:
+- Open Crop tool → CropResizeScreen opens.
+- Tap each aspect chip → frame snaps AND locks subsequent handle drags.
+- Tap Custom → lock clears.
+- Tap Flip H / Flip V → backdrop mirrors.
+- Tap each Fit chip → state updates.
+- Pinch on backdrop → zooms 1x to 6x with centroid stability.
+- Reset → all draft state restores to defaults.
+- Apply → mutations persist; reopen Crop shows the saved state.
+
+---
+
+## Self-review checklist
+
+- All 5 trim tasks (A1–A5) touch only `Timeline.kt`, `AppState.kt`, `EditorScreen.kt` (the latter only for haptic helpers).
+- All 4 crop tasks (B1–B4) touch only `CropResizeScreen.kt`.
+- New AppState methods (`trimVideoClipStart`, `trimAudioClipStart`, `trimAudioClipEnd`) follow the existing `mutateClip` pattern.
+- The locked-aspect math in `resizeCrop` mirrors the iOS `CropFrameGeometry.resize(..., lockedAspect:)` from `Features/Crop/CropFrameGeometry.swift`.
+- Pinch centroid math is `O = dV * (1 - m) + O0 * m` — same as iOS `CropEditorView`'s MagnifyGesture handler.
+- No new files; no test files; no `project.pbxproj`-equivalent edits (Android uses gradle, no project-file surgery needed).
+- Each commit is independent and the build stays green after every commit.
diff --git a/docs/superpowers/plans/2026-05-28-ios-trim-and-crop.md b/docs/superpowers/plans/2026-05-28-ios-trim-and-crop.md
new file mode 100644
index 00000000..8502b231
--- /dev/null
+++ b/docs/superpowers/plans/2026-05-28-ios-trim-and-crop.md
@@ -0,0 +1,2108 @@
+# iOS Trim Flicker + Full-Screen Crop Editor Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship the two iOS editor improvements from `docs/superpowers/specs/2026-05-28-ios-trim-and-crop-design.md` — fix the horizontal-jitter trim bug across all four timeline clip block types, and replace the slider-based crop sheet with a full-screen direct-manipulation crop editor.
+
+**Architecture:** Workstream 1 is three small, mechanical changes applied to each of the four `Timeline*ClipBlock` structs in `EditorView.swift` plus their call sites — no new files. Workstream 2 introduces a new `Features/Crop/` folder with `CropFrameGeometry.swift` (pure coordinate-math helper, unit-tested) and `CropEditorView.swift` (`fullScreenCover` view); routes the "Crop" tool taps to it; deletes the old `clipCropSheet` body and `EditingSheet.crop` case. A small `AppState` API addition (`setSelectedClipCrop`, `setSelectedClipFlip`) replaces the per-axis `updateSelectedClipCrop` slider API because the new screen produces a geometrically valid `Crop` rect in one shot.
+
+**Tech Stack:** Swift 5.10+, SwiftUI (DragGesture, MagnifyGesture, fullScreenCover, GestureMask), AVFoundation (for the video backdrop snapshot via the existing `MetalVideoSnapshotProvider`), Swift Testing (`import Testing`, `@Test`, `#expect`).
+
+**Test runner:** From the repo root:
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 17,OS=26.5" \
+ -only-testing:"Openreel VideoTests/<ClassName>" \
+ -quiet
+```
+
+Replace `<ClassName>` with the test class for the task. Drop `-only-testing:` to run the whole suite. To verify a build without running tests:
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+**Branch:** Already on `feat/ios-app`. Commit per task with the conventional-commit prefix shown in each step.
+
+---
+
+## File Structure
+
+Files this plan creates or modifies, with the responsibility of each:
+
+| File | Purpose | Status |
+|---|---|---|
+| `Openreel Video/Openreel Video/EditorView.swift` | Trim fix in 4 clip block structs + their call sites; remove `clipCropSheet`, `EditingSheet.crop` and its branches; add `.fullScreenCover` route for the new editor | Modify |
+| `Openreel Video/Openreel Video/AppState.swift` | New `setSelectedClipCrop` (full-rect setter, validated) and `setSelectedClipFlip(horizontal:vertical:)` (direct setter, not toggle); delete unused `updateSelectedClipCrop` per-axis method | Modify |
+| `Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift` | Pure functions: media-aspect-fit-rect math, preview-rect ↔ normalized `Crop` conversion, aspect-locked corner-drag resolution. No SwiftUI, no AppKit, no MainActor. | **Create** |
+| `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift` | The full-screen editor: layout, handles, aspect chips, pan/pinch/flip/reset, Done/Cancel. SwiftUI only. | **Create** |
+| `Openreel Video/Openreel VideoTests/CropFrameGeometryTests.swift` | Round-trip unit tests + aspect-lock math tests for the geometry helper | **Create** |
+
+Two new files plus one test file. All other work modifies existing files in place.
+
+---
+
+# Workstream 1 — Trim flicker (Phases 1.1 – 1.5)
+
+Apply identical three-part fix to each of the four clip block structs. Each phase is one struct + its call site so the build stays green after every task. Verification is manual after Phase 1.5.
+
+## Phase 1.1 — `TimelineClipBlock`
+
+### Task 1.1: Fix trim in `TimelineClipBlock` + its call site
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift` (struct at line 5485; call site at line 2656)
+
+- [ ] **Step 1: Change the `onTrim` property type to async**
+
+In `TimelineClipBlock` (line 5485), find the property:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) -> Void
+```
+
+Replace with:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) async -> Void
+```
+
+- [ ] **Step 2: Add `isTrimming` state**
+
+In the same struct's `@State` block (currently at lines 5521–5526), add a new line **after** `@State private var trailingTrimOffset: CGFloat = 0`:
+
+```swift
+@State private var isTrimming: Bool = false
+```
+
+So the block reads:
+
+```swift
+@State private var moveTranslation: CGFloat = 0
+@State private var moveVerticalTranslation: CGFloat = 0
+@State private var snapEdgeX: CGFloat? = nil
+@State private var snapClearTask: Task<Void, Never>? = nil
+@State private var leadingTrimOffset: CGFloat = 0
+@State private var trailingTrimOffset: CGFloat = 0
+@State private var isTrimming: Bool = false
+```
+
+- [ ] **Step 3: Anchor leading edge in the `.offset` modifier**
+
+In `TimelineClipBlock.body` (currently line 5631), find:
+
+```swift
+.offset(x: moveTranslation, y: moveVerticalTranslation)
+```
+
+Replace with:
+
+```swift
+.offset(x: moveTranslation + leadingTrimOffset, y: moveVerticalTranslation)
+```
+
+- [ ] **Step 4: Suppress move gesture during trim**
+
+In the same body (currently line 5637), find:
+
+```swift
+.simultaneousGesture(moveGesture)
+```
+
+Replace with:
+
+```swift
+.simultaneousGesture(moveGesture, including: isTrimming ? .subviews : .all)
+```
+
+- [ ] **Step 5: Rewrite the `.onEnded` of the trim handle's drag gesture**
+
+In `trimHandle(edge:)` (currently line 5644), find the `.onChanged` and `.onEnded` block:
+
+```swift
+.gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ switch edge {
+ case .leading:
+ leadingTrimOffset = min(value.translation.width, clipWidth - 44)
+ case .trailing:
+ trailingTrimOffset = max(value.translation.width, -(clipWidth - 44))
+ }
+ }
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ onTrim(edge, delta)
+ }
+)
+```
+
+Replace with:
+
+```swift
+.gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ isTrimming = true
+ switch edge {
+ case .leading:
+ leadingTrimOffset = min(value.translation.width, clipWidth - 44)
+ case .trailing:
+ trailingTrimOffset = max(value.translation.width, -(clipWidth - 44))
+ }
+ }
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ Task { @MainActor in
+ await onTrim(edge, delta)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ isTrimming = false
+ }
+ }
+)
+```
+
+Two differences vs original: `isTrimming = true` at the start of `.onChanged`, and `.onEnded` now wraps in `Task { @MainActor in ... }` so the offset reset and `isTrimming` reset happen **after** `await onTrim` returns (i.e., after the project state has updated and `clipWidth` reflects the new duration).
+
+- [ ] **Step 6: Update the call site to pass an async closure**
+
+In `visualTrackLane` (line 2642), find the `TimelineClipBlock(...)` initializer's `onTrim` argument (currently line 2665):
+
+```swift
+onTrim: { edge, delta in
+ Task {
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+ }
+},
+```
+
+Replace with:
+
+```swift
+onTrim: { edge, delta in
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+},
+```
+
+The `Task` wrapper goes away because the closure is now async — the trim handle's `.onEnded` owns its own `Task { ... }` so it can sequence the offset reset after the await.
+
+- [ ] **Step 7: Build to verify no compilation regressions**
+
+Run:
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`. The other three clip block types still use the old sync `onTrim`, but they are independent structs with independent properties — this one struct's change does not break them.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "fix(ios): trim flicker in TimelineClipBlock
+
+- Suppress simultaneous move gesture while trim drag is in progress
+ (via GestureMask.subviews) to stop mid-drag horizontal jumps.
+- Anchor leading edge to the finger by adding leadingTrimOffset to
+ the clip's .offset so the left edge moves with the drag instead of
+ the right edge collapsing.
+- Make onTrim async and reset the trim offsets inside the Task that
+ awaits the project-state update, eliminating the one-frame width
+ pop on release."
+```
+
+## Phase 1.2 — `TimelineAudioClipBlock`
+
+### Task 1.2: Apply the same fix to `TimelineAudioClipBlock` + its call site
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift` (struct at line 5816; call site in the audio track lane builder)
+
+- [ ] **Step 1: Find the audio call site**
+
+Run:
+
+```bash
+grep -n "TimelineAudioClipBlock(" "Openreel Video/Openreel Video/EditorView.swift"
+```
+
+Expected: one or more line numbers around the audio track lane builder. Note the line numbers — you'll need them for Step 7.
+
+- [ ] **Step 2: Change `onTrim` to async**
+
+In `TimelineAudioClipBlock` (line 5816), find:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) -> Void
+```
+
+Replace with:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) async -> Void
+```
+
+- [ ] **Step 3: Add `isTrimming` state**
+
+In the same struct's `@State` block (line 5828), add after `trailingTrimOffset`:
+
+```swift
+@State private var isTrimming: Bool = false
+```
+
+- [ ] **Step 4: Anchor leading edge in `.offset`**
+
+Find (line 5871):
+
+```swift
+.offset(x: moveTranslation, y: moveVerticalTranslation)
+```
+
+Replace with:
+
+```swift
+.offset(x: moveTranslation + leadingTrimOffset, y: moveVerticalTranslation)
+```
+
+- [ ] **Step 5: Suppress move gesture during trim**
+
+Find (line 5877):
+
+```swift
+.simultaneousGesture(moveGesture)
+```
+
+Replace with:
+
+```swift
+.simultaneousGesture(moveGesture, including: isTrimming ? .subviews : .all)
+```
+
+- [ ] **Step 6: Rewrite the trim handle's `.onChanged` and `.onEnded`**
+
+Find the `trimHandle(edge:)` method (line 5880). Replace the existing `.gesture(...)` block with:
+
+```swift
+.gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ isTrimming = true
+ switch edge {
+ case .leading:
+ leadingTrimOffset = min(value.translation.width, clipWidth - 44)
+ case .trailing:
+ trailingTrimOffset = max(value.translation.width, -(clipWidth - 44))
+ }
+ }
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ Task { @MainActor in
+ await onTrim(edge, delta)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ isTrimming = false
+ }
+ }
+)
+```
+
+- [ ] **Step 7: Update the audio call site**
+
+At the line number(s) you found in Step 1, find the `onTrim:` argument:
+
+```swift
+onTrim: { edge, delta in
+ Task {
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+ }
+},
+```
+
+Replace with:
+
+```swift
+onTrim: { edge, delta in
+ await appState.trimClip(clip.id, edge: edge, by: delta, playbackController: playbackController)
+},
+```
+
+- [ ] **Step 8: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "fix(ios): trim flicker in TimelineAudioClipBlock
+
+Same three-part fix as TimelineClipBlock: gesture-mask move
+suppression during trim, leading-edge follow-the-finger, async
+onTrim with deferred offset reset."
+```
+
+## Phase 1.3 — `TimelineTextClipBlock`
+
+### Task 1.3: Apply the same fix to `TimelineTextClipBlock` + its call site
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift` (struct at line 5986; call site at line 2559)
+
+- [ ] **Step 1: Change `onTrim` to async**
+
+In `TimelineTextClipBlock` (line 5986), find `let onTrim: (AppState.TrimEdge, TimeInterval) -> Void` and replace with:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) async -> Void
+```
+
+- [ ] **Step 2: Add `isTrimming` state**
+
+In the same struct's `@State` block, add after `trailingTrimOffset`:
+
+```swift
+@State private var isTrimming: Bool = false
+```
+
+- [ ] **Step 3: Anchor leading edge in `.offset`**
+
+Find `.offset(x: moveTranslation, y: moveVerticalTranslation)` in the body. Replace with:
+
+```swift
+.offset(x: moveTranslation + leadingTrimOffset, y: moveVerticalTranslation)
+```
+
+- [ ] **Step 4: Suppress move gesture during trim**
+
+Find `.simultaneousGesture(moveGesture)` in the body. Replace with:
+
+```swift
+.simultaneousGesture(moveGesture, including: isTrimming ? .subviews : .all)
+```
+
+- [ ] **Step 5: Rewrite the trim handle's `.onChanged` and `.onEnded`**
+
+Find `trimHandle(edge:)` (line 6102). Replace its `.gesture(...)` block with:
+
+```swift
+.gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ isTrimming = true
+ switch edge {
+ case .leading:
+ leadingTrimOffset = min(value.translation.width, clipWidth - 44)
+ case .trailing:
+ trailingTrimOffset = max(value.translation.width, -(clipWidth - 44))
+ }
+ }
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ Task { @MainActor in
+ await onTrim(edge, delta)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ isTrimming = false
+ }
+ }
+)
+```
+
+- [ ] **Step 6: Update the text call site**
+
+In `visualTrackLane` or its equivalent for text clips (call site at line 2559), find:
+
+```swift
+onTrim: { edge, delta in
+ Task {
+ await appState.trimTextClip(textClip.id, edge: edge, by: delta, playbackController: playbackController)
+ }
+},
+```
+
+(The exact AppState method name may be `trimTextClip` or similar — match the original call and keep the method name; only remove the `Task { ... }` wrapper.)
+
+Replace with the same call but without the Task wrapper:
+
+```swift
+onTrim: { edge, delta in
+ await appState.trimTextClip(textClip.id, edge: edge, by: delta, playbackController: playbackController)
+},
+```
+
+If the actual method name differs (e.g. `trimText`), preserve it — only the wrapper changes.
+
+- [ ] **Step 7: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "fix(ios): trim flicker in TimelineTextClipBlock
+
+Same three-part fix as the video/audio clip blocks."
+```
+
+## Phase 1.4 — `TimelineGraphicsClipBlock`
+
+### Task 1.4: Apply the same fix to `TimelineGraphicsClipBlock` + its call site
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift` (struct at line 6193; call site at line 2611)
+
+- [ ] **Step 1: Change `onTrim` to async**
+
+In `TimelineGraphicsClipBlock` (line 6193), find `let onTrim: (AppState.TrimEdge, TimeInterval) -> Void` and replace with:
+
+```swift
+let onTrim: (AppState.TrimEdge, TimeInterval) async -> Void
+```
+
+- [ ] **Step 2: Add `isTrimming` state**
+
+After `trailingTrimOffset` in the `@State` block, add:
+
+```swift
+@State private var isTrimming: Bool = false
+```
+
+- [ ] **Step 3: Anchor leading edge in `.offset`**
+
+Find (line 6243):
+
+```swift
+.offset(x: moveTranslation, y: moveVerticalTranslation)
+```
+
+Replace with:
+
+```swift
+.offset(x: moveTranslation + leadingTrimOffset, y: moveVerticalTranslation)
+```
+
+- [ ] **Step 4: Suppress move gesture during trim**
+
+Find (line 6249):
+
+```swift
+.simultaneousGesture(moveGesture)
+```
+
+Replace with:
+
+```swift
+.simultaneousGesture(moveGesture, including: isTrimming ? .subviews : .all)
+```
+
+- [ ] **Step 5: Rewrite the trim handle's `.onChanged` and `.onEnded`**
+
+Find `trimHandle(edge:)` (line 6269). Replace its `.gesture(...)` block with:
+
+```swift
+.gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ isTrimming = true
+ switch edge {
+ case .leading:
+ leadingTrimOffset = min(value.translation.width, clipWidth - 44)
+ case .trailing:
+ trailingTrimOffset = max(value.translation.width, -(clipWidth - 44))
+ }
+ }
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ Task { @MainActor in
+ await onTrim(edge, delta)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ isTrimming = false
+ }
+ }
+)
+```
+
+- [ ] **Step 6: Update the graphics call site**
+
+At line 2611, find the `TimelineGraphicsClipBlock(...)` `onTrim:` argument and remove the `Task { ... }` wrapper from the body, leaving just `await appState.trim...(...)`. Match the existing AppState method name (likely `trimGraphicsClip`).
+
+- [ ] **Step 7: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift"
+git commit -m "fix(ios): trim flicker in TimelineGraphicsClipBlock
+
+Same three-part fix as the video/audio/text clip blocks. Completes
+the trim flicker fix across all four Timeline*ClipBlock types."
+```
+
+## Phase 1.5 — Verify Workstream 1 end-to-end
+
+### Task 1.5: Run tests + manual smoke
+
+- [ ] **Step 1: Run the unit test suite**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 17,OS=26.5" \
+ -only-testing:"Openreel VideoTests" \
+ -quiet
+```
+
+Expected: tests pass. The trim math is already covered by existing `appState.trimClip` paths; the fix is gesture-layer-only, so no regressions in unit tests. If any pre-existing test was already failing (see `MOBILE-CODE-REVIEW-2026-05-27.md` reference to 17 failing tests at one point), do not consider those a regression unless their failure mode changed. Note any new failures and stop here.
+
+- [ ] **Step 2: Manual smoke on Simulator**
+
+Launch the app and create a project with at least one clip on each of: a video track, an audio track, a text track, and a graphics track. For each clip type:
+
+1. Drag the **leading** trim handle to the right slowly. Confirm the left edge of the clip follows your finger (does not stay anchored). Confirm no horizontal jumps.
+2. Drag the leading handle, pause for 1 second mid-drag without releasing, then continue. Confirm the clip does not suddenly slide horizontally during the pause.
+3. Drag the **trailing** trim handle. Confirm trailing edge follows finger. No jumps.
+4. Release after trimming. Confirm there's no width pop — the clip transitions smoothly from the dragging width to the final width with no flash to original size.
+
+Record the result of all four clip types in the task notes. If any clip type still flickers, return to that phase and re-inspect.
+
+- [ ] **Step 3: Workstream 1 sign-off**
+
+If all four clip types pass manual smoke, Workstream 1 is complete. No additional commit needed; the fix commits already shipped per-task.
+
+---
+
+# Workstream 2 — Full-screen Crop editor (Phases 2.1 – 2.7)
+
+## Phase 2.1 — Pure geometry helper + tests (TDD)
+
+### Task 2.1: Create `CropFrameGeometry` with unit tests
+
+**Files:**
+- Create: `Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift`
+- Create: `Openreel Video/Openreel VideoTests/CropFrameGeometryTests.swift`
+
+- [ ] **Step 1: Create the test file with failing tests**
+
+Create `Openreel Video/Openreel VideoTests/CropFrameGeometryTests.swift` with this content:
+
+```swift
+import CoreGraphics
+import Foundation
+import Testing
+@testable import Openreel_Video
+
+struct CropFrameGeometryTests {
+ @Test func mediaFitRectIsCenteredAndPreservesAspect() {
+ let preview = CGSize(width: 400, height: 300)
+ let media = CGSize(width: 1920, height: 1080)
+
+ let rect = CropFrameGeometry.mediaFitRect(previewSize: preview, mediaSize: media)
+
+ // 16:9 media in 4:3 preview -> letterboxed top/bottom, full width
+ #expect(abs(rect.width - 400) < 1e-6)
+ #expect(abs(rect.height - 225) < 1e-6)
+ #expect(abs(rect.minX - 0) < 1e-6)
+ #expect(abs(rect.minY - 37.5) < 1e-6)
+ }
+
+ @Test func mediaFitRectPillarboxesPortraitMediaInLandscapePreview() {
+ let preview = CGSize(width: 400, height: 300)
+ let media = CGSize(width: 1080, height: 1920)
+
+ let rect = CropFrameGeometry.mediaFitRect(previewSize: preview, mediaSize: media)
+
+ // 9:16 media in 4:3 preview -> pillarboxed, full height
+ #expect(abs(rect.height - 300) < 1e-6)
+ #expect(abs(rect.width - 168.75) < 1e-6)
+ }
+
+ @Test func cropFrameToNormalizedAndBack() {
+ let mediaFit = CGRect(x: 0, y: 37.5, width: 400, height: 225)
+ let cropFrame = CGRect(x: 100, y: 75, width: 200, height: 150)
+
+ let normalized = CropFrameGeometry.normalizedCrop(cropFrame: cropFrame, mediaFitRect: mediaFit)
+ #expect(abs(normalized.x - 0.25) < 1e-6)
+ #expect(abs(normalized.y - (37.5 / 225)) < 1e-6)
+ #expect(abs(normalized.width - 0.5) < 1e-6)
+ #expect(abs(normalized.height - (150 / 225)) < 1e-6)
+
+ let roundtrip = CropFrameGeometry.cropFrame(normalized: normalized, mediaFitRect: mediaFit)
+ #expect(abs(roundtrip.minX - cropFrame.minX) < 1e-6)
+ #expect(abs(roundtrip.minY - cropFrame.minY) < 1e-6)
+ #expect(abs(roundtrip.width - cropFrame.width) < 1e-6)
+ #expect(abs(roundtrip.height - cropFrame.height) < 1e-6)
+ }
+
+ @Test func resizeWithLockedAspectFromBottomRightKeepsRatio() {
+ let original = CGRect(x: 10, y: 10, width: 100, height: 50)
+ let bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
+ let drag = CGSize(width: 30, height: 80)
+
+ let resized = CropFrameGeometry.resize(
+ frame: original,
+ handle: .bottomRight,
+ drag: drag,
+ lockedAspect: 2.0,
+ bounds: bounds
+ )
+
+ let ratio = resized.width / resized.height
+ #expect(abs(ratio - 2.0) < 1e-6)
+ #expect(resized.minX == original.minX)
+ #expect(resized.minY == original.minY)
+ #expect(resized.maxX <= bounds.maxX)
+ #expect(resized.maxY <= bounds.maxY)
+ }
+
+ @Test func resizeFromTopLeftMovesOriginButKeepsOppositeCorner() {
+ let original = CGRect(x: 50, y: 50, width: 100, height: 100)
+ let bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
+ let drag = CGSize(width: 20, height: 20)
+
+ let resized = CropFrameGeometry.resize(
+ frame: original,
+ handle: .topLeft,
+ drag: drag,
+ lockedAspect: nil,
+ bounds: bounds
+ )
+
+ #expect(resized.maxX == original.maxX)
+ #expect(resized.maxY == original.maxY)
+ #expect(resized.width == 80)
+ #expect(resized.height == 80)
+ }
+
+ @Test func snapToAspectCentersWithinFrame() {
+ let frame = CGRect(x: 0, y: 0, width: 200, height: 200)
+ let bounds = CGRect(x: 0, y: 0, width: 400, height: 400)
+
+ let snapped = CropFrameGeometry.snapToAspect(
+ frame: frame,
+ aspect: 16.0 / 9.0,
+ bounds: bounds
+ )
+
+ let ratio = snapped.width / snapped.height
+ #expect(abs(ratio - 16.0 / 9.0) < 1e-6)
+ let originalCenterX = frame.midX
+ let originalCenterY = frame.midY
+ #expect(abs(snapped.midX - originalCenterX) < 1e-6)
+ #expect(abs(snapped.midY - originalCenterY) < 1e-6)
+ }
+}
+```
+
+- [ ] **Step 2: Run tests to verify they fail with "no such type"**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 17,OS=26.5" \
+ -only-testing:"Openreel VideoTests/CropFrameGeometryTests" \
+ -quiet
+```
+
+Expected: build fails with errors like `cannot find 'CropFrameGeometry' in scope` and `cannot find type 'CropFrameGeometry.Handle' in scope`. This confirms the test target is wired up and the helper does not exist yet.
+
+- [ ] **Step 3: Create the helper directory + file**
+
+Create the directory:
+
+```bash
+mkdir -p "Openreel Video/Openreel Video/Features/Crop"
+```
+
+Create `Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift` with this content:
+
+```swift
+import CoreGraphics
+import Foundation
+
+enum CropFrameGeometry {
+ enum Handle {
+ case topLeft, topRight, bottomLeft, bottomRight
+ case top, bottom, left, right
+ }
+
+ struct NormalizedCrop: Equatable {
+ var x: Double
+ var y: Double
+ var width: Double
+ var height: Double
+ }
+
+ static func mediaFitRect(previewSize: CGSize, mediaSize: CGSize) -> CGRect {
+ guard mediaSize.width > 0, mediaSize.height > 0,
+ previewSize.width > 0, previewSize.height > 0 else {
+ return .zero
+ }
+
+ let mediaAspect = mediaSize.width / mediaSize.height
+ let previewAspect = previewSize.width / previewSize.height
+
+ if mediaAspect > previewAspect {
+ let height = previewSize.width / mediaAspect
+ let y = (previewSize.height - height) / 2
+ return CGRect(x: 0, y: y, width: previewSize.width, height: height)
+ } else {
+ let width = previewSize.height * mediaAspect
+ let x = (previewSize.width - width) / 2
+ return CGRect(x: x, y: 0, width: width, height: previewSize.height)
+ }
+ }
+
+ static func normalizedCrop(cropFrame: CGRect, mediaFitRect: CGRect) -> NormalizedCrop {
+ guard mediaFitRect.width > 0, mediaFitRect.height > 0 else {
+ return NormalizedCrop(x: 0, y: 0, width: 1, height: 1)
+ }
+
+ let x = (cropFrame.minX - mediaFitRect.minX) / mediaFitRect.width
+ let y = (cropFrame.minY - mediaFitRect.minY) / mediaFitRect.height
+ let width = cropFrame.width / mediaFitRect.width
+ let height = cropFrame.height / mediaFitRect.height
+
+ return NormalizedCrop(
+ x: Double(max(0, min(1, x))),
+ y: Double(max(0, min(1, y))),
+ width: Double(max(0, min(1, width))),
+ height: Double(max(0, min(1, height)))
+ )
+ }
+
+ static func cropFrame(normalized: NormalizedCrop, mediaFitRect: CGRect) -> CGRect {
+ let x = mediaFitRect.minX + CGFloat(normalized.x) * mediaFitRect.width
+ let y = mediaFitRect.minY + CGFloat(normalized.y) * mediaFitRect.height
+ let width = CGFloat(normalized.width) * mediaFitRect.width
+ let height = CGFloat(normalized.height) * mediaFitRect.height
+ return CGRect(x: x, y: y, width: width, height: height)
+ }
+
+ static func resize(
+ frame: CGRect,
+ handle: Handle,
+ drag: CGSize,
+ lockedAspect: CGFloat?,
+ bounds: CGRect
+ ) -> CGRect {
+ let minSize: CGFloat = 40
+
+ var newFrame = frame
+ switch handle {
+ case .topLeft:
+ newFrame.origin.x += drag.width
+ newFrame.origin.y += drag.height
+ newFrame.size.width -= drag.width
+ newFrame.size.height -= drag.height
+ case .topRight:
+ newFrame.origin.y += drag.height
+ newFrame.size.width += drag.width
+ newFrame.size.height -= drag.height
+ case .bottomLeft:
+ newFrame.origin.x += drag.width
+ newFrame.size.width -= drag.width
+ newFrame.size.height += drag.height
+ case .bottomRight:
+ newFrame.size.width += drag.width
+ newFrame.size.height += drag.height
+ case .top:
+ newFrame.origin.y += drag.height
+ newFrame.size.height -= drag.height
+ case .bottom:
+ newFrame.size.height += drag.height
+ case .left:
+ newFrame.origin.x += drag.width
+ newFrame.size.width -= drag.width
+ case .right:
+ newFrame.size.width += drag.width
+ }
+
+ newFrame.size.width = max(newFrame.size.width, minSize)
+ newFrame.size.height = max(newFrame.size.height, minSize)
+
+ if let aspect = lockedAspect {
+ switch handle {
+ case .topLeft, .topRight, .bottomLeft, .bottomRight:
+ // Use width as dominant axis for corner drags
+ newFrame.size.height = newFrame.size.width / aspect
+ if newFrame.size.height < minSize {
+ newFrame.size.height = minSize
+ newFrame.size.width = minSize * aspect
+ }
+ // Anchor adjustments to keep opposite corner stable
+ switch handle {
+ case .topLeft:
+ newFrame.origin.x = frame.maxX - newFrame.size.width
+ newFrame.origin.y = frame.maxY - newFrame.size.height
+ case .topRight:
+ newFrame.origin.y = frame.maxY - newFrame.size.height
+ case .bottomLeft:
+ newFrame.origin.x = frame.maxX - newFrame.size.width
+ default:
+ break
+ }
+ case .top, .bottom:
+ newFrame.size.width = newFrame.size.height * aspect
+ newFrame.origin.x = frame.midX - newFrame.size.width / 2
+ case .left, .right:
+ newFrame.size.height = newFrame.size.width / aspect
+ newFrame.origin.y = frame.midY - newFrame.size.height / 2
+ }
+ }
+
+ return clamped(newFrame, to: bounds)
+ }
+
+ static func snapToAspect(frame: CGRect, aspect: CGFloat, bounds: CGRect) -> CGRect {
+ let center = CGPoint(x: frame.midX, y: frame.midY)
+ var width = frame.width
+ var height = width / aspect
+ if height > frame.height {
+ height = frame.height
+ width = height * aspect
+ }
+
+ var newFrame = CGRect(
+ x: center.x - width / 2,
+ y: center.y - height / 2,
+ width: width,
+ height: height
+ )
+ return clamped(newFrame, to: bounds)
+ }
+
+ static func translate(frame: CGRect, by delta: CGSize, bounds: CGRect) -> CGRect {
+ let proposed = frame.offsetBy(dx: delta.width, dy: delta.height)
+ return clamped(proposed, to: bounds)
+ }
+
+ private static func clamped(_ frame: CGRect, to bounds: CGRect) -> CGRect {
+ var clamped = frame
+ clamped.size.width = min(clamped.size.width, bounds.width)
+ clamped.size.height = min(clamped.size.height, bounds.height)
+ if clamped.minX < bounds.minX { clamped.origin.x = bounds.minX }
+ if clamped.minY < bounds.minY { clamped.origin.y = bounds.minY }
+ if clamped.maxX > bounds.maxX { clamped.origin.x = bounds.maxX - clamped.size.width }
+ if clamped.maxY > bounds.maxY { clamped.origin.y = bounds.maxY - clamped.size.height }
+ return clamped
+ }
+}
+```
+
+- [ ] **Step 4: Add the new files to the Xcode project**
+
+The project uses Xcode's file references. Add both files via the Xcode project:
+
+1. Open `Openreel Video.xcodeproj` in Xcode.
+2. Right-click the `Openreel Video/Openreel Video` group → New Group → name it `Features` if not present, then inside `Features` create `Crop`.
+3. Drag `CropFrameGeometry.swift` into the `Crop` group. Make sure the **Openreel Video** target is checked.
+4. Drag `CropFrameGeometryTests.swift` into the `Openreel VideoTests` group. Make sure the **Openreel VideoTests** target is checked.
+5. Save the project (`⌘S`).
+
+If you'd rather edit `project.pbxproj` directly, locate the existing entry for `FilterRendererTests.swift` (or any test in `Openreel VideoTests/`) and clone its `PBXBuildFile` / `PBXFileReference` / membership lines for `CropFrameGeometryTests.swift`; similarly clone an entry like `Features/Effects/EffectsTabPanel.swift` for the helper file under a new `Features/Crop/` group.
+
+- [ ] **Step 5: Run tests to verify they pass**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 17,OS=26.5" \
+ -only-testing:"Openreel VideoTests/CropFrameGeometryTests" \
+ -quiet
+```
+
+Expected: `Test Suite 'CropFrameGeometryTests' passed`. All 6 tests green.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift" \
+ "Openreel Video/Openreel VideoTests/CropFrameGeometryTests.swift" \
+ "Openreel Video/Openreel Video.xcodeproj"
+git commit -m "feat(ios): CropFrameGeometry helper for the crop editor
+
+Pure functions only: media-aspect fit, preview-rect <-> normalized
+crop conversion, locked-aspect resize from 8 handle positions,
+aspect snap-to-center, translation with bounds clamp. 6 round-trip
+and constraint tests."
+```
+
+## Phase 2.2 — AppState API for full-rect crop and direct flip set
+
+### Task 2.2: Add `setSelectedClipCrop` and `setSelectedClipFlip`; delete `updateSelectedClipCrop`
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/AppState.swift`
+
+- [ ] **Step 1: Replace `updateSelectedClipCrop` with `setSelectedClipCrop`**
+
+In `AppState.swift`, find `updateSelectedClipCrop` (line 2333). Replace the entire method body (lines 2333–2360) with:
+
+```swift
+func setSelectedClipCrop(
+ _ crop: OpenReelProject.Crop?,
+ playbackController: PlaybackController? = nil
+) async {
+ guard var project = currentProject,
+ let location = selectedClipLocation(in: project)
+ else {
+ return
+ }
+
+ let validated = crop.map { Self.validatedCrop($0) }
+ let primaryID = project.timeline.tracks[location.trackIndex].clips[location.clipIndex].id
+ for target in selectedClipTargets(in: project) {
+ project.timeline.tracks[target.trackIndex].clips[target.clipIndex].transform.crop = validated
+ }
+ normalizeTimeline(&project)
+ await commitEditedProject(project, selectedClipID: primaryID, playbackController: playbackController)
+}
+
+private static func validatedCrop(_ crop: OpenReelProject.Crop) -> OpenReelProject.Crop {
+ let minSize = 0.05
+ let width = max(min(crop.width, 1), minSize)
+ let height = max(min(crop.height, 1), minSize)
+ let x = max(0, min(crop.x, 1 - width))
+ let y = max(0, min(crop.y, 1 - height))
+ return OpenReelProject.Crop(x: x, y: y, width: width, height: height)
+}
+```
+
+The old per-axis `updateSelectedClipCrop` is gone (only the slider sheet called it; that sheet is deleted in Phase 2.6). The new method takes the full `Crop` in one shot and enforces geometric constraints (`x + width ≤ 1`, `y + height ≤ 1`, dimensions ≥ `minSize = 0.05`). Passing `nil` clears the crop.
+
+- [ ] **Step 2: Add `setSelectedClipFlip`**
+
+Right after the existing `toggleSelectedClipFlip` method (line 1685), add this new method:
+
+```swift
+func setSelectedClipFlip(
+ horizontal: Bool? = nil,
+ vertical: Bool? = nil,
+ playbackController: PlaybackController? = nil
+) async {
+ guard var project = currentProject,
+ let location = selectedClipLocation(in: project)
+ else {
+ return
+ }
+
+ var transform = project.timeline.tracks[location.trackIndex].clips[location.clipIndex].transform
+ if let horizontal {
+ transform.flipHorizontal = horizontal
+ }
+ if let vertical {
+ transform.flipVertical = vertical
+ }
+ project.timeline.tracks[location.trackIndex].clips[location.clipIndex].transform = transform
+ let clipID = project.timeline.tracks[location.trackIndex].clips[location.clipIndex].id
+ normalizeTimeline(&project)
+ await commitEditedProject(project, selectedClipID: clipID, playbackController: playbackController)
+}
+```
+
+This sets the flip values directly rather than toggling. The existing `toggleSelectedClipFlip` stays (the slider sheet's Flip H / Flip V preset buttons call it).
+
+- [ ] **Step 3: Build to confirm no callers were left dangling**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: build fails with `cannot find 'updateSelectedClipCrop' in scope` at the four call sites inside `clipCropSheet` (around lines 4470–4479). This is **expected** — those callers are deleted in Phase 2.6 together with the rest of the slider sheet. To keep the build green until then, temporarily leave the old method present alongside the new one:
+
+In `AppState.swift`, instead of replacing `updateSelectedClipCrop` (Step 1), **add** `setSelectedClipCrop` and `validatedCrop` as new methods directly below `updateSelectedClipCrop`. Leave the old method intact. Phase 2.6 deletes both the callers and the old method.
+
+Re-run the build:
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/AppState.swift"
+git commit -m "feat(ios): AppState setSelectedClipCrop + setSelectedClipFlip
+
+setSelectedClipCrop accepts a full Crop rect (or nil to clear) and
+validates geometric constraints in one shot — needed by the new
+full-screen crop editor which produces a valid rect from direct
+manipulation rather than per-axis sliders.
+
+setSelectedClipFlip sets horizontal/vertical directly instead of
+toggling, so the crop editor can persist its local flip state on
+Done without round-tripping through toggle math.
+
+The old per-axis updateSelectedClipCrop and the toggle-based
+toggleSelectedClipFlip stay for now; they're called only by the
+slider sheet which is removed in a later commit."
+```
+
+## Phase 2.3 — `CropEditorView` shell with header + dismiss
+
+### Task 2.3: Create the `CropEditorView` scaffolding (no interactions yet)
+
+**Files:**
+- Create: `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift`
+
+- [ ] **Step 1: Create the file**
+
+Create `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift` with this content:
+
+```swift
+import SwiftUI
+
+struct CropEditorView: View {
+ @Environment(\.dismiss) private var dismiss
+ @Environment(AppState.self) private var appState
+ @Environment(PlaybackController.self) private var playbackController
+
+ let clipID: String
+
+ @State private var cropFrame: CGRect = .zero
+ @State private var initialCropFrame: CGRect = .zero
+ @State private var mediaFitRect: CGRect = .zero
+ @State private var lockedAspect: CGFloat? = nil
+ @State private var flipH: Bool = false
+ @State private var flipV: Bool = false
+ @State private var initialFlipH: Bool = false
+ @State private var initialFlipV: Bool = false
+
+ var body: some View {
+ VStack(spacing: 0) {
+ topBar
+ previewArea
+ controlsArea
+ }
+ .background(Color.black.ignoresSafeArea())
+ .onAppear { loadInitialState() }
+ }
+
+ private var topBar: some View {
+ HStack {
+ Button("Cancel") { dismiss() }
+ .foregroundStyle(.white)
+
+ Spacer()
+
+ Text("Crop")
+ .font(.system(size: 17, weight: .semibold, design: .rounded))
+ .foregroundStyle(.white)
+
+ Spacer()
+
+ Button("Done") { apply(); dismiss() }
+ .foregroundStyle(OpenReelTheme.accent)
+ .fontWeight(.semibold)
+ }
+ .padding(.horizontal, 16)
+ .frame(height: 56)
+ }
+
+ private var previewArea: some View {
+ GeometryReader { proxy in
+ ZStack {
+ Color.black
+
+ if let image = backdropImage {
+ Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .scaleEffect(x: flipH ? -1 : 1, y: flipV ? -1 : 1)
+ }
+ }
+ .frame(width: proxy.size.width, height: proxy.size.height)
+ .onAppear {
+ let media = mediaPixelSize ?? CGSize(width: 16, height: 9)
+ mediaFitRect = CropFrameGeometry.mediaFitRect(
+ previewSize: proxy.size,
+ mediaSize: media
+ )
+ if cropFrame == .zero {
+ cropFrame = CropFrameGeometry.cropFrame(
+ normalized: initialNormalized,
+ mediaFitRect: mediaFitRect
+ )
+ initialCropFrame = cropFrame
+ }
+ }
+ }
+ .clipped()
+ }
+
+ private var controlsArea: some View {
+ VStack(spacing: 16) {
+ aspectChips
+ actionRow
+ }
+ .padding(.vertical, 20)
+ .padding(.horizontal, 16)
+ .background(Color(white: 0.05).ignoresSafeArea(edges: .bottom))
+ }
+
+ private var aspectChips: some View {
+ Text("Aspect chips placeholder")
+ .foregroundStyle(.white.opacity(0.4))
+ .font(.system(size: 12, weight: .medium))
+ .frame(maxWidth: .infinity)
+ }
+
+ private var actionRow: some View {
+ HStack(spacing: 32) {
+ Button {
+ flipH.toggle()
+ } label: {
+ VStack(spacing: 4) {
+ Image(systemName: "arrow.left.and.right.righttriangle.left.righttriangle.right")
+ Text("Flip H").font(.system(size: 11))
+ }
+ .foregroundStyle(.white)
+ }
+
+ Button {
+ flipV.toggle()
+ } label: {
+ VStack(spacing: 4) {
+ Image(systemName: "arrow.up.and.down.righttriangle.up.righttriangle.down")
+ Text("Flip V").font(.system(size: 11))
+ }
+ .foregroundStyle(.white)
+ }
+
+ Button {
+ reset()
+ } label: {
+ VStack(spacing: 4) {
+ Image(systemName: "arrow.counterclockwise")
+ Text("Reset").font(.system(size: 11))
+ }
+ .foregroundStyle(.white)
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ private var clip: OpenReelProject.Clip? {
+ appState.currentProject?.allClips.first(where: { $0.id == clipID })
+ }
+
+ private var mediaItem: OpenReelProject.MediaItem? {
+ guard let clip,
+ let project = appState.currentProject else { return nil }
+ return appState.mediaItem(for: clip.mediaId, in: project)
+ }
+
+ private var mediaPixelSize: CGSize? {
+ guard let m = mediaItem,
+ m.metadata.width > 0,
+ m.metadata.height > 0 else { return nil }
+ return CGSize(width: m.metadata.width, height: m.metadata.height)
+ }
+
+ private var initialNormalized: CropFrameGeometry.NormalizedCrop {
+ if let crop = clip?.transform.crop {
+ return CropFrameGeometry.NormalizedCrop(
+ x: crop.x, y: crop.y, width: crop.width, height: crop.height
+ )
+ }
+ return CropFrameGeometry.NormalizedCrop(x: 0, y: 0, width: 1, height: 1)
+ }
+
+ private var backdropImage: UIImage? {
+ // Replaced in Phase 2.7 with the real video-snapshot / photo loader.
+ return nil
+ }
+
+ private func loadInitialState() {
+ flipH = clip?.transform.flipHorizontal ?? false
+ flipV = clip?.transform.flipVertical ?? false
+ initialFlipH = flipH
+ initialFlipV = flipV
+ }
+
+ private func reset() {
+ cropFrame = mediaFitRect
+ lockedAspect = nil
+ flipH = false
+ flipV = false
+ }
+
+ private func apply() {
+ let normalized = CropFrameGeometry.normalizedCrop(
+ cropFrame: cropFrame,
+ mediaFitRect: mediaFitRect
+ )
+ Task {
+ await appState.setSelectedClipCrop(
+ OpenReelProject.Crop(
+ x: normalized.x,
+ y: normalized.y,
+ width: normalized.width,
+ height: normalized.height
+ ),
+ playbackController: playbackController
+ )
+
+ if flipH != initialFlipH || flipV != initialFlipV {
+ await appState.setSelectedClipFlip(
+ horizontal: flipH != initialFlipH ? flipH : nil,
+ vertical: flipV != initialFlipV ? flipV : nil,
+ playbackController: playbackController
+ )
+ }
+ }
+ }
+}
+```
+
+- [ ] **Step 2: Add to the Xcode project**
+
+Add the new file to the **Openreel Video** target via Xcode (same approach as Task 2.1 Step 4 — drag into the `Crop` group). Save the project.
+
+- [ ] **Step 3: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`. The view compiles even though it's not yet presented anywhere.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift" \
+ "Openreel Video/Openreel Video.xcodeproj"
+git commit -m "feat(ios): CropEditorView shell with header + flip + reset
+
+Layout, state, and the Cancel/Done flow plus Flip H/V/Reset buttons.
+No drag handles yet, no aspect chips, no media backdrop. Phases
+2.4 - 2.7 fill those in. Not yet routed from EditorView."
+```
+
+## Phase 2.4 — Aspect chips + draggable crop frame
+
+### Task 2.4: Add aspect chips and the 8-handle crop frame overlay
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift`
+
+- [ ] **Step 1: Replace the `aspectChips` placeholder**
+
+In `CropEditorView.swift`, replace the body of `aspectChips`:
+
+```swift
+private var aspectChips: some View {
+ Text("Aspect chips placeholder")
+ .foregroundStyle(.white.opacity(0.4))
+ .font(.system(size: 12, weight: .medium))
+ .frame(maxWidth: .infinity)
+}
+```
+
+with:
+
+```swift
+private var aspectChips: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 8) {
+ ForEach(Self.aspectOptions, id: \.label) { option in
+ aspectChip(label: option.label, ratio: option.ratio)
+ }
+ }
+ .padding(.horizontal, 4)
+ }
+}
+
+private static let aspectOptions: [(label: String, ratio: CGFloat?)] = [
+ ("Free", nil),
+ ("1:1", 1.0),
+ ("9:16", 9.0 / 16.0),
+ ("16:9", 16.0 / 9.0),
+ ("4:5", 4.0 / 5.0),
+ ("4:3", 4.0 / 3.0),
+ ("3:4", 3.0 / 4.0)
+]
+
+private func aspectChip(label: String, ratio: CGFloat?) -> some View {
+ let isSelected = (ratio == lockedAspect) || (ratio == nil && lockedAspect == nil)
+ return Button {
+ applyAspect(ratio: ratio)
+ } label: {
+ Text(label)
+ .font(.system(size: 13, weight: .semibold, design: .rounded))
+ .foregroundStyle(isSelected ? .black : .white)
+ .padding(.horizontal, 14)
+ .padding(.vertical, 8)
+ .background(
+ Capsule().fill(isSelected ? OpenReelTheme.accent : Color.white.opacity(0.08))
+ )
+ }
+ .buttonStyle(.plain)
+}
+
+private func applyAspect(ratio: CGFloat?) {
+ lockedAspect = ratio
+ if let ratio {
+ withAnimation(.easeInOut(duration: 0.18)) {
+ cropFrame = CropFrameGeometry.snapToAspect(
+ frame: cropFrame,
+ aspect: ratio,
+ bounds: mediaFitRect
+ )
+ }
+ }
+}
+```
+
+- [ ] **Step 2: Add the crop-frame overlay inside `previewArea`**
+
+Replace the entire `previewArea` body:
+
+```swift
+private var previewArea: some View {
+ GeometryReader { proxy in
+ ZStack {
+ Color.black
+
+ if let image = backdropImage {
+ Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .scaleEffect(x: flipH ? -1 : 1, y: flipV ? -1 : 1)
+ }
+ }
+ .frame(width: proxy.size.width, height: proxy.size.height)
+ .onAppear {
+ ...
+ }
+ }
+ .clipped()
+}
+```
+
+with this expanded version that adds the crop frame and 8 handles:
+
+```swift
+private var previewArea: some View {
+ GeometryReader { proxy in
+ ZStack {
+ Color.black
+
+ if let image = backdropImage {
+ Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .scaleEffect(x: flipH ? -1 : 1, y: flipV ? -1 : 1)
+ }
+
+ if mediaFitRect != .zero {
+ cropFrameOverlay
+ }
+ }
+ .frame(width: proxy.size.width, height: proxy.size.height)
+ .onAppear {
+ let media = mediaPixelSize ?? CGSize(width: 16, height: 9)
+ mediaFitRect = CropFrameGeometry.mediaFitRect(
+ previewSize: proxy.size,
+ mediaSize: media
+ )
+ cropFrame = CropFrameGeometry.cropFrame(
+ normalized: initialNormalized,
+ mediaFitRect: mediaFitRect
+ )
+ initialCropFrame = cropFrame
+ }
+ }
+ .clipped()
+}
+
+private var cropFrameOverlay: some View {
+ ZStack(alignment: .topLeading) {
+ // Dim outside the crop frame
+ Rectangle()
+ .fill(Color.black.opacity(0.55))
+ .mask(
+ cropFrameMask
+ )
+ .allowsHitTesting(false)
+
+ // Crop frame border + grid
+ Rectangle()
+ .stroke(Color.white, lineWidth: 1.5)
+ .frame(width: cropFrame.width, height: cropFrame.height)
+ .offset(x: cropFrame.minX, y: cropFrame.minY)
+ .allowsHitTesting(false)
+
+ thirdsGrid
+ .frame(width: cropFrame.width, height: cropFrame.height)
+ .offset(x: cropFrame.minX, y: cropFrame.minY)
+ .allowsHitTesting(false)
+
+ // 4 corner + 4 edge handles
+ ForEach(Self.allHandles, id: \.self) { handle in
+ handleView(for: handle)
+ }
+ }
+}
+
+private static let allHandles: [CropFrameGeometry.Handle] = [
+ .topLeft, .topRight, .bottomLeft, .bottomRight,
+ .top, .bottom, .left, .right
+]
+
+private var cropFrameMask: some View {
+ GeometryReader { proxy in
+ Path { path in
+ path.addRect(CGRect(origin: .zero, size: proxy.size))
+ path.addRect(cropFrame)
+ }
+ .fill(style: FillStyle(eoFill: true))
+ }
+}
+
+private var thirdsGrid: some View {
+ GeometryReader { proxy in
+ let w = proxy.size.width
+ let h = proxy.size.height
+ Path { path in
+ path.move(to: CGPoint(x: w / 3, y: 0))
+ path.addLine(to: CGPoint(x: w / 3, y: h))
+ path.move(to: CGPoint(x: 2 * w / 3, y: 0))
+ path.addLine(to: CGPoint(x: 2 * w / 3, y: h))
+ path.move(to: CGPoint(x: 0, y: h / 3))
+ path.addLine(to: CGPoint(x: w, y: h / 3))
+ path.move(to: CGPoint(x: 0, y: 2 * h / 3))
+ path.addLine(to: CGPoint(x: w, y: 2 * h / 3))
+ }
+ .stroke(Color.white.opacity(0.3), lineWidth: 0.5)
+ }
+}
+
+private func handleView(for handle: CropFrameGeometry.Handle) -> some View {
+ let position = handlePosition(handle)
+ let isCorner: Bool = switch handle {
+ case .topLeft, .topRight, .bottomLeft, .bottomRight: true
+ default: false
+ }
+
+ return ZStack {
+ if isCorner {
+ Circle()
+ .fill(Color.white)
+ .frame(width: 14, height: 14)
+ .overlay(Circle().stroke(Color.black.opacity(0.3), lineWidth: 0.5))
+ } else {
+ Capsule()
+ .fill(Color.white)
+ .frame(
+ width: handle == .left || handle == .right ? 4 : 24,
+ height: handle == .left || handle == .right ? 24 : 4
+ )
+ }
+ }
+ .frame(width: 44, height: 44)
+ .contentShape(Rectangle())
+ .position(position)
+ .gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ cropFrame = CropFrameGeometry.resize(
+ frame: initialCropFrame,
+ handle: handle,
+ drag: value.translation,
+ lockedAspect: lockedAspect,
+ bounds: mediaFitRect
+ )
+ }
+ .onEnded { _ in
+ initialCropFrame = cropFrame
+ }
+ )
+}
+
+private func handlePosition(_ handle: CropFrameGeometry.Handle) -> CGPoint {
+ switch handle {
+ case .topLeft: return CGPoint(x: cropFrame.minX, y: cropFrame.minY)
+ case .topRight: return CGPoint(x: cropFrame.maxX, y: cropFrame.minY)
+ case .bottomLeft: return CGPoint(x: cropFrame.minX, y: cropFrame.maxY)
+ case .bottomRight: return CGPoint(x: cropFrame.maxX, y: cropFrame.maxY)
+ case .top: return CGPoint(x: cropFrame.midX, y: cropFrame.minY)
+ case .bottom: return CGPoint(x: cropFrame.midX, y: cropFrame.maxY)
+ case .left: return CGPoint(x: cropFrame.minX, y: cropFrame.midY)
+ case .right: return CGPoint(x: cropFrame.maxX, y: cropFrame.midY)
+ }
+}
+```
+
+Add `import UIKit` at the top of the file (after `import SwiftUI`) — `UIImage` requires it on iOS targets that don't already pull it in transitively.
+
+`CropFrameGeometry.Handle` already conforms to nothing useful for `ForEach` — make the enum `Hashable` by adding `: Hashable` to its declaration in `CropFrameGeometry.swift`:
+
+In `Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift`, find:
+
+```swift
+enum Handle {
+ case topLeft, topRight, bottomLeft, bottomRight
+ case top, bottom, left, right
+}
+```
+
+Replace with:
+
+```swift
+enum Handle: Hashable {
+ case topLeft, topRight, bottomLeft, bottomRight
+ case top, bottom, left, right
+}
+```
+
+- [ ] **Step 3: Update `reset()` to also clear `initialCropFrame`**
+
+In `CropEditorView`, find `reset()`:
+
+```swift
+private func reset() {
+ cropFrame = mediaFitRect
+ lockedAspect = nil
+ flipH = false
+ flipV = false
+}
+```
+
+Replace with:
+
+```swift
+private func reset() {
+ cropFrame = mediaFitRect
+ initialCropFrame = mediaFitRect
+ lockedAspect = nil
+ flipH = false
+ flipV = false
+}
+```
+
+- [ ] **Step 4: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift" \
+ "Openreel Video/Openreel Video/Features/Crop/CropFrameGeometry.swift"
+git commit -m "feat(ios): crop editor aspect chips + 8 draggable handles
+
+7 aspect chips (Free / 1:1 / 9:16 / 16:9 / 4:5 / 4:3 / 3:4) with
+snap-to-aspect on tap. 4 corner + 4 edge handles with 44pt hit
+areas, locked-aspect math via CropFrameGeometry.resize. Outside-
+crop dimming and a rule-of-thirds grid for composition feedback."
+```
+
+## Phase 2.5 — Pan + pinch on the crop frame
+
+### Task 2.5: Pan inside the crop frame and pinch on the media
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift`
+
+- [ ] **Step 1: Add pan gesture inside the crop frame**
+
+In `cropFrameOverlay`, after the `thirdsGrid` overlay and before the `ForEach(Self.allHandles)`, insert a pannable transparent rectangle that sits **inside** the crop frame:
+
+```swift
+// Pannable area inside the crop frame (drag anywhere inside to move it)
+Rectangle()
+ .fill(Color.clear)
+ .contentShape(Rectangle())
+ .frame(width: cropFrame.width, height: cropFrame.height)
+ .offset(x: cropFrame.minX, y: cropFrame.minY)
+ .gesture(
+ DragGesture(minimumDistance: 2)
+ .onChanged { value in
+ cropFrame = CropFrameGeometry.translate(
+ frame: initialCropFrame,
+ by: value.translation,
+ bounds: mediaFitRect
+ )
+ }
+ .onEnded { _ in
+ initialCropFrame = cropFrame
+ }
+ )
+```
+
+Place it **before** the handles `ForEach` so the handles get drawn on top and remain hit-testable. `.contentShape(Rectangle())` makes the clear rectangle hit-test as a solid rectangle.
+
+- [ ] **Step 2: Add pinch-to-zoom for the media**
+
+Add new state at the top of `CropEditorView` (next to the existing `@State` declarations):
+
+```swift
+@State private var mediaScale: CGFloat = 1.0
+@State private var pinchStartScale: CGFloat = 1.0
+```
+
+In `previewArea`, change the `.scaleEffect(x: flipH ? -1 : 1, y: flipV ? -1 : 1)` line on the image to also apply `mediaScale`:
+
+```swift
+Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .scaleEffect(
+ x: (flipH ? -1 : 1) * mediaScale,
+ y: (flipV ? -1 : 1) * mediaScale
+ )
+```
+
+Add a pinch gesture to the preview ZStack. After the existing `.frame(width: proxy.size.width, height: proxy.size.height)` line inside `previewArea`'s `GeometryReader`, add:
+
+```swift
+.gesture(
+ MagnifyGesture()
+ .onChanged { value in
+ mediaScale = min(max(pinchStartScale * value.magnification, 1.0), 6.0)
+ }
+ .onEnded { _ in
+ pinchStartScale = mediaScale
+ }
+)
+```
+
+- [ ] **Step 3: Update `reset()` to also restore zoom**
+
+In `reset()`:
+
+```swift
+private func reset() {
+ cropFrame = mediaFitRect
+ initialCropFrame = mediaFitRect
+ lockedAspect = nil
+ flipH = false
+ flipV = false
+ mediaScale = 1.0
+ pinchStartScale = 1.0
+}
+```
+
+- [ ] **Step 4: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift"
+git commit -m "feat(ios): pan + pinch in crop editor
+
+Drag inside the crop frame to move it (clamped to media bounds).
+MagnifyGesture on the preview area zooms the media backdrop from
+1x to 6x; the crop frame stays in screen coords so the user can
+crop into details."
+```
+
+## Phase 2.6 — Route from `EditorView`, delete old slider sheet
+
+### Task 2.6: Present `CropEditorView` from `EditorView` and remove `clipCropSheet`
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/EditorView.swift`
+- Modify: `Openreel Video/Openreel Video/AppState.swift` (delete the now-unused `updateSelectedClipCrop`)
+
+- [ ] **Step 1: Add the `fullScreenCover` state to `EditorView`**
+
+In `EditorView.swift`, find an existing `@State` declaration near the top of the struct (around line 10). Add a new state below the existing `activeEditingSheet`:
+
+```swift
+@State private var presentedCropEditor: PresentedCropEditor?
+```
+
+In the same struct's nested type section (around line 242 where `ExportedVideo` is declared), add:
+
+```swift
+private struct PresentedCropEditor: Identifiable {
+ let id = UUID()
+ let clipID: String
+}
+```
+
+- [ ] **Step 2: Attach the `.fullScreenCover` modifier**
+
+In `EditorView.body`, find the existing `.sheet(item: $activeEditingSheet)` at line 388. Right after that modifier (on the next line), add:
+
+```swift
+.fullScreenCover(item: $presentedCropEditor) { presented in
+ CropEditorView(clipID: presented.clipID)
+ .environment(appState)
+ .environment(playbackController)
+}
+```
+
+- [ ] **Step 3: Reroute both "Crop" tool taps to the new editor**
+
+In `EditorView.swift`, find line 3417–3418:
+
+```swift
+case "Crop":
+ activeEditingSheet = .crop
+```
+
+Replace with:
+
+```swift
+case "Crop":
+ if let clipID = appState.selectedClipID {
+ activeEditingSheet = nil
+ presentedCropEditor = PresentedCropEditor(clipID: clipID)
+ }
+```
+
+Find the second occurrence at line 3597–3598:
+
+```swift
+case "Crop":
+ activeEditingSheet = .crop
+```
+
+Replace with the same block:
+
+```swift
+case "Crop":
+ if let clipID = appState.selectedClipID {
+ activeEditingSheet = nil
+ presentedCropEditor = PresentedCropEditor(clipID: clipID)
+ }
+```
+
+- [ ] **Step 4: Remove `EditingSheet.crop` case + its branches**
+
+In the `EditingSheet` enum (line 223), remove the `case crop` line:
+
+```swift
+private enum EditingSheet: String, Identifiable {
+ case volume
+ case pan
+ case fade
+ case speed
+ case crop // <-- delete this line
+ case filters
+ ...
+}
+```
+
+In `editingSheetHeight(for:)` (line 3658), remove the `.crop` case (line 3672–3673):
+
+```swift
+case .crop:
+ return 420
+```
+
+In `editingSheet(_:)` (line 3687), remove the `.crop` case (lines 3698–3699):
+
+```swift
+case .crop:
+ clipCropSheet
+```
+
+- [ ] **Step 5: Delete the `clipCropSheet` body**
+
+In `EditorView.swift`, find `clipCropSheet` (line 4445) and delete the entire computed property body — from `private var clipCropSheet: some View {` through its closing `}` (lines 4445–4495).
+
+- [ ] **Step 6: Delete the unused `updateSelectedClipCrop`**
+
+In `AppState.swift`, delete the entire `updateSelectedClipCrop` method (lines 2333–2360 of the original file — its line number may have shifted after Phase 2.2). After deletion, the only callers were the slider rows you just removed, so no other call sites should reference it.
+
+- [ ] **Step 7: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`. If you see `cannot find 'updateSelectedClipCrop'` or `cannot find 'clipCropSheet'`, search for the remaining references and remove them.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/EditorView.swift" \
+ "Openreel Video/Openreel Video/AppState.swift"
+git commit -m "feat(ios): route Crop tool to full-screen CropEditorView
+
+Both Crop tool tap paths now present CropEditorView as a
+.fullScreenCover. Deleted: the EditingSheet.crop case, the
+clipCropSheet slider body, and the per-axis updateSelectedClipCrop
+AppState method (only the deleted sliders called it)."
+```
+
+## Phase 2.7 — Wire up the media backdrop
+
+### Task 2.7: Load real photo / video-frame backdrop into `CropEditorView`
+
+**Files:**
+- Modify: `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift`
+
+- [ ] **Step 1: Replace `backdropImage` with real loading**
+
+In `CropEditorView`, find:
+
+```swift
+private var backdropImage: UIImage? {
+ // Replaced in Phase 2.7 with the real video-snapshot / photo loader.
+ return nil
+}
+```
+
+Replace with:
+
+```swift
+@State private var backdrop: UIImage? = nil
+
+private var backdropImage: UIImage? { backdrop }
+
+private func loadBackdrop() {
+ guard let clip,
+ let project = appState.currentProject,
+ let media = appState.mediaItem(for: clip.mediaId, in: project),
+ let url = appState.mediaURL(for: media, in: project) else {
+ backdrop = nil
+ return
+ }
+
+ switch media.type {
+ case .image:
+ backdrop = UIImage(contentsOfFile: url.path)
+ case .video:
+ if let snapshot = MetalVideoSnapshotProvider.snapshot {
+ let ciContext = CIContext()
+ if let cgImage = ciContext.createCGImage(snapshot, from: snapshot.extent) {
+ backdrop = UIImage(cgImage: cgImage)
+ return
+ }
+ }
+ Task { @MainActor in
+ backdrop = await loadFirstFrame(from: url)
+ }
+ case .audio:
+ backdrop = nil
+ }
+}
+
+private func loadFirstFrame(from url: URL) async -> UIImage? {
+ let asset = AVURLAsset(url: url)
+ let generator = AVAssetImageGenerator(asset: asset)
+ generator.appliesPreferredTrackTransform = true
+ let time = CMTime(seconds: max(playbackController.currentTime, 0), preferredTimescale: 600)
+ return await withCheckedContinuation { continuation in
+ generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { _, cgImage, _, _, _ in
+ if let cgImage {
+ continuation.resume(returning: UIImage(cgImage: cgImage))
+ } else {
+ continuation.resume(returning: nil)
+ }
+ }
+ }
+}
+```
+
+- [ ] **Step 2: Add `import AVFoundation` and `import CoreImage` at the top of the file**
+
+The top of `CropEditorView.swift` should now have:
+
+```swift
+import AVFoundation
+import CoreImage
+import SwiftUI
+import UIKit
+```
+
+- [ ] **Step 3: Invoke `loadBackdrop()` on appear**
+
+Find the `.onAppear { loadInitialState() }` modifier on the outer `VStack`. Change it to:
+
+```swift
+.onAppear {
+ loadInitialState()
+ loadBackdrop()
+}
+```
+
+- [ ] **Step 4: Build**
+
+```bash
+xcodebuild -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "generic/platform=iOS Simulator" \
+ -quiet build
+```
+
+Expected: `** BUILD SUCCEEDED **`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add "Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift"
+git commit -m "feat(ios): load media backdrop in CropEditorView
+
+Photos load directly via UIImage(contentsOfFile:). Videos prefer
+MetalVideoSnapshotProvider.snapshot (already in memory from the
+preview); fall back to AVAssetImageGenerator at the current
+playhead time."
+```
+
+## Phase 2.8 — End-to-end verification
+
+### Task 2.8: Full suite + manual smoke
+
+- [ ] **Step 1: Run the full test suite**
+
+```bash
+xcodebuild test \
+ -project "Openreel Video/Openreel Video.xcodeproj" \
+ -scheme "Openreel Video" \
+ -destination "platform=iOS Simulator,name=iPhone 17,OS=26.5" \
+ -only-testing:"Openreel VideoTests" \
+ -quiet
+```
+
+Expected: `CropFrameGeometryTests` (6 tests) green. Pre-existing test failures from `MOBILE-CODE-REVIEW-2026-05-27.md` are not regressions caused by this work; only flag new failures.
+
+- [ ] **Step 2: Manual smoke — photo crop**
+
+1. Launch the app in Simulator (iPhone 17, iOS 26.5).
+2. Create a project, import a still photo, drop it on the timeline.
+3. Tap the photo clip, then tap the "Crop" tool.
+4. Verify the full-screen editor opens with the photo visible.
+5. Drag corner handles — crop frame resizes from the corner.
+6. Drag inside the frame — frame pans within the photo bounds.
+7. Pinch on the photo — photo zooms 1x to 6x.
+8. Tap "1:1" — crop frame snaps to a square centered on its current position.
+9. Tap "16:9", then drag a corner — confirm the aspect ratio is preserved.
+10. Tap "Free" — confirm subsequent drags don't preserve ratio.
+11. Tap "Flip H" — photo mirrors horizontally.
+12. Tap "Reset" — full-frame crop, no flip, 1x zoom.
+13. Tap "Done" — return to editor. Verify the timeline preview shows the cropped photo.
+14. Re-open Crop on the same clip — verify the previous crop state is restored.
+
+- [ ] **Step 3: Manual smoke — video crop**
+
+1. Import a video, drop it on the timeline.
+2. Seek to a recognizable frame on the timeline.
+3. Tap the clip, tap "Crop".
+4. Verify the backdrop shows the frame near the current playhead (not necessarily exact — AVAssetImageGenerator returns the closest keyframe).
+5. Same gesture checks as photo (corners, edges, pan, pinch, aspect snap, flip, reset).
+6. Tap "Done". Verify the timeline preview reflects the crop.
+
+- [ ] **Step 4: Workstream 2 sign-off**
+
+If both photo and video paths pass, Workstream 2 is complete. Push the branch:
+
+```bash
+git push -u origin feat/ios-app
+```
+
+(Or your branch name if it differs.)
+
+- [ ] **Step 5: Final commit (if any cleanup found during smoke)**
+
+If smoke testing revealed any small leftover issue (e.g., a haptic missing, an off-by-one in the crop reset), fix it and commit:
+
+```bash
+git add <files>
+git commit -m "fix(ios): <whatever-the-fix-was> in CropEditorView"
+```
+
+Otherwise nothing more is needed — the per-task commits already shipped everything.
+
+---
+
+## Self-review
+
+Run through the spec one more time and check the plan covers it:
+
+- **Workstream 1, change 1** (suppress moveGesture during trim): Tasks 1.1–1.4 Steps 4 / 5 ✓
+- **Workstream 1, change 2** (leading edge follows finger): Tasks 1.1–1.4 Step 3 ✓
+- **Workstream 1, change 3** (async onTrim, no release pop): Tasks 1.1–1.4 Steps 1, 5, 6 ✓
+- **Workstream 1, all 4 clip block types**: Tasks 1.1–1.4 ✓
+- **Workstream 2, new file `CropEditorView.swift`**: Tasks 2.3, 2.4, 2.5, 2.7 ✓
+- **Workstream 2, new file `CropFrameGeometry.swift` + tests**: Task 2.1 ✓
+- **Workstream 2, fullScreenCover route**: Task 2.6 Step 2 ✓
+- **Workstream 2, 8 handles, aspect chips, pan, pinch, flip, reset, Cancel/Done**: Tasks 2.3, 2.4, 2.5 ✓
+- **Workstream 2, video backdrop via MetalVideoSnapshotProvider with AVAssetImageGenerator fallback**: Task 2.7 ✓
+- **Workstream 2, photo backdrop via UIImage(contentsOfFile:)**: Task 2.7 ✓
+- **Workstream 2, delete `clipCropSheet`, `EditingSheet.crop`, `updateSelectedClipCrop`**: Task 2.6 ✓
+- **Workstream 2, reuse existing `OpenReelProject.Crop` model unchanged**: ✓ (no model task — by design)
+- **Workstream 2, opacity + Fit mode stay in their existing tool paths**: ✓ (Crop editor never references them)
+
+No gaps. Ship it.
diff --git a/docs/superpowers/plans/2026-06-02-desktop-phase3-resolve-editor.md b/docs/superpowers/plans/2026-06-02-desktop-phase3-resolve-editor.md
index 48f2b254..4ae8e5e0 100644
--- a/docs/superpowers/plans/2026-06-02-desktop-phase3-resolve-editor.md
+++ b/docs/superpowers/plans/2026-06-02-desktop-phase3-resolve-editor.md
@@ -1,5 +1,8 @@
# Desktop Phase 3 — Resolve Editor (functional Edit/Color/Deliver) Implementation Plan
+> **Architecture update (2026-07-31):** The cloud GPU render queue referenced in
+> this historical plan has been removed. Deliver/export is local-only.
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make the desktop app a usable, DaVinci-Resolve-style editor: a project-start surface, then Edit (media pool · viewer · timeline · inspector), Color (viewer · scopes · grading), and Deliver (export + render queue) pages — each a bespoke desktop layout that **reuses the existing engine-bound panels** (Preview, Timeline, AssetsPanel, InspectorPanel) and shared stores, themed charcoal/teal.
diff --git a/docs/superpowers/plans/2026-06-18-phase4-headless-agent.md b/docs/superpowers/plans/2026-06-18-phase4-headless-agent.md
index e1dc5abc..71c49fa8 100644
--- a/docs/superpowers/plans/2026-06-18-phase4-headless-agent.md
+++ b/docs/superpowers/plans/2026-06-18-phase4-headless-agent.md
@@ -1,5 +1,9 @@
# Phase 4: Headless / Cloud Agent — Status
+> **Retired path (2026-07-31):** The GPU runner, broker, and remote export path
+> described below were removed. The headless agent now edits project files only;
+> app-hosted exports run locally.
+
**Branch:** `feat/agent-phase0-readiness` · **Status:** ✅ Complete (GPU export E2E needs live infra — noted below)
**Verification:** `@openreel/agent-runner` typecheck clean; 16 runner tests green; `tsup` builds a standalone CLI (227 KB, agent+core submodules bundled, no WebGPU barrel); built `openreel-agent` binary runs (usage + missing-key paths verified).
diff --git a/docs/superpowers/plans/2026-06-27-native-render-engine.md b/docs/superpowers/plans/2026-06-27-native-render-engine.md
index 422d0a07..b8d0323e 100644
--- a/docs/superpowers/plans/2026-06-27-native-render-engine.md
+++ b/docs/superpowers/plans/2026-06-27-native-render-engine.md
@@ -1,5 +1,8 @@
# OpenReel Native Render Engine — Build Plan ("Aurora")
+> **Architecture update (2026-07-31):** Any cloud render-farm/GPU-worker stage in
+> this plan is cancelled. Aurora, if implemented, must run as a local desktop sidecar.
+
> Goal: a Blender-class 3D renderer **built into the OpenReel desktop app** (Electron, macOS-first, Windows next). Months-long, greenfield, native. Codename **Aurora** (placeholder).
>
> Canonical references to keep on the desk: *Physically Based Rendering* (Pharr/Jakob/Humphreys, pbrt), Blender **Cycles** (path tracer) and **EEVEE** (realtime) source, Intel **OIDN**, **OpenColorIO/ACES**, **OpenUSD/Hydra**.
diff --git a/docs/superpowers/specs/2026-05-18-openreel-v2-ecosystem-design.md b/docs/superpowers/specs/2026-05-18-openreel-v2-ecosystem-design.md
index 30d737b3..06d4906a 100644
--- a/docs/superpowers/specs/2026-05-18-openreel-v2-ecosystem-design.md
+++ b/docs/superpowers/specs/2026-05-18-openreel-v2-ecosystem-design.md
@@ -1,5 +1,9 @@
# OpenReel v2 Ecosystem Design
+> **Historical only (retired 2026-07-31):** All cloud-GPU worker, Spot-instance,
+> auth-broker, and token-for-cloud-access proposals in this design are cancelled.
+> Shipping clients use local processing or omit features without a safe local replacement.
+
## Overview
OpenReel v2 transforms the iOS video editor into a full creator platform competing with CapCut. The app remains fully functional offline with on-device AI, enhanced by cloud GPU power, a token-based economy ($ORC on Solana), a creator marketplace, and real-time collaboration.
diff --git a/docs/superpowers/specs/2026-05-22-ios-timeline-fixes-design.md b/docs/superpowers/specs/2026-05-22-ios-timeline-fixes-design.md
new file mode 100644
index 00000000..2b9e4dc2
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-22-ios-timeline-fixes-design.md
@@ -0,0 +1,429 @@
+# iOS Timeline Fixes — Design Spec
+
+**Date:** 2026-05-22
+**Status:** Approved (pending spec review)
+**Scope:** iOS app only (`Openreel Video/Openreel Video/...`). Android parity is **out of scope** for this iteration but should follow once the iOS implementation is settled.
+
+## 1. Problem statement
+
+Users editing on iOS hit five related issues that combine into a "the timeline is hard to use" experience:
+
+1. There is no on-screen zoom control. The pinch gesture works but is undiscoverable and awkward for fine-grained adjustments.
+2. **Splitting a clip black-outs the preview.** After any split (or other edit that produces 2+ video sources), the preview goes dark and the user perceives playback as broken.
+3. Clip movement is purely horizontal — there is no way to move a clip from one track to another, even between tracks of the same media type.
+4. Clips on the same track can overlap freely. This produces silently-corrupt timelines and unintentional blank gaps that users have to clean up manually.
+5. Splitting and moving clips feels slower than it should — long-press timing, lack of visual snap feedback, and the round-trip to the toolbar for split combine into friction.
+
+## 2. Goals & non-goals
+
+**Goals**
+- Always-visible zoom controller in the timeline header, top-right.
+- Preview never goes dark after editing a single clip into multiple clips.
+- Drag a clip between tracks of the same media type.
+- Same-track overlap is impossible; clips snap to the nearest legal position.
+- Visible snap feedback (line + haptic) when clips snap to neighbors.
+- Slightly faster clip-lift on long-press; one-tap split from the selected clip.
+
+**Non-goals**
+- Cross-type clip moves (video → audio, etc.). Same-type only.
+- Ripple-edit / push-neighbors-aside. Snap-to-gap only.
+- Multi-clip selection or group-move.
+- Android parity in this iteration.
+- General performance audit. Only perf wins that fall out naturally from these fixes are in scope.
+
+## 3. User-visible behavior summary
+
+| Interaction | Today | After |
+|---|---|---|
+| Zoom timeline | Pinch only | Pinch **or** `[− 100% +]` chip; long-press percent for presets |
+| Split a clip | Toolbar button at playhead, then preview goes dark | Toolbar button **or** scissors mini-button on selected clip; preview keeps showing the frame at the cut |
+| Drag clip horizontally | Long-press 0.25 s, then horizontal drag; clips can overlap | Long-press 0.18 s, then drag; snaps flush to neighbor edges; cannot overlap |
+| Drag clip to another track | Not possible | Vertical drag in addition to horizontal; allowed only between same-media-type tracks |
+| Snap feedback | Silent | Vertical accent line at snap edge + soft haptic |
+
+## 4. Architecture
+
+Three layers are touched; the changes are coordinated by a single new piece of state-layer logic (the **placement resolver**) that all UI changes call through.
+
+```
+┌────────────────────────────────────────────────────────┐
+│ EditorView.swift │
+│ ┌──────────────────┐ ┌───────────────────────────┐ │
+│ │ TimelineZoomChip │ │ Timeline*ClipBlock │ │
+│ │ (new subview) │ │ - moveGesture (2-D) │ │
+│ └────────┬─────────┘ │ - snap indicator overlay │ │
+│ │ │ - scissors mini-button │ │
+│ │ └────────────┬──────────────┘ │
+└───────────┼──────────────────────────┼─────────────────┘
+ │ writes │ calls
+ ▼ ▼
+┌────────────────────────────────────────────────────────┐
+│ AppState.swift │
+│ - timelineZoom (existing, clamp [20, 300]) │
+│ - resolveClipPlacement(...) (new) │
+│ - moveClip(..., destinationTrackID:) (new overload) │
+└─────────────────────────┬──────────────────────────────┘
+ │ via syncPlayback
+ ▼
+┌────────────────────────────────────────────────────────┐
+│ Playback │
+│ PlaybackCompositionBuilder │
+│ - buildVideoComposition: skip custom compositor │
+│ when no transitions; use layer instructions │
+│ MetalVideoView │
+│ - nudgePausedFrame: nudge by 1 frame (not 1/600s) │
+│ - re-trigger nudge when currentItem changes │
+└────────────────────────────────────────────────────────┘
+```
+
+### 4.1 Why a placement resolver
+
+Today, three concerns are tangled across `moveClip`, `addClip`, and import paths: frame-snapping, edge-snapping, and (missing) collision avoidance. Three different code paths each implement a partial version. Centralizing in `resolveClipPlacement` gives a single source of truth that:
+
+- Every move/import path can call.
+- Is independently unit-testable without spinning up SwiftUI.
+- Is the only place collision-avoidance logic lives.
+
+## 5. Section A — Zoom controller
+
+### 5.1 UI
+
+A new private subview `TimelineZoomChip` rendered in the timeline header overlay, anchored top-right with `padding(.trailing, 12)` and `padding(.top, 6)`. The chip is a `Capsule()` background containing a single `HStack(spacing: 8)`:
+
+```
+┌──────────────────────┐
+│ − 100% + │
+└──────────────────────┘
+```
+
+Each element is a `Button(action:)` with `buttonStyle(.plain)`. Hit targets are 36 × 36 pt.
+
+### 5.2 Behavior
+
+| Action | Effect |
+|---|---|
+| Tap `−` | `appState.timelineZoom = max(20, appState.timelineZoom / 1.5)` |
+| Tap `+` | `appState.timelineZoom = min(300, appState.timelineZoom * 1.5)` |
+| Tap label | `appState.timelineZoom = 48` (= 100 %) |
+| Long-press label | Open a `Menu` with `25%, 50%, 100%, 200%, 400%, Fit` |
+| Pinch (existing) | Unchanged, same `[20, 300]` clamp |
+
+`Fit` computes `appState.timelineZoom = max(20, min(300, trackAreaWidth / max(project.timeline.duration, 1)))`.
+
+The displayed percentage is `Int(round(appState.timelineZoom / 48 * 100))`.
+
+### 5.3 Animation
+
+Chip step changes are wrapped in `withAnimation(.spring(response: 0.25, dampingFraction: 0.85))` so the timeline glides between discrete zoom levels. Pinch is left raw (no animation wrapper) to keep the gesture's continuous feel.
+
+### 5.4 Files touched
+
+- `EditorView.swift`: new `TimelineZoomChip` private struct; chip is inserted into the `timeline(for:)` view's `overlay(alignment: .topTrailing) { ... }`.
+
+## 6. Section B — Fix dark preview after split
+
+### 6.1 Root cause
+
+After a split, the project goes from 1 → 2+ video sources. `PlaybackCompositionBuilder.build`:
+
+1. Always creates two video tracks (`trackA`, `trackB`).
+2. Inserts clips alternating: clip[0] → A, clip[1] → B, clip[2] → A, ...
+3. When `sources.count >= 2`, calls `buildVideoComposition` which sets `customVideoCompositorClass = TransitionVideoCompositor.self`.
+
+`AVPlayer` then routes all rendering through the custom compositor. The compositor only produces output when AVPlayer requests a render. On install, `MetalVideoView.nudgePausedFrame` tries to force a render by `seek(by: CMTime(value: 1, timescale: 600))` with `tolerance: .zero` — i.e., **~1.67 ms**, smaller than one frame at 30 fps (~33 ms). With zero tolerance AVPlayer rounds to the same frame, the compositor is not re-invoked, `AVPlayerItemVideoOutput.copyPixelBuffer` returns nil, `lastFrame` stays nil, Metal clears to black.
+
+Secondary issue: the custom compositor is also used when there are zero transitions, adding a code path with no benefit for the common case.
+
+### 6.2 Fix B1 — Skip custom compositor when there are no transitions
+
+In `PlaybackCompositionBuilder.buildVideoComposition`:
+
+```swift
+// Pseudocode of the new branch
+if transitions.isEmpty {
+ let videoComposition = AVMutableVideoComposition()
+ videoComposition.instructions = buildPassthroughInstructions(
+ sources: sources,
+ clipTrackMap: clipTrackMap,
+ videoTracks: videoTracks
+ )
+ videoComposition.renderSize = resolvedRenderSize
+ videoComposition.frameDuration = CMTime(value: 1, timescale: CMTimeScale(max(frameRate.rounded(), 1)))
+ // Note: no customVideoCompositorClass — AVPlayer's built-in compositor handles passthrough
+ return videoComposition
+}
+// existing custom-compositor path for the transitions != [] case
+```
+
+`buildPassthroughInstructions(...)` produces one `AVMutableVideoCompositionInstruction` per time segment with two `AVMutableVideoCompositionLayerInstruction`s (one per video track), where the active track has `setOpacity(1, at: segment.start)` and the inactive track has `setOpacity(0, at: segment.start)`.
+
+The active layer's transform is set via `setTransform(_:at:)` to a `CGAffineTransform` that (a) orients the source frame using the asset track's `preferredTransform`, then (b) aspect-fits the result into `renderSize` — i.e., the same fit math currently in `TransitionVideoCompositor.fitTransform`, lifted into a `CGAffineTransform`. The inactive layer gets `.identity` (it's at opacity 0, the transform is irrelevant but must not be missing). The composition's per-track `preferredTransform` (set on the composition track at insert time) is still set as before, so seeking is correct even before the first layer instruction's time.
+
+This is the change that eliminates the dark-preview symptom for the overwhelming majority of edits, because the most common case after splitting a single clip is exactly this: 2+ video sources, 0 transitions.
+
+### 6.3 Fix B2 — Reliable paused-frame nudge
+
+In `MetalVideoView.forceCompositorRefresh`:
+
+```swift
+private func forceCompositorRefresh(on item: AVPlayerItem) {
+ guard let player = currentPlayer, player.currentItem === item else { return }
+ let resolvedFrameRate = max(frameRate, 1)
+ let frameDuration = CMTime(value: 1, timescale: CMTimeScale(resolvedFrameRate.rounded()))
+ let currentTime = player.currentTime()
+ let nudgedTime = CMTimeAdd(currentTime, frameDuration)
+
+ player.seek(to: nudgedTime, toleranceBefore: .zero, toleranceAfter: .zero) { [weak self, weak player] _ in
+ Task { @MainActor [weak self, weak player] in
+ guard let self, let player else { return }
+ player.seek(to: currentTime, toleranceBefore: .zero, toleranceAfter: .zero)
+ self.pumpFrameUntilDelivered(remainingAttempts: 3)
+ }
+ }
+}
+
+private func pumpFrameUntilDelivered(remainingAttempts: Int) {
+ metalView.draw()
+ guard remainingAttempts > 0, lastFrame == nil else { return }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.033) { [weak self] in
+ guard let self else { return }
+ self.pumpFrameUntilDelivered(remainingAttempts: remainingAttempts - 1)
+ }
+}
+```
+
+Three attempts × 33 ms = ~100 ms upper bound. Cheap on idle, decisive when the compositor is slow to warm up.
+
+Additionally, in `setPlayer` add a KVO subscription on `player.currentItem` and call `installVideoOutput()` again on change. This defends against any future code path that swaps the AVPlayerItem inside the same AVPlayer instance.
+
+### 6.4 Files touched
+
+- `Core/Playback/PlaybackCompositionBuilder.swift`: branch in `buildVideoComposition`, new helper `buildPassthroughInstructions(...)`.
+- `Features/Preview/MetalVideoView.swift`: `forceCompositorRefresh`, new `pumpFrameUntilDelivered`, KVO on `currentItem`.
+
+## 7. Section C — Placement resolver: snap + no overlap
+
+### 7.1 API
+
+```swift
+extension AppState {
+ struct PlacementResolution {
+ let start: TimeInterval
+ let trackID: String
+ let didSnap: Bool
+ }
+
+ func resolveClipPlacement(
+ clipID: String,
+ proposedStart: TimeInterval,
+ destinationTrackID: String,
+ in project: OpenReelProject
+ ) -> PlacementResolution?
+}
+```
+
+Returns `nil` only when the destination has zero room (clip duration > any gap on that track). Callers fall back to the source position on `nil`.
+
+### 7.2 Algorithm
+
+1. Look up the moving clip's `duration`. If not found → return `nil`.
+2. Compute `frameSnapped = snappedTimelineTime(proposedStart, frameRate: ...)`.
+3. **Edge snap**: collect snap edges (clip starts/ends on **all** tracks, plus text/graphics edges, plus `0`). Threshold = `max(0.05, 8 / max(timelineZoom, 1))` — so snap is generous when zoomed out, precise when zoomed in. If any edge is within threshold of `frameSnapped` *or* `frameSnapped + duration`, snap to it.
+4. **Collision resolution** on `destinationTrackID` only (exclude the moving clip itself):
+ - Build a sorted list `neighbors = [(start, end)]` of every other clip on the destination track, sorted by `start`.
+ - If `[start, start + duration]` does not overlap any neighbor → return `(start, destinationTrackID, didSnap = edge-snap-fired)`.
+ - Otherwise, build candidate positions = the set `{ 0 } ∪ { n.end for n in neighbors } ∪ { n.start − duration for n in neighbors }`, dropping any candidate where `candidate < 0` or `candidate + duration` overlaps any neighbor (computed once against the sorted list — `O(N log N)`).
+ - Sort candidates by `|candidate − frameSnappedProposedStart|` ascending. Take the first.
+ - If the candidate set is empty → return `nil` (no gap on the destination is large enough for this clip's duration).
+ - `didSnap = true` in this branch by definition.
+
+Candidates are derived once from the static neighbor list, so the iteration cap mentioned in earlier drafts is unnecessary — there is no loop. Complexity is `O(N log N)` in clips on the destination track.
+
+### 7.3 Linked-audio coupling
+
+The existing `linkedClipLocations(for:in:)` returns the linked audio sibling for a video clip. When the user moves a video clip:
+
+1. Resolve placement for the video clip → `videoResolution`. If `nil` → abort, snap back.
+2. Compute `actualDelta = videoResolution.start − originalVideoStart`.
+3. For each linked sibling, call the resolver with:
+ - `proposedStart = sibling.startTime + actualDelta`
+ - `destinationTrackID = sibling.trackId` (linked audio stays on its current audio track; the user is moving the video, not the audio)
+4. If any sibling resolution returns `nil` or returns a `start` different from `sibling.startTime + actualDelta`, **abort the entire move** — restore the original project state, no clips moved, no haptic.
+5. Otherwise commit all moves in one `commitEditedProject(...)` call so the change is a single undo step.
+
+The "or returns a different start" check is the key: we never silently let the linked audio land somewhere other than the exact mirror of the video move. Audio either moves in lockstep with video, or no one moves.
+
+### 7.4 Visual feedback
+
+`TimelineClipBlock` (and the three sibling block types) gain `@State private var snapEdgeX: CGFloat? = nil`. When the live drag passes through a snap-edge proximity, `snapEdgeX` is set to that edge's pixel x for 200 ms (cleared by a `DispatchWorkItem` cancellation token). Render:
+
+```swift
+.overlay(alignment: .leading) {
+ if let snapEdgeX {
+ Rectangle()
+ .fill(OpenReelTheme.accent)
+ .frame(width: 1, height: laneHeight + 8)
+ .offset(x: snapEdgeX - currentLeadingOffset)
+ .opacity(0.9)
+ .animation(.easeOut(duration: 0.15), value: snapEdgeX)
+ }
+}
+```
+
+A `UIImpactFeedbackGenerator(style: .soft)` fires on the rising edge of `snapEdgeX != nil`.
+
+### 7.5 Files touched
+
+- `AppState.swift`: new `PlacementResolution`, `resolveClipPlacement`, modified `moveClip(...)` to call it.
+- `EditorView.swift`: per-block `snapEdgeX` overlay; haptic on snap.
+
+## 8. Section D — Cross-track movement
+
+### 8.1 Gesture extension
+
+The shared move-gesture helper is extracted from the four block types:
+
+```swift
+@MainActor
+private func makeMoveGesture(
+ pixelsPerSecond: Double,
+ laneHeight: CGFloat,
+ rowSpacing: CGFloat,
+ onTranslate: @escaping (CGSize) -> Void,
+ onCommit: @escaping (TimeInterval, Int) -> Void
+) -> some Gesture {
+ LongPressGesture(minimumDuration: 0.18)
+ .sequenced(before: DragGesture(minimumDistance: 1))
+ .onChanged { value in
+ if case .second(true, let drag?) = value {
+ onTranslate(drag.translation)
+ }
+ }
+ .onEnded { value in
+ guard case .second(true, let drag?) = value else { return }
+ let timeDelta = drag.translation.width / max(pixelsPerSecond, 1)
+ let trackDelta = Int(round(drag.translation.height / (laneHeight + rowSpacing)))
+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+ onCommit(timeDelta, trackDelta)
+ }
+}
+```
+
+Each block type's `moveGesture` becomes a thin wrapper that supplies its own `pixelsPerSecond`/`laneHeight` and routes `(timeDelta, trackDelta)` to a corresponding AppState method.
+
+### 8.2 Destination resolution
+
+Caller computes the destination track:
+
+```swift
+func destinationTrack(
+ for clip: OpenReelProject.Clip,
+ trackDelta: Int,
+ in project: OpenReelProject
+) -> String? {
+ guard let sourceTrack = project.timeline.tracks.first(where: { $0.id == clip.trackId }) else { return nil }
+ let candidates = project.timeline.tracks
+ .filter { $0.type == sourceTrack.type }
+ .sorted { sortIndex(for: $0, in: project) < sortIndex(for: $1, in: project) }
+ guard let sourceIndex = candidates.firstIndex(where: { $0.id == sourceTrack.id }) else { return nil }
+ let targetIndex = max(0, min(candidates.count - 1, sourceIndex + trackDelta))
+ return candidates[targetIndex].id
+}
+```
+
+Same-type only. Cross-type drags are silently clamped to the source track (no track switch), so the move degrades to a horizontal move.
+
+### 8.3 Live drag visuals
+
+During an active drag:
+- The clip block applies `offset(x: dragWidth, y: dragHeight)` so the user sees the clip follow their finger between rows.
+- `.zIndex(isDragging ? 10 : 0)` so the dragged clip renders above siblings.
+- `.scaleEffect(isDragging ? 1.04 : 1.0)` plus a `shadow(radius: isDragging ? 12 : 0)` for a clear "lifted" affordance.
+- On commit, `offset` resets to `0` in the same animation transaction that commits the new project state, so the clip slides into its resolved position rather than teleporting.
+
+### 8.4 Files touched
+
+- `EditorView.swift`: extract `makeMoveGesture`; apply in all 4 block types; live drag visuals.
+- `AppState.swift`: `moveClip(clipID:, by:, destinationTrackID:)` overload that calls `resolveClipPlacement`; helper `destinationTrack(...)`.
+
+## 9. Section E — Easier split & move polish
+
+These are intentionally small, ride on top of the above sections, and can be removed without breaking anything else:
+
+1. **Long-press activation 0.25 s → 0.18 s** — already in Section D's gesture helper.
+2. **Lifted-state visuals** — `scaleEffect(1.04)` + shadow during drag (Section D.3).
+3. **Scissors mini-button on selected clip**: render a small button above the clip block when **all three** of these hold:
+ - the clip is selected (`isSelected == true`),
+ - the rendered clip width is > 80 pt (avoids visual clutter on tiny clips at low zoom),
+ - the current `playbackController.currentTime` falls strictly inside `(clip.startTime, clip.startTime + clip.duration)` (so the split would actually do something — matches the precondition in `splitSelectedClip`).
+ Tapping it calls the same `splitSelectedClip(at: playbackController.currentTime, ...)` path the toolbar uses. Hit target 32 × 32 pt, accent color.
+4. **Post-split playhead seek**: after `splitSelectedClip` commits, seek the playhead to the split point so it sits right at the cut. Implementation: pass the resolved `splitTime` back out of `splitSelectedClip` and have the caller (or a small AppState helper) call `playbackController.seek(to: splitTime)`.
+
+## 10. Data model changes
+
+**None.** All five sections operate on the existing `OpenReelProject` schema. No new fields on `Clip`, `Track`, `Transition`, or `TimelineSettings`. No migration concerns.
+
+## 11. Backwards compatibility
+
+- Existing projects open and play identically.
+- The custom-compositor path is preserved for projects with transitions, so transition rendering is unchanged.
+- `appState.timelineZoom` is unchanged; chip and pinch are coordinated views on the same value.
+- `moveClip(clipID:by:playbackController:)` (the existing single-argument form) is preserved as a thin wrapper that calls the new overload with `destinationTrackID = clip's current trackId`.
+
+## 12. Testing
+
+### 12.1 Unit tests (Swift Testing, `Openreel VideoTests`)
+
+`PlaybackCompositionBuilderTests`:
+- 2 sources, 0 transitions → returned `videoComposition` has `customVideoCompositorClass == nil`.
+- 2 sources, 1 transition → returned `videoComposition` has `customVideoCompositorClass == TransitionVideoCompositor.self`.
+- 1 source → no `videoComposition` returned (unchanged behavior).
+
+`PlacementResolverTests`:
+- No conflict on destination track → returns `proposedStart` (frame-snapped).
+- Single neighbor to the left → snaps to its end when proposed range overlaps.
+- Single neighbor to the right → snaps to `neighbor.start - duration`.
+- Sandwiched (no room between two neighbors) → returns `nil`.
+- Wrong-type destination track → caller never calls resolver with it; not a resolver concern, covered by destinationTrack unit test.
+- Edge-snap kicks in within threshold; not beyond it.
+
+`DestinationTrackTests`:
+- Cross-type clamps to source track.
+- Out-of-range delta clamps to first/last same-type track.
+
+### 12.2 Manual test plan (in PR body)
+
+1. Add one video → split at playhead → press play. **Expect:** video plays, no dark preview.
+2. Add two videos → drag the second next to the first → release with proposed range overlapping. **Expect:** snaps flush against the first clip's trailing edge.
+3. With two video tracks, drag a clip from track 1 down to track 2. **Expect:** clip moves between tracks. Drag it back up. **Expect:** returns to track 1.
+4. Try to drag a video clip onto an audio track. **Expect:** no track switch occurs (clamps to source).
+5. Pinch to zoom in → chip reads correct percentage. Tap chip's `100%` → returns to default. Long-press `100%` → preset menu opens.
+6. Add many clips → confirm scroll + zoom remain smooth.
+
+## 13. Risks & mitigations
+
+| Risk | Likelihood | Mitigation |
+|---|---|---|
+| The "skip custom compositor" branch in B1 changes how transitions interact with passthrough segments | Low — branch is only taken when `transitions.isEmpty` | Backstop unit test asserts the branch boundary |
+| Cross-track drag accidentally fires on small finger jitter | Medium — users may drag horizontally and pick up tiny vertical noise | `trackDelta` uses `round(dy / (laneHeight + spacing))` — needs ≥ half a row of vertical motion to register as a row change |
+| Placement resolver loops indefinitely | Low | 8-iteration cap; falls through to `nil` (caller snaps back to source) |
+| Linked audio refuses moves a user expected to work | Medium | Snap-back visual is clear; resolver returns `didSnap=false` and we render a brief "no room" indicator (sub-200 ms red tint on the linked audio block) |
+| Scissors mini-button overlaps trim handles on narrow clips | Low | Only shown when clip width > 80 pt (Section E.3) |
+
+## 14. Out of scope, but called out
+
+- **Performance audit** of the editor as a whole. `EditorView.swift` (5538 lines) and `AppState.swift` (5260 lines) would both benefit from decomposition, and the AsyncImage-per-thumbnail pattern is a likely hotspot when zoomed in. These are tracked separately.
+- **Android parity** for these features. Once the iOS implementation is stable, the Android Compose timeline should follow the same UX (chip, snap, cross-track move, no overlap). See `Openreel Video Android/.../ui/editor/Timeline.kt`.
+- **Multi-clip selection and group-drag.** Useful follow-up but not part of this iteration.
+- **Ripple-edit mode.** Considered and rejected in favor of snap-to-gap; can be re-added behind a toggle later if users ask for it.
+
+## 15. Implementation order (recommended for the plan)
+
+1. **B1 + B2 first** — preview fix is the most user-visible. Standalone, doesn't depend on resolver work. Shipping this alone would already improve the app.
+2. **Zoom chip (Section A)** — tiny, low-risk, gives users instant visible feedback that we're shipping fixes.
+3. **Placement resolver + tests (Section C, state layer only)** — fully unit-testable without UI.
+4. **Snap visuals + same-track collision wired up via resolver** — Section C UI half.
+5. **Cross-track gesture extension (Section D)** — depends on resolver.
+6. **Polish (Section E)** — last, since it's lightest-touch.
+
+Each step can ship independently; the plan should treat them as separate commits.
diff --git a/docs/superpowers/specs/2026-05-28-android-trim-and-crop-parity-design.md b/docs/superpowers/specs/2026-05-28-android-trim-and-crop-parity-design.md
new file mode 100644
index 00000000..5c73d75a
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-28-android-trim-and-crop-parity-design.md
@@ -0,0 +1,193 @@
+# Android Trim + Crop Parity — Design Spec
+
+**Date:** 2026-05-28
+**Status:** Pending spec review
+**Scope:** Android app only (`Openreel Video Android/...`). iOS counterpart shipped on the same day under `docs/superpowers/specs/2026-05-28-ios-trim-and-crop-design.md`.
+
+## 1. Problem statement
+
+Two related sets of issues bring Android behind the freshly-shipped iOS experience:
+
+1. **Trim quality + feature gaps.** Video clips only support trailing-edge trim (no leading-edge); audio clips have decorative trim handles with no gesture; every drag event mutates the project state, producing a fresh undo entry per frame; there's no snap feedback. The trim drags feel jittery and litter the undo stack.
+2. **Crop editor has feature gaps vs iOS.** Android's `CropResizeScreen` is sophisticated (8 handles, aspect-ratio strip, rotation slider, position scrubber, rule-of-thirds grid, outside-dim) — but it's missing four things iOS now has: aspect-ratio LOCK during handle drags (Android only snaps on tap), Flip H / Flip V, Fit mode chips (Contain / Cover / Stretch / None), and pinch-to-zoom with centroid stability on the media backdrop.
+
+## 2. Goals & non-goals
+
+**Goals**
+
+- All trim drags use snapshot-based drag math: capture initial duration on `onDragStart`, accumulate the cumulative delta locally, commit ONCE on `onDragEnd`. Result: a single undo entry per drag, no per-frame state churn.
+- Video clips gain a leading-edge trim handle that adjusts `startTime + inPoint` (in addition to the existing trailing handle).
+- Audio clips gain both leading + trailing trim gestures (handles are currently decorative).
+- Snap-to-neighbor edges produces a visible indicator and a light haptic; matches the iOS pattern.
+- `CropResizeScreen` gains aspect-lock-during-drag, Flip H/V row, Fit chips row, and pinch-to-zoom (1x–6x) with centroid stability.
+- Android keeps its existing rotation slider and position scrubber — iOS does not have these, and removing them would be a regression for Android users.
+
+**Non-goals**
+
+- Adding rotation or position scrubber to iOS (different spec).
+- Refactoring the Android editor screen layout. Touch only the affected components.
+- Migrating the existing trim/crop tests or adding new instrumentation tests. The existing test suite stays green; manual smoke covers the gesture changes.
+- Cross-platform timeline-correctness work — this is purely a UX polish + feature-parity pass.
+- Audio crop or audio waveform editing in this iteration.
+
+## 3. User-visible behavior summary
+
+| Interaction | Today | After |
+|---|---|---|
+| Drag trailing trim handle on video clip | Mutates clip every frame → 20+ undo entries per drag | Snapshot-based: single undo entry, smooth motion |
+| Drag leading edge of video clip | Not possible (no gesture wired) | Drag handle appears at left edge; updates `startTime + inPoint` |
+| Drag any trim handle on an audio clip | Visual handle but no response | Functional like video clips: leading + trailing trim with snapshot drag |
+| Snap to neighbor edge while trimming | Silent | Vertical accent line at snap edge + soft haptic |
+| Tap aspect chip in CropResizeScreen | Snaps crop to that ratio | Same — also locks subsequent handle drags to that ratio (tap "Custom" to unlock) |
+| Flip H / Flip V in CropResizeScreen | Not available in this screen | New action chips next to Reset |
+| Fit mode (Contain/Cover/Stretch/None) | Not exposed in CropResizeScreen | New chip row above Aspect ratio strip |
+| Pinch on the crop preview backdrop | No-op | Zooms backdrop 1x–6x; the pinched point stays under the user's fingers (centroid stable) |
+| Rotation slider, position scrubber | Already present | Unchanged |
+
+## 4. Workstream A — Android trim polish
+
+### 4.1 Snapshot-based drag pattern
+
+Today's pattern (every clip type that has trim):
+
+```kotlin
+.pointerInput(clip.id, pixelsPerSecond) {
+ detectDragGestures { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ onTrimEnd(clip, (deltaDp / pixelsPerSecond).toDouble())
+ }
+}
+```
+
+`dragAmount` is per-event, so each event calls `onTrimEnd` with a small partial delta. `onTrimEnd` mutates the clip immediately, producing one undo step per event and recomposing on every frame.
+
+After:
+
+```kotlin
+.pointerInput(clip.id, pixelsPerSecond) {
+ var accumulatedDp = 0f
+ detectDragGestures(
+ onDragStart = { accumulatedDp = 0f; onTrimDragStart() },
+ onDragEnd = {
+ val seconds = (accumulatedDp / pixelsPerSecond).toDouble()
+ if (kotlin.math.abs(seconds) > 0.001) onTrimEndCommit(clip, seconds)
+ onTrimDragEnd()
+ },
+ onDragCancel = { onTrimDragEnd() },
+ ) { _, dragAmount ->
+ val deltaDp = with(density) { dragAmount.x.toDp().value }
+ accumulatedDp += deltaDp
+ onTrimPreview(clip, (accumulatedDp / pixelsPerSecond).toDouble())
+ }
+}
+```
+
+- `onTrimPreview(clip, seconds)` updates LOCAL state — purely visual. No `appState.mutateClip` call.
+- `onTrimEndCommit(clip, seconds)` is the existing `onTrimEnd` semantic, called ONCE on release.
+- `onTrimDragStart / End` flip an `isDraggingTimelineItem` flag so the parent suppresses unrelated gestures while a trim is in progress (same flag already used by `onDragInteraction`).
+
+The local preview state lives in the clip block. The clip block already gets `clip` re-passed when state mutates; during a drag, parent state is stable (no `mutateClip` calls) so the local `accumulatedDp` is the only thing changing. The block renders its width as `(clip.duration + accumulatedDp/pixelsPerSecond) * pixelsPerSecond`. On release, the commit happens and `accumulatedDp` resets via the `key` change on `pointerInput(clip.id, pixelsPerSecond)`.
+
+### 4.2 Leading-edge trim on video clips
+
+Today's video clip in `Timeline.kt` line 1018 renders the leading `TrimHandle` decoratively. After: wrap it in a `Box` with `.pointerInput { detectDragGestures(...) }` mirroring the trailing handle's wrapper, but emitting `onTrimStart(clip, delta)` (analogous to existing graphics/text overlay `onTrimStart` callbacks).
+
+A new `appState.trimVideoClipStart(trackId, clipId, deltaSeconds)` operation:
+- Reduces `clip.startTime` by `delta` while increasing `clip.inPoint` by `delta` (keep source frame the user sees).
+- Clamps so `startTime ≥ 0` and `duration ≥ 0.05`.
+
+While the leading handle is dragged, the clip's left edge visually follows the finger via the same snapshot-based pattern: local `accumulatedDp` shifts the visual `xOffset` and shrinks the visual width.
+
+### 4.3 Audio clip trim
+
+`AudioTrackLane` in `Timeline.kt` line 1132 currently has the same `TrimHandle` visuals but no gestures. Wrap each in a Box with the snapshot-drag pattern, emitting `onTrimStart` and `onTrimEnd` callbacks on `AudioTrackLane`.
+
+New `appState.trimAudioClipStart` / `appState.trimAudioClipEnd` operations that mutate the audio clip's start/duration (same shape as video's trim methods).
+
+### 4.4 Snap indicator + haptic
+
+The existing `appState.snapEdit(seconds)` returns a possibly-snapped time. During a trim drag's `onDragEnd` (commit), if the snapped value differs from the proposed value by more than 1ms, we already snap — but the user has no signal.
+
+Add to the snapshot drag's `onDragEnd`:
+- After computing `final = appState.snapEdit(...)`, compare against the raw target; if snapped, emit a soft haptic via the existing `rememberHaptics().perform(HapticEvent.Light)`.
+
+A visual snap line (1dp vertical accent strip at the snap x-coordinate) during the drag — show via local state when the in-progress accumulated delta would land within the snap window. This requires calling `snapEdit` continuously during the drag without committing it. Render the indicator as an overlay in the parent track lane.
+
+### 4.5 Text + graphics + adjustment trim
+
+These already have leading + trailing trim via `onTrimStart` / `onTrimEnd`, but they use the same per-event commit pattern. Convert each to snapshot-based drag (steps 4.1) so they get the single-undo-step + snap haptic benefits.
+
+## 5. Workstream B — Crop editor parity
+
+### 5.1 Aspect-ratio LOCK during drag
+
+Today's `CropResizeScreen` lets the user tap "9:16" → crop frame snaps to 9:16 once. Subsequent corner/edge drags use `resizeCrop(...)` which does NOT preserve the ratio.
+
+Add:
+- `var lockedAspect by remember(clip.id) { mutableStateOf<Float?>(null) }` next to `draftCrop`.
+- When the user taps an aspect option, set `lockedAspect = opt.ratio` (or `null` for Custom). Existing snap math stays.
+- `resizeCrop(crop, handle, dx, dy)` (line 555) gains an optional `lockedAspect: Float?` parameter. When non-null:
+ - For corner handles: compute the dominant axis (width-driven), set the other axis from `width = height * lockedAspect`, then re-anchor so the opposite corner stays in place.
+ - For mid-edge handles: derive the perpendicular axis from the dragged axis to maintain the ratio, centered on the perpendicular midpoint.
+
+Math is the same as iOS's `CropFrameGeometry.resize(..., lockedAspect:)` (the iOS implementation is the reference).
+
+### 5.2 Flip H / Flip V chips
+
+`OpenReelProject.Transform` already has `flipHorizontal: Boolean` and `flipVertical: Boolean` (per Android's existing model). Add two `@Composable` action chips to the body of `CropResizeScreen`, between the Aspect ratio section and the Reset button. Tapping toggles a local `draftFlipH` / `draftFlipV`. On Apply (the existing `onApply` callback), if changed, persist via `appState.mutateClip(...) { it.copy(transform = it.transform.copy(flipHorizontal = draftFlipH, flipVertical = draftFlipV)) }`.
+
+The flip transform is applied to the `CropPreview`'s backdrop via `Modifier.graphicsLayer { scaleX = if (draftFlipH) -1f else 1f; scaleY = if (draftFlipV) -1f else 1f }` on the existing backdrop Box.
+
+### 5.3 Fit mode chips
+
+`OpenReelProject.Transform.fitMode: FitMode?` already exists. Add a chip row above the Aspect ratio strip: four chips for Contain / Cover / Stretch / None. Local `draftFitMode` initialized from `clip.transform.fitMode ?: FitMode.Contain`. On Apply, if changed, persist via `appState.mutateClip(...) { it.copy(transform = it.transform.copy(fitMode = draftFitMode)) }`.
+
+Reset clears `draftFitMode = FitMode.Contain` (matches iOS default behavior).
+
+### 5.4 Pinch-to-zoom with centroid
+
+`CropPreview`'s backdrop (the `AndroidView`/`AsyncImage` inside the rotated `graphicsLayer` Box) gains a pinch gesture using Compose's `Modifier.pointerInput { detectTransformGestures { centroid, pan, zoom, rotation -> ... } }` — but we ignore `rotation` and `pan` and use `centroid` + `zoom`.
+
+Local state:
+- `var mediaScale by remember(clip.id) { mutableFloatStateOf(1f) }`
+- `var mediaOffset by remember(clip.id) { mutableStateOf(Offset.Zero) }`
+- `var pinchStartScale by remember(clip.id) { mutableFloatStateOf(1f) }`
+- `var pinchStartOffset by remember(clip.id) { mutableStateOf(Offset.Zero) }`
+- `var pinchStartCentroid by remember(clip.id) { mutableStateOf<Offset?>(null) }`
+
+On gesture begin (first `detectTransformGestures` callback after a lift): capture pinchStartScale = mediaScale, pinchStartOffset = mediaOffset, pinchStartCentroid = centroid.
+
+Each frame:
+- `newScale = (pinchStartScale * accumulatedZoomFromStart).coerceIn(1f, 6f)`
+- `dV = pinchStartCentroid - viewCenter`
+- `m = newScale / pinchStartScale`
+- `mediaOffset = dV * (1 - m) + pinchStartOffset * m`
+
+Apply both: `Modifier.graphicsLayer { scaleX = ... * mediaScale; scaleY = ... * mediaScale; translationX = mediaOffset.x; translationY = mediaOffset.y }` on the backdrop only.
+
+Reset also resets `mediaScale = 1f` and `mediaOffset = Offset.Zero`.
+
+NOTE: `detectTransformGestures` doesn't give us a clean "gesture start" signal — we synthesize one by detecting that `pinchStartCentroid` is null and the user just started pinching (zoom != 1f or pan != Offset.Zero). On `onTouchEvent` lift / `awaitEachGesture` completion the centroid is cleared. Simpler alternative: use `awaitEachGesture { awaitFirstDown(); ...loop detectTransformGestures inline... }` to scope the gesture explicitly. Both work; pick whichever is cleaner to wire.
+
+## 6. Testing
+
+**Trim:**
+- Manual: each clip type × each edge (leading + trailing) × confirm: smooth follow-the-finger, single undo entry per drag, snap haptic on neighbor edges, visible snap line.
+- No new unit tests; the AppState mutation paths (`mutateClip`, `trimGraphicsOverlay*`, `resizeTextOverlay`, the new `trimVideoClipStart`, `trimAudioClipStart/End`) are simple wrappers around existing patterns.
+
+**Crop:**
+- Manual: open Crop for a photo + a video. Tap each aspect chip → frame snaps. Drag handles after locking → ratio preserved. Tap Flip H / Flip V → backdrop mirrors. Tap each Fit chip → state updates. Pinch on backdrop → zooms 1x–6x, pinch point stays anchored. Reset → all draft state restores to defaults; backdrop back to 1x, no flip, no fit.
+- No new unit tests; the locked-aspect math mirrors iOS `CropFrameGeometry.resize(..., lockedAspect:)` which is unit-tested on iOS. Port to Android only if instrumented coverage gains warrant it (not in this iteration).
+
+**Build:** `./gradlew assembleDebug` and `./gradlew testDebugUnitTest` must stay green.
+
+## 7. Open questions
+
+None — the iOS spec resolves the design decisions; this is translation.
+
+## 8. Implementation order
+
+1. **Workstream A first (trim polish)** — 5 tasks. Each task adds the snapshot drag pattern to one clip type (video trailing first to establish the pattern, then video leading, audio, then text/graphics/adjustment polish). Snap indicator + haptic last.
+2. **Workstream B second (crop parity)** — 4 tasks: aspect-lock, flip, fit, pinch.
+
+Each ships as a separate commit. Manual smoke after each workstream.
diff --git a/docs/superpowers/specs/2026-05-28-ios-trim-and-crop-design.md b/docs/superpowers/specs/2026-05-28-ios-trim-and-crop-design.md
new file mode 100644
index 00000000..51615167
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-28-ios-trim-and-crop-design.md
@@ -0,0 +1,250 @@
+# iOS Timeline Trim Flicker + Full-Screen Crop Editor — Design Spec
+
+**Date:** 2026-05-28
+**Status:** Pending spec review
+**Scope:** iOS app only (`Openreel Video/Openreel Video/...`). Android parity is out of scope for this iteration.
+
+## 1. Problem statement
+
+Two unrelated but co-located issues degrade the iOS editing experience:
+
+1. **Timeline trim handles flicker/jump horizontally during drag.** When the user drags either edge of a clip on the timeline to adjust duration, the clip visibly jitters or jumps sideways. This happens for video, audio, text, and graphics clips — all four block types share the same broken gesture stack.
+2. **Photo cropping uses a weak slider-based bottom sheet.** Tapping the "Crop" tool opens `clipCropSheet` (a 420 pt sheet with Left/Top/Width/Height sliders). Sliders are the wrong control for spatial cropping — users can't see the result interactively and have no direct manipulation. This affects both photo and video cropping today; the user asked specifically for a screen-based experience.
+
+## 2. Goals & non-goals
+
+**Goals**
+
+- Trim drag on every timeline clip type tracks the user's finger smoothly with no horizontal jitter, no mid-drag jumps, and no one-frame pop on release.
+- The leading trim handle visually follows the finger (clip's left edge moves with the drag), matching iMovie / Final Cut / CapCut conventions.
+- A new full-screen Crop editor is the entry point for the "Crop" tool, for both photos and videos.
+- The Crop editor supports direct manipulation: draggable corner + edge handles, pan inside the frame, pinch to zoom, aspect-ratio presets, flip H/V, reset.
+- Existing crop data model (`OpenReelProject.Crop` — normalized 0..1 coordinates) is reused unchanged.
+
+**Non-goals**
+
+- Rotation. No rotate-by-degrees control, no 90° quick rotation buttons. (Can be added later; explicitly out of scope here.)
+- AI auto-reframe. The "Auto reframe" tool already exists separately and is not folded in.
+- Per-frame scrubbing inside the Crop editor for videos. The editor uses the current playhead frame as the backdrop; users scrub from the timeline.
+- A trim "mode" with enlarged handles or a source-frame scrubber. Trim stays as inline edge drag; only the flicker bugs are fixed.
+- Android parity. iOS only this iteration.
+- Refactoring `EditorView.swift` (6600 lines). Touch only the affected sections.
+
+## 3. User-visible behavior summary
+
+| Interaction | Today | After |
+|---|---|---|
+| Drag right edge of clip | Jitters; sometimes whole clip pops sideways if finger pauses | Smooth; trailing edge follows finger; no pop on release |
+| Drag left edge of clip | Left edge stays put; clip shrinks from the right; reads as broken | Left edge follows finger; trailing edge stays put |
+| Release after trim | Brief flash to original width before snapping to new width | Single frame: new width is shown immediately |
+| Tap "Crop" tool | 420 pt bottom sheet with 4 sliders + Fit/Flip/Opacity | Full-screen editor with live preview, drag handles, aspect presets, flip, reset |
+| Crop a photo | Same sheet as video (sliders) | Same full-screen editor as video |
+| Adjust opacity / fit mode | In the crop sheet | Stays in the existing transform UI path (see §5.2) — not folded into the new Crop screen |
+
+## 4. Workstream 1 — Timeline trim flicker fix
+
+### 4.1 Root causes (verified by reading `EditorView.swift`)
+
+The same three problems exist in all four clip-block structs: `TimelineClipBlock` (line 5485), `TimelineAudioClipBlock` (5816), `TimelineTextClipBlock` (5986), `TimelineGraphicsClipBlock` (6193).
+
+**Cause A — `simultaneousGesture(moveGesture)` fires alongside the trim handle's drag.** The move gesture is `LongPressGesture(minimumDuration: 0.18).sequenced(before: DragGesture(minimumDistance: 1))`. While the trim handle has its own `DragGesture(minimumDistance: 1)` and starts immediately, if the user's finger pauses for 0.18 s mid-trim, the long press completes, the sequenced drag activates, `moveTranslation` starts updating, and the entire clip body is offset by `.offset(x: moveTranslation, ...)`. The visible result is a sudden horizontal jump.
+
+**Cause B — Leading edge is anchored.** `liveClipWidth = clipWidth + trailingTrimOffset − leadingTrimOffset` shrinks the frame width during a leading trim, but there's no corresponding `.offset(x: leadingTrimOffset)` on the clip body. The clip is positioned in the parent via `.offset(x: clip.startTime * pixelsPerSecond)`, which doesn't move during drag. Net result: the left edge stays glued in place, and the clip shrinks from the right while the user is dragging the left handle. The user perceives this as the handle not tracking their finger.
+
+**Cause C — One-frame pop on release.** `.onEnded` resets `leadingTrimOffset = 0` and `trailingTrimOffset = 0` synchronously, then fires `onTrim(edge, delta)` which schedules an async `Task` that calls `appState.trimClip(...)`. For one render frame, `liveClipWidth` is back to the original `clipWidth` (offsets are zero, duration hasn't updated yet). Then the project state catches up and the clip jumps to the new width.
+
+### 4.2 Changes (apply identically to all four clip block types)
+
+1. **Add `@State private var isTrimming: Bool = false`** alongside the existing `leadingTrimOffset` / `trailingTrimOffset` state.
+
+2. **Suppress move gesture while trimming.** Change `.simultaneousGesture(moveGesture)` to `.gesture(moveGesture, including: isTrimming ? .subviews : .all)`. The `GestureMask.subviews` value means the gesture is active only on subviews of the body's gesture target, which effectively disables the move gesture on the clip body itself. Set `isTrimming = true` in the trim handle's `.onChanged` and `isTrimming = false` at the end of the trim flow (see step 4 below).
+
+3. **Leading edge tracks finger.** Add `leadingTrimOffset` into the existing `.offset(...)` on the clip body:
+
+ ```swift
+ .offset(
+ x: moveTranslation + leadingTrimOffset,
+ y: moveVerticalTranslation
+ )
+ ```
+
+ During a leading trim, `moveTranslation` is 0 (suppressed by step 2) and `leadingTrimOffset > 0`, so the clip visually slides right by `leadingTrimOffset` while its width shrinks by the same amount. Net effect: left edge follows the finger; right edge is stationary. During a trailing trim or a move, `leadingTrimOffset` stays 0 and behavior is unchanged.
+
+4. **Eliminate the release pop.** Change the `onTrim` callback type from `(AppState.TrimEdge, TimeInterval) -> Void` to `(AppState.TrimEdge, TimeInterval) async -> Void`. In the trim handle's `.onEnded`:
+
+ ```swift
+ .onEnded { value in
+ let delta = value.translation.width / max(pixelsPerSecond, 1)
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+ Task { @MainActor in
+ await onTrim(edge, delta)
+ leadingTrimOffset = 0
+ trailingTrimOffset = 0
+ isTrimming = false
+ }
+ }
+ ```
+
+ The state update (clip.duration) completes before the offsets reset, so both happen in the same render pass — no pop. Update the four call sites in `visualTrackLane` and the audio/text/graphics equivalents to make the closure async (no other changes needed since they already wrap in `Task`).
+
+### 4.3 What stays the same
+
+- Min-drag-distance of 1 pt on the trim DragGesture.
+- The `clipWidth − 44` clamp on `leadingTrimOffset` / `trailingTrimOffset`.
+- The `UIImpactFeedbackGenerator(style: .light)` haptic on release.
+- The scissors mini-button, the snap edge indicator, the move gesture itself.
+
+### 4.4 Files touched
+
+- `Openreel Video/Openreel Video/EditorView.swift` — four clip block structs (~25 lines changed across all four), and the four call sites in `visualTrackLane`-equivalents (closure becomes async).
+
+No model, AppState, or storage changes.
+
+## 5. Workstream 2 — Full-screen Crop editor
+
+### 5.1 New view: `CropEditorView`
+
+**Location:** `Openreel Video/Openreel Video/Features/Crop/CropEditorView.swift` (new folder, new file).
+
+**Presentation:** Bound to a new `@State private var presentedCropEditor: PresentedCropEditor?` in `EditorView`, shown via `.fullScreenCover(item: $presentedCropEditor)`. Use `.fullScreenCover` (not `.sheet`) so the editor truly fills the screen — spatial cropping needs the room.
+
+**Routing:** In `handleToolTap` (line 3369), the existing `case "Crop"` branches that currently set `activeEditingSheet = .crop` are changed to set `presentedCropEditor = PresentedCropEditor(clipID: selectedClipID)`. The `EditingSheet.crop` enum case and its `clipCropSheet` body (`EditorView.swift` lines 4445–4495 plus the `case .crop` branches in `editingSheet` and `editingSheetHeight`) are removed.
+
+**Layout:**
+
+```
+┌──────────────────────────────────────────────┐
+│ Cancel Crop Done │ 56 pt top bar
+├──────────────────────────────────────────────┤
+│ │
+│ ┌──────────────────────────┐ │
+│ │ ●──────●──────● │ │ preview area
+│ │ │ │ │ │ (flex, dark backdrop)
+│ │ ● live media ● │ │ crop frame + 8 handles
+│ │ │ │ │ │
+│ │ ●──────●──────● │ │
+│ └──────────────────────────┘ │
+│ │
+├──────────────────────────────────────────────┤
+│ [Free] [1:1] [9:16] [16:9] [4:5] [4:3] │ scrollable aspect chips
+│ │
+│ ↔ Flip H ↕ Flip V ↺ Reset │ action row
+└──────────────────────────────────────────────┘
+```
+
+**Aspect chip presets (final list):** Free, 1:1, 9:16, 16:9, 4:5, 4:3, 3:4. Locking an aspect snaps the current crop frame to that ratio centered on its current center, and constrains all subsequent handle drags to that ratio. Tapping `Free` unlocks.
+
+**State (all `@State` local to `CropEditorView`):**
+
+- `cropFrame: CGRect` — current frame in preview-view coords
+- `lockedAspect: CGFloat?` — `nil` = Free, else width/height ratio
+- `mediaScale: CGFloat` — 1.0 default; pinch updates this within `[1.0, 6.0]`
+- `mediaOffset: CGSize` — pan applied to the media (for zoom)
+- `flipH: Bool`, `flipV: Bool` — initialized from `clip.transform`
+
+**Initialization:**
+
+- Read `clip.transform.crop` (normalized) and convert to a `CGRect` in preview-view coords, given the media's aspect ratio and the available preview area.
+- Read `clip.transform.flipHorizontal` / `flipVertical` into the flip state.
+
+**Interactions:**
+
+| Gesture | Effect |
+|---|---|
+| Drag a corner handle | Resize from that corner; if `lockedAspect != nil`, constrain to ratio (the moving edge picks the dominant axis) |
+| Drag an edge midpoint handle | Resize one dimension (or both, if aspect-locked) |
+| Drag inside the crop frame | Pan the frame within the media bounds; clamp to media edges |
+| Pinch on media area | Scale `mediaScale` between 1.0 and 6.0; updates `mediaOffset` to keep the pinch centroid stable |
+| Tap aspect chip | Animate `cropFrame` to the target ratio centered on its current center; set `lockedAspect` |
+| Tap Flip H / Flip V | Toggle `flipH` / `flipV`; preview updates immediately |
+| Tap Reset | `cropFrame` = full media bounds; `lockedAspect = nil`; `mediaScale = 1.0`; `mediaOffset = .zero`; `flipH = flipV = false` |
+| Tap Cancel | Dismiss without applying |
+| Tap Done | Convert `cropFrame` back to normalized coords and apply (see §5.4) |
+
+**Handle hit area:** 44×44 pt invisible hit shape behind each 16×16 pt visible dot (corner handles) or 28×8 pt visible pill (edge handles). Same expanded-hit-area pattern as today's trim handle.
+
+### 5.2 Backdrop for video vs photo
+
+- **Photo:** Render the underlying `UIImage` from the clip's media URL via `AsyncImage` (or `Image(uiImage:)` if already loaded).
+- **Video:** Render the frame at `playbackController.currentTime`. Reuse `MetalVideoSnapshotProvider.snapshot` (already exists per the FilterPicker integration at line 4506). The backdrop is a still image, not a live video — no playback in this screen.
+
+The flip transform is applied to the backdrop only as a CSS-style visual flip (`.scaleEffect(x: flipH ? -1 : 1, y: flipV ? -1 : 1)`); the crop frame stays in screen orientation.
+
+### 5.3 What this screen does **not** handle
+
+- **Opacity** — stays in the existing transform UI (`clipOpacitySheet` is the current path; unchanged here).
+- **Fit mode (Contain / Cover / Stretch / None)** — keep as is. Fit mode is a render-time setting that interacts with the canvas aspect ratio, not the spatial crop region. Adding it would muddy the Crop screen. The user can change Fit mode from the existing tool path.
+
+This is a deliberate scope choice: the new screen does **spatial cropping + flip**, not "everything in the old sheet."
+
+### 5.4 Data flow on Done
+
+```
+cropFrame (preview-view coords)
+ │
+ ▼ convert via media→preview transform
+normalized Crop(x, y, width, height) ∈ [0,1]
+ │
+ ▼ call existing AppState API
+appState.updateSelectedClipCrop(x:, y:, width:, height:)
+ │
+ ▼ if flips changed
+appState.toggleSelectedClipFlip(horizontal: …) / (vertical: …)
+ │
+ ▼
+dismiss
+```
+
+`updateSelectedClipCrop` already exists in `AppState.swift` (it's what the current sliders call). No API changes.
+
+### 5.5 What's reused, what's deleted
+
+**Reused unchanged:**
+
+- `OpenReelProject.Crop` model (normalized 0..1 coords).
+- `appState.updateSelectedClipCrop(x:y:width:height:)`.
+- `appState.toggleSelectedClipFlip(horizontal:)`.
+- `appState.resetSelectedClipCrop`.
+- `MetalVideoSnapshotProvider.snapshot` for the video backdrop.
+
+**Deleted:**
+
+- `clipCropSheet` body (EditorView.swift lines 4445–4495, ~50 LOC).
+- `EditingSheet.crop` case + its branches in `editingSheet(_:)` and `editingSheetHeight(for:)`.
+
+### 5.6 Files touched
+
+- **New:** `Features/Crop/CropEditorView.swift` (estimated 450–550 LOC including the crop-frame gesture math).
+- **New:** `Features/Crop/CropFrameGeometry.swift` — pure helper for converting between preview-view CGRect ↔ normalized Crop, plus aspect-locked corner-drag math. Pure functions; trivially unit-testable.
+- **Modified:** `EditorView.swift` — remove the old sheet, add the `.fullScreenCover` route, update `handleToolTap` and the equivalent for the photo path.
+- **Modified:** `EditorView.swift` `EditingSheet` enum — remove `.crop`.
+
+No AppState changes, no model changes, no storage changes.
+
+## 6. Testing
+
+**Workstream 1 (trim flicker):**
+
+- Manual: drag left handle right slowly, then pause for 1 s mid-drag, then continue. Clip must not jump. Repeat with right handle. Repeat for audio, text, graphics clips.
+- Manual: drag left handle and watch the leading edge — it should track the finger to the pixel.
+- Manual: release after trim — no width pop, single visible frame transitions to final width.
+- Unit (optional, low value): the trim math itself is already covered by `appState.trimClip` tests; the changes don't touch that code path.
+
+**Workstream 2 (crop editor):**
+
+- Unit: `CropFrameGeometry` — round-trip a CGRect through normalize → denormalize and assert equality at 1e-6 tolerance. Aspect-lock math: drag corner with locked aspect produces a frame whose width/height ratio matches `lockedAspect`.
+- Manual: open Crop for a photo, drag corners and edges, switch aspect presets, flip, reset, Done. Verify the saved crop renders correctly on the timeline preview and in export.
+- Manual: open Crop for a video at a specific playhead time. Backdrop must show the frame at that time, not the first frame.
+- Manual: cancel without applying — clip's transform must be unchanged.
+- UI smoke: existing iOS UI smoke test stays green (launch + open Crop is enough; full interaction not required in smoke).
+
+## 7. Open questions
+
+None.
+
+## 8. Implementation order
+
+1. **Workstream 1 first** — small, safe, immediately improves a daily-friction interaction.
+2. **Workstream 2 second** — larger surface, new file, but isolated and independent of Workstream 1.
+
+These ship as separate PRs.
diff --git a/docs/superpowers/specs/2026-06-02-electron-desktop-native-offload-design.md b/docs/superpowers/specs/2026-06-02-electron-desktop-native-offload-design.md
index 7ae7dbe7..acfcf430 100644
--- a/docs/superpowers/specs/2026-06-02-electron-desktop-native-offload-design.md
+++ b/docs/superpowers/specs/2026-06-02-electron-desktop-native-offload-design.md
@@ -1,5 +1,8 @@
# OpenReel Desktop (Electron + Native Media Offload) — Design Spec
+> **Architecture update (2026-07-31):** Cloud GPU endpoints and broker flows in
+> this draft are retired. Desktop processing and export are local-only.
+
**Status:** Draft for review
**Date:** 2026-06-02
**Supersedes:** [`2026-05-28-kael-openreel-desktop-design.md`](./2026-05-28-kael-openreel-desktop-design.md) (native Rust + wgpu + kael rewrite)
@@ -213,16 +216,13 @@ Capture ships in two steps inside Phase 3: first video-only native capture with
`window.openreel.probeHardware()` returns real specs from the main process: CPU model/physical+logical cores (`os.cpus()`), total/free RAM (`os.totalmem()`), GPU model(s) (platform queries — `system_profiler` on macOS, `wmic`/DXGI on Windows, `lspci`/`glxinfo` on Linux), and the probed encoder list (§6.2). This replaces the heuristic `device-capabilities.ts` (UA + WebGL-string + `navigator.deviceMemory` default-4) in desktop mode and feeds `export-estimator.ts` accurate, deterministic inputs (native encode FPS is far more predictable than the in-browser micro-benchmark).
-### 6.8 Cloud / AI: server-proxy **and** BYOK
-
-`window.openreel.cloud.fetch(service, path, options)` in the main process decides per call:
-
-- **BYOK mode (default if a user key exists):** the key is read through the main-process key store (OS keychain where available, or `safeStorage`-encrypted ciphertext persisted under `userData`; never exposed to the renderer) and the request is made **directly from the main process** to `api.openai.com` / `api.anthropic.com` / `api.elevenlabs.io` using the `DIRECT_CONFIG` headers already defined in `api-proxy.ts`. No same-origin proxy needed; works offline-of-Cloudflare.
-- **Server-proxy mode (signed-in users without their own key):** the main process calls the **absolute** cloud Worker proxy (`https://openreel-cloud.<...>.workers.dev` / `api.openreel.video`) — *not* the relative `/api/proxy/*` Pages Function, which has no same-origin under `app://`. This requires two backend changes:
- 1. The Pages Function `ALLOWED_ORIGINS` allowlist (`functions/api/proxy/[[catchall]].ts`) — or a new Worker route — must accept the desktop client. Since the desktop request originates from the **main process** (Node, not a browser), it isn't subject to browser CORS; it sends a desktop auth token instead.
- 2. **Desktop auth:** the cloud auth broker today attests only Apple App Attest / Play Integrity (`apps/cloud/wrangler.jsonc`). Add a desktop path: browser-based OAuth/device-code handoff → short-lived scoped JWT, stored in the keychain, sent as a bearer token to the Worker. This mirrors the mobile short-lived-token model without native attestation.
+### 6.8 External AI providers and local media work
-The GPU services (transcribe `cloud.openreel.video`, TTS `transcribe.openreel.video`, render `ai.openreel.video`) are reached the same way (main-process fetch with the desktop JWT).
+The OpenReel-hosted speech and GPU-processing services are retired. Desktop
+media processing and export stay in the app or its local sidecars. Optional
+third-party AI providers are BYOK: credentials remain in the desktop keychain
+and requests go directly through the existing main-process proxy. There is no
+OpenReel GPU token, broker, job queue, or remote-render fallback.
## 7. Data flows
diff --git a/docs/superpowers/specs/2026-06-18-ai-agent-editing-design.md b/docs/superpowers/specs/2026-06-18-ai-agent-editing-design.md
index 25834992..dea15e28 100644
--- a/docs/superpowers/specs/2026-06-18-ai-agent-editing-design.md
+++ b/docs/superpowers/specs/2026-06-18-ai-agent-editing-design.md
@@ -1,5 +1,9 @@
# AI Agent Video Editing — Design Spec
+> **Architecture update (2026-07-31):** Remote GPU job delegation and auth-broker
+> sections are superseded. Agent renders use the local app host; the headless CLI
+> edits project files without submitting remote GPU jobs.
+
- **Date:** 2026-06-18
- **Status:** Design (architecture approved; pending spec review)
- **Surfaces:** Web app (`apps/web`), Desktop app (`apps/desktop`), shared core (`packages/core`), cloud (`apps/cloud`)
diff --git a/docs/superpowers/specs/2026-08-27-universal-timeline-tracks-design.md b/docs/superpowers/specs/2026-08-27-universal-timeline-tracks-design.md
new file mode 100644
index 00000000..8008e2db
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-27-universal-timeline-tracks-design.md
@@ -0,0 +1,450 @@
+# Universal Timeline Tracks Design
+
+**Date:** 2026-08-27
+
+**Status:** Proposed — design only
+
+**Primary scope:** Web and desktop editor, shared project schema, iOS/Android readers
+
+## Summary
+
+OpenReel should stop treating a track's historical type as a restriction on the clips it can contain. A normal timeline track should accept video, image, text, graphics, and audio items. The item itself determines how it is rendered, inspected, mixed, and exported.
+
+The interaction must also solve the workflow behind the report: when an editor drops an image or other visual over an occupied video interval, OpenReel should automatically place it on a standard track immediately above the source track. The editor should not need to create and arrange an image-specific track first.
+
+This should be delivered as a reader-first migration. Rendering, audio, export, inspection, history, and project loading must understand mixed tracks before the UI starts writing mixed-track projects.
+
+## Problem
+
+The current model declares five track types:
+
+- `video`
+- `audio`
+- `image`
+- `text`
+- `graphics`
+
+That type is used both as presentation metadata and as a content capability. The timeline UI only lets a media clip move to a track with the same type. Text and graphics use separate storage and separate movement paths. Preview and export often decide what a clip is from `track.type` instead of from the clip or its media item.
+
+This creates unnecessary setup during fast editing. An editor has to create or locate the right kind of track before placing an item, even though the timeline can determine the item's behavior itself.
+
+It also creates fragile internal behavior. The action executor currently permits some mixed placements, but multiple render and audio paths ignore those clips because the containing track has the "wrong" type.
+
+## Audit findings
+
+This is broader than drag and drop:
+
+- The TypeScript web/core code has 141 direct `track.type` branches across 63 files.
+- The shared project model is mirrored by native clients. The audit found track-type logic in 5 Swift files and 19 Android production Kotlin files.
+- `Track.clips` contains media clips, while text, shapes, SVGs, and stickers live in project-level collections and refer back to a track with `trackId`.
+- `ClipComponent` rejects cross-track moves when the destination type differs.
+- `pasteOverlayClip` explicitly requires a text or graphics track.
+- Preview, `VideoEngine`, `AudioEngine`, `PlaybackController`, and `ExportEngine` use track type as a render or audio gate.
+- The inspector partly checks media type, but still treats an audio track as proof that any contained clip is audio.
+- Transitions are exposed only on video tracks, even though video-to-image transitions are a valid visual operation.
+- Track duplication and removal operate on `Track.clips` and do not consistently include project-level text and graphics items owned by that track.
+- The JSON wrapper is still `1.0.0`; its migration method normalizes fields but does not perform a structural version migration.
+
+Important current hotspots include:
+
+- `packages/core/src/types/timeline.ts`
+- `packages/core/src/actions/action-executor.ts`
+- `packages/core/src/actions/action-validator.ts`
+- `packages/core/src/video/video-engine.ts`
+- `packages/core/src/audio/audio-engine.ts`
+- `packages/core/src/playback/playback-controller.ts`
+- `packages/core/src/export/export-engine.ts`
+- `apps/web/src/components/editor/Timeline.tsx`
+- `apps/web/src/components/editor/timeline/TrackLane.tsx`
+- `apps/web/src/components/editor/timeline/ClipComponent.tsx`
+- `apps/web/src/components/editor/Preview.tsx`
+- `apps/web/src/components/editor/InspectorPanel.tsx`
+- `apps/web/src/stores/project/clip-slice.ts`
+- `apps/web/src/stores/project/text-graphics-slice.ts`
+- `apps/web/src/stores/project/history-slice.ts`
+
+## Product decisions
+
+### 1. Normal tracks are universal
+
+Every normal track accepts every timeline item:
+
+- video
+- image
+- audio
+- text
+- shape
+- SVG
+- sticker or emoji
+- motion or generated visual instances when those are represented on the editing timeline
+
+"Video Track", "Image Track", "Text Track", and "Graphics Track" should become one **Track** action. Existing specialized tracks remain valid and become universal when opened by a compatible reader.
+
+Audio roles such as dialogue, music, effects, and ambience remain useful, but they describe mixing intent rather than placement capability. A track with a music role can still accept a visual item. Dropping an item must not fail only because of that role.
+
+### 2. Content determines capabilities
+
+Track type must no longer answer questions such as:
+
+- Does this item draw pixels?
+- Does this item produce audio?
+- Which inspector should open?
+- Can this item receive a visual transition?
+- Does it need a thumbnail, waveform, or text preview?
+
+Those answers come from the item kind and its resolved media metadata.
+
+A video item may have both visual and audio capabilities. An image has visual capability only. An audio file has audio capability only. Text and graphics have visual capability and their own authoring capabilities.
+
+### 3. A row is one editorial lane
+
+A single track should not contain unrelated items that overlap in time. This keeps selection, transitions, trim behavior, and visual ordering predictable. A transition may temporarily consume handles from two adjacent items, but it is not an arbitrary overlap.
+
+This matches the useful part of traditional NLE behavior: tracks accept different visual item types, while simultaneous layers occupy different rows.
+
+### 4. Dropping over content automatically stacks above it
+
+When a user drops a new item onto an occupied time range:
+
+1. Show a placement ghost on a row immediately above the occupied track.
+2. Reuse the nearest unlocked standard track above when it has room.
+3. Otherwise create a new standard track immediately above.
+4. Place the item there in the same undoable transaction.
+
+This is the fast path for "put an image on a video clip." The editor does not need to create or arrange a track first.
+
+Dropping into an empty interval stays on the selected track. Insert and overwrite editing can be added as explicit tools later; they should not be hidden side effects of the default drop.
+
+### 5. Track order remains the layer order
+
+The top timeline row composites above lower rows. Rendering should traverse lower rows first and composite higher rows last. A new auto-stacked track is inserted immediately above the target so its visual relationship is obvious.
+
+### 6. Controls reflect contributions, not a type badge
+
+Every standard track header shows:
+
+- visibility control for visual contributions
+- mute and solo controls for audio contributions
+- lock control for all items
+- name and optional semantic role
+
+Hiding a track does not mute its audio. Muting a track does not hide its visuals. Solo only participates in audio resolution for tracks that currently contribute audio.
+
+Clip colors and icons identify item type. The row itself uses a neutral standard-track appearance.
+
+## Compatibility-first data model
+
+The first release should not move every item into a new `Track.items` array. That would combine a storage migration, every engine refactor, and the interaction change into one high-risk release.
+
+Instead, preserve the current serialized locations and add a unified read model over them.
+
+### Unified timeline item view
+
+Introduce a shared discriminated union similar to:
+
+```ts
+type TimelineItemKind =
+ | "media"
+ | "text"
+ | "shape"
+ | "svg"
+ | "sticker"
+ | "adjustment"
+ | "motion";
+
+interface TimelineItemRef {
+ id: string;
+ trackId: string;
+ kind: TimelineItemKind;
+ startTime: number;
+ duration: number;
+}
+
+interface TimelineItemCapabilities {
+ visual: boolean;
+ audio: boolean;
+ transformable: boolean;
+ trimSource: boolean;
+ transitionSource: boolean;
+ textEditable: boolean;
+ graphicEditable: boolean;
+}
+```
+
+Core selectors should become the only supported way to ask for items and capabilities:
+
+```ts
+getTimelineItems(project): TimelineItemRef[]
+getTrackItems(project, trackId): TimelineItemRef[]
+resolveTimelineItem(project, itemId): ResolvedTimelineItem | null
+getTimelineItemCapabilities(project, item): TimelineItemCapabilities
+trackHasVisualItems(project, trackId): boolean
+trackHasAudioItems(project, trackId): boolean
+```
+
+Media capability resolution should preserve optional `hasVideo` and `hasAudio` values from import metadata. Until those fields exist on older projects, use safe fallbacks from `MediaItem.type`, dimensions, sample rate, and channels.
+
+### Track fields
+
+Keep the existing `Track.type` field during the migration so older project readers do not fail on an unknown enum value. Treat it as a deprecated compatibility hint, not an acceptance rule.
+
+Add optional, additive metadata:
+
+```ts
+interface Track {
+ // Existing compatibility field. Do not use for item capability checks.
+ type: "video" | "audio" | "image" | "text" | "graphics";
+
+ // New clients default missing values to "standard".
+ mode?: "standard";
+
+ // Optional editorial meaning, independent from capability.
+ role?: "general" | "captions" | "dialogue" | "music" | "effects" | "ambience";
+}
+```
+
+New tracks can serialize with `type: "video"` plus `mode: "standard"` until all clients can safely read a new canonical schema. Existing track types do not need an eager destructive rewrite.
+
+### Cross-platform rollout
+
+The project schema is shared with iOS and Android, so writers must not get ahead of readers.
+
+Use this rollout order:
+
+1. Add the unified selectors, optional fields, and capability marker to TypeScript, Swift, and Kotlin readers.
+2. Make all preview and export readers render mixed assignments correctly.
+3. Add a project capability such as `universal-tracks-v1` and a minimum-reader guard. An incompatible app must ask the user to update instead of silently omitting items.
+4. Only then enable the UI paths that write mixed assignments.
+
+The web serializer needs real version fixtures and migrations before the writer flag is enabled. A version mismatch cannot continue to be treated as normalization only.
+
+## Engine behavior
+
+### Preview and export
+
+For every visible track at a frame time:
+
+1. Resolve active items through the unified item view.
+2. Render items with visual capability using the renderer for the item kind.
+3. Composite by track order.
+4. Do not infer item kind from the track.
+
+Preview and export must use the same ordering and capability rules. Golden-frame tests should compare both paths for mixed projects.
+
+The blurred canvas backdrop should choose the lowest active visual media item, not the lowest item on a track whose type happens to be video or image.
+
+### Audio
+
+Audio scheduling should include every media clip whose resolved source has audio, regardless of its track type. This includes video clips on formerly image, text, or graphics tracks and audio-only clips on a standard track.
+
+Mute and solo resolution operates at the track level. Clip volume, automation, effects, speed, reverse state, and source audio-track selection remain clip properties.
+
+### Inspector
+
+The inspector should resolve the selected item first and then build sections from item capabilities:
+
+- image: transform, crop, color, visual effects
+- video without audio: visual sections only
+- video with audio: visual and audio sections
+- audio-only: audio sections only
+- text: text, transform, animation, compatible visual effects
+- graphics: graphic-specific controls, transform, compatible visual effects
+
+The track is only consulted for lock, visibility, mute, solo, and role state.
+
+### Transitions
+
+For the first universal-track release:
+
+- Preserve transitions between adjacent video and image media items, including video-to-image and image-to-video.
+- Determine eligibility from both items' visual capabilities, not the track type.
+- Keep text and graphics entry/exit animation behavior unchanged.
+- Do not silently offer a transition between item kinds that the renderer cannot rasterize consistently.
+
+A later generalized transition pass can render any visual item into an intermediate frame and transition between those frames.
+
+## Editing command model
+
+Media and overlays currently have separate move, copy, paste, delete, split, and undo paths. Universal tracks need commands that work on a timeline item union.
+
+Add command-level operations such as:
+
+```ts
+placeTimelineItem(itemId, targetTrackId, startTime, policy)
+moveTimelineItems(moves, policy)
+duplicateTimelineItems(itemIds, destination)
+removeTimelineItems(itemIds)
+splitTimelineItems(itemIds, time)
+duplicateTrackWithItems(trackId)
+removeTrackWithItems(trackId)
+```
+
+`policy` should initially support:
+
+- `gap`: place only when the destination interval is clear
+- `stack-above`: resolve or create a row above when occupied
+
+Insert and overwrite policies can be added later with explicit UI.
+
+Each command must:
+
+- validate source and destination locks
+- update `trackId` for media, text, and graphics items
+- update engine caches after project data changes
+- preserve linked captions and grouped items
+- recalculate duration once
+- create one deterministic history transaction
+- restore both the item and any auto-created track on undo
+
+Track duplicate and remove must include every project-level item whose `trackId` matches the track, not only `Track.clips`.
+
+## Timeline interaction
+
+### Add track
+
+Replace the five primary add-track entries with:
+
+- **Track**
+- optional role shortcuts: Dialogue, Music, Captions
+
+Role shortcuts create a standard track with a role; they do not restrict content.
+
+### Drag and drop
+
+While dragging:
+
+- Every unlocked track is a valid destination.
+- The ghost uses the dragged item's icon and color.
+- Empty interval: show the ghost in that row.
+- Occupied interval: show the ghost in the resolved row above and label it "Place above."
+- Locked row: skip to the nearest valid row above or show a clear locked state.
+- Never show an invalid state solely because item and legacy track types differ.
+
+External file drops and asset-panel drops use the same placement resolver as internal clip moves.
+
+### Selection and trimming
+
+Selection, box selection, snapping, trimming, and keyboard movement should enumerate the unified item view. Timeline rendering should choose the clip component from item kind, not from the row type.
+
+### Overlap rules
+
+The command layer enforces the non-overlap invariant for unrelated items in one row. Existing projects containing accidental overlaps remain readable; load normalization should preserve them and surface a repair action rather than silently moving content.
+
+## Implementation sequence
+
+### Phase 0 — Characterization and schema safety
+
+- Add mixed-project fixtures and lock current preview/export/audio behavior for normal projects.
+- Add true schema version and minimum-reader tests across TypeScript, Swift, and Kotlin.
+- Preserve `hasVideo` and `hasAudio` import metadata.
+- Inventory every direct track-type branch and assign it to capability, role, or presentation.
+
+Exit condition: old projects round-trip without visual, audio, timing, or ordering changes.
+
+### Phase 1 — Unified read model
+
+- Add timeline item and capability selectors in core.
+- Replace track-type gates in preview, native playback, audio, export, inspectors, duration calculation, captions, multicam, and templates.
+- Add mixed-track read fixtures, while the UI still writes legacy placements.
+- Land equivalent reader behavior on iOS and Android.
+
+Exit condition: a hand-authored mixed project renders and exports correctly everywhere.
+
+### Phase 2 — Universal commands and history
+
+- Add union-aware item placement and mutation commands.
+- Make track duplicate, remove, undo, and redo include media and overlay collections.
+- Centralize overlap resolution and automatic track creation.
+- Add transaction and deterministic-ID tests.
+
+Exit condition: mixed item moves, automatic stacking, undo, redo, save, and reload are lossless through headless commands.
+
+### Phase 3 — Timeline user experience
+
+- Replace typed add-track controls with the standard track action.
+- Remove same-type drag rejection.
+- Add placement ghosts and automatic stacking.
+- Derive row controls from actual visual/audio contributions.
+- Derive clip component, color, icon, and inspector from item kind.
+
+Exit condition: the complete workflow is usable by mouse, trackpad, keyboard, and screen reader.
+
+### Phase 4 — Hardening and rollout
+
+- Enable `universal-tracks-v1` project writes only for compatible readers.
+- Run preview/export golden tests and long mixed-timeline playback tests.
+- Test autosave recovery, shared project files, templates, nested sequences, captions, multicam, transitions, and desktop native export.
+- Roll out behind a feature flag, then make it the default after compatibility telemetry is clean.
+
+## Acceptance criteria
+
+1. A user can place video, image, text, graphics, or audio on any unlocked standard track.
+2. A row can contain a video followed by an image followed by text without manual track setup.
+3. Dropping an image over an occupied video interval creates or reuses a row immediately above and composites the image above the video.
+4. Moving an existing text or graphic item between rows is one undoable action.
+5. The selected item's inspector is correct regardless of its row's legacy type.
+6. Video audio and audio-only items play, mute, solo, and export correctly from any row.
+7. Hiding a mixed row affects its visuals but not its audio; muting affects audio but not visuals.
+8. Adjacent video and image items can use supported transitions on the same row.
+9. Duplicate track, delete track, undo, redo, autosave recovery, save, and reload preserve every item kind.
+10. Existing projects render and export identically before and after the reader migration.
+11. An older incompatible client is prevented from silently opening a mixed-track project.
+12. Web preview, web export, desktop preview, desktop native export, iOS, and Android agree on track order and active items.
+
+## Test matrix
+
+At minimum, cover these combinations:
+
+| Scenario | Preview | Export | Audio | History | Round trip |
+| --- | --- | --- | --- | --- | --- |
+| Video then image on one row | Yes | Yes | Video audio | Yes | Yes |
+| Text then video on one row | Yes | Yes | Video audio | Yes | Yes |
+| Graphic on former audio row | Yes | Yes | N/A | Yes | Yes |
+| Audio on former text row | No visual | Yes | Yes | Yes | Yes |
+| Video with audio on any row | Yes | Yes | Yes | Yes | Yes |
+| Image stacked above video | Correct z-order | Correct z-order | Video audio | One undo | Yes |
+| Mixed row hidden | No visual | No visual | Audio remains | Yes | Yes |
+| Mixed row muted | Visual remains | Visual remains | No audio | Yes | Yes |
+| Video-to-image transition | Yes | Yes | Continuous | Yes | Yes |
+| Delete or duplicate mixed row | Correct | Correct | Correct | Yes | Yes |
+
+## Risks and mitigations
+
+### Silent content loss in older clients
+
+Mitigation: reader-first rollout, explicit capability marker, minimum-reader guard, and cross-platform fixtures before enabling writes.
+
+### Preview and export disagree
+
+Mitigation: shared capability and ordering selectors plus golden-frame tests that exercise both paths.
+
+### Audio disappears from mixed tracks
+
+Mitigation: resolve audio from media capability, not row type, and use the same resolver for realtime playback and offline export.
+
+### Overlay history becomes inconsistent
+
+Mitigation: replace parallel media and overlay movement paths with union-aware transactional commands before changing drag behavior.
+
+### Same-row overlaps produce undefined z-order
+
+Mitigation: enforce one-lane non-overlap for new edits and automatically stack above. Preserve and explicitly repair legacy accidental overlaps.
+
+### Scope expands into a full NLE rewrite
+
+Mitigation: preserve existing serialized item collections for the first release, keep text/graphics animations as-is, and defer generalized cross-kind transitions, insert/overwrite tools, folders, and nested lanes.
+
+## Not in the first release
+
+- Arbitrary overlapping items within one row
+- Full insert/overwrite/replace editing modes
+- Generalized transitions between every visual item kind
+- Track folders or nested lanes
+- A destructive migration to one `Track.items` storage array
+- Removal of the legacy `Track.type` field before all clients have migrated
+
+## Recommendation
+
+Proceed with the reader-first four-phase plan. Do not implement this by only loosening the current drag check. That would create projects that appear correct in the timeline but lose visuals or audio in preview, export, history, or another platform.
+
+The first implementation commit should contain only shared item-capability selectors, metadata preservation, and characterization tests. The UI should not write mixed assignments until the read paths and command transactions are complete.
diff --git a/infra/db/schema.sql b/infra/db/schema.sql
new file mode 100644
index 00000000..1bfb898d
--- /dev/null
+++ b/infra/db/schema.sql
@@ -0,0 +1,252 @@
+-- =====================================================================
+-- OpenReel Marketplace — canonical Postgres schema (STUDIO_PLAN Appendix F)
+--
+-- Money is always bigint cents, never float (§33.1). IDs are uuid; expose
+-- opaque handles/slugs externally, never internal ids (§33.2). Apply with:
+-- psql "$DATABASE_URL" -f infra/db/schema.sql
+-- A Cloudflare D1 (SQLite) variant lives in infra/db/schema.d1.sql.
+-- =====================================================================
+
+CREATE EXTENSION IF NOT EXISTS citext;
+
+-- =====================================================================
+-- Identity and creators
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS users (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ email citext UNIQUE NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE IF NOT EXISTS creators (
+ user_id uuid PRIMARY KEY REFERENCES users(id),
+ handle citext UNIQUE NOT NULL,
+ bio text,
+ avatar_uri text,
+ kyc_level smallint NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ banned_at timestamptz
+);
+
+CREATE TABLE IF NOT EXISTS payout_methods (
+ creator_id uuid PRIMARY KEY REFERENCES creators(user_id),
+ rail text NOT NULL CHECK (rail IN ('stripe','paystack','flutterwave','wise')),
+ external_id text NOT NULL,
+ currency text NOT NULL,
+ verified_at timestamptz
+);
+
+-- =====================================================================
+-- Assets and versioning
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS assets (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_id uuid NOT NULL REFERENCES creators(user_id),
+ slug citext NOT NULL,
+ kind text NOT NULL CHECK (kind IN ('template','filter','effect')),
+ category text,
+ current_version smallint,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (creator_id, slug)
+);
+CREATE INDEX IF NOT EXISTS assets_kind_category ON assets (kind, category);
+
+CREATE TABLE IF NOT EXISTS asset_versions (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ asset_id uuid NOT NULL REFERENCES assets(id),
+ version smallint NOT NULL,
+ abi text NOT NULL,
+ manifest jsonb NOT NULL,
+ fxpkg_uri text NOT NULL,
+ review_state text NOT NULL DEFAULT 'submitted',
+ attestation jsonb,
+ submitted_at timestamptz NOT NULL DEFAULT now(),
+ approved_at timestamptz,
+ UNIQUE (asset_id, version)
+);
+CREATE INDEX IF NOT EXISTS asset_versions_review ON asset_versions (review_state, submitted_at);
+
+CREATE TABLE IF NOT EXISTS drafts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_id uuid NOT NULL REFERENCES creators(user_id),
+ asset_id uuid,
+ kind text NOT NULL CHECK (kind IN ('template','filter','effect')),
+ title text,
+ graph jsonb NOT NULL,
+ manifest_draft jsonb NOT NULL,
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS drafts_creator ON drafts (creator_id, updated_at DESC);
+
+CREATE TABLE IF NOT EXISTS draft_snapshots (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ draft_id uuid NOT NULL REFERENCES drafts(id),
+ graph jsonb NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS draft_snapshots_draft ON draft_snapshots (draft_id, created_at DESC);
+
+CREATE TABLE IF NOT EXISTS submissions (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ draft_id uuid NOT NULL REFERENCES drafts(id),
+ asset_version_id uuid REFERENCES asset_versions(id),
+ creator_id uuid NOT NULL REFERENCES creators(user_id),
+ state text NOT NULL,
+ fxpkg_uri text NOT NULL,
+ validator_log jsonb,
+ reviewer_notes text,
+ reviewer_id uuid,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS submissions_state ON submissions (state, created_at);
+
+-- =====================================================================
+-- Usage and projects
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS projects (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES users(id),
+ timeline jsonb NOT NULL,
+ timeline_version int NOT NULL DEFAULT 1,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE IF NOT EXISTS installs (
+ user_id uuid NOT NULL REFERENCES users(id),
+ asset_id uuid NOT NULL REFERENCES assets(id),
+ installed_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, asset_id)
+);
+
+-- =====================================================================
+-- Mobile media uploads
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS media_uploads (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES users(id),
+ kind text NOT NULL CHECK (kind IN ('proxy', 'original')),
+ parent_id uuid REFERENCES media_uploads(id),
+ storage_uri text NOT NULL,
+ size_bytes bigint NOT NULL,
+ duration_ms int,
+ width int,
+ height int,
+ codec text,
+ bitrate_kbps int,
+ sha256 text NOT NULL,
+ device_fingerprint text,
+ uploaded_at timestamptz NOT NULL DEFAULT now(),
+ last_accessed_at timestamptz NOT NULL DEFAULT now(),
+ evict_after timestamptz
+);
+CREATE INDEX IF NOT EXISTS media_uploads_user ON media_uploads (user_id, uploaded_at DESC);
+CREATE INDEX IF NOT EXISTS media_uploads_evict ON media_uploads (evict_after) WHERE evict_after IS NOT NULL;
+
+-- =====================================================================
+-- Rendering
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS render_jobs (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES users(id),
+ project_id uuid REFERENCES projects(id),
+ kind text NOT NULL CHECK (kind IN ('preview_frame', 'preview_strip', 'export')),
+ timeline_version int NOT NULL,
+ params jsonb NOT NULL,
+ status text NOT NULL DEFAULT 'queued',
+ output_uri text,
+ error text,
+ started_at timestamptz,
+ completed_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS render_jobs_status ON render_jobs (status, created_at);
+CREATE INDEX IF NOT EXISTS render_jobs_user ON render_jobs (user_id, created_at DESC);
+
+CREATE TABLE IF NOT EXISTS strip_cache (
+ cache_key text PRIMARY KEY,
+ strip_uri text NOT NULL,
+ tier text NOT NULL DEFAULT 'hot',
+ created_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz NOT NULL
+);
+CREATE INDEX IF NOT EXISTS strip_cache_expiry ON strip_cache (expires_at);
+
+CREATE TABLE IF NOT EXISTS exports (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ render_job_id uuid REFERENCES render_jobs(id),
+ project_id uuid NOT NULL REFERENCES projects(id),
+ user_id uuid NOT NULL REFERENCES users(id),
+ started_at timestamptz NOT NULL DEFAULT now(),
+ finished_at timestamptz,
+ status text NOT NULL DEFAULT 'queued',
+ output_uri text,
+ content_hash text,
+ duration_ms int
+);
+CREATE INDEX IF NOT EXISTS exports_user ON exports (user_id, started_at);
+
+CREATE TABLE IF NOT EXISTS attributions (
+ export_id uuid NOT NULL REFERENCES exports(id),
+ asset_version_id uuid NOT NULL REFERENCES asset_versions(id),
+ share numeric(5,4) NOT NULL CHECK (share >= 0 AND share <= 1),
+ is_primary boolean NOT NULL DEFAULT false,
+ PRIMARY KEY (export_id, asset_version_id)
+);
+
+-- =====================================================================
+-- Money (cents, never float — §33.1)
+-- =====================================================================
+
+CREATE TABLE IF NOT EXISTS creator_balances (
+ creator_id uuid PRIMARY KEY REFERENCES creators(user_id),
+ pending_cents bigint NOT NULL DEFAULT 0,
+ payable_cents bigint NOT NULL DEFAULT 0,
+ paid_cents bigint NOT NULL DEFAULT 0,
+ currency text NOT NULL DEFAULT 'USD',
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE IF NOT EXISTS earnings_ledger (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_id uuid NOT NULL REFERENCES creators(user_id),
+ export_id uuid NOT NULL REFERENCES exports(id),
+ asset_version_id uuid NOT NULL REFERENCES asset_versions(id),
+ gross_cents bigint NOT NULL,
+ creator_cents bigint NOT NULL,
+ state text NOT NULL DEFAULT 'pending', -- pending | payable | paid | reversed
+ earned_at timestamptz NOT NULL DEFAULT now(),
+ payable_at timestamptz,
+ paid_at timestamptz,
+ payout_id uuid
+);
+CREATE INDEX IF NOT EXISTS earnings_ledger_creator ON earnings_ledger (creator_id, state, earned_at);
+
+CREATE TABLE IF NOT EXISTS payouts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_id uuid NOT NULL REFERENCES creators(user_id),
+ amount_cents bigint NOT NULL,
+ currency text NOT NULL,
+ rail text NOT NULL,
+ external_ref text,
+ status text NOT NULL DEFAULT 'pending',
+ period_start date NOT NULL,
+ period_end date NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ paid_at timestamptz
+);
+
+CREATE TABLE IF NOT EXISTS events_archive (
+ day date NOT NULL,
+ creator_id uuid,
+ asset_id uuid,
+ event_type text NOT NULL,
+ count bigint NOT NULL DEFAULT 0,
+ PRIMARY KEY (day, creator_id, asset_id, event_type)
+);
diff --git a/packages/agent/src/registry.timeline-editing.test.ts b/packages/agent/src/registry.timeline-editing.test.ts
new file mode 100644
index 00000000..b7d06355
--- /dev/null
+++ b/packages/agent/src/registry.timeline-editing.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import { executeTool } from "./executor";
+import { HeadlessHost } from "./headless-host";
+import { getTool, toOpenAITools } from "./registry";
+import { makeProjectWithClip } from "./test-fixtures";
+
+function makeProjectWithAdjacentClips() {
+ const project = makeProjectWithClip();
+ const track = project.timeline.tracks[0];
+ const first = track.clips[0];
+ (track.clips as unknown as Array<typeof first>).push({
+ ...structuredClone(first),
+ id: "c2",
+ startTime: 5,
+ });
+ (project.timeline as { duration: number }).duration = 10;
+ return project;
+}
+
+describe("main-timeline agent tools", () => {
+ it("publishes actionable schemas for transform, keyframes, and audio effects", () => {
+ const schemas = toOpenAITools([
+ "set_clip_transform",
+ "add_keyframe",
+ "set_clip_keyframes",
+ "add_audio_effect",
+ ]);
+
+ expect(schemas).toHaveLength(4);
+ expect(JSON.stringify(schemas)).toContain("position.x");
+ expect(JSON.stringify(schemas)).toContain("scale.x");
+ expect(JSON.stringify(schemas)).toContain("noiseReduction");
+ expect(
+ ((getTool("add_keyframe")?.inputSchema.required ?? []) as string[]),
+ ).toContain("value");
+ });
+
+ it("edits transform, speed, effects, audio, and keyframe animation on an existing clip", async () => {
+ const host = new HeadlessHost(makeProjectWithClip());
+
+ const results = await Promise.all([
+ executeTool("set_clip_transform", {
+ clipId: "c1",
+ transform: { position: { x: 24 }, scale: { x: 1.2, y: 1.2 } },
+ }, host),
+ executeTool("set_clip_speed", { clipId: "c1", speed: 1.25 }, host),
+ executeTool("add_video_effect", {
+ clipId: "c1",
+ effectType: "contrast",
+ params: { value: 12 },
+ }, host),
+ executeTool("set_clip_volume", { clipId: "c1", volume: 0.75 }, host),
+ executeTool("set_clip_fade", {
+ clipId: "c1",
+ fadeIn: 0.2,
+ fadeOut: 0.3,
+ }, host),
+ executeTool("add_audio_effect", {
+ clipId: "c1",
+ effectType: "compressor",
+ params: { threshold: -18 },
+ }, host),
+ ]);
+
+ expect(results.every((result) => result.ok)).toBe(true);
+
+ const keyframes = await executeTool("set_clip_keyframes", {
+ clipId: "c1",
+ keyframes: [
+ { time: 0, property: "scale.x", value: 1, easing: "ease-in-out" },
+ { time: 2, property: "scale.x", value: 1.35, easing: "ease-in-out" },
+ { time: 0, property: "scale.y", value: 1, easing: "ease-in-out" },
+ { time: 2, property: "scale.y", value: 1.35, easing: "ease-in-out" },
+ ],
+ }, host);
+ expect(keyframes.ok).toBe(true);
+
+ const clip = host.getProject().timeline.tracks[0].clips[0];
+ expect(clip.transform.position).toEqual({ x: 24, y: 0 });
+ expect(clip.transform.scale).toEqual({ x: 1.2, y: 1.2 });
+ expect(clip.speed).toBe(1.25);
+ expect(clip.effects.some((effect) => effect.type === "contrast")).toBe(true);
+ expect(clip.volume).toBe(0.75);
+ expect(clip.fade).toEqual({ fadeIn: 0.2, fadeOut: 0.3 });
+ expect(clip.audioEffects?.some((effect) => effect.type === "compressor")).toBe(true);
+ expect(clip.keyframes).toHaveLength(4);
+ expect(clip.keyframes.every((keyframe) => Boolean(keyframe.id))).toBe(true);
+ });
+
+ it("adds a transition and can trim and split existing timeline clips", async () => {
+ const transitionHost = new HeadlessHost(makeProjectWithAdjacentClips());
+ const transition = await executeTool("add_transition", {
+ clipAId: "c1",
+ clipBId: "c2",
+ transitionType: "whipPan",
+ duration: 0.4,
+ }, transitionHost);
+ expect(transition.ok).toBe(true);
+ expect(transitionHost.getProject().timeline.tracks[0].transitions).toHaveLength(1);
+
+ const trimHost = new HeadlessHost(makeProjectWithClip());
+ const trim = await executeTool("trim_clip", {
+ clipId: "c1",
+ inPoint: 0.5,
+ outPoint: 4.5,
+ }, trimHost);
+ expect(trim.ok).toBe(true);
+ expect(trimHost.getProject().timeline.tracks[0].clips[0].duration).toBe(4);
+
+ const split = await executeTool("split_clip", {
+ clipId: "c1",
+ time: 2,
+ }, trimHost);
+ expect(split.ok).toBe(true);
+ expect(trimHost.getProject().timeline.tracks[0].clips).toHaveLength(2);
+ });
+});
diff --git a/packages/agent/src/registry.ts b/packages/agent/src/registry.ts
index f35f5636..d5b04dba 100644
--- a/packages/agent/src/registry.ts
+++ b/packages/agent/src/registry.ts
@@ -306,6 +306,10 @@ import {
type MotionRotation3D,
} from "@openreel/core/motion/types";
import type { Keyframe, Marker } from "@openreel/core/types/timeline";
+import {
+ AUDIO_EFFECT_TYPES,
+ TRANSITION_TYPES,
+} from "@openreel/core/types/effects";
import { normalizeMotionBlurSettings } from "@openreel/core/motion/motion-blur";
import type { BlendMode } from "@openreel/core/video/types";
import type { LottieAnimation } from "@openreel/core/types/lottie";
@@ -412,6 +416,45 @@ const obj = (
required: string[] = [],
): JSONSchema => ({ type: "object", properties, required, additionalProperties: true });
+const timelineKeyframePropertySchema: JSONSchema = {
+ type: "string",
+ enum: [
+ "opacity",
+ "position.x",
+ "position.y",
+ "scale.x",
+ "scale.y",
+ "rotation",
+ "effect.brightness",
+ "effect.contrast",
+ "effect.saturation",
+ "effect.blur",
+ ],
+};
+
+const easingSchema: JSONSchema = { type: "string", enum: [...EASING_TYPES] };
+
+const timelineKeyframeInputSchema: JSONSchema = obj(
+ {
+ id: str,
+ time: num,
+ property: timelineKeyframePropertySchema,
+ value: {},
+ easing: easingSchema,
+ },
+ ["time", "property", "value"],
+);
+
+const clipTransformSchema: JSONSchema = obj({
+ position: obj({ x: num, y: num }),
+ scale: obj({ x: num, y: num }),
+ rotation: num,
+ opacity: num,
+ anchor: obj({ x: num, y: num }),
+ crop: obj({ x: num, y: num, width: num, height: num }),
+ fitMode: { type: "string", enum: ["contain", "cover", "stretch", "none"] },
+});
+
function vec2FromObject(
value: unknown,
): { readonly x: number; readonly y: number } | undefined {
@@ -15518,15 +15561,15 @@ const TOOLS: RegisteredTool[] = [
actionTool({ name: "add_clip", domain: "clip", actionType: "clip/add", title: "Add clip", description: "Add a media clip to a track at a time.", inputSchema: obj({ trackId: str, mediaId: str, startTime: num }, ["trackId", "mediaId", "startTime"]) }),
actionTool({ name: "remove_clip", domain: "clip", actionType: "clip/remove", title: "Remove clip", description: "Remove a clip.", inputSchema: obj({ clipId: str }, ["clipId"]), destructive: true }),
actionTool({ name: "move_clip", domain: "clip", actionType: "clip/move", title: "Move clip", description: "Move a clip to a new start time / track.", inputSchema: obj({ clipId: str, startTime: num, trackId: str }, ["clipId", "startTime"]) }),
- actionTool({ name: "trim_clip", domain: "clip", actionType: "clip/trim", title: "Trim clip", description: "Set a clip's in/out points (seconds).", inputSchema: obj({ clipId: str, inPoint: num, outPoint: num }, ["clipId"]) }),
- actionTool({ name: "split_clip", domain: "clip", actionType: "clip/split", title: "Split clip", description: "Split a clip at a time.", inputSchema: obj({ clipId: str, time: num }, ["clipId", "time"]) }),
+ actionTool({ name: "trim_clip", domain: "clip", actionType: "clip/trim", title: "Trim clip", description: "Trim an existing main-timeline clip by setting either or both source-media inPoint/outPoint values in seconds. Read the current values with get_clip first.", inputSchema: obj({ clipId: str, inPoint: num, outPoint: num }, ["clipId"]) }),
+ actionTool({ name: "split_clip", domain: "clip", actionType: "clip/split", title: "Split clip", description: "Split an existing main-timeline clip at an absolute timeline time in seconds. The time must fall strictly inside the clip's startTime..startTime+duration range.", inputSchema: obj({ clipId: str, time: num }, ["clipId", "time"]) }),
actionTool({ name: "ripple_delete_clip", domain: "clip", actionType: "clip/rippleDelete", title: "Ripple delete", description: "Delete a clip and close the gap.", inputSchema: obj({ clipId: str }, ["clipId"]), destructive: true }),
actionTool({ name: "slip_clip", domain: "clip", actionType: "clip/slip", title: "Slip clip", description: "Slip a clip's source by delta.", inputSchema: obj({ clipId: str, delta: num }, ["clipId", "delta"]) }),
actionTool({ name: "slide_clip", domain: "clip", actionType: "clip/slide", title: "Slide clip", description: "Slide a clip by delta.", inputSchema: obj({ clipId: str, delta: num, prevClipId: str, nextClipId: str }, ["clipId", "delta"]) }),
actionTool({ name: "roll_edit", domain: "clip", actionType: "clip/roll", title: "Roll edit", description: "Roll the edit point between two clips.", inputSchema: obj({ leftClipId: str, rightClipId: str, delta: num }, ["leftClipId", "rightClipId", "delta"]) }),
actionTool({ name: "trim_to_playhead", domain: "clip", actionType: "clip/trimToPlayhead", title: "Trim to playhead", description: "Trim a clip's start/end to a time.", inputSchema: obj({ clipId: str, playheadTime: num, trimStart: bool }, ["clipId", "playheadTime", "trimStart"]) }),
actionTool({ name: "close_gap", domain: "clip", actionType: "clip/closeGapBefore", title: "Close gap", description: "Close the gap before a clip.", inputSchema: obj({ clipId: str }, ["clipId"]) }),
- actionTool({ name: "set_clip_speed", domain: "speed", actionType: "clip/setSpeed", title: "Set speed", description: "Set clip playback speed (recomputes duration).", inputSchema: obj({ clipId: str, speed: num }, ["clipId", "speed"]) }),
+ actionTool({ name: "set_clip_speed", domain: "speed", actionType: "clip/setSpeed", title: "Set speed", description: "Set an existing main-timeline clip's playback-speed multiplier (for example 0.5 = half speed, 2 = double speed); recomputes its duration. Use get_capabilities speed.range for limits.", inputSchema: obj({ clipId: str, speed: num }, ["clipId", "speed"]) }),
actionTool({ name: "set_clip_reverse", domain: "speed", actionType: "clip/setReverse", title: "Reverse clip", description: "Toggle clip reverse.", inputSchema: obj({ clipId: str, reversed: bool }, ["clipId", "reversed"]) }),
actionTool({ name: "set_clip_pitch_correction", domain: "speed", actionType: "clip/setPitchCorrection", title: "Pitch correction", description: "Toggle pitch correction on speed changes.", inputSchema: obj({ clipId: str, pitchCorrection: bool }, ["clipId", "pitchCorrection"]) }),
actionTool({ name: "set_speed_ramp", domain: "speed", actionType: "speed/setRampData", title: "Speed ramp", description: "Set speed keyframes / freeze frames / pitch.", inputSchema: obj({ clipId: str, keyframes: { type: "array" }, freezeFrames: { type: "array" }, pitchCorrection: bool }, ["clipId"]) }),
@@ -15534,7 +15577,7 @@ const TOOLS: RegisteredTool[] = [
actionTool({ name: "set_clip_chroma_key", domain: "speed", actionType: "clip/setChromaKey", title: "Chroma key", description: "Set green-screen / chroma-key settings.", inputSchema: obj({ clipId: str, chromaKey: { type: "object" } }, ["clipId"]) }),
// transform / blend
- actionTool({ name: "set_clip_transform", domain: "transform", actionType: "transform/update", title: "Transform clip", description: "Set position/scale/rotation/opacity/crop/fitMode.", inputSchema: obj({ clipId: str, transform: { type: "object" } }, ["clipId", "transform"]) }),
+ actionTool({ name: "set_clip_transform", domain: "transform", actionType: "transform/update", title: "Transform clip", description: "Update an existing main-timeline clip's static transform. position is a pixel offset from canvas center; scale uses 1 = 100%; rotation is degrees; opacity is 0..1. Partial nested updates are safely merged, so {scale:{x:1.2,y:1.2}} performs a 120% zoom without resetting position.", inputSchema: obj({ clipId: str, transform: clipTransformSchema }, ["clipId", "transform"]) }),
actionTool({ name: "set_clip_blend_mode", domain: "transform", actionType: "clip/setBlendMode", title: "Blend mode", description: "Set a clip's blend mode.", inputSchema: obj({ clipId: str, blendMode: str }, ["clipId", "blendMode"]) }),
actionTool({ name: "set_clip_blend_opacity", domain: "transform", actionType: "clip/setBlendOpacity", title: "Blend opacity", description: "Set a clip's blend opacity (0..1).", inputSchema: obj({ clipId: str, opacity: num }, ["clipId", "opacity"]) }),
@@ -15602,7 +15645,32 @@ const TOOLS: RegisteredTool[] = [
actionTool({ name: "set_clip_volume", domain: "audio", actionType: "audio/setVolume", title: "Set volume", description: "Set a clip's volume (0..1+).", inputSchema: obj({ clipId: str, volume: num }, ["clipId", "volume"]) }),
actionTool({ name: "set_clip_fade", domain: "audio", actionType: "audio/setFade", title: "Set fade", description: "Set audio fade in/out seconds.", inputSchema: obj({ clipId: str, fadeIn: num, fadeOut: num }, ["clipId"]) }),
actionTool({ name: "add_audio_automation", domain: "audio", actionType: "audio/addAutomation", title: "Audio automation", description: "Add audio automation points.", inputSchema: obj({ clipId: str, points: { type: "array" } }, ["clipId", "points"]) }),
- actionTool({ name: "add_audio_effect", domain: "audio", actionType: "audio/addEffect", title: "Add audio effect", description: "Add an audio effect to a clip.", inputSchema: obj({ clipId: str, effect: { type: "object" } }, ["clipId", "effect"]) }),
+ actionTool({
+ name: "add_audio_effect",
+ domain: "audio",
+ actionType: "audio/addEffect",
+ title: "Add audio effect",
+ description: "Add an audio effect to an existing main-timeline clip. Pass effectType (gain|pan|eq|compressor|reverb|delay|noiseReduction|fadeIn|fadeOut) and optional params; the effect id is generated automatically. A complete legacy effect object is also accepted.",
+ inputSchema: {
+ ...obj({
+ clipId: str,
+ effectType: { type: "string", enum: [...AUDIO_EFFECT_TYPES] },
+ params: { type: "object" },
+ effect: { type: "object" },
+ }, ["clipId"]),
+ anyOf: [{ required: ["effectType"] }, { required: ["effect"] }],
+ },
+ mapParams: (args) => ({
+ clipId: args.clipId,
+ effect:
+ asRecord(args.effect) ?? {
+ id: genId(),
+ type: args.effectType,
+ enabled: true,
+ params: asRecord(args.params) ?? {},
+ },
+ }),
+ }),
actionTool({ name: "remove_audio_effect", domain: "audio", actionType: "audio/removeEffect", title: "Remove audio effect", description: "Remove an audio effect.", inputSchema: obj({ clipId: str, effectId: str }, ["clipId", "effectId"]) }),
actionTool({ name: "update_audio_effect", domain: "audio", actionType: "audio/updateEffect", title: "Update audio effect", description: "Update an audio effect's params.", inputSchema: obj({ clipId: str, effectId: str, params: { type: "object" } }, ["clipId", "effectId", "params"]) }),
actionTool({ name: "toggle_audio_effect", domain: "audio", actionType: "audio/toggleEffect", title: "Toggle audio effect", description: "Enable/disable an audio effect.", inputSchema: obj({ clipId: str, effectId: str, enabled: bool }, ["clipId", "effectId", "enabled"]) }),
@@ -15615,13 +15683,33 @@ const TOOLS: RegisteredTool[] = [
actionTool({ name: "set_subtitle_style", domain: "subtitle", actionType: "subtitle/setStyle", title: "Subtitle style", description: "Set the global subtitle style.", inputSchema: obj({ style: { type: "object" } }, ["style"]) }),
// keyframe
- actionTool({ name: "add_keyframe", domain: "keyframe", actionType: "keyframe/add", title: "Add keyframe", description: "Add a keyframe for a clip property.", inputSchema: obj({ clipId: str, property: str, time: num, value: {} }, ["clipId", "property", "time"]) }),
+ actionTool({ name: "add_keyframe", domain: "keyframe", actionType: "keyframe/add", title: "Add keyframe", description: "Animate an existing main-timeline clip by adding a property keyframe at clip-local time in seconds. Supported transform properties are opacity, position.x/y, scale.x/y, and rotation; supported effect properties are effect.brightness/contrast/saturation/blur. Add at least two keyframes for interpolation.", inputSchema: obj({ clipId: str, property: timelineKeyframePropertySchema, time: num, value: {}, easing: easingSchema }, ["clipId", "property", "time", "value"]) }),
actionTool({ name: "remove_keyframe", domain: "keyframe", actionType: "keyframe/remove", title: "Remove keyframe", description: "Remove a keyframe.", inputSchema: obj({ clipId: str, property: str, time: num }, ["clipId", "property", "time"]) }),
- actionTool({ name: "set_clip_keyframes", domain: "keyframe", actionType: "keyframe/setAll", title: "Set keyframes", description: "Replace all keyframes on a clip.", inputSchema: obj({ clipId: str, keyframes: { type: "array" } }, ["clipId", "keyframes"]) }),
+ actionTool({
+ name: "set_clip_keyframes",
+ domain: "keyframe",
+ actionType: "keyframe/setAll",
+ title: "Set keyframes",
+ description: "Replace all animation keyframes on an existing main-timeline clip. Times are clip-local seconds. Each item needs property, time, and value; id and easing default automatically.",
+ inputSchema: obj({ clipId: str, keyframes: { type: "array", items: timelineKeyframeInputSchema } }, ["clipId", "keyframes"]),
+ mapParams: (args) => ({
+ clipId: args.clipId,
+ keyframes: Array.isArray(args.keyframes)
+ ? args.keyframes.map((value) => {
+ const keyframe = asRecord(value) ?? {};
+ return {
+ ...keyframe,
+ id: optionalString(keyframe.id) ?? genId(),
+ easing: optionalString(keyframe.easing) ?? "linear",
+ };
+ })
+ : args.keyframes,
+ }),
+ }),
// transition
- actionTool({ name: "add_transition", domain: "transition", actionType: "transition/add", title: "Add transition", description: "Add a transition between two clips.", inputSchema: obj({ clipAId: str, clipBId: str, transitionType: str, duration: num }, ["clipAId", "clipBId", "transitionType", "duration"]) }),
- actionTool({ name: "update_transition", domain: "transition", actionType: "transition/update", title: "Update transition", description: "Update a transition.", inputSchema: obj({ transitionId: str, type: str, duration: num }, ["transitionId"]) }),
+ actionTool({ name: "add_transition", domain: "transition", actionType: "transition/add", title: "Add transition", description: "Add a rendered transition between two adjacent existing clips on the same main-timeline track. Use list_clips for ordered clip ids and get_capabilities transitionTypes for values such as whipPan, zoom, push, glitch, or flash.", inputSchema: obj({ clipAId: str, clipBId: str, transitionType: { type: "string", enum: [...TRANSITION_TYPES] }, duration: num }, ["clipAId", "clipBId", "transitionType", "duration"]) }),
+ actionTool({ name: "update_transition", domain: "transition", actionType: "transition/update", title: "Update transition", description: "Update an existing main-timeline transition's type and/or duration.", inputSchema: obj({ transitionId: str, type: { type: "string", enum: [...TRANSITION_TYPES] }, duration: num }, ["transitionId"]) }),
actionTool({ name: "remove_transition", domain: "transition", actionType: "transition/remove", title: "Remove transition", description: "Remove a transition.", inputSchema: obj({ transitionId: str }, ["transitionId"]) }),
// marker
diff --git a/packages/agent/src/system-prompt.ts b/packages/agent/src/system-prompt.ts
index 5686882f..72a10bd9 100644
--- a/packages/agent/src/system-prompt.ts
+++ b/packages/agent/src/system-prompt.ts
@@ -24,6 +24,8 @@ export function buildSystemPrompt(
"- Refer to clips by `clipId` (from list_clips/get_clip). You may also pass `clipIndex` or `atSec` and the tool will resolve the clip.",
"- Read before you write: use get_editor_state, list_clips, get_clip, and get_capabilities to ground your edits in valid ids and enum values.",
"- Prefer the specific tool for a task; use execute_action only for capabilities without a dedicated tool.",
+ "- Existing clips on the main editor timeline are fully editable. Use trim_clip/split_clip, set_clip_transform, add_keyframe/set_clip_keyframes, set_clip_speed/set_speed_ramp, add_video_effect, the audio tools, and add_transition as requested. Do not claim that a capability is unavailable when its tool appears below.",
+ "- Do not confuse main-timeline clip animation with Motion Creator. For an existing clip, use the clip transform/keyframe tools; use Motion tools only when the user asks for a Motion composition or motion-graphics layers.",
"- Use duplicate_track for timeline-backed video/image/audio tracks. For repeated Motion styling, use transfer_motion_effect_stack or transfer_motion_mask_stack so animated parameters, expressions, ordering, and independent ids are preserved across target layers.",
"- Destructive/expensive tools (delete, remove, export, AI jobs) require user confirmation — explain what you're about to do.",
"- After making the requested edits, stop and summarize what you changed.",
diff --git a/packages/agent/src/tool-router.test.ts b/packages/agent/src/tool-router.test.ts
index 7536290e..27bfc47c 100644
--- a/packages/agent/src/tool-router.test.ts
+++ b/packages/agent/src/tool-router.test.ts
@@ -42,4 +42,36 @@ describe("agent tool router", () => {
});
expect(names).toContain("animate_layer");
});
+
+ it("does not mistake existing-clip animation for Motion-only work", () => {
+ const names = selectToolsForPrompt(
+ "On the main timeline, animate the existing clips with zoom keyframes, add a whipPan transition, trim and split the footage, speed it up, add a video effect, and fade the audio",
+ );
+
+ expect(names.length).toBeLessThanOrEqual(DEFAULT_AGENT_TOOL_LIMIT);
+ expect(names).toEqual(
+ expect.arrayContaining([
+ "set_clip_transform",
+ "add_keyframe",
+ "set_clip_keyframes",
+ "add_transition",
+ "trim_clip",
+ "split_clip",
+ "set_clip_speed",
+ "add_video_effect",
+ "set_clip_fade",
+ "add_audio_effect",
+ ]),
+ );
+ });
+
+ it.each([
+ ["Animate a slow zoom on the first video clip", "add_keyframe"],
+ ["Move and scale the existing clip", "set_clip_transform"],
+ ["Add a glitch transition between these clips", "add_transition"],
+ ["Split the clip and make the second half faster", "split_clip"],
+ ["Clean up the audio on this footage", "add_audio_effect"],
+ ])("routes main-timeline request %j to %s", (prompt, expectedTool) => {
+ expect(selectToolsForPrompt(prompt)).toContain(expectedTool);
+ });
});
diff --git a/packages/agent/src/tool-router.ts b/packages/agent/src/tool-router.ts
index 268bb75a..e2a02649 100644
--- a/packages/agent/src/tool-router.ts
+++ b/packages/agent/src/tool-router.ts
@@ -29,9 +29,32 @@ const ALWAYS_AVAILABLE = new Set([
"batch_actions",
]);
-const MOTION_TERMS = /\b(motion|composition|layer|keyframe|animate|animation|after effects|lower third|title card|kinetic|lottie|svg|figma|particle|shader|mask|matte|precomp|camera|render frame)\b/i;
+// Keep this list specific to Motion Creator. Generic editing words such as
+// "animate", "animation", and "keyframe" also describe ordinary timeline
+// clips; treating them as Motion-only used to remove every main-timeline
+// mutation tool from the request.
+const MOTION_TERMS = /\b(motion(?: creator| graphics?)?|composition|layer|after effects|lower third|title card|kinetic|lottie|svg|figma|particle|shader|mask|matte|precomp|camera|render frame)\b/i;
const CREATION_TERMS = /\b(3d|three[- ]?d|product|character|scene|model|gltf|glb|rig|mesh|material|texture|bevel|displacement|x[- ]?ray|cloth|camera module|exploded|cinematic|decal|cutaway)\b/i;
+const TIMELINE_TERMS = /\b(timeline|clip|clips|footage|video|audio|transition|trim|split|cut|speed|slow(?:er| down)?|fast(?:er| forward)?|reverse|volume|sound|fade|effect|filter|color|zoom|scale|position|crop|opacity|rotate|keyframe|animate|animation)\b/i;
+
+const TIMELINE_DOMAINS = new Set([
+ "track",
+ "clip",
+ "transform",
+ "effect",
+ "color",
+ "speed",
+ "audio",
+ "text",
+ "subtitle",
+ "graphics",
+ "transition",
+ "keyframe",
+ "marker",
+ "ai",
+]);
+
const words = (value: string): string[] =>
value
.toLowerCase()
@@ -71,6 +94,7 @@ export function selectToolsForPrompt(
const maxTools = Math.max(1, options.maxTools ?? DEFAULT_AGENT_TOOL_LIMIT);
const wantsMotion = MOTION_TERMS.test(prompt);
const wantsCreation = CREATION_TERMS.test(prompt);
+ const wantsTimeline = TIMELINE_TERMS.test(prompt);
const prior = new Set(options.priorToolNames ?? []);
const promptWords = new Set(words(prompt));
@@ -79,6 +103,10 @@ export function selectToolsForPrompt(
if (!wantsMotion && !wantsCreation) return tool.domain !== "motion";
if (wantsCreation && isCreationTool(tool)) return true;
if (wantsMotion && tool.domain === "motion" && !isCreationTool(tool)) return true;
+ // A request can legitimately combine Motion/3D work with edits to an
+ // existing main-timeline clip. Do not make those tool families mutually
+ // exclusive when the user explicitly refers to timeline editing.
+ if (wantsTimeline && TIMELINE_DOMAINS.has(tool.domain)) return true;
return tool.domain === "read" || ["project", "media", "export", "raw"].includes(tool.domain);
});
@@ -90,7 +118,8 @@ export function selectToolsForPrompt(
relevance(tool, promptWords) +
(prior.has(tool.name) ? 5_000 : 0) +
(wantsCreation && isCreationTool(tool) ? 100 : 0) +
- (wantsMotion && tool.domain === "motion" ? 50 : 0),
+ (wantsMotion && tool.domain === "motion" ? 50 : 0) +
+ (wantsTimeline && TIMELINE_DOMAINS.has(tool.domain) ? 50 : 0),
}))
.sort((a, b) => b.score - a.score || a.index - b.index)
.slice(0, maxTools)
diff --git a/packages/core/src/actions/action-executor.test.ts b/packages/core/src/actions/action-executor.test.ts
index 2c6f2cf0..62eea09c 100644
--- a/packages/core/src/actions/action-executor.test.ts
+++ b/packages/core/src/actions/action-executor.test.ts
@@ -220,6 +220,56 @@ describe("ActionExecutor transform/update", () => {
});
});
+describe("ActionExecutor AI timeline editing actions", () => {
+ it("computes duration from the new in and out points in one trim", async () => {
+ const executor = new ActionExecutor();
+ const project = makeProjectWithClip();
+
+ const result = await executor.execute({
+ id: "trim-both",
+ type: "clip/trim",
+ params: { clipId: "c1", inPoint: 0.5, outPoint: 4.5 },
+ timestamp: Date.now(),
+ } as Action, project);
+
+ expect(result.success).toBe(true);
+ expect(project.timeline.tracks[0].clips[0]).toMatchObject({
+ inPoint: 0.5,
+ outPoint: 4.5,
+ duration: 4,
+ });
+ });
+
+ it("preserves requested easing and creates stable unique keyframe ids", async () => {
+ const executor = new ActionExecutor();
+ const project = makeProjectWithClip();
+
+ for (const [id, time, value] of [
+ ["zoom-start", 0, 1],
+ ["zoom-end", 2, 1.3],
+ ] as const) {
+ const result = await executor.execute({
+ id,
+ type: "keyframe/add",
+ params: {
+ clipId: "c1",
+ property: "scale.x",
+ time,
+ value,
+ easing: "ease-in-out",
+ },
+ timestamp: Date.now(),
+ } as Action, project);
+ expect(result.success).toBe(true);
+ }
+
+ expect(project.timeline.tracks[0].clips[0].keyframes).toMatchObject([
+ { id: "keyframe-zoom-start", easing: "ease-in-out" },
+ { id: "keyframe-zoom-end", easing: "ease-in-out" },
+ ]);
+ });
+});
+
describe("ActionExecutor compound instance synchronization", () => {
it("keeps persisted nested timing aligned with timeline move and trim edits", async () => {
const executor = new ActionExecutor();
diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.ts
index f7fbf903..07527321 100644
--- a/packages/core/src/actions/action-executor.ts
+++ b/packages/core/src/actions/action-executor.ts
@@ -940,16 +940,14 @@ export class ActionExecutor {
...track,
clips: track.clips.map((clip: MutableClip) => {
if (clip.id === params.clipId) {
- const updates: Partial<MutableClip> = {};
- if (params.inPoint !== undefined) {
- updates.inPoint = params.inPoint;
- updates.duration = clip.outPoint - params.inPoint;
- }
- if (params.outPoint !== undefined) {
- updates.outPoint = params.outPoint;
- updates.duration = params.outPoint - clip.inPoint;
- }
- return { ...clip, ...updates };
+ const inPoint = params.inPoint ?? clip.inPoint;
+ const outPoint = params.outPoint ?? clip.outPoint;
+ return {
+ ...clip,
+ inPoint,
+ outPoint,
+ duration: outPoint - inPoint,
+ };
}
return clip;
}),
@@ -1564,13 +1562,16 @@ export class ActionExecutor {
time: number;
property: string;
value: unknown;
+ easing?: EasingType;
};
const newKeyframe = {
- id: `keyframe-${Date.now()}`,
+ // Derive the id from the action so rapid sequential agent calls and
+ // redo cannot collide within the same millisecond.
+ id: `keyframe-${(action as Action).id}`,
time: params.time,
property: params.property,
value: params.value,
- easing: "linear" as const,
+ easing: params.easing ?? ("linear" as const),
};
timeline.tracks = timeline.tracks.map((track: MutableTrack) => ({
diff --git a/packages/core/src/actions/action-history.ts b/packages/core/src/actions/action-history.ts
index a88fda72..1fa635e7 100644
--- a/packages/core/src/actions/action-history.ts
+++ b/packages/core/src/actions/action-history.ts
@@ -49,6 +49,7 @@ const ACTION_DESCRIPTIONS: Record<
"transform/update": () => "Transform clip",
"keyframe/add": (params) => `Add ${params.property} keyframe`,
"keyframe/remove": () => "Remove keyframe",
+ "keyframe/setAll": () => "Replace clip keyframes",
"transition/add": (params) => `Add ${params.transitionType} transition`,
"transition/set": () => "Add transition",
"transition/update": () => "Update transition",
diff --git a/packages/core/src/actions/action-validator.ts b/packages/core/src/actions/action-validator.ts
index 9411733b..d912835b 100644
--- a/packages/core/src/actions/action-validator.ts
+++ b/packages/core/src/actions/action-validator.ts
@@ -16,6 +16,8 @@ import type {
MarkerAction,
} from "../types/actions";
import type { Project, Timeline, Track, Clip } from "../types";
+import { EASING_TYPES } from "../types/timeline";
+import { TRANSITION_TYPES } from "../types/effects";
import { getActionHandler } from "./registry";
export class ActionValidator {
@@ -953,6 +955,8 @@ export class ActionValidator {
const errors: ValidationError[] = [];
const timeline = project.timeline;
+ // The registered bulk-set handler owns validation for this action. This
+ // branch also narrows the legacy validator's remaining action union.
if (action.type === "keyframe/setAll") {
return errors;
}
@@ -1001,6 +1005,18 @@ export class ActionValidator {
});
}
+ if (
+ action.type === "keyframe/add" &&
+ action.params.easing !== undefined &&
+ !EASING_TYPES.includes(action.params.easing)
+ ) {
+ errors.push({
+ code: "INVALID_PARAMS",
+ message: "Easing must be a supported easing type",
+ path: "params.easing",
+ });
+ }
+
return errors;
}
@@ -1035,6 +1051,17 @@ export class ActionValidator {
});
}
+ if (
+ typeof action.params.transitionType !== "string" ||
+ !TRANSITION_TYPES.includes(action.params.transitionType)
+ ) {
+ errors.push({
+ code: "INVALID_PARAMS",
+ message: "Transition type must be supported",
+ path: "params.transitionType",
+ });
+ }
+
if (
typeof action.params.duration !== "number" ||
action.params.duration <= 0
@@ -1128,6 +1155,18 @@ export class ActionValidator {
});
}
+ if (
+ action.type === "transition/update" &&
+ action.params.type !== undefined &&
+ !TRANSITION_TYPES.includes(action.params.type)
+ ) {
+ errors.push({
+ code: "INVALID_PARAMS",
+ message: "Transition type must be supported",
+ path: "params.type",
+ });
+ }
+
if (
action.type === "transition/update" &&
action.params.duration !== undefined
@@ -1235,11 +1274,18 @@ export class ActionValidator {
break;
case "audio/addEffect": {
- const effect = action.params.effect as { id?: unknown } | undefined;
- if (!effect || typeof effect.id !== "string") {
+ const effect = action.params.effect as
+ | { id?: unknown; type?: unknown }
+ | undefined;
+ if (
+ !effect ||
+ typeof effect.id !== "string" ||
+ typeof effect.type !== "string" ||
+ !effect.type
+ ) {
errors.push({
code: "INVALID_PARAMS",
- message: "A valid effect object with an id is required",
+ message: "A valid effect object with an id and type is required",
path: "params.effect",
});
}
diff --git a/packages/core/src/types/actions.ts b/packages/core/src/types/actions.ts
index de90cda1..b122ccc0 100644
--- a/packages/core/src/types/actions.ts
+++ b/packages/core/src/types/actions.ts
@@ -303,6 +303,7 @@ export type KeyframeAction =
property: string;
time: number;
value: unknown;
+ easing?: EasingType;
};
}
| {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 627a17d6..179b6613 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -26,6 +26,34 @@ importers:
specifier: ^0.1.1
+ apps/cloud:
+ dependencies:
+ '@openreel/fxpkg':
+ specifier: workspace:*
+ version: link:../../packages/fxpkg
+ hono:
+ specifier: ^4.11.4
+ version: 4.13.12
+ jose:
+ specifier: ^6.2.3
+ version: 6.2.12
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
+ devDependencies:
+ '@cloudflare/workers-types':
+ specifier: ^4.20260117.0
+ version: 4.20260117.0
+ typescript:
+ specifier: ^5.5.2
+ version: 5.9.3
+ vitest:
+ specifier: ^1.6.0
+ version: 1.6.1(@types/[email protected])(@vitest/[email protected])([email protected])
+ wrangler:
+ specifier: ^3.101.0
+ version: 3.114.17(@cloudflare/[email protected])
+
apps/desktop:
dependencies:
electron-updater:
@@ -4002,6 +4030,10 @@ packages:
resolution: {integrity: sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==}
+ resolution: {integrity: sha512-6E2QDAc9Ick9Sq77ZrGS/dk2WUYni91aufTw6LJKpV7w8kW5/GxVUc650FOADOmlwg3K+f7Pun6XlV+pYmW6gw==}
+ engines: {node: '>=16.9.0'}
+
resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}
engines: {node: '>=10'}
@@ -4192,6 +4224,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
+ resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
+
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
@@ -6215,8 +6250,7 @@ snapshots:
'@cloudflare/[email protected]':
optional: true
- '@cloudflare/[email protected]':
- optional: true
+ '@cloudflare/[email protected]': {}
'@cspotcode/[email protected]':
dependencies:
@@ -9173,6 +9207,8 @@ snapshots:
+
dependencies:
lru-cache: 6.0.0
@@ -9341,6 +9377,8 @@ snapshots:
+
diff --git a/scripts/check-mobile-offline.mjs b/scripts/check-mobile-offline.mjs
new file mode 100644
index 00000000..dd9fdccd
--- /dev/null
+++ b/scripts/check-mobile-offline.mjs
@@ -0,0 +1,99 @@
+import { createHash } from "node:crypto";
+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
+import { extname, join, relative, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
+const androidRoot = join(root, "Openreel Video Android");
+const iosRoot = join(root, "Openreel Video", "Openreel Video");
+const failures = [];
+
+function assert(condition, message) {
+ if (!condition) failures.push(message);
+}
+
+function filesBelow(directory, extensions) {
+ const files = [];
+ for (const name of readdirSync(directory)) {
+ const path = join(directory, name);
+ if (statSync(path).isDirectory()) files.push(...filesBelow(path, extensions));
+ else if (extensions.has(extname(path))) files.push(path);
+ }
+ return files;
+}
+
+function rejectPatterns(files, patterns, label) {
+ for (const file of files) {
+ const source = readFileSync(file, "utf8");
+ for (const pattern of patterns) {
+ assert(!pattern.test(source), `${label}: ${relative(root, file)} matches ${pattern}`);
+ }
+ }
+}
+
+const manifestPath = join(androidRoot, "app", "src", "main", "AndroidManifest.xml");
+const manifest = readFileSync(manifestPath, "utf8");
+assert(
+ /android\.permission\.INTERNET"\s+tools:node="remove"/.test(manifest),
+ "Android must explicitly remove transitive INTERNET permission",
+);
+assert(
+ /android\.permission\.ACCESS_NETWORK_STATE"\s+tools:node="remove"/.test(manifest),
+ "Android must explicitly remove transitive network-state permission",
+);
+assert(manifest.includes('android:allowBackup="false"'), "Android backups must remain disabled");
+
+const androidFiles = filesBelow(join(androidRoot, "app", "src", "main", "java"), new Set([".kt", ".java"]));
+rejectPatterns(
+ androidFiles,
+ [/\bokhttp3\b/, /\bPlayIntegrity\b/, /\bAICloudJob\b/, /https?:\/\//],
+ "Android online dependency",
+);
+rejectPatterns(
+ [join(androidRoot, "app", "build.gradle.kts"), join(androidRoot, "gradle", "libs.versions.toml")],
+ [/okhttp/i, /play.?integrity/i, /mockwebserver/i],
+ "Android build dependency",
+);
+
+const iosFiles = filesBelow(iosRoot, new Set([".swift"]));
+rejectPatterns(
+ iosFiles,
+ [/\bURLSession\b/, /\bAppAttest\b/, /\bAICloudJob\b/, /\bS3MediaUploader\b/, /https?:\/\//],
+ "iOS online dependency",
+);
+rejectPatterns(
+ [join(root, "Openreel Video", "Openreel Video.xcodeproj", "project.pbxproj")],
+ [/OpenReelAuthBroker/i, /https?:\/\//],
+ "iOS online build configuration",
+);
+
+for (const path of [
+ join(iosRoot, "AIWorkerConfiguration.plist"),
+ join(iosRoot, "Core", "AI", "AICloudJobService.swift"),
+ join(androidRoot, "app", "src", "main", "java", "com", "pythonxi", "openreelvideo", "core", "ai", "AICloudJobService.kt"),
+]) {
+ assert(!existsSync(path), `Legacy cloud file still exists: ${relative(root, path)}`);
+}
+
+const expectedLutSha = "35ea0282ab20cdec4a1a506f8323219c79baea6852337236c10df55a7296c137";
+for (const path of [
+ join(iosRoot, "Resources", "Filters", "cinematic.teal_orange.cube"),
+ join(androidRoot, "app", "src", "main", "assets", "filters", "cinematic.teal_orange.cube"),
+]) {
+ assert(existsSync(path), `Bundled LUT missing: ${relative(root, path)}`);
+ if (existsSync(path)) {
+ const digest = createHash("sha256").update(readFileSync(path)).digest("hex");
+ assert(digest === expectedLutSha, `Bundled LUT digest mismatch: ${relative(root, path)}`);
+ }
+}
+
+const iosAudioSources = readFileSync(join(iosRoot, "Features", "Audio", "AudioSources.swift"), "utf8");
+assert(iosAudioSources.includes("showsCloudItems = false"), "iOS music picker must hide cloud-only media");
+
+if (failures.length) {
+ console.error(`Mobile offline check failed (${failures.length}):`);
+ for (const failure of failures) console.error(`- ${failure}`);
+ process.exit(1);
+}
+
+console.log(`Mobile offline check passed (${androidFiles.length} Android and ${iosFiles.length} iOS source files scanned).`);
diff --git a/scripts/check-retired-cloud-gpu.mjs b/scripts/check-retired-cloud-gpu.mjs
new file mode 100644
index 00000000..881c0450
--- /dev/null
+++ b/scripts/check-retired-cloud-gpu.mjs
@@ -0,0 +1,74 @@
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { extname, join, relative, resolve } from "node:path";
+
+const root = resolve(import.meta.dirname, "..");
+const sourceRoots = ["apps", "packages"].map((path) => join(root, path));
+const sourceExtensions = new Set([".cjs", ".js", ".jsx", ".mjs", ".ts", ".tsx"]);
+const ignoredDirectories = new Set(["build", "dist", "node_modules", "out"]);
+const forbidden = [
+ /ai\.openreel\.video/i,
+ /cloud\.openreel\.video/i,
+ /\bAICloudJob\b/,
+ /\bAIWorker(?:Configuration|Job|Result|Artifact)\b/,
+ /\bGpuJob\b/,
+ /gpu-job/i,
+ /runCloudToolAction/,
+ /\bisCloudEnabled\b/,
+ /\bOPENREEL_(?:AI|TTS|TRANSCRIBE)_/,
+];
+
+function walk(directory) {
+ if (!existsSync(directory)) return [];
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ return ignoredDirectories.has(entry.name) ? [] : walk(path);
+ }
+ return entry.isFile() && sourceExtensions.has(extname(entry.name)) ? [path] : [];
+ });
+}
+
+function containsAnyFile(directory) {
+ if (!existsSync(directory)) return false;
+ return readdirSync(directory, { withFileTypes: true }).some((entry) => {
+ const path = join(directory, entry.name);
+ return entry.isFile() || (entry.isDirectory() && containsAnyFile(path));
+ });
+}
+
+const failures = [];
+const files = sourceRoots.flatMap(walk);
+for (const file of files) {
+ const contents = readFileSync(file, "utf8");
+ for (const pattern of forbidden) {
+ if (pattern.test(contents)) {
+ failures.push(`${relative(root, file)} matches ${pattern}`);
+ }
+ }
+}
+
+for (const retiredDirectory of ["infra/gpu-worker", "infra/transcribe-service"]) {
+ const path = join(root, retiredDirectory);
+ if (existsSync(path) && statSync(path).isDirectory() && containsAnyFile(path)) {
+ failures.push(`${retiredDirectory} still contains files`);
+ }
+}
+
+const retiredFiles = [
+ "apps/desktop/src/main/gpu/job-client.ts",
+ "apps/desktop/src/main/gpu/token-provider.ts",
+ "apps/web/src/services/gpu-jobs.ts",
+ "apps/web/src/stores/gpu-job-store.ts",
+ "packages/agent-runner/src/gpu-job-runner.ts",
+ "packages/core/src/ai/cloud-job-types.ts",
+];
+for (const file of retiredFiles) {
+ if (existsSync(join(root, file))) failures.push(`${file} still exists`);
+}
+
+if (failures.length > 0) {
+ console.error("Retired cloud-GPU check failed:\n" + failures.map((item) => `- ${item}`).join("\n"));
+ process.exit(1);
+}
+
+console.log(`Retired cloud-GPU check passed (${files.length} runtime source files scanned).`);
diff --git a/scripts/parity/compare_averages.py b/scripts/parity/compare_averages.py
new file mode 100755
index 00000000..d56aba39
--- /dev/null
+++ b/scripts/parity/compare_averages.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Cross-platform parity gate for filter-rendered averages.
+
+Compares two CSV-style triples (R,G,B integer averages) and exits non-zero
+if any channel diverges beyond the tolerance.
+"""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+
+def parse(path: Path) -> tuple[int, int, int]:
+ parts = path.read_text().strip().split(",")
+ if len(parts) != 3:
+ raise SystemExit(f"expected 'R,G,B' in {path}, got {parts!r}")
+ return tuple(int(p) for p in parts) # type: ignore[return-value]
+
+
+def main() -> int:
+ if len(sys.argv) < 3:
+ print("usage: compare_averages.py <ios.txt> <android.txt> [tolerance]", file=sys.stderr)
+ return 2
+ ios = parse(Path(sys.argv[1]))
+ android = parse(Path(sys.argv[2]))
+ tolerance = int(sys.argv[3]) if len(sys.argv) > 3 else 2
+ deltas = [abs(a - b) for a, b in zip(ios, android)]
+ if max(deltas) > tolerance:
+ print(f"FAIL ios={ios} android={android} deltas={deltas} tolerance={tolerance}", file=sys.stderr)
+ return 1
+ print(f"OK ios={ios} android={android} deltas={deltas} tolerance={tolerance}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())