Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): bootstrap the v3 editor model and shell, and make it the only editor
Etienne Lescot1320121d83c2
diff --git a/biome.json b/biome.jsonindex 517be7287..b7c87298d 100644--- a/biome.json+++ b/biome.json@@ -1,7 +1,10 @@{"$schema": "https://biomejs.dev/schemas/2.4.12/schema.json","vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },- "files": { "ignoreUnknown": false, "includes": ["**", "!**/*.css"] },+ "files": {+ "ignoreUnknown": false,+ "includes": ["**", "!**/*.css", "!**/design/**", "!**/.worktrees/**"]+ },"formatter": {"enabled": true,"indentStyle": "tab",@@ -92,7 +95,14 @@"useGetterReturn": "error"}},- "includes": ["**", "**/dist", "**/.eslintrc.cjs", "!**/*.css"]+ "includes": [+ "**",+ "**/dist",+ "**/.eslintrc.cjs",+ "!**/*.css",+ "!**/design/**",+ "!**/.worktrees/**"+ ]},"javascript": { "formatter": { "quoteStyle": "double" } },"overrides": [diff --git a/docs/architecture/ai-edition-collision-analysis.md b/docs/architecture/ai-edition-collision-analysis.mdnew file mode 100644index 000000000..f469b8925--- /dev/null+++ b/docs/architecture/ai-edition-collision-analysis.md@@ -0,0 +1,355 @@+# AI Edition Merge — Collision Analysis & Edge Cases++> Cross-references `ai-edition-merge-plan.md`, `openscreen-inventory.md`, `axcut-inventory.md`. Every collision listed here must be resolved before its owning phase starts.+>+> **Severity legend:** 🔴 breaks the merge · 🟠 will cause user-visible regressions · 🟡 polish / nice-to-have.++---++## 1. Schema collisions (Phase 0)++### 1.1 Both projects have `version: 2` but mean different things 🔴+- OpenScreen: `projectPersistence.ts:65` — `PROJECT_VERSION = 2`, denotes the `EditorProjectData` envelope.+- axcut: `axcut-schema/src/index.ts:1` — `axcutSchemaVersion = 2`, denotes the `AxcutDocument` shape.+- **Resolution:** bump everything to v3. Single `SCHEMA_VERSION = 3` constant lives in `src/lib/ai-edition/schema/`. Migration is bidirectional: v2 OpenScreen ↔ v3 ↔ v2 axcut. Document the migration paths in `migrateDocument(value, fromVersion)`:+ - `fromVersion = 2, source = 'openscreen'` → wrap `EditorProjectData` into `AxcutDocument` (single asset, single clip spanning full duration, trimRegions inverted to skipRanges).+ - `fromVersion = 2, source = 'axcut'` → pass-through (already valid).+ - `fromVersion = 3` → no-op.+- Auto-detect source by sniffing for `media.screenVideoPath` (OpenScreen) vs `assets[]` (axcut). No source-of-origin field needed in v3.++### 1.2 Axcut's merged primary `transcript` vs per-asset `transcripts[]` 🟠+- `axcut-schema/src/index.ts:96-100` — `documentSchema` carries **both** a single merged `transcript` and a `transcripts[]` array.+- `document-service.ts:73-83` — every `updateTranscript` call merges all per-asset transcripts into the single primary via `mergeTranscripts`.+- The merge exists because axcut's `VirtualPreview` only consumes one transcript.+- **Collision:** with multi-asset projects, the merge is lossy — you can't tell which words came from which asset.+- **Resolution:** Phase 1 stores only `transcripts[]`; `VirtualPreview` (Phase 2) reads the per-clip `clip.wordRefs[]` instead of a single primary. Drop the `transcript` (singular) field in v3.++### 1.3 OpenScreen's `trimRegions` are inverses of axcut's `skipRanges` 🟠+- OpenScreen: `types.ts:211` — `TrimRegion { id, startMs, endMs }` — regions are **kept**.+- axcut: `axcut-schema/src/index.ts:79` — `skipRangeSchema` — regions are **removed**.+- **Resolution:** migration from v2 OpenScreen inverts: each `trimRegion` becomes a `skipRange` pair (everything outside trim = kept, inside trim = skipped). For the simple case of a single trim region `[a, b]`, you get `skipRanges = [{startSec: 0, endSec: a}, {startSec: b, endSec: duration}]`.+- **Edge case:** when an OpenScreen project has **zero trim regions** (entire recording kept), the migrated project has `skipRanges: []` and **one clip spanning the full duration**. This is the "single-take" baseline — should be the most common migration result.++### 1.4 OpenScreen has fields axcut lacks 🔴+| OpenScreen field | Map to AxcutDocument v3 |+|---|---|+| `editor.trimRegions[]` | invert into `skipRanges[]` |+| `editor.zoomRegions[]` | new `zoomRanges[]` field in `documentSchema` |+| `editor.annotationRegions[]` | new `annotations[]` field in `documentSchema` |+| `editor.speedRegions[]` | already in axcut as `timeline.speedRanges[]` (rangeSchema shape) |+| `editor.{wallpaper, shadowIntensity, showBlur, motionBlurAmount, borderRadius, padding, cropRegion, aspectRatio, webcamLayoutPreset, webcamMaskShape, webcamMirrored, webcamReactiveZoom, webcamSizePreset, webcamPosition, cursorTheme}` | new `legacyEditor` envelope; applied at export time |+| Cursor telemetry (`useScreenRecorder.ts` writes `.cursor.json` next to WebM) | **NOT** in document; stays as sidecar asset metadata. Add `asset.cursorTelemetryPath?` to `assetSchema`. |++### 1.5 Schema fields need asset-scoped addressing 🟠+- In a single-asset OpenScreen project, `zoomRegion.startMs/endMs` are timeline-absolute.+- In a multi-asset project, a zoom region applies to **one source asset** within one **clip**. The simplest model is: zoom regions are clip-scoped, not document-scoped.+- **Resolution:** in v3, `zoomRanges[]`, `annotations[]`, and `speedRanges[]` all carry `clipId?` (optional — null means "apply globally if there's exactly one clip, otherwise error"). OpenScreen's migrated projects (one clip) keep their regions with `clipId: null`. Multi-clip projects require `clipId`.+- This needs a `resolveRegionScope(document, region)` helper.++### 1.6 axcut's `clip_<n>` id generation is fragile 🟡+- `timeline.ts:50-66` — auto-generated ids `clip_1, clip_2, ...`. New clips scan for the next free index. Could collide with user-provided ids.+- **Resolution:** use `crypto.randomUUID()` for all auto-generated clip ids (matching `TimelineEditor.tsx:17` pattern OpenScreen already uses). Update `retimeClips` to skip the numeric generation.++---++## 2. Process model collisions (Phases 0, 6)++### 2.1 Python worker + Faster-Whisper → drop entirely 🔴+- axcut spawns Python as a child process via `PythonWorker` (`apps/server/src/services/python-worker.ts:14`). On Windows, finding `python` on PATH is unreliable; on macOS, codesigning a Python interpreter is a nightmare.+- OpenScreen's `transformers.js` Whisper (`src/lib/captioning/transcribe.ts:44`) runs in a Web Worker, already bundled via `caption-assets/`.+- **Resolution:** axcut's `enqueueTranscription` becomes a renderer-side call to `transcribeMono16kToSegments`. `enqueueAssetIngest` (which calls probe + proxy + transcribe) becomes: renderer reads metadata via `mediabunny` probe; transcribes via Whisper; updates the document.+- **Edge case:** axcut's Whisper defaults to `medium` (1.5 GB); OpenScreen bundles `tiny` (~75 MB). Need a user setting `transcriptionModel` (default `tiny`, opt-in to `medium`). The model download flow must happen in the renderer (transformers.js) — no Python download server.++### 2.2 Fastify + SSE → Electron IPC + `webContents.send` 🔴+- axcut: Fastify listens on `127.0.0.1:4010`, SSE stream at `GET /api/projects/:id/events`.+- OpenScreen: Electron main process + IPC handlers.+- **Resolution:** every axcut route becomes a `native-bridge:invoke` domain action (or a new `ai-edition:invoke` channel). The EventBus stays in the main process; fan-out happens via `webContents.send('ai-edition:event', { projectId, event })`. Renderer subscribes via a new `useAiEditionEvents(projectId)` hook.+- **Edge case:** SSE supports auto-reconnect; raw `webContents.send` does not. If the renderer reloads (e.g. user opens DevTools and hits Cmd+R), it must re-subscribe on mount. Plan accordingly in `VideoEditor.tsx`'s `useEffect`.+- **Edge case:** `webContents.send` only reaches the window it targets. Multiple editor windows? OpenScreen currently has one editor window; verify the renderer doesn't open multiple before assuming fan-out works.++### 2.3 SQLite location `.axcut-data/metadata.sqlite` → `app.getPath('userData')` 🔴+- axcut hardcodes the data dir under the repo.+- OpenScreen uses `app.getPath('userData')` (the OS-standard user data location: `~/Library/Application Support/OpenScreen` on macOS, `%APPDATA%/openscreen` on Windows).+- **Resolution:** move SQLite to `app.getPath('userData')/ai-edition/metadata.sqlite`. WAL mode is fine for Electron.+- **Edge case:** `better-sqlite3` is a native module. OpenScreen already has `@electron/rebuild` in devDeps — verify it's wired in `electron-builder.json5` rebuild step. If not, add `npm rebuild better-sqlite3` to the build script.++### 2.4 axcut's `queueMicrotask` job runner → real cancellation 🔴+- axcut `job-service.ts:18-22` schedules work via `queueMicrotask(() => void runX(...))`. No way to cancel.+- **Edge case:** user closes the editor mid-ingest. axcut's Fastify stays alive, the job keeps running, the renderer never sees the result. User is confused.+- **Resolution:** main-process job runner tracks `Set<JobId>` per window. When the editor window closes, mark all its jobs as `cancelled` and abort the underlying `Worker.terminate()` (caption) or `AbortController.abort()` (HTTP fetch for transcription).++### 2.5 axcut credentials in plain JSON → `safeStorage` 🟠+- axcut: `llm-credentials.json` is plain JSON, written under `.axcut-data/`.+- **Security regression:** OpenScreen should not store credentials as plain JSON. Use Electron's `safeStorage.encryptString()` (OS keychain: Keychain on macOS, DPAPI on Windows, libsecret on Linux).+- **Resolution:** `LlmConfigService` (Phase 7) encrypts keys with `safeStorage` before write; decrypts on read. Keys migrate: on first run, detect plain JSON and re-encrypt.+- **Edge case:** `safeStorage.isEncryptionAvailable()` may return false on Linux without a desktop session. Fallback: `electron-store` with a user-set passphrase, or warn + opt-out.++---++## 3. UX / UI collisions (Phases 1, 5)++### 3.1 Single recording vs multi-take workflow 🔴+- Today: `useScreenRecorder.ts:621` `stopRecording` → `switchToEditor()` is unconditional.+- Plan said: stay-in-recorder with prompt. **Conflict with the existing flow.** Need a decision:+ - **Stay-in-recorder** (Screen Studio feel): every stop → toast "Saved to project X. Record another or open editor?" → two buttons.+ - **Auto-open-editor** (today's feel): every stop → editor opens. The user's mental model matches existing.+- **Recommendation:** default to **stay-in-recorder** when `aiEdition` flag is on and there's an active project; default to **auto-open-editor** when there's no active project. The HUD needs a "Switch project" / "New project" affordance.+- **Edge case:** if the user starts recording without an active project, axcut's flow says "create a new project first." OpenScreen today has no project concept on the HUD. Need a quick-create button.+- **Edge case:** what if recording fails (stream error)? Plan path: don't create the asset; don't switch window; show toast.++### 3.2 `Ctrl+C / Ctrl+V` clip duplicate collides with Electron Edit menu 🔴+- Inventory §9 already flagged this. **Resolution:**+ - Override the application menu's `Edit > Copy` / `Edit > Paste` roles to call `webContents.send('editor:clipboard', { op: 'copy' | 'paste' })` when the editor window is focused. The editor's React handler intercepts and triggers clip duplicate.+ - In text inputs (`<input>`, `<textarea>`, `[contenteditable]`), let the default behavior happen.+ - Existing `Ctrl+D` (`deleteSelected`) collision: rename to `Ctrl+Backspace` for delete (less common) OR keep `Ctrl+D` and pick another binding for duplicate-clip (`Cmd+Shift+D`?).+- **Edge case:** axcut's web app has no system menu to override. The Electron-native approach is new to axcut's clip-dup UX. Test on all three platforms.++### 3.3 Modals stack: axcut uses many modals; OpenScreen uses dialogs + sonner 🟠+- axcut has `ProviderSettingsDialog`, `LoadVideoDialog`, `SessionHistoryDialog`, `WorktreeDialog`, `TranscriptDialog`, `InsertAssetDialog`. All rendered as `modal-backdrop` divs.+- OpenScreen uses `@radix-ui/react-dialog` (`src/components/ui/dialog.tsx`, z-index 9999/10000) and `@radix-ui/react-select` (z-index 100000).+- **Collision:** z-index wars. axcut's CSS uses `.modal` and `.modal-backdrop` classes; mixing with Radix's portal-based stacking is fragile.+- **Resolution:** rewrite axcut's modals to use Radix `Dialog` primitive. Keep the surface (`models / providers / settings` screens) but back them with Radix's portal.+- **Edge case:** the `ProviderSettingsDialog` has a "popover" mode (anchored to a button) and a "modal" mode (full screen). Map popover → Radix `Popover`, modal → Radix `Dialog`. Single component, two surfaces.++### 3.4 Window model: 4 OpenScreen windows vs 1 axcut web app 🟠+- OpenScreen: HUD-overlay, SourceSelector, CountdownOverlay, Editor. They coordinate via IPC + main-process singletons.+- axcut: one web page with everything.+- **Resolution:** the AI-edition view is part of the Editor window. When AI-edition is enabled and a project is open, the editor renders the new layout (resources + preview + transcript + chat + timeline). No new window.+- **Edge case:** during recording, the HUD is open. Should the chat be visible? **No.** Chat is editor-only. Plan accordingly.++### 3.5 i18n: axcut has none; OpenScreen has 13 locales × 7 namespaces 🔴+- axcut: every UI string is hardcoded English.+- OpenScreen: 91 JSON files; `npm run i18n:check` enforces parity.+- **Resolution:** every AI-edition string must go through `useScopedT(namespace)` from `I18nContext.tsx`. Two new namespaces: `ai-edition.editor`, `ai-edition.transcript`, `ai-edition.chat`, `ai-edition.providers`. Run `npm run i18n:check` before each PR.+- **Edge case:** axcut has lots of long descriptive text ("Click a word, then shift-click another..."). Translation to 13 languages will require a translator pass — not just machine translation, since some of these are domain-specific. Plan a translator round before Phase 9 ships.++### 3.6 Markdown rendering for chat bubbles 🟡+- axcut's `CurrentTranscriptView` likely renders assistant messages as markdown (verify by reading the file in detail). OpenScreen has no markdown renderer.+- **Resolution:** add `react-markdown` + `remark-gfm` to deps. Bundle cost ~30 KB gzipped.+- **Edge case:** markdown content from the LLM can be hostile (XSS, prompt injection). Sanitize with `rehype-sanitize`. Do NOT use `dangerouslySetInnerHTML`.++### 3.7 React Query vs plain IPC 🟠+- axcut uses `@tanstack/react-query` extensively. OpenScreen has no React Query.+- **Resolution:** add React Query as a dependency, OR replace with `useEffect` + `useState` + an event subscription. React Query is 13 KB gzipped but adds value (caching, retries, optimistic updates). **Recommendation:** add React Query. Phase 6 (agent runtime) leans on it heavily for the message list + project snapshot queries.++### 3.8 Radix `Select` z-index 100000 vs Dialog z-index 9999 🟡+- OpenScreen's `select.tsx:86` uses z-index 100000 to sit above dialog.+- axcut's modals don't use Radix. After rewriting modals to Radix Dialog (z-index 9999), the Select z-index is correct (above dialog content but below modal backdrop is not quite right — select should close when dialog opens).+- **Resolution:** in the new Radix-backed modals, use `Dialog.Close` to dismiss on outside interaction. Select inside Dialog should work normally.++### 3.9 The `Cursor` recorder is not in axcut 🟠+- OpenScreen has cursor telemetry → editable overlay cursor in preview/export.+- axcut's `clips[]` and `skipRanges[]` don't model cursor at all. In a multi-asset timeline, when a clip replays, the cursor must replay the asset's telemetry for the clip's source-time range.+- **Resolution:** extend `axcut-schema` v3 `clipSchema` with `cursorEnabled?: boolean` (default `true` if the asset has cursor telemetry). Phase 3 (exporter) reads this and applies `getSmoothedCursorPath` per clip.+- **Edge case:** axcut's `applySkipRangesToClips` clones the clip and changes its `id` (e.g. `clip_1__skip_part_1`). The clone needs to inherit cursorEnabled.++---++## 4. Feature collisions (each phase)++### 4.1 OpenScreen-only features to preserve+- **Auto-caption annotation injection** (`annotationsFromCaptions.ts`). After Phase 4 (transcription), the renderer should write to **both** `transcripts[]` (axcut-style) **and** auto-create `AnnotationRegion[]` from the same words (OpenScreen-style). Or: pick one. **Recommendation:** drop the auto-caption annotation flow in favor of axcut's TranscriptDialog; lower-third captions are a different feature (user-added annotations), not auto-captions. Users who want captions-on-video can add them manually or via a "render captions as overlay" export preset (future).+- **3D rotation presets** (`Rotation3D`, `types.ts:34`). Stay in v3 schema.+- **GIF export** (`gifExporter.ts`). Keep; out of scope for AI-edition but harmless to preserve.+- **Native capture helpers** (Swift/CMake). Frozen; no changes.+- **Single-instance lock + tray** (`singleInstanceLock.ts`, `main.ts:304-360`). Keep.+- **Shortcuts file** (`userData/shortcuts.json`). Keep — extend for clip-dup, move-clip, etc.++### 4.2 axcut-only features to drop or rewrite+- **`worktreeService`** — drop entirely. Video projects don't need git worktrees.+- **`proxy.mp4` per asset** — axcut generates a low-res proxy during ingest for fast preview scrubbing. OpenScreen already has the streaming decoder. **Decision (locked 2026-06-25):** no proxy files; rely on `StreamingVideoDecoder` (WebCodecs) to seek the source on demand. **Known concern:** users have reported scrubbing lag on long recordings (>30 min). Documented in `ai-edition-merge-plan.md §8.1` with a revival path (per-asset "Generate proxy" button + auto-enable threshold at 30 min duration).+- **`.axcut-data/` directory tree** — replaced by `app.getPath('userData')/ai-edition/` and `app.getPath('userData')/projects/`.+- **ChatGPT device-flow OAuth** (`openai-account.ts`) — keep; it works in Electron main process.+- **GitHub Copilot token exchange** (`copilot-account.ts`) — keep.+- **`@axcut/schema` package as a separate package** — fold into `src/lib/ai-edition/schema/`. No monorepo.++### 4.3 Recording format collisions 🟠+- OpenScreen outputs: `.webm` (browser), `.mp4` (native Windows), `.mp4` + separate `.mp4` (native macOS for screen + webcam).+- axcut accepts: `.mp4, .mov, .m4v, .webm, .mkv`.+- **Resolution:** the AI-edition asset validator accepts the same set. Macos webcam `.mp4` from native recording flows in fine. Browser recording `.webm` flows in fine.++### 4.4 Cursor file sidecar format 🟠+- OpenScreen writes `<screenFileName>.session.json` (manifest) + `<screenFileName>.cursor.json` (telemetry v2 format).+- axcut doesn't know about these.+- **Resolution:** when ingesting an OpenScreen-recorded asset, copy the `.cursor.json` into `app.getPath('userData')/projects/<id>/assets/<assetId>.cursor.json` (or symlink). Reference it from `asset.cursorTelemetryPath`.++### 4.5 Webcam-as-separate-file (macOS) vs muxed (Windows) 🟠+- macOS native: screen WebM/MP4 + webcam MP4 as two separate files. `attachNativeMacWebcamRecording` (`handlers.ts:2141`) binds them into a session.+- Windows native: muxed.+- **Resolution:** an AI-edition "Recording" asset is logically one recording session that may produce two physical files (screen + webcam). Model as: `RecordingSessionAsset { screenAsset: AxcutAsset, webcamAsset?: AxcutAsset, sessionManifestPath: string }`. The composite is opaque to the timeline; the renderer/exporter reads both.+- **Edge case:** user records without webcam (browser-only or native screen-only). Webcam asset is absent. Renderer handles null.++---++## 5. Edge cases the plan didn't cover++### 5.1 Chat session per project, not global 🔴+- axcut: each project has N sessions; `projectId × sessionId` is the unit.+- OpenScreen's `currentRecordingSession` is a single value, replaced wholesale.+- **Resolution:** introduce `ai-edition:projects:list` IPC, `ai-edition:projects:set-active` to switch the active project. The Editor window always renders the active project. Chat is per-active-project.++### 5.2 What if the recording file is moved/deleted? 🟠+- axcut trusts absolute paths. If the file is moved, ops referencing `startSec/endSec` still work but rendering breaks (file not found).+- **Resolution:** on every render of VirtualPreview or export, check `await fetch(asset.originalPath)` for 200/404. On 404, show a "file missing" banner with a "Locate file" button. `electron/dialog.showOpenDialog` to pick the replacement. Update `asset.originalPath` via `updateAsset`.++### 5.3 Migration of v2 project opened in AI-edition mode, then user toggles back off 🟡+- Project is migrated to v3 on first AI-edition save. If the user toggles AI-edition off, the project has already been saved as v3. The legacy `EditorProjectData` reader can't open v3.+- **Resolution:** either (a) never migrate in place — keep a v2 copy next to v3; or (b) the legacy reader learns to read v3 and discard unknown fields. **(b)** is simpler and the right call: extend `projectPersistence.ts` `validateProjectData` to accept v3 and ignore `clips/skipRanges` etc.++### 5.4 Undo/redo across checkpoints 🟠+- OpenScreen has `useEditorHistory.ts` (80-step ring buffer) for UI-driven undo.+- axcut has `document.history.revisions[]` for full restoration.+- **Resolution:** pick one as SSOT. **Recommendation:** `revisions[]` is the SSOT. UI undo = pop the last revision, restore document. The 80-step ring buffer goes away. Existing OpenScreen undo history migrates to a single `revision` with `operations[]` of the diff (compute via `JSON.parse(JSON.stringify(prev))` for now, optimize later).++### 5.5 Auto-caption annotation regeneration after timeline edits 🟠+- OpenScreen's `captionSegmentsToAnnotationRegions` is idempotent; the editor merges new regions with existing.+- After AI-edition timeline edits (clips added, skips added), the captions are still in `transcripts[]` but the annotations are stale (referring to times that no longer exist in the timeline).+- **Resolution:** clear `annotations[]` of `annotationSource = 'auto-caption'` on any timeline op. Re-run auto-caption generation. Or: skip auto-caption entirely (recommendation in §4.1).++### 5.6 Multiple sequential recordings append to the same project 🔴+- Today: each `stopRecording` overwrites the current pointer.+- Post-merge: each stop appends to active project.+- **Edge case:** the user records take 1, takes a break, records take 2 (after pause/resume → 2 segments, 1 file) → 1 new asset, 1 new clip. Records take 3 (after switching source) → 1 new asset, 1 new clip. Project has 3 assets, 3 clips.+- **Edge case:** what if the user does NOT want to add to the current project? Need a "Save to project..." picker or "New project" button in the HUD. Today there's none.++### 5.7 Recording while a chat run is in flight 🟠+- New recording → new asset → document updates → agent's next tool call sees the new asset → op might apply to the wrong asset.+- **Resolution:** at the start of every chat turn, snapshot the document. At the end, check if any `assetId` referenced by applied ops still exists. If not, the op is dropped with a warning logged.+- Alternatively: lock the document during chat run (UI shows "Editing in progress"). **Recommendation:** snapshot + verify, not lock. Locks feel slow.++### 5.8 Provider config in env vs UI 🔴+- axcut reads env keys (`OPENAI_API_KEY` etc.) and they win over stored keys.+- OpenScreen currently has no LLM provider; doesn't matter.+- **Resolution:** port axcut's env precedence. Document in the AI-edition settings UI: "Detected OPENAI_API_KEY in environment — using that." with an option to override.++### 5.9 ChatGPT OAuth device flow in Electron 🟠+- axcut's `chat-codex-oauth.ts` uses `https://chatgpt.com/backend-api/codex/responses`. The device-flow challenge shows a code + URL the user opens in a browser.+- **Resolution:** show the code in a Radix Dialog. On completion, optionally open the URL via `electron.shell.openExternal`. Store the refresh token in `safeStorage`-encrypted JSON.+- **Edge case:** the `codex_cli_rs` originator header is hardcoded. If OpenAI rate-limits the originator, the auth still works but the chat completion fails. Need a retry + clear error.++### 5.10 Reasoning effort persistence 🟠+- axcut stores `reasoningEffort` per project.+- OpenScreen has no equivalent.+- **Resolution:** Phase 7 adds `reasoningEffort` to `UserPreferences` (global default) + `AxcutLocalConfig` (per-provider) + `AxcutDocument.export` (last-used).++### 5.11 App quit during in-flight LLM stream 🔴+- User starts chat → 30s into the LLM response → closes the window.+- axcut's Fastify stays alive; the run completes; user sees no result.+- **Resolution:** the main process `before-quit` waits up to N seconds for in-flight runs to finish (saving the final assistant message + checkpoint). After timeout, force-quit. Use Electron's `app.on('before-quit', e => e.preventDefault(); await drain(); app.quit())`.++### 5.12 Concurrent edits: agent + user 🟠+- User clicks "Add skip" while agent is mid-run.+- axcut's `DocumentService.applyOperation` reads + writes; no locking.+- **Resolution:** serialize via a per-project async lock (a simple promise chain). User ops get queued. After agent run, queued ops apply.++### 5.13 Transcript quality vs project scale 🟠+- A 1-hour screen recording × `medium` Whisper model = ~30 minutes transcription + 1.5 GB model download.+- **Resolution:** show a warning when transcription is starting on a long file. Allow cancellation (`AbortController` on the caption worker). Allow user to pick model size before transcription starts.++### 5.14 Cross-platform path handling 🟠+- axcut: pure POSIX path semantics in `paths.ts`.+- OpenScreen: Windows uses `\` or `/` depending on context. `fromFileUrl` / `toFileUrl` (`projectPersistence.ts:148-184`) handles this.+- **Resolution:** all axcut paths in `electron/ai-edition/` use Node `path.join` (already cross-platform). The renderer receives `file://` URLs via the existing pattern.++### 5.15 File watcher on `app.getPath('userData')` 🟡+- AI-edition writes to userData frequently. If a backup tool or `git init` runs in there, things break.+- **Resolution:** no fix needed; document that the userData dir is managed by Electron.++### 5.16 Schema v3 → v4 in the future 🟡+- If we change the schema again, we need migration code.+- **Resolution:** Phase 0 introduces `migrateDocument(value, fromVersion): { document: AxcutDocument, fromVersion: number }`. Set the bar for future migrations now.++---++## 6. Performance / scaling++### 6.1 VirtualPreview with many clips 🟠+- Two `<video>` layers with crossfade. For 2 clips, perfect. For 10 clips, the next clip must preload in the inactive layer. If the user seeks across 5 clips rapidly, you get 5 sequential seek+play cycles.+- **Resolution:** keep the two-layer design but add a "smart preload" — preload the next 2 clips when within 0.5s of a boundary. For 10+ clips, consider adding a single-frame "thumbnail strip" seek bar.++### 6.2 Export with mediabunny across multiple sources 🟠+- Each source clip needs a separate demuxer instance. mediabunny supports this but each demuxer has its own decoder pool.+- **Resolution:** prototype in Phase 3 PR 3.1 with a 3-clip fixture. If memory blows up (>2 GB), consider a sequential approach: render each clip to an intermediate file, then concat via `mp4box.js`.++### 6.3 Project file size 🟡+- A 5-clip project with full transcripts (each ~30 KB JSON) + zoom + annotation + cursor telemetry refs = ~500 KB JSON. Per-save JSON.stringify on 500 KB is fast but not free.+- **Resolution:** debounce saves to 250ms after last edit. Or write incrementally (only the changed slice). For Phase 0, debounce is enough.++---++## 7. Testing strategy additions++### 7.1 E2E for AI-edition happy path 🟠+- New `tests/e2e/ai-edition-happy-path.spec.ts`: launch Electron → record 5s → editor opens → add asset → trigger transcription (mock LLM) → chat "remove silences" (mock LLM) → preview → export → ffprobe the output.+- **Edge case:** ffprobe may not be on CI. Mark assertion as conditional.++### 7.2 Mock LLM responses 🟠+- axcut doesn't mock LLMs in tests (relies on canned transcripts).+- OpenScreen tests don't involve LLMs.+- **Resolution:** create a `MockChatModel` class that returns canned `AIMessage`s from fixtures. Used in agent-runtime unit tests + e2e. Lives in `electron/ai-edition/__mocks__/`.++### 7.3 SQLite migration test 🟡+- `database.ts` migrations are inline ALTER TABLEs. Need a test that creates a v1 schema, applies v2 + v3 migrations, asserts final schema.+- **Resolution:** add a `database.test.ts` that uses an in-memory `:memory:` SQLite db.++### 7.4 Cursor telemetry replay test 🟡+- A multi-clip timeline with cursor telemetry must replay the right cursor per clip's source-time range.+- **Resolution:** fixture: 3 clips × cursor telemetry. Assert: at virtual time 0:05 (inside clip 1), cursor reads from clip 1's telemetry; at virtual time 0:30 (inside clip 2), from clip 2's.++---++## 8. Phase ordering adjustments (delta from the plan)++Based on the above, two phase adjustments:++### Phase 0 needs to grow+- ✅ Schema v3 with `annotations`, `zoomRanges`, `legacyEditor`, `cursorTelemetryPath`.+- ✅ Real `migrateDocument(value, fromVersion, source)` — bidirectional v2 ↔ v3.+- ✅ Drop axcut's `transcript` (singular) field — only `transcripts[]` in v3.+- ✅ Add `clipSchema.cursorEnabled` and region `clipId?` scoping.+- ✅ `crypto.randomUUID()` for all auto-generated clip ids.++### Phase 6 (agent runtime) needs to split+- 6.1: document + chat-service + event-bus + IPC channels + SQLite (no LLM yet).+- 6.2: LLM config + provider-registry port.+- 6.3: agent-runtime + deepagent integration + streaming events + suggestion approval flow.+- 6.4: checkpoints + restore (depends on 6.1 + 6.3).++Reasoning: the streaming agent code is hard to test without a working chat pipeline underneath. Splitting lets 6.1 land first and provide the IPC contract that 6.3 builds on.++### New Phase 2.5: cursor in multi-clip+- After Phase 2 (VirtualPreview) but before Phase 3 (exporter), add cursor-aware clip playback.+- This is a small phase (~200 LOC) but important for parity with OpenScreen's existing cursor editing.++---++## 9. Locked decisions (resolved 2026-06-25)++All questions resolved with the user before Phase 0. Decisions are also recorded in `ai-edition-merge-plan.md §5`.++1. **Stop behavior** — ✅ first recording = auto-open (current behavior); second-and-later recordings in an active AI-edition project = stay-in-recorder with "Open editor / Record another" prompt. Preserves existing UX for users who don't use AI Edition. Decision §3.1.+2. **Auto-caption annotations** — ✅ drop entirely. AI-edition's transcript is richer; users add overlay annotations manually if needed. Decision §4.1.+3. **React Query** — ✅ add `@tanstack/react-query` as a dependency. Phase 6 leans on it. Decision §3.7.+4. **Credential storage** — ✅ use Electron's `safeStorage` (OS keychain). Plain JSON is a security regression. Decision §2.5.+5. **Whisper model default** — ✅ bundle OpenScreen's existing smaller model. Add a "Transcription model" picker in settings with download size + speed hints; user opts into larger. Decision §2.1 + §5.13.+6. **Proxy MP4 generation** — ✅ drop. Rely on `StreamingVideoDecoder`. **Documented limitation:** users have reported scrubbing lag on long recordings (>30 min). Revival path in `ai-edition-merge-plan.md §8.1`. Decision §4.2.+7. **File extension** — ✅ keep `.openscreen`. No rename. Decision §3 of the merge plan + §6.3.+8. **Repository / packaging model** — ✅ **single package, in-tree.** AI-edition lives inside the openscreen repo at `src/lib/ai-edition/`, `electron/ai-edition/`, `src/components/ai-edition/`, `src/i18n/locales/<locale>/ai-edition.*`. One `package.json`, one CI, one release. No monorepo, no separate npm package, no separate repo. Decision §4.2 + §6 of the merge plan.++---++## 10. Summary of deltas to the original plan++| Original plan | This analysis recommends | Why |+|---|---|---|+| Phase 0: vendor schema, add v3 fields | Phase 0+: real `migrateDocument`, drop primary transcript field, add `clipId?` scoping | The original was too light on migration; primary transcript is lossy. |+| Phase 1: 3 PRs | Phase 1: 3 PRs as planned | Same. |+| Phase 2: VirtualPreview | Phase 2 + 2.5: VirtualPreview + cursor-aware playback | Cursor in multi-clip is a small but important addition. |+| Phase 3: Exporter | Phase 3: as planned, with explicit perf testing on 3-clip fixture | Same. |+| Phase 4: Transcription | Phase 4: as planned + drop auto-caption annotation flow | Auto-caption collides with axcut's transcript model. |+| Phase 5: Recorder preservation | Phase 5: as planned, with the "first recording auto-opens editor" carve-out | Preserves existing UX. |+| Phase 6: Agent runtime (2 PRs) | Phase 6: split into 6.1/6.2/6.3/6.4 | Testability + ordering. |+| Phase 7: Providers | Phase 7: as planned + `safeStorage` | Security. |+| Phase 8: History + checkpoints | Phase 8: as planned + revisions become the SSOT (replace useEditorHistory) | Single source of truth. |+| Phase 9: Polish | Phase 9: as planned + add `ai-edition.*` i18n namespaces | i18n. |+| Phase 10: Cut-over | Phase 10: as planned | Same. |\ No newline at end of filediff --git a/docs/architecture/ai-edition-comprehensive-handover.md b/docs/architecture/ai-edition-comprehensive-handover.mdnew file mode 100644index 000000000..67eacf71f--- /dev/null+++ b/docs/architecture/ai-edition-comprehensive-handover.md@@ -0,0 +1,499 @@+# AI-Edition Comprehensive Handover — v2++**Date**: 2026-06-29+**Branch**: `docs/ai-edition-plan` (base `4a2f4e4`)+**Worktree**: `C:\Users\etien\.local\share\opencode\worktree\860f8cb1426d647abeba0cc732d7de1694294ae9\mighty-falcon`+**Dev**: `http://localhost:5173/?windowType=editor`+**Verify**: `npx tsc --noEmit` (0 err) / `npm run test` (353 pass) / `npm run lint` (2 known, rest pre-existing locale UTF-8)++> This replaces the handover at `docs/architecture/ai-edition-handover.md`. Read that first for the data-flow diagrams and per-component wiring tables. This doc adds: conversation history, origin labelling (OpenScreen vs Axcut per feature), all file paths, and the merge-status matrix.++---++## 1. Conversation History++### Session 1 — Phases 0–3 foundation (merge-plan creation)+- Reviewed `ai-edition-merge-plan.md`, `openscreen-inventory.md`, `axcut-inventory.md`, `ai-edition-collision-analysis.md`+- Confirmed strategy: **Axcut's data model + UX patterns, re-implemented on OpenScreen primitives** (no Python sidecar, no Fastify, no monorepo)+- Set `AI_FEATURES_ENABLED` flag semantics: gates only LLM/agent surface; new editor is default for all+- Decided: single package, in-tree, no monorepo++### Session 2 — Design tokens + 4-row shell + Titlebar+- Created `design/openscreen-editor.html` (4686-line reference) from design assets+- Built `design-tokens.css`: 270 CSS vars (light + dark)+- Built `NewEditorShell.tsx` / `.module.css`: 4-row grid (titlebar 34px / workbench 7-col / 6px handle / bottombar 224px), resize handles+- Built `Titlebar.tsx`: brand, inline rename, saved status, Save dropdown, Open/New modals, language picker, New Recording, Return to recorder, Export, 3 panel toggles, theme toggle, settings, `-webkit-app-region: drag`++### Session 3 — Bottombar + RightPanes + Preview + Modals+- Built `Bottombar.tsx`: view-tools (zoom/trim/annotation/speed/captions), aspect ratio, auto-focus, 3 lane rows with pills, zoombar, existing TimelinePane+- Built `RightPanes.tsx`: Background (wallpaper presets), Video Effects, Layout, Cursor, Timeline — all wired to `useEditorSettings`+- Built `RightPanelStack.tsx`: container + RegionInspector when region selected (zoom depth, annotation text, speed, delete)+- Built `Preview.tsx`: VirtualPreview, transport (play/pause, prev/next, loop, fullscreen, scrub slider, time, REC)+- Built `Modals.tsx`: OpenProject, NewProject(4 templates), Crop, UnsavedChanges, AutoCaptions, InsertSource, SourceTranscript, ChatHistory+- Built `ExportDialog.tsx`: MP4 720/1080/Source, GIF FPS/Size/Loop, progress bar++### Session 4 — Chat + LeftPanel + Backend+- Built `LeftPanel.tsx`: left rail (Chat/Media tabs), MediaPane, ChatStripPanel, ChatHistoryModal+- Built `ChatPanel.tsx`: real LLM call via `fetch` (OpenAI-compat + Anthropic)+- Built `ProviderSettings.tsx`: 8-provider grid → form → save/disconnect+- Built `electron/ai-edition/llm-call.ts`: fetch-based, no LangChain+- Built `electron/ai-edition/chat-service.ts`: in-memory per-project, real LLM call+- Built `electron/ai-edition/provider-registry.ts`: 8 providers+- Built `electron/ai-edition/llm-config-store.ts`: safeStorage credentials+- Wired IPC: `electron/native-bridge/services/aiEditionService.ts`, `electron/ipc/handlers.ts`, `electron/ipc/nativeBridge.ts`++### Session 5 — Store layer + Multi-clip + Undo/redo+- Built `projectStore.ts` (Zustand): `projectId, document, revision, dirty, lastSavedAt, saveDocument, setDocument, addAsset, removeAsset, replaceTimeline, restoreFullTimeline`+- Built `editorSettings.ts` + `editorSettings.test.ts` (8 tests): typed get/patch over `legacyEditor` envelope+- Built `useEditorSettings.ts` hook: `set(patch)` commit, `setLive(patch)` preview, `commit()` flush+- Built `useTimeline.ts`: region CRUD (`addZoom/Skip/Annotation/Speed/removeRegion`), clip ops (`addClipBefore/After`, `splitAndInsert`), selection+- Built `undo.ts`: `pushHistory` in `setDocument`, `undo()`/`redo()` + `useUndoRedoShortcuts` (Cmd+Z / Cmd+Shift+Z)+- Built `regionClipboard.ts`: per-region copy/paste (Cmd+C/V)++### Session 6 — i18n + keyboard shortcuts + unsaved-changes + polish+- Added locale keys (`editor.json` → `"shell"`) to all 13 locales+- Wired language picker in Titlebar → `useI18n().setLocale()`+- Wired keyboard shortcuts in `NewEditorShell.tsx`: Cmd+S/N/O, Space, Z/T/A/S, Del, ?+- Added `beforeunload` handler for unsaved-changes-on-close+- Added status chips: media card dot (green/gray), transcript ready pill+- Wired auto-captions: modal min/max words → `captionSegmentsToAnnotationRegions`; auto-transcribes if no transcript++### Session 7 — Handover document creation+- Created `docs/architecture/ai-edition-handover.md` (367 lines)+- This session: creating the comprehensive v2 handover++---++## 2. Feature Origin Legend++| Tag | Source |+|-----|--------|+| [OS] | OpenScreen original feature (preserved in new editor) |+| [AX] | Axcut feature (ported/reimplemented) |+| [NEW] | New feature created for the merge (neither had it) |++---++## 3. Implemented & Merged Features (click → data → persisted)++### 3.1 Shell & Layout+| Feature | Origin | File |+|---------|--------|------|+| 4-row grid layout (titlebar/workbench/handle/bottombar) | [NEW] | `src/components/ai-edition/NewEditorShell.module.css` |+| Resize handles (left/right/bottom panels via CSS vars) | [NEW] | `NewEditorShell.tsx` |+| Light + dark theme (270 CSS tokens) | [NEW] | `src/styles/design-tokens.css` |+| Theme toggle (persisted localStorage) | [NEW] | `src/hooks/useTheme.ts`, `Titlebar.tsx` |+| Panel toggles (left/right/timeline via `data-collapse`) | [NEW] | `NewEditorShell.tsx` |++### 3.2 Titlebar+| Feature | Origin | File |+|---------|--------|------|+| Brand + project name (inline rename) | [AX] | `Titlebar.tsx:423` |+| Dirty status + lastSavedAt | [OS] | `projectStore.ts` |+| Save/SaveAs dropdown | [OS] | `Titlebar.tsx:220` |+| Open/New project modals | [OS] | `Modals.tsx` |+| Language picker → `useI18n().setLocale()` | [OS] | `Titlebar.tsx:353` |+| New Recording (with unsaved prompt) | [OS] | `NewEditorShell.tsx:360` |+| Return to recorder | [OS] | `NewEditorShell.tsx:372` |+| Export button → ExportDialog | [OS]+[AX] | `NewEditorShell.tsx:376`, `ExportDialog.tsx` |+| Theme toggle | [NEW] | `Titlebar.tsx` |+| WebkitAppRegion drag region | [NEW] | `NewEditorShell.module.css:39` |++### 3.3 Bottombar+| Feature | Origin | File |+|---------|--------|------|+| Zoom view-tool (+ button → `addZoom()`) | [OS] | `Bottombar.tsx`, `useTimeline.ts` |+| Trim view-tool (+ button → `addSkip()`) | [OS] | `Bottombar.tsx`, `useTimeline.ts` |+| Annotation view-tool (+ button → `addAnnotation()`) | [OS] | `Bottombar.tsx`, `useTimeline.ts` |+| Speed view-tool (+ button → `addSpeed()`) | [OS] | `Bottombar.tsx`, `useTimeline.ts` |+| Captions button → AutoCaptionsModal | [OS] | `NewEditorShell.tsx` |+| Aspect ratio dropdown | [OS] | `Bottombar.tsx` |+| Auto-focus toggle | [OS] | `Bottombar.tsx` |+| 3 lane rows (Zoom/Annotation/Speed pills) | [OS] | `Bottombar.tsx:306` |+| Region selection (click pill → select) | [NEW] | `Bottombar.tsx`, `useTimeline.ts` |+| Region delete (× button) | [OS] | `Bottombar.tsx` |+| Zoombar | [NEW] | `Bottombar.tsx` |+| TimelinePane (existing) | [AX] | `TimelinePane.tsx` |++### 3.4 Right Panels+| Feature | Origin | File |+|---------|--------|------|+| Background (16 thumbnails / 25 gradients) | [OS] | `RightPanes.tsx` |+| Video Effects (blur/motion/shadow/roundness/padding) | [OS] | `RightPanes.tsx` |+| Layout (preset/mirror/shrink/shape/size) | [OS] | `RightPanes.tsx` |+| Cursor (show/clip/style/sliders) | [OS] | `RightPanes.tsx` |+| Timeline (waveform toggle) | [OS] | `RightPanes.tsx` |+| Region Inspector (zoom depth, annotation text/color/size, speed, delete) | [OS] | `RightPanelStack.tsx` |++### 3.5 Preview & Transport+| Feature | Origin | File |+|---------|--------|------|+| VirtualPreview (single-video) | [AX] | `VirtualPreview.tsx`, `Preview.tsx` |+| Play/pause (Space) | [OS] | `Preview.tsx` |+| Prev/Next clip | [AX] | `Preview.tsx:82,94` |+| Loop toggle | [OS] | `Preview.tsx:106` |+| Fullscreen | [OS] | `Preview.tsx` |+| Time display | [OS] | `Preview.tsx` |+| REC button | [NEW] | `Preview.tsx` |+| Scrub slider | [OS] | `Preview.tsx` |++### 3.6 Chat (gated by `AI_FEATURES_ENABLED`)+| Feature | Origin | File |+|---------|--------|------|+| Send message → real LLM call (fetch-based) | [AX] | `LeftPanel.tsx:288` |+| Message bubbles (role/time) | [AX] | `LeftPanel.tsx` |+| Model picker cycle | [AX] | `LeftPanel.tsx:332` |+| Reasoning effort pill | [AX] | `LeftPanel.tsx:338` |+| Context pill | [AX] | `LeftPanel.tsx:353` |+| New chat / History modal | [AX] | `LeftPanel.tsx:324` |+| Provider Settings (8 providers, form, save/disconnect) | [AX] | `ProviderSettings.tsx` |++### 3.7 Multi-clip & Insert Source+| Feature | Origin | File |+|---------|--------|------|+| Drag media card (dataTransfer with assetId) | [AX] | `LeftPanel.tsx:70` |+| Drop on timeline → InsertSourceModal (3 choices) | [AX] | `NewEditorShell.tsx:385,600` |+| Add clip before | [AX] | `useTimeline.ts:173` |+| Add clip after | [AX] | `useTimeline.ts:196` |+| Split and insert | [AX] | `useTimeline.ts:219` |++### 3.8 Keyboard Shortcuts+| Feature | Origin | File |+|---------|--------|------|+| Cmd+S (save) | [OS] | `NewEditorShell.tsx:446` |+| Cmd+N (new project) | [OS] | `NewEditorShell.tsx:452` |+| Cmd+O (open project) | [OS] | `NewEditorShell.tsx:464` |+| Space (play/pause) | [OS] | `NewEditorShell.tsx:477` |+| Z / T / A / S (region tools) | [OS] | `NewEditorShell.tsx:535-553` |+| Del/Backspace (remove region) | [OS] | `NewEditorShell.tsx:488` |+| Cmd+Z / Cmd+Shift+Z (undo/redo) | [NEW] | `undo.ts`, `NewEditorShell.tsx` |+| Cmd+C / Cmd+V (region copy/paste) | [OS] | `regionClipboard.ts` |++### 3.9 Backend (Electron main process)+| Feature | Origin | File |+|---------|--------|------|+| 8 provider definitions | [AX] | `electron/ai-edition/provider-registry.ts` |+| LLM config store (safeStorage) | [AX]+[NEW] | `electron/ai-edition/llm-config-store.ts` |+| LLM call (fetch, no LangChain) | [AX]+[NEW] | `electron/ai-edition/llm-call.ts` |+| Chat service (in-memory per-project) | [AX] | `electron/ai-edition/chat-service.ts` |+| Document service (CRUD .axcut files) | [AX] | `electron/ai-edition/document-service.ts` |+| IPC bridge (aiEdition domain) | [NEW] | `electron/native-bridge/services/aiEditionService.ts` |++### 3.10 Store Layer+| Feature | Origin | File |+|---------|--------|------|+| Zustand projectStore (document + dirty + IPC) | [NEW] | `src/lib/ai-edition/store/projectStore.ts` |+| EditorSettings (typed get/patch over legacyEditor) | [NEW] | `editorSettings.ts`, `editorSettings.test.ts` |+| useEditorSettings hook (set/setLive/commit) | [NEW] | `useEditorSettings.ts` |+| useTimeline hook (region CRUD + clip ops) | [NEW] | `useTimeline.ts` |+| Undo stack (Cmd+Z / Cmd+Shift+Z) | [NEW] | `undo.ts` |+| Region clipboard | [OS] | `regionClipboard.ts` |++### 3.11 i18n+| Feature | Origin | File |+|---------|--------|------|+| Locale keys added to all 13 locales (editor.json → "shell") | [NEW] | `src/i18n/locales/*/editor.json` |+| Language picker → locale change | [OS] | `Titlebar.tsx` |++### 3.12 Misc+| Feature | Origin | File |+|---------|--------|------|+| UnsavedChangesDialog (beforeunload + new/open/record) | [OS] | `Modals.tsx`, `NewEditorShell.tsx` |+| Auto-captions (modal → annotation regions) | [OS] | `NewEditorShell.tsx`, `annotationsFromCaptions.ts` |+| Browser shim (localStorage fallback) | [NEW] | `src/native/browserShim.ts` |+| Native client + contracts | [NEW] | `src/native/client.ts`, `contracts.ts` |+| Schema (v3 AxcutDocument zod) | [AX] | `src/lib/ai-edition/schema/index.ts` |+| Migration (v2 ↔ v3) | [NEW] | `src/lib/ai-edition/document/migrate.ts` |+| Timeline math (normalizeIntervals, subtractInterval) | [AX] | `src/lib/ai-edition/document/timeline.ts` |+| Virtual preview math | [AX] | `src/lib/ai-edition/timeline/virtual-preview.ts` |+| Document exporter → VideoExporterConfig/GifExporterConfig | [NEW] | `src/lib/ai-edition/exporter/documentExporter.ts` |+| Auto-transcribe if no transcript exists | [NEW] | `NewEditorShell.tsx`, `transcribe.ts` |++---++## 4. Features Still to Be Merged (remaining items)++### 4.1 High Priority — Functionality Gaps+| # | Feature | Origin | What's missing | Files to touch |+|---|---|---|---|---|+| **1** | Auto-captions → auto-Transcribe | [OS] | If no transcript, "Captions" button should trigger `transcribeAsset` before `captionSegmentsToAnnotationRegions`. Currently just a toast. | `NewEditorShell.tsx:handleGenerateCaptions` |+| **2** | Playback scrub slider | [OS] | Transport bar has time display but no `<input type="range">`. Design has a progress bar. | `Preview.tsx` |+| **3** | Timeline playhead scrub | [OS] | Click/drag on ruler → preview seeks. `TimelinePane` has this but not exposed to Preview. | `TimelinePane.tsx`, `Bottombar.tsx` |+| **4** | Source Transcript modal — real data | [AX] | `transcriptText` is always null. Should show `document.transcript` content. | `LeftPanel.tsx`, `Modals.tsx` |+| **5** | UnsavedChangesDialog on Cmd+W | [OS] | Only wired for New Recording. Missing close-window handler. | `NewEditorShell.tsx` |+| **6** | Region inspector — persist depth/text | [OS] | Zoom depth buttons and annotation textarea update local state but don't call `saveDocument`. | `RightPanelStack.tsx:RegionInspector` |+| **7** | Media file 4-state indicator | [AX] | Dot is always green. Should reflect transcript status (pend/run/complete/fail). | `LeftPanel.tsx:MediaList` |+| **8** | Per-file transcript availability check | [AX] | `SourceTranscriptModal` should show transcript if available. Currently always "Not generated yet". | `LeftPanel.tsx`, `Modals.tsx` |++### 4.2 Medium Priority — Visual Polish+| # | Feature | Origin | What's missing | Files to touch |+|---|---|---|---|---|+| **9** | Canvas preview rendering | [OS] | Wallpaper, shadow, border-radius, crop, webcam PiP, cursor, zoom, annotations not shown in live preview (only `<video>` tag). | `Preview.tsx`, `VirtualPreview.tsx` or new Pixi overlay |+| **10** | Live-run feed (Thinking cards) | [AX] | During LLM call, no intermediate feedback. Message appears all at once. | `LeftPanel.tsx:ChatStripPanel` |+| **11** | Status chips | [AX] | Transcription/export job status (idle/running/ready/error) — no job queue. | New component or `LeftPanel.tsx` |+| **12** | Region shape customization | [OS] | Arrow direction, figure color, blur shape/color/mosaic, annotation font family/size/animation not in inspector. | `RightPanelStack.tsx:RegionInspector` |+| **13** | i18n migration of all new components | [NEW] | All strings in Titlebar/Bottombar/LeftPanel/RightPanes/Modals are hardcoded English. Locale keys exist but aren't used. | All `src/components/ai-edition/*.tsx` |+| **14** | Edit Clip modal | [AX] | Pencil button on track blocks doesn't exist. Need modal for sourceStartSec/sourceEndSec. | New modal in `Modals.tsx` + `TimelinePane.tsx` |+| **15** | Per-region Copy/Paste (Cmd+C/V) | [OS] | `regionClipboard.ts` exists in legacy but not wired in new shell. | `NewEditorShell.tsx` + new clipboard hook |+| **16** | Conversation History — multiple sessions | [AX] | Currently 1 session only. Backend session management missing. | `electron/ai-edition/chat-service.ts` |++### 4.3 Lower Priority — Backend Features+| # | Feature | Origin | What's missing | Files to touch |+|---|---|---|---|---|+| **17** | OAuth device flow | [AX] | ChatGPT/GitHub Copilot OAuth. "Not implemented" placeholders. | `llm-call.ts`, `ProviderSettings.tsx` |+| **18** | Reconnect banner on expired API key | [AX] | No `provider_auth_expired` event. | `ProviderSettings.tsx` |+| **19** | SSE streaming for project changes | [AX] | Not needed in single-user Electron, could improve reactivity. | — |+| **20** | SQLite sessions/checkpoints | [AX] | Chat history is in-memory (lost on restart). Axcut used `better-sqlite3`. | `electron/ai-edition/chat-service.ts` |+| **21** | Conversation History rename/delete | [AX] | Basic modal exists, but only 1 session, no rename, no delete. | `Modals.tsx:ChatHistoryModal` |+| **22** | Undo/redo verification | [NEW] | Wired but verify Cmd+Z / Cmd+Shift+Z work in browser. | `NewEditorShell.tsx` |++### 4.4 Missing OpenScreen Features from Old Editor+| # | Feature | What's missing | Spec section |+|---|---|---|---|+| **23** | EditorEmptyState | Logo + import video + load project + drag & drop overlay + supported formats. Simple text placeholder now. | OpenScreen §5.4 |+| **24** | Drag & drop `.openscreen` file | Handler missing. | OpenScreen §5.4 |+| **25** | ShortcutsConfigDialog | Loaded lazily in App.tsx, never shown. No "customise shortcuts" button. | OpenScreen §5.10 |+| **26** | Annotations settings panel | Text/Image/Arrow tabs, font/size/color/animation, custom fonts, duplicate. Not wired. | OpenScreen §5.5.3 |+| **27** | Blur settings panel | Shape/color/mosaic size. Not wired. | OpenScreen §5.5.3 |+| **28** | Auto-zoom (wand) suggestions | Wand button disabled. Not ported. | OpenScreen §5.5.4 |+| **29** | Webcam PIP real-time preview | Placeholder "Webcam" div. No real webcam layer. | OpenScreen §5.5.1 |+| **30** | Cursor rendering in preview | Theme art, smoothing, motion blur, click bounce not rendered. | OpenScreen §5.5.1 |++---++## 5. File Index — Complete Path Reference++### 5.1 Design References+| File | Description |+|------|-------------|+| `design/openscreen-editor.html` | **Canonical** 4686-line static HTML reference (light + dark) |+| `design/DESIGN.md` | Design system documentation (156 lines) |++### 5.2 Architecture Docs+| File | Description |+|------|-------------|+| `docs/architecture/ai-edition-merge-plan.md` | 420-line merge plan (Phases 0-10, locked decisions) |+| `docs/architecture/openscreen-inventory.md` | Full OpenScreen codebase catalog (~750 lines) |+| `docs/architecture/axcut-inventory.md` | Full Axcut codebase catalog (458 lines) |+| `docs/architecture/ai-edition-collision-analysis.md` | 355-line collision analysis with resolutions |+| `docs/architecture/ai-edition-handover.md` | Previous handover (367 lines) |+| `docs/architecture/native-bridge.md` | Native bridge documentation |+| **`docs/architecture/ai-edition-comprehensive-handover.md`** | **This file** |++### 5.3 UX Specifications+| File | Description |+|------|-------------|+| `docs/openscreen-ux-ui-spec.md` | OpenScreen UX/UI spec (570 lines) |+| `docs/axcut-ux-ui-spec.md` | Axcut UX/UI spec (397 lines) |++### 5.4 Renderer Components (`src/components/ai-edition/`)+| File | Lines | Description |+|------|-------|-------------|+| `NewEditorShell.tsx` | ~830 | Top-level shell: state, IPC handlers, keyboard shortcuts |+| `NewEditorShell.module.css` | ~200 | 4-row grid layout + resize handles |+| `Titlebar.tsx` | ~450 | Brand, rename, save, open/new, lang, recorder, panels, theme |+| `Bottombar.tsx` | ~400 | View-tools + 3 lane rows + zoombar + TimelinePane |+| `Preview.tsx` | ~300 | Preview frame + transport + scrub |+| `LeftPanel.tsx` | ~670 | Left rail (Chat/Media) + MediaPane + ChatStripPanel |+| `RightPanelStack.tsx` | ~200 | Right panel container + RegionInspector |+| `RightPanes.tsx` | ~350 | 6 individual panes (Background/Effects/Layout/Cursor/Timeline) |+| `Modals.tsx` | ~500 | All modals (Open/New/Crop/Unsaved/AutoCaptions/InsertSource/Transcript/ChatHistory) |+| `ExportDialog.tsx` | ~250 | MP4 + GIF export with progress |+| `ProviderSettings.tsx` | ~200 | 8-provider grid → form → save/disconnect |+| `VirtualPreview.tsx` | ~233 | Single-video preview (ported from Axcut) |+| `VirtualPreview.module.css` | ~93 | Preview component styles |+| `TimelinePane.tsx` | ~837 | Timeline: ruler, clips, skip strips, navigator (Axcut port) |+| `TimelinePane.module.css` | ~304 | Timeline component styles |+| `TranscriptEditor.tsx` | ~117 | Click-word seek, shift-click range, strikethrough |+| `TranscriptEditor.module.css` | ~75 | Transcript editor styles |+| `ChatPanel.tsx` | ~114 | OLD chat panel (replaced by ChatStripPanel in LeftPanel) |+| `ProjectPanel.tsx` | ~225 | OLD project picker (kept for reference) |+| `AiEditionShell.tsx` | ~12 | Lazy-load entrypoint |++### 5.5 Lib/AI-Edition (`src/lib/ai-edition/`)+| File | Lines | Description |+|------|-------|-------------|+| `schema/index.ts` | ~489 | v3 AxcutDocument Zod schema |+| `schema/index.test.ts` | ~190 | Schema tests |+| `document/migrate.ts` | ~325 | v2 ↔ v3 bidirectional migration |+| `document/migrate.test.ts` | ~305 | Migration tests |+| `document/timeline.ts` | ~174 | Pure interval math (normalizeIntervals, subtractInterval, etc.) |+| `document/timeline.test.ts` | ~230 | Timeline math tests |+| `document/transcribe.ts` | ~100 | Wraps existing captioning pipeline |+| `document/ids.ts` | ~8 | createId(prefix) → uuid |+| `store/projectStore.ts` | ~204 | Zustand store (document, dirty, IPC) |+| `store/projectStore.test.ts` | ~141 | Store tests |+| `store/editorSettings.ts` | ~100 | Typed get/patch over legacyEditor envelope |+| `store/editorSettings.test.ts` | ~80 | Editor settings tests (8) |+| `store/useEditorSettings.ts` | ~80 | React hook (set/setLive/commit) |+| `store/useTimeline.ts` | ~250 | Region CRUD + clip ops + selection |+| `store/undo.ts` | ~70 | Undo stack module |+| `store/regionClipboard.ts` | ~50 | Per-region copy/paste |+| `exporter/documentExporter.ts` | ~218 | Document → Video/Gif exporter config |+| `timeline/virtual-preview.ts` | ~84 | Pure time-mapping utilities |+| `timeline/virtual-preview.test.ts` | ~79 | Virtual preview tests |++### 5.6 Styles+| File | Description |+|------|-------------|+| `src/styles/design-tokens.css` | 270 CSS vars (light + dark) |++### 5.7 Hooks+| File | Description |+|------|-------------|+| `src/hooks/useTheme.ts` | Light/dark toggle, persisted in localStorage |++### 5.8 Native Bridge+| File | Description |+|------|-------------|+| `src/native/browserShim.ts` | Auto-installs stubs in browser (localStorage persistence) |+| `src/native/client.ts` | nativeBridgeClient (system/project/cursor/aiEdition) |+| `src/native/contracts.ts` | TypeScript types for IPC bridge |++### 5.9 Electron Main Process+| File | Lines | Description |+|------|-------|-------------|+| `electron/ai-edition/provider-registry.ts` | ~87 | 8 provider definitions |+| `electron/ai-edition/llm-config-store.ts` | ~90 | safeStorage encrypted credentials |+| `electron/ai-edition/llm-call.ts` | ~100 | Fetch-based LLM call (OpenAI-compat + Anthropic) |+| `electron/ai-edition/chat-service.ts` | ~72 | In-memory chat with real LLM call |+| `electron/ai-edition/document-service.ts` | ~219 | CRUD on .axcut JSON files |+| `electron/ai-edition/document-service.test.ts` | ~193 | Document service tests |+| `electron/native-bridge/services/aiEditionService.ts` | ~141 | IPC bridge for aiEdition domain |+| `electron/ipc/handlers.ts` | ~2800+ | Extended with aiEdition channel handlers |+| `electron/ipc/nativeBridge.ts` | ~98 | Versioned bridge router |++### 5.10 Deleted Files+| File | Reason |+|------|--------|+| `src/components/ai-edition/IconRail.tsx` | Replaced by `LeftPanel.tsx::LeftRail` |+| `src/components/ai-edition/EditorSettings.tsx` | Replaced by `RightPanes.tsx` + `useEditorSettings` |++---++## 6. Merge Status Matrix++### Phase 0 — Foundation (Schema + Migration)+| Item | Status | Files |+|------|--------|-------|+| v3 AxcutDocument schema with annotations, zoomRanges, legacyEditor | ✅ Done | `schema/index.ts` |+| v2 → v3 migration (bidirectional) | ✅ Done | `document/migrate.ts` |+| v2 → v3 migration tests | ✅ Done | `document/migrate.test.ts` |+| Schema tests | ✅ Done | `schema/index.test.ts` |+| Timeline math (normalizeIntervals, etc.) | ✅ Done | `document/timeline.ts` |+| Timeline math tests | ✅ Done | `document/timeline.test.ts` |++### Phase 1 — Core Merge (Clips/Skips/Multi-Asset)+| Item | Status | Files |+|------|--------|-------|+| PR 1.1: Resources panel + asset model | ✅ Done | `projectStore.ts`, `document-service.ts`, `LeftPanel.tsx:MediaPane` |+| PR 1.2: Timeline rewrite (TimelinePane) | ✅ Done (port) | `TimelinePane.tsx` |+| PR 1.3: New editor default (AIEditionShell) | ✅ Done | `NewEditorShell.tsx`, `AiEditionShell.tsx` |+| **Kill-switch removal** | **⚠️ Not done** — `App.tsx` still has conditional render | `App.tsx` |+| Recording → asset (append to project) | **⏳ Partially done** — store has `addAsset` but recording not wired | `NewEditorShell.tsx` |+| Deprecate legacy VideoEditor.tsx | **⏳ Not done** — legacy file unchanged on disk | `VideoEditor.tsx` |++### Phase 2 — VirtualPreview+| Item | Status | Files |+|------|--------|-------|+| VirtualPreview (two-layer, crossfade) | ✅ Done (port) | `VirtualPreview.tsx` |+| Preview transport (play/pause, loop, fullscreen, scrub) | ✅ Done | `Preview.tsx` |+| Cursor-aware clip playback | **❌ Not done** (Phase 2.5) | — |+| Webcam PIP real-time preview | **❌ Not done** (#29) | — |+| Canvas rendering (wallpaper, blur, etc.) | **❌ Not done** (#9) | — |++### Phase 3 — Exporter Rewrite+| Item | Status | Files |+|------|--------|-------|+| Document → VideoExporterConfig | ✅ Done | `documentExporter.ts` |+| ExportDialog (MP4 720/1080/Source + GIF) | ✅ Done | `ExportDialog.tsx` |+| Export IPC (pick path + write) | ✅ Done | `NewEditorShell.tsx` |+| Round-trip export test | **❌ Not done** — needs Electron | — |++### Phase 4 — Transcription + Transcript Editor+| Item | Status | Files |+|------|--------|-------|+| Auto-captions (annotation regions from transcript) | ✅ Done | `NewEditorShell.tsx`, `annotationsFromCaptions.ts` |+| Auto-Transcribe if no transcript | **⚠️ Partially** (#1) | `NewEditorShell.tsx` |+| TranscriptEditor (click-word seek, shift-click range) | ✅ Done (port) | `TranscriptEditor.tsx` |++### Phase 5 — Recorder Feature Preservation+| Item | Status | Files |+|------|--------|-------|+| Return to recorder button | ✅ Done | `NewEditorShell.tsx:372` |+| Unsaved-changes on close | ✅ Done | `NewEditorShell.tsx`, `Modals.tsx` |+| Keyboard shortcuts (all 12) | ✅ Done | `NewEditorShell.tsx` |++### Phase 6 — Agent Runtime (Gated by `AI_FEATURES_ENABLED`)+| Item | Status | Files |+|------|--------|-------|+| 6.1: Chat service + IPC | ✅ Done | `chat-service.ts`, `aiEditionService.ts` |+| 6.2: LLM config + provider registry | ✅ Done | `provider-registry.ts`, `llm-config-store.ts` |+| 6.3: Agent runtime + DeepAgentJS | **❌ Not done** | — |+| 6.4: Checkpoints + restore | **❌ Not done** | — |++### Phase 7 — LLM Providers+| Item | Status | Files |+|------|--------|-------|+| 8 provider definitions | ✅ Done | `provider-registry.ts` |+| Provider settings dialog | ✅ Done | `ProviderSettings.tsx` |+| LLM call (fetch, no LangChain) | ✅ Done | `llm-call.ts` |+| OAuth device flow | **❌ Not done** (#17) | `llm-call.ts` |++### Phase 8 — Conversation History + Checkpoints+| Item | Status | Files |+|------|--------|-------|+| Chat history modal | ✅ Done (basic) | `Modals.tsx:ChatHistoryModal` |+| Multiple sessions | **❌ Not done** (#16) | `chat-service.ts` |+| SQLite persistence | **❌ Not done** (#20) | — |+| Session rename/delete | **❌ Not done** (#21) | `Modals.tsx` |++### Phase 9 — Polish+| Item | Status | Files |+|------|--------|-------|+| i18n locale keys added (13 locales) | ✅ Done | `src/i18n/locales/*/editor.json` |+| i18n migration of components | **⚠️ Partially** (#13) — Titlebar partially done | All `*.tsx` |+| Settings sync | **❌ Not done** | — |+| Empty states | **❌ Not done** (#23) | — |+| Error toasts | **❌ Not done** | — |++### Phase 10 — Cut-over+| Item | Status | Files |+|------|--------|-------|+| AI_FEATURES_ENABLED defaults off | ✅ Done | `featureFlags.ts` |+| Legacy editor deletion | **⏳ Not done** — legacy VideoEditor.tsx still on disk (2961 lines) | `VideoEditor.tsx` |++---++## 7. Next Steps (Ordered)++### Immediate (Before next agent session)+1. `npm run dev` → `http://localhost:5173/?windowType=editor` → create a project → explore+2. Check `git status` — 42 files changed/untracked. **Commit or stash before branching.**++### Priority Fixes (3 lines or less each)+3. **#1**: Auto-Transcribe before captions — add `transcribeAsset` call in `handleGenerateCaptions`+4. **#6**: Region inspector persist — add `saveDocument()` after depth/text edits+5. **#8**: Source transcript modal data — wire `document.transcript` to modal content++### Cleanup+6. Remove `App.tsx` kill-switch (make new editor unconditional)+7. Delete `IconRail.tsx` and `EditorSettings.tsx` (already replaced)++### Next Feature Work+8. **#9**: Canvas preview — Pixi overlay for wallpaper/shadow/blur/crop/webcam/cursor/zoom/annotations+9. **#13**: i18n migration — use `useScopedT` in all `<ai-edition/*.tsx>` (keys exist in all 13 locales)+10. **#14**: Edit Clip modal — pencil button on TimelinePane track blocks+11. **#16**: Conversation History — push sessions, rename/delete in modal+12. **#23**: EditorEmptyState — full drop-zone with logo + supported formats + `.openscreen` drag handler++---++## 8. Critical Context++- **All files under `src/components/ai-edition/` are new/rewritten** — they're either modified in the `4a2f4e4` commit or untracked. The base commit's versions may be stale.+- **`legacyEditor` is kept as `Record<string, unknown>`** in schema — typed accessors live in `editorSettings.ts`. No schema migration needed for v2 round-trips.+- **Browser shim** stores in `localStorage["browser-shim-document"]`. Clear with `localStorage.clear()` in console.+- **Zoom/annotation/speed use ms** (`startMs/endMs`); skip/clip use seconds. Handled in `useTimeline.ts` by multiplying `currentTimeSec * 1000`.+- **`useExhaustiveDependencies` warning** on keyboard shortcut `useEffect` in `NewEditorShell.tsx` — intentional (handler registered once).+- **`npm start` / `npm run build` (Electron) untested** — primary dev mode is browser shim at `:5173/?windowType=editor`.diff --git a/docs/architecture/ai-edition-handover.md b/docs/architecture/ai-edition-handover.mdnew file mode 100644index 000000000..08c7559b6--- /dev/null+++ b/docs/architecture/ai-edition-handover.md@@ -0,0 +1,375 @@+# AI-Edition Handover — opencode coding agent++**Date**: 2026-06-29+**Branch**: `docs/ai-edition-plan` (commit parent `cf25858`)+**Dev server**: `http://localhost:5173/?windowType=editor` (browser mode with shim)+**Worktree**: `C:\Users\etien\.local\share\opencode\worktree\860f8cb1426d647abeba0cc732d7de1694294ae9\mighty-falcon`++---++## 1. What this is++OpenScreen (free, open-source screen recorder + video editor, Electron + React + Pixi.js) is being merged with Axcut (AI-powered video editor) to create a unified editing experience. The new editor is **default for all users** — no kill switch. AI features (LLM chat) are opt-in via `AI_FEATURES_ENABLED` flag in `src/components/video-editor/featureFlags.ts`.++This handover covers **what's been implemented in the current session** (UI redesign + feature wiring) and **what remains to be connected**.++The canonical design reference is `design/openscreen-editor.html` (4686-line static HTML). The behavior specs are `docs/openscreen-ux-ui-spec.md` (legacy OpenScreen features) and `docs/axcut-ux-ui-spec.md` (Axcut features).++---++## 2. Start here++```bash+cd C:\Users\etien\.local\share\opencode\worktree\860f8cb1426d647abeba0cc732d7de1694294ae9\mighty-falcon+npm install # Node 22, npm 10+npm run dev # http://localhost:5173/?windowType=editor+# In browser: http://localhost:5173/?windowType=editor+```++The app runs in browser mode (no Electron needed) — shims are auto-installed via `installBrowserShims()` in `src/App.tsx:4`. Projects persist in `localStorage`.++**Verify**:+```bash+npx tsc --noEmit # typecheck+npm run lint # 367 files, clean+npm run test # 353 tests, 44 test files+```++---++## 3. Architecture map++```text+src/+├── styles/+│ └── design-tokens.css # light + dark CSS vars (:root / :root[data-theme="dark"])+├── hooks/+│ └── useTheme.ts # light/dark toggle, persisted in localStorage+├── App.tsx # imports design-tokens.css, installs browser shims+├── components/ai-edition/+│ ├── NewEditorShell.tsx # TOP-LEVEL: 4-row grid, all state, IPC handlers+│ ├── NewEditorShell.module.css # layout (titlebar 34px / workbench 7-col / handle / bottombar)+│ ├── Titlebar.tsx # brand, rename, save, open/new, lang, recorder, panel toggles, theme+│ ├── Bottombar.tsx # view-tools (zoom/trim/annot/speed) + 3 lane rows + TimelinePane + zoombar+│ ├── Preview.tsx # preview frame + PIP placeholder + transport (play/prev/next/loop/fullscreen/REC)+│ ├── LeftPanel.tsx # left rail (Chat/Media) + MediaPane + ChatStripPanel + ChatHistoryModal+│ ├── RightPanelStack.tsx # right panel container + RegionInspector when a region is selected+│ ├── RightPanes.tsx # 6 individual panes: Background, Transcript, Video Effects, Layout, Cursor, Timeline+│ ├── Modals.tsx # all modals: ModalShell, OpenProject, NewProject, Crop, UnsavedChanges,+│ │ # AutoCaptions, InsertSource, SourceTranscript, ChatHistory+│ ├── ExportDialog.tsx # MP4 (720/1080/Source) + GIF (FPS/Size/Loop) + progress + write to disk+│ ├── ProviderSettings.tsx # 8-provider grid → form (API key/model/baseUrl/reasoning) → save/disconnect+│ ├── VirtualPreview.tsx # single-video preview component (ported from axcut)+│ ├── TimelinePane.tsx # 837-line timeline: ruler, clips, skip strips, navigator (ported from axcut)+│ ├── TranscriptEditor.tsx # click-word → seek, shift-click-range → "Cut" button, strikethrough+│ ├── ProjectPanel.tsx # OLD project picker (kept for reference, not used in the new layout)+│ ├── ChatPanel.tsx # OLD chat panel (replaced by ChatStripPanel in LeftPanel)+│ └── AiEditionShell.tsx # lazy-load entrypoint+│+├── lib/ai-edition/+│ ├── schema/index.ts # v3 AxcutDocument schema (zod)+│ ├── document/+│ │ ├── timeline.ts # pure interval math: normalizeIntervals, subtractInterval, etc.+│ │ ├── migrate.ts # v2 EditorProjectData ↔ v3 AxcutDocument (bidirectional)+│ │ ├── transcribe.ts # wraps existing captioning pipeline+│ │ └── ids.ts # createId(prefix) → uuid+│ ├── store/+│ │ ├── projectStore.ts # Zustand: projectId, document, dirty, lastSavedAt, IPC-backed mutations+│ │ ├── editorSettings.ts # pure get/patch over document.legacyEditor (typed, type-guarded)+│ │ ├── editorSettings.test.ts # 8 tests+│ │ ├── useEditorSettings.ts # React hook: set(patch) → save, setLive(patch) → preview+│ │ └── useTimeline.ts # React hook: addZoom/Skip/Annotation/Speed, addClipBefore/After, splitAndInsert, selection+│ ├── exporter/+│ │ └── documentExporter.ts # AxcutDocument → VideoExporterConfig / GifExporterConfig+│ └── timeline/+│ └── virtual-preview.ts # pure time-mapping: totalVirtualDuration, locateVirtualPosition, etc.+│+├── lib/captioning/ # EXISTING OpenScreen captioning pipeline (used by auto-captions)+│ ├── annotationsFromCaptions.ts # captionSegmentsToAnnotationRegions(segments, id, z, layout)+│ ├── transcribe.ts # transcribeMono16kToSegments (local Whisper)+│ └── ...+│+└── native/+ ├── browserShim.ts # auto-installs stubs for window.electronAPI + nativeBridgeClient in browser+ ├── client.ts # nativeBridgeClient with aiEdition, project, cursor domains+ └── contracts.ts # TypeScript types for the IPC bridge++electron/+├── ai-edition/+│ ├── document-service.ts # CRUD on .axcut JSON files under userData/projects/+│ ├── chat-service.ts # in-memory chat, real LLM call via llm-call.ts+│ ├── llm-call.ts # NEW: fetch-based LLM call (OpenAI-compat + Anthropic, no LangChain dep)+│ ├── llm-config-store.ts # credentials in safeStorage, config in plain JSON+│ └── provider-registry.ts # 8 provider definitions (static)+└── native-bridge/services/+ └── aiEditionService.ts # wraps DocumentService + LlmConfigStore into IPC++design/+├── openscreen-editor.html # CANONICAL design reference (4686 lines, light + dark)+└── DESIGN.md # design system documentation+```++---++## 4. Deleted files (confirm before cleaning)++| File | Why |+|---|---|+| `src/components/ai-edition/IconRail.tsx` | Replaced by `LeftPanel.tsx::LeftRail` |+| `src/components/ai-edition/EditorSettings.tsx` | Bridge to legacy SettingsPanel — removed; new panes use `useEditorSettings` directly |++---++## 5. Features fully wired (click → data → persisted)++### 5.1 Titlebar++| Control | Action | File |+|---|---|---|+| Project name | Click → inline edit → Enter/Esc/Blur → `saveDocument` with renamed title | `Titlebar.tsx:423` |+| Language picker | Click language → `useI18n().setLocale(code)` → i18n locale changes + persisted | `Titlebar.tsx:353` |+| Save button + dropdown | Save → `saveDocument(doc)`, Save As → `window.prompt(rename)` + `saveDocument` | `Titlebar.tsx:220`, `NewEditorShell.tsx:254` |+| Open/New project | Open modal → select/create → `loadProject`/`createProject` | `Modals.tsx` |+| New Recording | `promptUnsaved("record")` → `startNewRecording()` | `NewEditorShell.tsx:360` |+| Return to recorder | `switchToHud()` | `NewEditorShell.tsx:372` |+| Export | Opens `ExportDialog` (MP4 720/1080/Source + GIF FPS/Size/Loop) | `NewEditorShell.tsx:376` |+| Panel toggles (left/right/timeline) | Toggle CSS vars `--panel-w-left/right/bottom` via `data-collapse` | `NewEditorShell.tsx` |+| Theme toggle | `useTheme().toggle()` → `data-theme="dark"` on `:root`, persisted | `Titlebar.tsx`, `useTheme.ts` |+| Dirty status | `dirty` bool + `lastSavedAt` timestamp in Zustand store | `projectStore.ts` |+| WebkitAppRegion | `drag` on titlebar, `no-drag` on buttons | `NewEditorShell.module.css:39` |++### 5.2 Bottombar (view-tools + lanes)++| Button | Action | File |+|---|---|---|+| Zoom (+) | `addZoom()` → 2s region at playhead in `document.zoomRanges[]` | `Bottombar.tsx`, `useTimeline.ts` |+| Auto-focus | Toggle → `set({ autoFocusAll })` | `Bottombar.tsx` |+| Trim (scissors) | `addSkip()` → 2s skip at playhead in `document.timeline.skipRanges[]` | `Bottombar.tsx`, `useTimeline.ts` |+| Annotation | `addAnnotation()` → 2s annotation at playhead in `document.annotations[]` | `Bottombar.tsx`, `useTimeline.ts` |+| Speed | `addSpeed()` → 2s region at playhead in `legacyEditor.speedRegions[]` | `Bottombar.tsx`, `useTimeline.ts` |+| Captions | Opens `AutoCaptionsModal` → `captionSegmentsToAnnotationRegions()` → regenerated `annotations[]` | `NewEditorShell.tsx` |+| Aspect ratio | Dropdown wired to `set({ aspectRatio })` → persisted in `legacyEditor` | `Bottombar.tsx` |+| **3 lane rows** (Zoom/Annotation/Speed) | Pill per region, click → select, × button → delete | `Bottombar.tsx:306` |+| **Region inspector** | When selected → right panel shows depth buttons (zoom), text area (annotation), speed label, delete | `RightPanelStack.tsx:118` |++### 5.3 Right panes (Background/Effects/Layout/Cursor/Timeline)++All writable via `useEditorSettings` → `editorSettings.ts` pure functions → `legacyEditor` envelope:++| Pane | Control | Field |+|---|---|---|+| Background | 16 thumbnails / 25 gradients | `wallpaper` |+| Video Effects | Toggle + 4 sliders | `showBlur`, `motionBlurAmount`, `shadowIntensity`, `borderRadius`, `padding` |+| Layout | Preset select + toggles + shape + slider | `webcamLayoutPreset`, `webcamMaskShape`, `webcamMirrored`, `webcamReactiveZoom`, `webcamSizePreset` |+| Cursor | Toggles + 5 styles + 4 sliders | `cursorShow`, `cursor.clipToBounds`, `cursorTheme`, `cursor.size/smoothing/motionBlur/clickBounce` |+| Timeline | Toggle waveform | `showTrimWaveform` |++### 5.4 Preview + playback++| Control | Action | File |+|---|---|---|+| Play/pause | Toggle `video.play()`/`pause()` (also `Space` global) | `Preview.tsx` |+| Prev/Next clip | Seek to boundary of previous/next timeline clip | `Preview.tsx:82,94` |+| Loop | `videoElement.loop = true/false` | `Preview.tsx:106` |+| Fullscreen | `requestFullscreen()` on video parent | `Preview.tsx` |+| Time display | `formatTC(currentTimeSec)` / `formatTC(sourceDurationSec)` | `Preview.tsx` |+| REC button | Toggle play (placeholder for real recording) | `Preview.tsx` |++### 5.5 Chat (left rail, gated by `AI_FEATURES_ENABLED`)++| Feature | Status | File |+|---|---|---|+| Send message | `chatRun(projectId, text)` → real fetch LLM call (OpenAI compat + Anthropic) | `LeftPanel.tsx:288` |+| Message bubbles | Role (You/OpenScreen) + time + content | `LeftPanel.tsx` |+| Model picker | Cycles through 3 alternatives (visual placeholder, no model switch) | `LeftPanel.tsx:332` |+| Reasoning pill | Shows active reasoning effort level | `LeftPanel.tsx:338` |+| Provider Settings gear | Opens `ProviderSettings` modal → 8 providers → form (API key/model/baseUrl/reasoning) → save/disconnect | `LeftPanel.tsx`, `ProviderSettings.tsx` |+| History button | Opens `ChatHistoryModal` (1 session for now, in-memory) | `LeftPanel.tsx` |+| New chat | Clears messages, increments session counter | `LeftPanel.tsx:324` |+| Context pill | "0% context" (static, no real token tracking) | `LeftPanel.tsx:353` |++### 5.6 Multi-clip + Insert Source++| Feature | Action | File |+|---|---|---|+| Drag media card | `dragstart` sets `dataTransfer` with `assetId` | `LeftPanel.tsx:70` |+| Drop on timeline | Opens `InsertSourceModal` with 3 choices | `NewEditorShell.tsx:385`, `NewEditorShell.tsx:600` |+| Add before | `addClipBefore(assetId)` → shifts all clips forward | `useTimeline.ts:173` |+| Add after | `addClipAfter(assetId)` → appends clip at end | `useTimeline.ts:196` |+| Split and insert | `splitAndInsert(assetId, splitTime)` → splits target clip, inserts between halves | `useTimeline.ts:219` |++### 5.7 Keyboard shortcuts++| Key | Action | File |+|---|---|---|+| `Cmd+S` | Save document | `NewEditorShell.tsx:446` |+| `Cmd+N` | New project (with unsaved prompt) | `NewEditorShell.tsx:452` |+| `Cmd+O` | Open project (with unsaved prompt) | `NewEditorShell.tsx:464` |+| `Space` | Play/pause video | `NewEditorShell.tsx:477` |+| `Z` | Add zoom region | `NewEditorShell.tsx:535` |+| `T` | Add trim/skip region | `NewEditorShell.tsx:545` |+| `A` | Add annotation | `NewEditorShell.tsx:549` |+| `S` | Add speed region | `NewEditorShell.tsx:553` |+| `Del / Backspace` | Remove selected region | `NewEditorShell.tsx:488` |++### 5.8 Backend (Electron main process)++| Feature | Status | File |+|---|---|---|+| 8 provider definitions | Static, fully defined | `electron/ai-edition/provider-registry.ts` |+| LLM config store | `safeStorage` encrypted credentials, plain JSON config | `electron/ai-edition/llm-config-store.ts` |+| LLM call (fetch-based) | OpenAI compat `POST /chat/completions` + Anthropic `POST /messages`, no LangChain | `electron/ai-edition/llm-call.ts` |+| Chat service | In-memory per-project message store, uses real LLM call | `electron/ai-edition/chat-service.ts` |+| Document service | CRUD on `.axcut` JSON files under `userData/projects/` | `electron/ai-edition/document-service.ts` |+| IPC bridge | `aiEdition` domain with `document.*`, `llm.*`, `chat.*` actions | `electron/native-bridge/services/aiEditionService.ts` |++---++## 6. Remaining items — exhaustive list++### 6.1 High priority — functionality gaps++| # | Feature | What's missing | Spec section | Files to touch |+|---|---|---|---|---|+| 1 | **Auto captions when no transcript** | If the user hasn't transcribed yet, the "Captions" button just shows a toast. It should trigger `transcribeAsset` automatically before calling `captionSegmentsToAnnotationRegions`. | OpenScreen §5.6 | `NewEditorShell.tsx:handleGenerateCaptions` |+| 2 | **Playback scrub slider** | The transport bar shows time but has no range input. The design's transport has a progress bar. | Design HTML: `.transport` | `Preview.tsx` |+| 3 | **Timeline playhead scrub** | Click/drag on the ruler → preview seeks. The existing `TimelinePane` has this, but it's not exposed to the Preview component. | OpenScreen §5.5.4 | `TimelinePane.tsx`, `Bottombar.tsx` |+| 4 | **Source Transcript modal — real data** | Currently `transcriptText` is always `null`. Should show `document.transcript` text content. | Axcut §9.4 | `LeftPanel.tsx`, `Modals.tsx` |+| 5 | **UnsavedChangesDialog on Cmd+W (close window)** | Only wired for `New Recording`. Missing for close. Needs `window.onbeforeunload` or `electronAPI`. | OpenScreen §5.9 | `NewEditorShell.tsx` |+| 6 | **Region inspector — persist depth/text** | The zoom depth buttons and annotation textarea update local state but don't call `saveDocument`. | OpenScreen §5.5.3 | `RightPanelStack.tsx:RegionInspector` |+| 7 | **Media file 4-state indicator** | The dot on media cards is always green. Should reflect transcript status (pend/run/complete/fail). | Axcut §4.2 | `LeftPanel.tsx:MediaList` |+| 8 | **Per-file transcript availability check** | The `SourceTranscriptModal` should show the transcript if available. Currently always "Not generated yet". | Axcut §9.4 | `LeftPanel.tsx`, `Modals.tsx` |++### 6.2 Medium priority — visual polish++| # | Feature | What's missing | Spec section | Files to touch |+|---|---|---|---|---|+| 9 | **Canvas preview rendering** (wallpaper, shadow, border-radius, crop, webcam PiP, cursor, zoom, annotations) | The export pipeline renders all of these via Pixi.js, but the live preview doesn't show them. The `VirtualPreview` is a plain `<video>` tag. | OpenScreen §5.5.1 | `Preview.tsx`, `VirtualPreview.tsx`, or a new Pixi overlay |+| 10 | **Live-run feed** (Thinking/Operation/Draft cards) | During LLM call, there's no intermediate feedback. The assistant's message appears all at once. | Axcut §5.3 | `LeftPanel.tsx:ChatStripPanel` |+| 11 | **Status chips** (Transcription `idle|running|ready|error`, Export `idle|running|ready|error`) | No job queue → no status chips. These would appear in the project panel or as a floating pill. | Axcut §10.1 | New component or `LeftPanel.tsx` |+| 12 | **Region shape customization** (crop frame resize, annotation position/size/style) | The region inspector shows basic controls but not: arrow direction, figure color, blur shape/color/mosaic, annotation font family/size/animation, etc. | OpenScreen §5.5.3 | `RightPanelStack.tsx:RegionInspector` |+| 13 | **i18n on new components** | All strings in `Titlebar.tsx`, `Bottombar.tsx`, `LeftPanel.tsx`, `RightPanes.tsx`, `Modals.tsx`, etc. are hardcoded English. The 13 locale files exist under `src/i18n/locales/<locale>/` but the new components don't use `useScopedT`. | Spec §8 | All `src/components/ai-edition/*.tsx` |+| 14 | **Edit Clip modal** | The pencil icon on track blocks (design HTML) doesn't exist in the current `TimelinePane`. Need a modal to edit `sourceStartSec`/`sourceEndSec`. | Axcut §8.5, OpenScreen §5.5.4 | New modal in `Modals.tsx` + `TimelinePane.tsx` |+| 15 | **Per-region Copy/Paste** (Cmd+C/V between regions) | `regionClipboard.ts` exists in the legacy editor but isn't wired in the new shell. | OpenScreen §5.10 | `NewEditorShell.tsx` + new clipboard hook |+| 16 | **Conversation History — multiple sessions** | Currently 1 session only (stored messages + session counter). No backend session management. | Axcut §9.2 + §11 | `electron/ai-edition/chat-service.ts` (needs sessions) |++### 6.3 Lower priority — backend features++| # | Feature | What's missing | Spec section | Files to touch |+|---|---|---|---|---|+| 17 | **OAuth device flow** (ChatGPT/GitHub Copilot) | Currently returns "not implemented yet". Needs token endpoint polling + device code UI. | Axcut §12 | `electron/ai-edition/llm-call.ts`, `ProviderSettings.tsx` |+| 18 | **Reconnect banner** on Provider Settings when API key expires | No `provider_auth_expired` event → no banner. | Axcut §12 | `ProviderSettings.tsx` |+| 19 | **SSE streaming** for project changes | The old Axcut app used `/api/projects/:id/stream` for live updates. Not needed in single-user Electron, but could improve reactivity. | Axcut §15 | Not urgent |+| 20 | **SQLite sessions/checkpoints** | Chat history is in-memory (lost on restart). Axcut used `better-sqlite3` + `PersistentFileCheckpointSaver`. | Axcut §14 | `electron/ai-edition/chat-service.ts` |+| 21 | **Conversation History** with rename/delete | Basic modal exists, but only 1 session, no rename, no delete. | Axcut §9.2 | `Modals.tsx:ChatHistoryModal` |+| 22 | **Undo/redo** (Cmd+Z, Cmd+Shift+Z) | The keyboard handler skips Cmd+Z. No undo stack exists in the store. | OpenScreen §5.10 | `projectStore.ts` (needs undo stack) |++### 6.4 Missing OpenScreen features from the old editor++| # | Feature | What's missing | Spec section |+|---|---|---|---|+| 23 | **EditorEmptyState** (logo + import video + load project + drag & drop overlay + supported formats) | The new editor shows a simple text placeholder, not the full dashboard. | OpenScreen §5.4 |+| 24 | **Drag and drop `.openscreen` file** on the empty state | Handler missing. | OpenScreen §5.4 |+| 25 | **ShortcutsConfigDialog** (customizable shortcuts) | Loaded in `App.tsx` via lazy import, but never shown. No "customise shortcuts" button. | OpenScreen §5.10 |+| 26 | **Annotations settings panel** (Text/Image/Arrow tabs, font family/size/color/animation, custom fonts, duplicate) | The new editor has no annotation settings panel. The legacy `AnnotationSettingsPanel` exists but isn't wired. | OpenScreen §5.5.3 |+| 27 | **Blur settings panel** (shape/color/mosaic size) | Not wired. | OpenScreen §5.5.3 |+| 28 | **Auto-zoom (wand) suggestions** | The wand button in the bottombar is disabled. The legacy editor's `auto-suggest zone` feature isn't ported. | OpenScreen §5.5.4 |+| 29 | **Webcam PIP real-time preview** | The preview shows a placeholder "Webcam" div. No real webcam layer. | OpenScreen §5.5.1 |+| 30 | **Cursor rendering** (theme art, smoothing, motion blur, click bounce) | Not rendered in the preview. The legacy `cursorRenderer.ts` handles it. | OpenScreen §5.5.1 |++---++## 7. State management summary++### Zustand store (`src/lib/ai-edition/store/projectStore.ts`)+```ts+{+ projectId: string | null,+ document: AxcutDocument | null,+ revision: number,+ dirty: boolean, // true when setDocument() was called without saveDocument()+ lastSavedAt: Date | null, // timestamp of last successful saveDocument()+ // Actions: loadProject, createProject, saveDocument, setDocument, addAsset,+ // removeAsset, replaceTimeline, restoreFullTimeline, setTranscript,+ // markClean, clear+}+```++### Editor settings (`src/lib/ai-edition/store/editorSettings.ts`)+- `getEditorSettings(doc) → EditorSettingsSnapshot` (typed, type-guarded)+- `patchEditorSettings(doc, patch) → AxcutDocument` (immutable)++### Hook layer (`src/lib/ai-edition/store/useEditorSettings.ts`)+- `set(patch)` → `setDocument` + `saveDocument` (commit)+- `setLive(patch)` → `setDocument` only (preview, no persist)+- `commit()` → `saveDocument` (flush)++### Timeline hook (`src/lib/ai-edition/store/useTimeline.ts`)+- Region CRUD: `addZoom`, `addSkip`, `addAnnotation`, `addSpeed`, `removeRegion`+- Clip operations: `addClipBefore`, `addClipAfter`, `splitAndInsert`+- Selection: `selectRegion(kind, id)`, `clearSelection()`, `selection: { kind, id }`++---++## 8. Data flow — how a click hits the document++```text+User clicks "Add zoom" in Bottombar+ → Bottombar calls tl.addZoom() [useTimeline.ts]+ → useTimeline reads currentTimeSec from store [projectStore.ts]+ → Creates a ZoomRegion at playhead+ → Calls saveDocument(next) [projectStore.ts]+ → nativeBridgeClient.aiEdition.save(doc) [client.ts]+ → IPC → aiEditionService [electron/native-bridge/]+ → DocumentService.saveProject [electron/ai-edition/document-service.ts]+ → writes .axcut JSON to disk+ → set({ document: parsed, dirty: false, lastSavedAt: now })++React re-renders:+ → Bottombar reads updated zoomRegions+ → Timeline lanes show new pill+ → User clicks pill → selectRegion("zoom", id)+ → RightPanelStack sees selection → shows RegionInspector+ → User clicks depth button → updates zoomRegion.depth → setDocument() → saves+```++---++## 9. Dev server quick-ref++```bash+# Start (from worktree root)+npm run dev+# Opens at http://localhost:5173/?windowType=editor++# Stop+Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*vite*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }++# Logs+Get-Content "$env:TEMP\openscreen-dev.err" -Tail 20+Get-Content "$env:TEMP\openscreen-dev.out" -Tail 20+```++The shim in `src/native/browserShim.ts` auto-installs when `window.electronAPI` is absent. Projects are stored in `localStorage["browser-shim-document"]`. To clear: `localStorage.clear()` in the browser console.++---++## 10. Known rough edges++1. **`useExhaustiveDependencies` warning** on the keyboard shortcut `useEffect` in `NewEditorShell.tsx:466` — intentional (the handler is registered once, not on every state change).+2. **Zoom region timing**: zoom/annotation/speed use **ms** units (`startMs`/`endMs`), but skip/clip use **seconds**. Handled in `useTimeline.ts` by multiplying `currentTimeSec * 1000`.+3. **`legacyEditor` is loosely typed** — `Record<string, unknown>` in the schema. The `editorSettings.ts` module provides typed accessors, but if a v2 `.openscreen` project has unexpected shapes, they'll fall back to defaults.+4. **Browser shim doesn't persist** to disk — `saveDocument` writes to `localStorage` only. Real Electron writes to `.axcut` files.+5. **No Electron window open** in dev mode — the renderer renders in a browser tab without the native recorder/export pipeline. For export testing, use the SourceTranscript dummy or wait for Electron.++---++## 11. Suggested first actions for the next agent++1. `npm run dev` → open `http://localhost:5173/?windowType=editor` → create a project → add a video → explore all the wired features+2. Fix item #1 (auto-Transcribe before captions) — it's a 3-line change in `handleGenerateCaptions`+3. Fix item #6 (region inspector persist) — add `saveDocument` call after depth/text edits+4. Fix item #8 (source transcript modal data) — wire `document.transcript` to the modal+5. Fix item #12 (region inspector customization) — expand `RegionInspector` in `RightPanelStack.tsx` to include: annotation font/color/size, arrow direction, blur shape/color, zoom focus X/Y+6. Pick up items #13–#16 for visual polish+7. If Electron build is needed: `npm run build` (typecheck + Vite + electron-builder)diff --git a/docs/architecture/ai-edition-merge-plan.md b/docs/architecture/ai-edition-merge-plan.mdnew file mode 100644index 000000000..d62316923--- /dev/null+++ b/docs/architecture/ai-edition-merge-plan.md@@ -0,0 +1,420 @@+# AI Edition Merge Plan — OpenScreen × Axcut++> **Goal.** Make OpenScreen the host of the Axcut engine. The recorder stays the front door; the new project model (multi-asset → clips → skips) becomes the canonical timeline; AI features (transcript, agent, providers) sit on top as an opt-in layer.+>+> **Outcome.** The recording you make today becomes a resource in a multi-clip project. Transcript, clips, skips, agent chat, and BYO-LLM providers integrate cleanly with OpenScreen's recorder, exporter, and UX — without forking the codebase.++---++## 0. Framing — two layers, one merge++This merge ships **two independent layers** that the original plan conflated under one "AI-edition" banner. The split matters because they have different opt-in, privacy, and rollout profiles:++| Layer | What it is | Default? | Privacy model | Rollout |+|---|---|---|---|---|+| **New editing model** | Multi-asset projects, clips + skip ranges, transcript-driven editing, virtual preview, document-driven exporter | **Default** for everyone once Phase 1 PR 1.3 lands | Local-first — no data leaves the machine | Replaces the single-track timeline for all users |+| **AI features** | LLM providers (BYO key), agent chat, suggestions, conversation history, checkpoints | **Opt-in** behind `AI_FEATURES_ENABLED` | Sends transcript + ops to the chosen provider per locked decision 4 (`safeStorage` for credentials) | Phase 6+, surfaces in a collapsible right panel |++**What this means in practice:**++- Local Whisper transcription is **not** gated. It runs in-browser via `@xenova/transformers` (`src/lib/captioning/`), bundled with the app, never calls out. Privacy-safe by construction.+- The new editing model is **the editor going forward**. There is no "AI-edition project" vs. "legacy project" in user-facing terms — only one editor, with v3 AxcutDocument as its save format from Phase 0 onward.+- `AI_FEATURES_ENABLED` (renamed from `AI_EDITION_ENABLED` on 2026-06-26) controls **only** the LLM/agent surface: provider settings dialog, chat panel, suggestions list, "Restore checkpoint" actions. It does **not** gate the editor itself, the project panel, the timeline, the transcript editor, or the exporter.+- Legacy `.openscreen` (v2) projects migrate to v3 on first open regardless of the flag. The migration is the front door; the flag is a UI affordance.++**Naming convention going forward:**+- `AI_FEATURES_ENABLED` — the flag.+- `src/lib/ai-edition/` — schema, document helpers, agent runtime, provider config, AI-feature UI components.+- `src/components/video-editor/` — the editor (new model, default).++The earlier `AI_EDITION_ENABLED` constant was renamed because it conflated the two layers in PR 1.1. Phase 1 PR 1.2+ ships the new editor as the default rendering path; `AI_FEATURES_ENABLED` only governs the opt-in AI layer.++---++## 1. Why this is bigger than "merge two repos"++Axcut was built as a separate TypeScript-control / Python-worker web app with its own Fastify server, SQLite, and sidecar Python process. OpenScreen is an Electron + React app with an in-browser exporter (mediabunny) and an in-browser Whisper (`@xenova/transformers`). Forcing axcut's process model into OpenScreen would mean:++- Two transcription pipelines (browser Whisper + Python faster-whisper) → inconsistent UX, double downloads+- A sidecar Python process inside an Electron app → fragile on macOS/Windows, huge native footprint+- A separate Fastify server inside Electron → wasted cycle+- Two exporters (mediabunny + Python ffmpeg pipeline) → divergent output, double maintenance++So the merge strategy is **not "port axcut's files in"**. It's **"adopt axcut's data model and UX patterns, re-implement them on OpenScreen's existing primitives"**. The Python + Fastify layers in axcut die; the schema, the agent runtime, and the UI patterns live.++---++## 2. Architecture — the SSOT++### 2.1 The new project document (SSOT)++`AxcutDocument` from `packages/axcut-schema/src/index.ts` becomes OpenScreen's canonical project model. It already has:++- `project` (id, title, timestamps, primaryAssetId)+- `assets[]` (video sources with metadata)+- `transcripts[]` (per-asset)+- `timeline { clips, gaps, skipRanges, muteRanges, speedRanges, captionRanges }`+- `agent { baseIntent, pendingQuestions, suggestions, lastAppliedOperations }`+- `preview { strategy, revision }`+- `export { preset, lastJobId }`+- `history { revisions[] }`++This is the SSOT. Timeline, transcript, agent, history — all read and write through this document. Renderer, main process, and exporter all consume the same shape.++**Migration:** existing `EditorProjectData` projects (v2) get a one-shot migration on first open in AI Edition:++| Legacy field | Maps to |+|---|---|+| `media.screenVideoPath` / `media.cameraVideoPath` | a single `asset` + a single clip spanning its full duration |+| `editor.trimRegions[]` | the inverse — gaps in the timeline, expressed as `skipRanges` on the asset |+| `editor.speedRegions[]` | timeline.speedRanges |+| `editor.zoomRegions[]` | timeline (modeled as `captionRanges` annotation + a new `zoomRanges[]` field added to the schema — see §2.4) |+| `editor.annotationRegions[]` | a new `annotations[]` field on the schema |+| `editor.{wallpaper, aspectRatio, cursor, padding, crop, webcam*, motionBlur, borderRadius}` | `editor.*` stays; rename legacy `editor` to `legacyEditor` on migration and apply those fields through the export pipeline the same way as today |++**Single source of truth, two views.** The renderer keeps a local store of `AxcutDocument` (via Zustand or plain context, TBD in Phase 1); the main process persists it to `app.getPath('userData')/projects/<id>.axcut` and SQLite for sessions/messages/checkpoints/jobs.++### 2.2 Renderer layout (post-merge)++```+src/+ lib/+ ai-edition/ ← new namespace; everything AI-Edition is here+ schema/ ← Zod schemas copied/adapted from @axcut/schema+ document/ ← mutations, history, ids, validate+ timeline/ ← normalizeIntervals, buildTimelineFromIntervals, virtual-preview+ transcript/ ← editable-transcript (LCS deletion)+ agent/ ← deepagentjs tool factories (renderer-side helpers only)+ providers/ ← provider list & capability map (mirrors axcut's)+ exporter/ ← existing, refactored to consume AxcutDocument+ captioning/ ← existing; expose as a reusable service for AI-Edition+ components/+ ai-edition/ ← mirrors apps/web/src/components in axcut+ VirtualPreview.tsx+ TimelinePane.tsx+ TranscriptEditor.tsx+ CurrentTranscriptView.tsx+ SuggestionList.tsx+ ProviderSettingsDialog.tsx+ LlmSetupPanel.tsx+ SessionHistoryDialog.tsx+ InsertAssetDialog.tsx+ TranscriptDialog.tsx+ video-editor/ ← existing; rewritten to consume AxcutDocument+ VideoEditor.tsx ← becomes the AI-Edition shell+ VideoPlayback.tsx ← deprecated in favor of ai-edition/VirtualPreview+ timeline/ ← existing single-track TimelineEditor deprecated; TimelineWrapper + Row + Subrow stay as low-level primitives if useful+electron/+ ai-edition/ ← main-process counterparts+ document-service.ts ← port of axcut's DocumentService+ agent-session-service.ts ← port; SQLite-backed checkpoints+ agent-runtime.ts ← port; creates DeepAgentJS from provider config+ chat-service.ts ← port; persists messages, runs runtime, emits events+ llm-config-service.ts ← port; provider credentials, models, base URLs+ database.ts ← better-sqlite3 schema (projects, messages, jobs, sessions, checkpoints)+ event-bus.ts ← per-project pub/sub for renderer sync+ ipc.ts ← IPC channel map (typed)+ python/ ← DELETED. Everything in axcut's py/ dies.+ ipc/handlers.ts ← extended with ai-edition channel handlers+```++Why a new `ai-edition/` namespace inside `src/` and `electron/` instead of a separate package? OpenScreen is a single-package app (`package.json` has no `workspaces`). A monorepo refactor is a 10x cost with no payoff. We adopt `axcut-schema`'s *schema and semantics*, but the schema lives in `src/lib/ai-edition/schema/` as part of the OpenScreen package.++### 2.3 Schema delta++Two additions to `AxcutDocument` to keep OpenScreen's existing UX (zoom, annotations, appearance):++```ts+// added to documentSchema in src/lib/ai-edition/schema/index.ts+annotations: z.array(annotationRegionSchema).default([]), // mirrors editor.annotationRegions+zoomRanges: z.array(zoomRegionSchema).default([]), // mirrors editor.zoomRegions+legacyEditor: legacyEditorSchema.nullable().default(null), // migration target for old projects+```++Legacy fields (`wallpaper`, `aspectRatio`, `cursor`, `webcam*`, `motionBlur`, `borderRadius`, `cropRegion`, `padding`) live under `legacyEditor` and are applied at export time exactly as today. Renderer reads them; main process reads them at export.++Schema version bumps to **3**.++### 2.4 Process model — kill the sidecar++| Axcut layer | Replaced by |+|---|---|+| `apps/server` (Fastify + SQLite + jobs) | `electron/ai-edition/` (main-process modules + better-sqlite3) |+| `py/axcut-core` (ffprobe, faster-whisper, render) | DELETED. Use OpenScreen's `src/lib/exporter` (mediabunny) and `src/lib/captioning` (transformers.js Whisper). |+| `py/axcut-worker` (CLI subprocess) | DELETED. No Python in OpenScreen. |+| `apps/web` (React app served by Fastify) | OpenScreen's renderer. Same React, different mount point — the AI Edition opens inside `VideoEditor` (or a sibling route), not as a standalone window. |+| Docker Compose | DELETED. OpenScreen is an Electron app, no container. |++**Trade-off:** axcut's ffmpeg-Python exporter has more flexibility (precise control over filters, complex cut/join). mediabunny covers our needs for clips+skips with `seek()` on multiple source videos and an in-browser MP4 mux. If a clip needs cross-clip transitions or fades that mediabunny can't do, we use WebCodecs + a frame queue — already in `src/lib/exporter/`. So we lose nothing in practice.++---++## 3. UX integration — OpenScreen feel stays++### 3.1 Recording flow → multi-asset project++Today: `Record → Trim on single-track timeline → Export`. The recording is the project.++After merge: `Record` produces an `asset` and a `clip`. Pressing **Stop** does not auto-trim — it appends to the project. The user can record more takes. The project grows.++- A new **Resources** panel lists assets (recordings + imported files).+- The timeline shows clips + skips. New recordings default to `append at end`; users drag-reorder.+- Pressing **Stop** doesn't close the editor — that's the new behavior for AI-edition projects (locked decision §5.1: first recording still auto-opens; subsequent ones stay in the recorder with a prompt).++### 3.2 Trim visualization++Replace OpenScreen's single-video `<VideoPlayback>` with axcut's `VirtualPreview` (two-layer, crossfade-at-clip-end) for AI-Edition projects. Native-recording scrubbing preview stays for the recorder side (it already lives there).++Visually: identical to axcut's current preview, with OpenScreen's design tokens (rounded corners, neutral dark, typography from the launch window). Re-skin, don't rewrite.++### 3.3 Clips management on the timeline++axcut's `TimelinePane` is the new timeline. It already supports:++- Drag a source from the **Resources** panel → drops at a position → opens `InsertAssetDialog` (before / after / split).+- Drag a clip's body → reorder (with ghost + insert marker).+- Pencil button → enters clip-edit mode (handles on left/right).+- Skip handles at left/right (always-visible).+- Ctrl+C / Ctrl+V → duplicate clip.+- Zoom + pan via the existing OpenScreen `TimelineWrapper` zoom/pan logic.++We re-skin it to match OpenScreen's design tokens. The **Timeline component rewrite** is the most visible Phase 1 work — but most of the logic ports directly from axcut.++### 3.4 Agent chat panel++A collapsible right-side panel inside the editor (mirror of axcut's App layout: project panel left, transcript center, chat right, timeline bottom). Mounted only when the AI Edition flag is on. Provider settings open in a modal, same flow as axcut's `ProviderSettingsDialog`.++When the AI Edition flag is off, the editor looks like today's OpenScreen: single asset, single track, trim, export.++---++## 4. Phasing — ten phases, each ships as 1–3 PRs++Each phase ends in a usable, tested state. **Do not** start a phase until the previous one is on `main`.++### Phase 0 — Foundation (≈ 1 PR) (revised 2026-06-26)++The flag is renamed to `AI_FEATURES_ENABLED` and gates nothing in Phase 0. The schema, migration, and persistence are unconditionally v3.++- Vendor `packages/axcut-schema/src/index.ts` into `src/lib/ai-edition/schema/`. Rename types from `Axcut*` → keep as `Axcut*` (already the right namespace, no churn for readers of axcut docs).+- Bump schema version to 3, add the `annotations`, `zoomRanges`, `legacyEditor` fields (§2.3).+- Add `featureFlags.AI_FEATURES_ENABLED` (defaults off — controls only LLM/agent UI, see §0 and §5.9).+- Migrate `EditorProjectData` persistence: **always** save as `AxcutDocument`. When loading, v2 projects migrate on first open. No flag gate.+- Add migration: existing v2 `EditorProjectData` → v3 `AxcutDocument` (single asset + clip + skipRanges from inverse of trimRegions). Function in `src/lib/ai-edition/document/migrate.ts`.+- New unit tests for the schema + migration.++**Acceptance:** `npm run test` green. Loading an old `.openscreen` project produces a valid v3 document unconditionally. AI features stay opt-in.++### Phase 1 — Core merge: clips, skips, multi-asset (≈ 3 PRs) (revised 2026-06-26)++This is the **default editor** rollout, not an opt-in. From Phase 1 PR 1.3 onward, every user gets the new editor. The legacy single-track timeline is deprecated at the end of this phase and removed in a later major release.++Three PRs because the change is large and benefits from reviewable chunks.++**PR 1.1 — Resources panel + asset model**++- `electron/ai-edition/document-service.ts` (port of axcut's DocumentService, slimmed: no separate `paths.ts`, lives in `app.getPath('userData')`).+- Renderer store: `useProjectStore` (Zustand) holding `AxcutDocument` + revision counter.+- `src/components/ai-edition/ProjectPanel.tsx` — left sidebar, lists assets + compositions.+- IPC: `aiEdition.document.listProjects` / `get` / `create` / `save` / `delete` / `addAsset` / `removeAsset` (added to the existing typed-envelope native bridge).+- Visible behind a temporary `AI_FEATURES_ENABLED` kill-switch in App.tsx so PR 1.1 can ship without rewriting the legacy VideoEditor.tsx. **The kill-switch is removed at the end of PR 1.3** — see below.++**PR 1.2 — Timeline rewrite (clips + skips)**++- Port `apps/web/src/components/TimelinePane.tsx` → `src/components/ai-edition/TimelinePane.tsx`.+- Drop source from Resources → drop on timeline → `InsertAssetDialog`.+- Clip drag-reorder, duplicate (Ctrl+C/V), move.+- Skip range handles (always-on; pencil button toggles clip-handle mode).+- IPC + reducer ops: `addClip` / `updateClipRange` / `moveClip` / `duplicateClip` / `addSkipRange` / `updateSkipRange` / `removeSkipRange`.+- Re-skin to OpenScreen design tokens.++**PR 1.3 — Make the new editor the default — kill-switch removal**++- Replace `App.tsx`'s VideoEditor lazy-import with the new editor shell (`NewEditorShell`).+- The new shell contains: `ProjectPanel` (left), new `TimelinePane` (bottom), `VirtualPreview` (center, replaces `VideoPlayback`), `SettingsPanel` (right), legacy annotation/zoom/blur inspector (right drawer).+- Wire legacy `VideoPlayback.tsx` → `VirtualPreview.tsx` (Phase 2 work, done as part of PR 1.3).+- Wire the legacy exporter (`src/lib/exporter/videoExporter.ts`) to accept `AxcutDocument` (Phase 3 work, done as part of PR 1.3).+- Recording → resource (PR 1.3 original plan): append new recording to current project's `assets`, create a clip spanning the full duration, insert at end of timeline. Stop behavior per locked decision §5.1: first recording still auto-opens the editor; subsequent ones stay in the recorder with an "Open editor / Record another" prompt.+- Delete `src/components/ai-edition/AiEditionShell.tsx` and the kill-switch in App.tsx — every user now renders the new editor.+- Deprecate (don't delete yet): `src/components/video-editor/timeline/TimelineEditor.tsx`, `src/components/video-editor/VideoPlayback.tsx`.++**Acceptance:** every user, with or without the AI features flag, sees the new editor. Record two takes → both appear as clips in a project → reorder → trim handles work → export produces a cut video of the timeline.++### Phase 2 — VirtualPreview (≈ 1 PR) — folded into PR 1.3++The new `VirtualPreview` ships as part of PR 1.3 (the default-editor rollout). There is no longer a separate Phase 2 PR — it was always going to ship with the editor itself, not as an opt-in toggle.++### Phase 3 — Exporter rewrite (≈ 2 PRs) — folded into PR 1.3++The document-driven exporter ships as part of PR 1.3 too. The export pipeline accepts `AxcutDocument` instead of single clip from day one of the new editor.++**PR 3.2 (now part of PR 1.3 follow-up)** — Round-trip test: render a 3-clip project with one skip region → output MP4 → ffprobe → assert duration + presence of expected frames. Linux CI is sufficient; macOS + Windows smoke after.++### Phase 4 — Transcription + transcript editor (≈ 2 PRs) — NOT gated++Local Whisper is privacy-safe; the transcript editor is part of the new editing model, not an AI feature. **Neither is gated by `AI_FEATURES_ENABLED`.**++**PR 4.1 — Transcription pipeline**++- Reuse OpenScreen's existing `src/lib/captioning/transcribe.ts` (transformers.js Whisper). Wrap it as `transcribeAsset(asset, language)` → returns `AxcutTranscript`.+- In the renderer: run on demand from `TranscriptDialog` (re-skin of axcut's).+- Persist into `AxcutDocument.transcripts[]`.++**PR 4.2 — Transcript editor**++- Port `TranscriptEditor.tsx` + `CurrentTranscriptView.tsx` → `src/components/ai-edition/`.+- Click-word, shift-click-word → range → "Cut" → `dropWordRange` op.+- `editable-transcript.ts` (LCS-based deletion) ports as-is.+- Kept / skipped styling: OpenScreen's existing token for `danger` / `muted`.++**Acceptance:** transcript appears within minutes (cached model); deleting a word from the transcript re-derives the timeline intervals and updates the preview. Default behavior; no opt-in needed.++### Phase 5 — Removed++There is no longer a "recorder-side feature preservation" phase. The recorder has always worked; the new editor is the editor; nothing needs preserving.++---++### Phase 6 — Agent runtime (≈ 2 PRs) — first AI-feature phase++**This is the first phase that the `AI_FEATURES_ENABLED` flag actually gates.** Everything before Phase 6 ships to every user.++**PR 6.1 — Main process**++- Port `agent-session-service.ts` (sessions, checkpoints, SQLite-backed `PersistentFileCheckpointSaver`).+- Port `axcut-deep-agent.ts` → `electron/ai-edition/agent-runtime.ts`; builds DeepAgentJS tool set from `AxcutDocument` ops.+- Port `chat-service.ts` → `electron/ai-edition/chat-service.ts`; uses the existing EventBus for renderer sync.+- IPC: `ai-edition:chat:run`, `ai-edition:sessions:list` / `create` / `rename` / `delete` / `select`.+- Credentials stored via `safeStorage` per locked decision 4.++**PR 6.2 — Renderer**++- Port `apps/web/src/components/CurrentTranscriptView.tsx` (chat panel) and `SuggestionList.tsx` (pending cut suggestions).+- Wire to IPC + React Query (added per locked decision 3).+- Mount only when `AI_FEATURES_ENABLED`.++**Acceptance:** "Remove silences" prompt produces a real `replace_timeline` op applied to the document, with a checkpoint saved before/after.++### Phase 7 — LLM providers + BYO config (≈ 1 PR) — gated++- Port `provider-registry.ts`, `llm-config-store.ts`, `llm-config-service.ts`, `create-chat-model.ts`, `openai-account.ts`, `copilot-account.ts`, `chat-codex-oauth.ts` → `electron/ai-edition/`.+- Port `ProviderSettingsDialog.tsx` (the modal with providers/models/reasoning/device-challenge for OAuth) → `src/components/ai-edition/`.+- Mount only when `AI_FEATURES_ENABLED`.++**Acceptance:** all axcut-supported providers (OpenAI, Anthropic, Google, Mistral, OpenRouter, OpenAI-compatible, GitHub Copilot, OpenAI OAuth) work; reasoning effort selectable. Visible only to opted-in users.++### Phase 8 — Conversation history, checkpoints, context compaction — gated++- Renderer's `SessionHistoryDialog.tsx` (port from axcut).+- Per-session checkpoint restore: clicking "Restore" rewinds `AxcutDocument` to that point + rebuilds the agent's langgraph state.+- Context compaction: keep the existing `before-compaction` / `after-compaction` checkpoint reasons from axcut's `AgentSessionService`. The compaction algorithm (long-context summarization) ports as-is.++**Acceptance:** users can branch off any past checkpoint; the agent's memory survives a project reload.++### Phase 9 — Polish++- 13-locale i18n pass on every new string (`npm run i18n:check`).+- Settings sync (`userPreferences.ts`): `AI_FEATURES_ENABLED` toggle, default provider, default model, default reasoning effort. The toggle lives in Settings; off by default.+- ROADMAP update: the "AI Edition" section turns from "direction" into "shipped phases X-Y; remaining Z".+- Empty states, error toasts (sonner already in deps), keyboard shortcuts help.+- Permission pass on native-bridge changes (record → asset adds a path to the document, which gets rendered back via `file://` — must use the same `assetBaseUrl` pattern already in `transcribe.ts`).++### Phase 10 — Cut-over (revised 2026-06-26)++There is **no editor cut-over** anymore. The new editing model (multi-asset, clips, transcript) is the default from Phase 1 PR 1.3 onward — users get it automatically.++The only "cut-over" left is for the AI features:++- `AI_FEATURES_ENABLED` stays **off** by default indefinitely — users opt in via Settings.+- New users get the new editor with no opt-in required.+- Existing users get the new editor as soon as Phase 1 PR 1.3 ships; no flag involved.+- The legacy single-track timeline (`src/components/video-editor/timeline/TimelineEditor.tsx` + `VideoPlayback.tsx`) is **deprecated** once the new editor is the default rendering path, but stays in the repo for the deprecation window. Removal happens in a future major release.++---++## 5. Locked decisions (resolved before Phase 0)++These were the open questions going into the merge. They're now decided — see `ai-edition-collision-analysis.md §9` for the reasoning behind each.++1. **Stop behavior.** First recording always auto-opens the editor (current behavior). Second-and-later recordings in an active project stay in the recorder with an "Open editor / Record another" prompt. Locked: 2026-06-25.+2. **Auto-caption annotation injection (`annotationsFromCaptions.ts`).** Drop entirely. The transcript editor is the source of truth for spoken-word regions; users add overlay annotations manually if needed. Locked: 2026-06-25.+3. **React Query.** Add `@tanstack/react-query` as a dependency. Phase 6 (agent runtime) leans on it heavily. Locked: 2026-06-25.+4. **LLM credential storage.** Use Electron's `safeStorage` (OS keychain). Plain JSON storage (axcut's choice) is a security regression. Locked: 2026-06-25.+5. **Whisper model default.** Bundle OpenScreen's existing smaller model. Add a clear "Transcription model" picker in settings: `tiny / base / small / medium` with download size + speed hints, opt-in to larger. Local Whisper is **not** an AI feature for opt-in purposes — it's bundled, runs in-browser, never calls out. Locked: 2026-06-25 (updated 2026-06-26).+6. **Proxy MP4 generation.** Drop. Rely on `StreamingVideoDecoder` (WebCodecs) for editor scrubbing. **Known limitation:** users have reported scrubbing lag on long recordings (>30 min). See §8 for the documented concern and the revival path. Locked: 2026-06-25.+7. **File extension.** Keep `.openscreen`. No rename. Existing users have files with that extension; internal users get a one-time migration only if desired. Locked: 2026-06-25.+8. **Repository / packaging model.** AI-edition lives **in-tree** as `src/lib/ai-edition/`, `electron/ai-edition/`, `src/components/ai-edition/`, `src/i18n/locales/<locale>/ai-edition.*` — **single package, single repo, single `package.json`, single CI, single release.** No separate npm package, no monorepo tooling. Locked: 2026-06-25.+9. **Flag semantics (`AI_FEATURES_ENABLED`).** The flag controls **only** the LLM-dependent surface: provider settings, chat panel, suggestions list, "Restore checkpoint" actions. It does **not** gate the new editing model (multi-asset / clips / transcript), the project panel, the timeline, the exporter, or local Whisper. Default off. Rename of the previous `AI_EDITION_ENABLED` constant to `AI_FEATURES_ENABLED` happened on 2026-06-26 to reflect this split — see §0 above. Locked: 2026-06-26.++---++## 6. Files that change, files that don't++**Don't touch** (avoid scope creep):+- `electron/native/` (ScreenCaptureKit + WGC helpers)+- `src/lib/cursor/` (cursor capture + smoothing)+- `src/lib/wallpaper.ts`, `src/lib/recordingSession.ts`, `src/lib/shortcuts.ts`+- `src/components/launch/`+- `tests/e2e/` for recorder flow++**Rewrite** (in order):+- `src/components/video-editor/VideoEditor.tsx` — becomes the AI Edition shell+- `src/components/video-editor/VideoPlayback.tsx` — deprecated+- `src/components/video-editor/timeline/*` — kept as low-level primitives; `TimelineEditor.tsx` deprecated+- `src/lib/exporter/*` — accepts `AxcutDocument`+- `src/components/video-editor/projectPersistence.ts` — extended with v3 save format++**Add**:+- `src/lib/ai-edition/` (schema, document, timeline, transcript, agent, providers)+- `src/components/ai-edition/` (UI)+- `electron/ai-edition/` (services + runtime)++**Delete** (in the merge commit):+- axcut's `py/` entirely+- axcut's `apps/server/` and `apps/web/` (the implementations; the *patterns* live on in OpenScreen)++---++## 7. Verification++- **Per-PR:** `npx tsc --noEmit` clean, `npm run lint` clean (or pre-existing warnings), `npm run test` green, new tests for new code (vitest, jsdom).+- **Per-phase:** manual smoke test on Linux (CI), macOS, Windows. macOS+Windows specifically for any exporter or recorder-touching change. The native helpers stay frozen so this is a renderer + main-process job.+- **Endgame:** end-to-end script — record → transcript → "remove silences" prompt → review → export → ffprobe the output. Runs in CI via Playwright e2e on Linux. Headless on Windows/macOS is best-effort.++---++## 8. Known limitations & future work++Things we knowingly trade away in this merge, with a documented path back if they bite us.++### 8.1 Long-recording scrubbing (>30 min) — proxy MP4++**Decision:** drop proxy MP4 generation. Rely on `StreamingVideoDecoder` (WebCodecs) to seek the source on demand.++**Why we accept the tradeoff:** OpenScreen users typically record 2–15 min screen captures. `StreamingVideoDecoder` hardware-decodes those in real time with no proxy file.++**Why we know it bites:** the team has reports of scrubbing lag on long recordings (>30 min). With proxy dropped, every seek in the editor triggers a new WebCodecs keyframe search + decode ramp-up on the original file. On lower-end machines this stutters.++**Revival path (if needed):** add a per-asset "Generate proxy" button in the asset panel (Phase 1+ scope). When clicked, the main process transcodes a low-res keyframe-dense MP4 alongside the asset (`<assetId>.proxy.mp4` in `app.getPath('userData')/projects/<id>/assets/`). The exporter + VirtualPreview fall back to the proxy only when scrubbing (export still uses the original). Threshold: enable proxy generation automatically when `assetDurationMs > 30 * 60 * 1000`. See `ai-edition-collision-analysis.md §4.2` for the original decision record.++### 8.2 macOS native helper code-signing for proxy ffmpeg++Not applicable yet (no proxy). If we revive §8.1, the ffmpeg binary used for proxy transcoding needs to ship with the app and be codesigned on macOS. Plan for that alongside the revival PR.++### 8.3 Auto-caption annotation flow (removed)++OpenScreen's old `annotationsFromCaptions.ts` automatically created lower-third caption annotations from Whisper output. **Removed in this merge.** Reason: same words now live in `transcripts[]` (the transcript editor) — two writers for the same source is a collision. Users can still add overlay annotations manually via the existing annotation tools.++**Revival path:** if users ask for "captions burned into the video" as an export preset (separate from the transcript editor), add it as an export-pipeline option in a future phase. It would be a one-shot burn-in at export time, not a live annotation.++### 8.4 `EditorProjectData` v2 schema (frozen, not deleted)++The legacy v2 schema stays readable and writable throughout the merge. v2 → v3 migration happens eagerly on first open once the new editor is the default (Phase 1 PR 1.3+), with a v2 backup kept next to the v3 file. The migration is the front door — it is no longer gated behind any feature flag. The "lazy on first AI-edition save" behavior from the original plan is obsolete.++---++## 9. Next step++If this plan looks right, I'll start with **Phase 0 PR** — vendor `axcut-schema`, add the v3 schema fields, write the migration from `EditorProjectData` → `AxcutDocument`, add the feature flag. One PR, ~600 LOC including tests, foundation for everything else.++The order matters: Phase 0 first, then Phase 1 in three PRs as outlined, then the rest in dependency order.\ No newline at end of filediff --git a/docs/architecture/axcut-inventory.md b/docs/architecture/axcut-inventory.mdnew file mode 100644index 000000000..179f03b9d--- /dev/null+++ b/docs/architecture/axcut-inventory.md@@ -0,0 +1,458 @@+# Axcut Inventory — Merge into OpenScreen++> Catalog of the axcut codebase at `/home/etienne/repos/axcut/` (in WSL Ubuntu) as it stands for the AI-edition merge. Path notation is `path:line` relative to the axcut repo root.++---++## 1. Schema (`@axcut/schema` package)++`packages/axcut-schema/src/index.ts` (402 lines) is the SSOT Zod schema for the project. Re-exports `axcutSchemaVersion = 2`.++### Core types (every Zod schema → inferred type)+| Schema | Fields | Notes |+|---|---|---|+| `wordSchema` | `id`, `assetId?`, `segmentId`, `startSec`, `endSec`, `text` | Whisper tokens; `assetId` is optional for back-compat with single-asset transcripts. |+| `transcriptSegmentSchema` | `id`, `assetId?`, `kind: 'speech'\|'silence'`, `startSec`, `endSec`, `text`, `wordIds[]` | `kind = 'silence'` is rendered separately by the editor. |+| `transcriptSchema` | `assetId`, `language`, `sourceDslPath?`, `sourceJsonPath?`, `segments[]`, `words[]` | One transcript per asset. |+| `assetSchema` | `id`, `kind: 'video'`, `label`, `originalPath`, `proxyPath?`, `waveformPath?`, `durationSec?`, `video?`, `audio?` | `video`/`audio` populated by Python `probe_media`. |+| `clipSchema` | `id`, `assetId`, `sourceStartSec`, `sourceEndSec`, `timelineStartSec`, `timelineEndSec`, `wordRefs[]`, `origin: 'system'\|'agent'\|'user'`, `reason` | The mounted unit on the timeline. |+| `gapSchema` | `id`, `timelineStartSec`, `timelineEndSec`, `reason` | Placeholder gaps between clips (rarely used). |+| `rangeSchema` | `startSec`, `endSec`, `reason` | Shared shape for `muteRanges`, `speedRanges`, `captionRanges`. |+| `skipRangeSchema` | `id`, `assetId`, `startSec`, `endSec`, `reason`, `origin` | Skips reference source-time on the **asset**, not the timeline. |+| `timelineSchema` | `clips[]`, `gaps[]`, `skipRanges[]`, `muteRanges[]`, `speedRanges[]`, `captionRanges[]` | All ranges in source-time coordinates. |+| `pendingQuestionSchema` | `id`, `question`, `reason`, `startWordId?`, `endWordId?` | Agent asks the user. |+| `suggestionSchema` | `id`, `status: 'pending'\|'approved'\|'rejected'`, `category`, `suggestion`, `reason`, `startWordId?`, `endWordId?`, `startSec?`, `endSec?`, `proposedOperation?` | The agent's pending edits. |+| `agentStateSchema` | `baseIntent?`, `pendingQuestions[]`, `suggestions[]`, `lastAppliedOperations[]`, `lastReasoningSummary?` | Per-project agent memory. |+| `previewSchema` | `strategy: 'seek'\|'mse-proxy'`, `revision: number` | `revision` increments on any change that affects playback. |+| `exportStateSchema` | `preset: 'preview-low'\|'final-balanced'\|'final-high'`, `lastJobId?` | |+| `timelineOperationSchema` | discriminated union of `replace_timeline`, `drop_range`, `drop_word_range`, `add_skip_range`, `update_skip_range`, `remove_skip_range`, `update_clip_range`, `duplicate_clip`, `move_clip`, `restore_full_timeline`, `insert_asset_clip` | Every edit the UI or agent can apply. |+| `revisionSchema` | `id`, `createdAt`, `author`, `summary`, `operations[]` | History entry. |+| `documentSchema` | wraps `project`, `assets[]`, `transcript` (merged primary), `transcripts[]` (per-asset), `timeline`, `agent`, `preview`, `export`, `history` | Full document. |++### Helpers in the schema package+- `createEmptyDocument(input)` — fresh empty doc with empty arrays.+- `ensureDocument(value)` — Zod-parse an unknown, throw on mismatch.+- `normalizeSkipRanges(skipRanges[])` — merge overlapping/adjacent skips, sort, return dedup'd list. Used everywhere.+- `applySkipRangesToClips(clips[], skipRanges[])` — materialize the timeline by walking each clip, splitting on overlapping skip ranges, retiming into a flat clip array (the "kept" segments). **This is the key function the exporter must call.**++### Schema migration story+- Only v1 → v2 is documented in code. There are no migration functions — `ensureDocument` just parses whatever version it finds.+- **For OpenScreen, this is a problem.** Phase 0 must add a real `migrateDocument(value, fromVersion)` function so legacy `EditorProjectData` (v2) and axcut `AxcutDocument` (also v2, different shape) both round-trip cleanly into the new v3 `AxcutDocument`.++### Things missing from axcut's schema (OpenScreen has them)+- `annotations[]` (text/image/figure/blur overlay regions) — `types.ts:287`.+- `zoomRegions[]` (zoom regions with depth, focus, rotation preset) — `types.ts:71`.+- `legacyEditor` envelope (wallpaper, aspect ratio, padding, crop, cursor, webcam, etc.) — `projectPersistence.ts:67`.+- Cursor telemetry data (raw points) — `types.ts:178`.+- Speed regions (`SpeedRegion[]`) — already in axcut's schema (`rangeSchema`-shaped `speedRanges`).+- Trim regions — **NOT in axcut's schema** (replaced by `skipRanges`).++---++## 2. Server services (`apps/server/src/services/`)++### `document-service.ts` — DocumentService+- Owns the on-disk `.axcut` document; `readDocument / writeDocument / mutateDocument / appendRevision`.+- `addAsset(projectId, input)` resolves `path` to absolute, validates extension set `{mp4, mov, m4v, webm, mkv}`, creates `AxcutAsset`, sets `project.primaryAssetId` if first asset.+- `updateTranscript` normalizes + re-sorts transcripts per asset, **merges to a single primary transcript** (used by VirtualPreview which only consumes one), calls `retimeClips`.+- `applyOperation` (the workhorse) — applies any `AxcutOperation`, appends a `revision`, returns `{ document, revisionId }`.+- `replaceTimeline(projectId, intervals[], summary, author)` — full structural rebuild of clips from normalized intervals (used by `replace_timeline` op and the manual "Restore" button).+- `setSuggestions` — replaces `agent.suggestions[]`.+- `updateExportState` — toggles preset/lastJobId.++### `agent-session-service.ts` — AgentSessionService+- Per-session records persisted under `.axcut-data/deepagent-sessions/records/` (one JSON file per session).+- Per-session checkpoints persisted under `.axcut-data/deepagent-sessions/checkpoints/` (langgraph checkpoint tuples).+- `PersistentFileCheckpointSaver` (custom) implements `BaseCheckpointSaver` against `langgraph-checkpoint`. Uses `WRITES_IDX_MAP` from `@langchain/langgraph-checkpoint`.+- `CheckpointReason` = `'manual' | 'auto' | 'before-message' | 'after-run' | 'before-compaction' | 'after-compaction'`.+- `SessionCheckpointPayload { version: 1, projectId, document, messages, compactedContext? }` is the snapshot of full state at checkpoint time. **This is the rollback unit.**+- `restoreCheckpoint(sessionId, checkpointId)` returns `{ checkpoint, payload?, langGraphRestored, warnings }`. Two restore paths: langgraph state (for runtime thread) + document state (for user-visible timeline).+- `compactedContext` is the post-compaction summary that the agent sees instead of the raw message history.++### `axcut-deep-agent.ts` — AxcutDeepAgentService+- Wraps `createDeepAgent(...)` from `deepagents` (LangGraph-based) with six tools:+ - `transcriptSearch` (query, limit)+ - `suggestCuts` (kind: filler|pause, minDurationSec, limit)+ - `applyTimelineOperation` — dispatches to all 11 timeline ops+ - `approveSuggestion` / `rejectSuggestion`+- `AXCUT_DEEP_AGENT_PROMPT` is hardcoded — system prompt defining Axcut's editorial rules (prefer skip ops for cleanup, structural ops for montage, never invent timestamps).+- Streaming via `agent.streamEvents()` parses `on_chat_model_start|stream|end`, `on_tool_start|end|error`, `on_chain_end` to emit `agent.operation`, `agent.message.delta` events on the `EventBus`.+- Per-session langgraph thread keyed by `sessions.buildSessionConfig(sessionId)`.++### `axcut-agent-runtime.ts` — AxcutAgentRuntime+- Thin façade over `AxcutDeepAgentService`. Exposes `getOrCreateSession`, `createSession`, `getSession`, `listSessions`, `renameSession`, `deleteSession`, `listCheckpoints`, `saveCheckpoint`, `restoreCheckpoint`, `runTurn`.+- `runTurn(projectId, sessionId, userMessage, history)` — runs the agent and returns `{ text, state, document }`.+- Checkpoint orchestration: every user message creates a `before-message` checkpoint; every agent response creates an `after-run` checkpoint.+- **Critical**: `restoreCheckpoint` rewrites the `AxcutDocument` AND truncates messages AND resets the langgraph thread.++### `chat-service.ts` — ChatService+- Single public method `run(projectId, input)`: validates `ChatInput`, gets/creates session, saves `before-message` checkpoint, inserts user message, calls runtime, inserts assistant message, saves `after-run` checkpoint, emits events.+- Returns `{ assistantMessage, document, sessionId }`.++### `database.ts` — DatabaseService (better-sqlite3)+- File: `.axcut-data/metadata.sqlite` (WAL mode).+- Tables: `projects (id, title, document_path, created_at, updated_at)`, `messages (id, project_id, session_id, role, content, revision_id, checkpoint_id, created_at)`, `jobs (id, project_id, kind, status, progress, message, payload_json, result_json, created_at, updated_at)`.+- Indexes: `idx_messages_project_created`, `idx_messages_project_session_created`, `idx_jobs_project_updated`.+- Schema migrations inline (no migration framework). Notable: `messages.session_id` and `messages.checkpoint_id` were added later via `ALTER TABLE`.++### `event-bus.ts` — EventBus+- Simple per-project Node `EventEmitter`. Topics keyed by `project:<projectId>`.+- Events emitted by axcut: `agent.message.user`, `agent.message.assistant`, `agent.message.delta`, `agent.operation`, `agent.checkpoint.saved`, `agent.checkpoint.restored`, `project.revision.created`, `project.asset.updated`, `preview.ready`, `job.queued`, `job.completed`, `job.failed`.+- Renderer subscribes via Fastify SSE endpoint (`/api/projects/:id/events`).+- **For OpenScreen**: replace the EventEmitter fan-out with `webContents.send` so each renderer window receives events. Reuse the existing `NativeBridgeEventName` (`src/native/contracts.ts:230-238`) as the event-channel union.++### `job-service.ts` — JobService+- Long-running async operations queue: `enqueueAssetIngest`, `enqueueTranscription`, `enqueueExport`.+- For asset ingest: probe → proxy → optional transcribe. Each step emits `project.asset.updated`, `preview.ready`, etc.+- Uses `queueMicrotask` to schedule work — no real worker pool. **Edge case**: if the user closes the editor mid-ingest, the job keeps running. axcut handles this implicitly because the Fastify process stays alive; OpenScreen needs explicit "cancel on editor close" logic.++### `llm-config-service.ts` — LlmConfigService+- Wraps `LlmConfigStore` (config on disk + credentials).+- `getSnapshot()` returns `ready, source, stored, effective, providers, connectedProviders, availableProviders` — the shape `ProviderSettingsDialog` consumes.+- Handles `connectProvider`, `selectModel`, OAuth device-flow for ChatGPT (`beginCodexDeviceAuth`, `completeCodexDeviceAuth`), GitHub Copilot (`fetchGitHubCopilotModels`).++### `python-worker.ts` — PythonWorker+- Spawns the Python CLI as a child process: `python -m axcut_worker.cli <args>`.+- Args: `probe`, `proxy`, `transcribe`, `export`, `export-sequence`.+- JSON in, JSON out (`{ ok, data }` or stderr).+- `PYTHONPATH` set to `py/axcut-core/src:py/axcut-worker/src`.+- Uses `pythonExecutable = path.join(repoRoot, '.venv', 'bin', 'python')` — assumes local venv. **Drop with the Python worker in the merge.**++### `worktree-service.ts` — WorktreeService+- Spawns `git worktree add` / `git worktree list --porcelain` / `git worktree remove`.+- Stores worktrees under `.axcut-data/worktrees/<branch>`.+- **Why it exists**: axcut's earlier design (now superseded) let the agent edit *project source files* in an isolated git worktree. The current UX still exposes a "Worktrees" dialog but most users don't use it. **Drop entirely in OpenScreen merge** — video projects don't need git isolation.++---++## 3. Server libs (`apps/server/src/lib/`)++### `timeline.ts` (~200 lines)+- `normalizeIntervals(durationSec, intervals)` — clamp + sort + merge overlapping → flat kept intervals.+- `timelineIntervals(document)` — derives current kept intervals from `document.timeline.clips` filtered to primary asset.+- `buildTimelineFromIntervals(assetId, intervals, { origin, reason, transcript })` — creates clips with retimed `timelineStartSec/EndSec` and collected `wordRefs`.+- `retimeClips(clips, transcript)` — re-flows `timelineStartSec/EndSec` and regenerates `clip_N` ids for new clips.+- `subtractInterval(intervals, cut)` — used by `editable-transcript.ts` LCS deletion.+- `resolveWordRange(document, startWordId, endWordId)` — throws if cross-asset ambiguous; prefers mounted clips over all transcripts.+- `applySourceCutToAsset(clips, assetId, cut, origin, reason)` — internal split helper.+- `applyTimelineOperation(document, operation, origin)` — the big dispatcher (every timeline op).++### `document-operations.ts`+- `applyDocumentOperation(document, operation, origin)` — top-level dispatch (timeline ops + approve/reject_suggestion).+- `replaceSuggestions(document, suggestions, lastReasoningSummary)`.+- `clearExecutedSuggestions(suggestions, operation)` — when an op matches a pending suggestion, mark it `approved`.+- **Uses `JSON.stringify` to compare operations** (`sameOperation`). Fast and works for primitive ops; risk if any op carries non-JSON fields.++### `document-history.ts`+- `appendRevision(document, input, createRevisionId, createdAt?)` — appends a `revision` to `document.history.revisions[]`.+- `refreshProjectUpdatedAt(document, updatedAt?)` — bumps `project.updatedAt`.++### `structured-agent.ts`+- `searchTranscript(document, query, limit)` — tokenized BM25-lite scoring across all transcripts.+- `buildFillerSuggestions(document, minDurationSec, limit)` — finds filler-word runs ("uh", "um", etc.) and emits `AxcutSuggestion[]` with proposed `add_skip_range` ops.+- `buildPauseSuggestions(document, minDurationSec, limit)` — finds long silence pauses similarly.+- Filler lexicon hardcoded at `:11-21`.+- These run **without LLM** — they're cheap pre-LLM suggestions.++### `ids.ts`+- `createId(prefix)` — `prefix_<random>` via `crypto.randomUUID()`.++### `paths.ts` (66 lines)+- `repoRoot`, `dataRoot = '.axcut-data'`, `runtimeRoot`, `projectsRoot`, `agentSessionsRoot`, `llmConfigPath`, `llmCredentialsPath`, `accountAuthRoot`, `databasePath`, `serverRuntimePath`.+- `projectRoot(projectId)`, `projectArtifactsRoot(projectId)`, `projectDocumentPath(projectId)` = `projectRoot/projectId/project.axcut`.+- **No `app.getPath('userData')`** — axcut lives in the repo. **For OpenScreen, swap to `app.getPath('userData')`** (the standard Electron user-data path).++### `media-stream.ts`+- Helpers for video source URL construction (asset-id → file:// URL).++### `utils.ts`+- Generic helpers (`safeStringify`, `truncate`).++---++## 4. LLM provider layer (`apps/server/src/llm/`)++### `provider-registry.ts` — `PROVIDER_DEFINITIONS`+10 providers with full metadata:+| ID | Label | Default model | Auth | Reasoning effort |+|---|---|---|---|---|+| `anthropic` | Claude API | `claude-haiku-4-5` | API key | Yes |+| `openai` | OpenAI API | `gpt-4o` | API key | Yes (gpt-5 family) |+| `google` | Gemini API | `gemini-3-flash-preview` | API key | Yes (gemini-thinking) |+| `mistral` | Mistral API | (uses model name) | API key | No |+| `openrouter` | OpenRouter | (configurable) | API key | Yes |+| `openai-oauth` | ChatGPT (OAuth) | `gpt-5.4` | Device-flow OAuth | Yes |+| `copilot-proxy` | GitHub Copilot | `gpt-4.1` | GitHub PAT | Yes |+| `minimax` | MiniMax API | `MiniMax-M2.7` | API key | No (per axcut) |+| `minimax-token-plan` | MiniMax token-plan | (configurable) | API key | No |+| `openai-compatible` | OpenAI-compatible endpoint | (configurable) | Optional | (model-dep) |++Each definition carries `envKeys[]` (env vars to auto-pick the API key).++### `create-chat-model.ts`+- Returns a LangChain `BaseChatModel` based on `LlmConfigStore.getRuntimeConfig()`.+- Routes by `provider`: `ChatAnthropic`, `ChatMistralAI`, `ChatOpenAI`, or `createLocalProviderLangChainModel` for the four OAuth/special providers.+- For `openrouter/google/openai-compatible` it picks the right `baseURL`.++### `create-langchain-model.ts` — `createLocalProviderLangChainModel`+- `openai-oauth` → `ChatCodexOAuth` (custom subclass of `BaseChatModel`).+- `copilot-proxy` → `ChatOpenAI` with token exchanged from GitHub PAT (`resolveCopilotApiToken`), `defaultHeaders` spoofing VS Code Copilot Chat UA. Custom `CopilotCompletionsModel` extracts `reasoning_text` deltas.+- `minimax` / `minimax-token-plan` → also routes through `ChatOpenAI` against MiniMax's OpenAI-compatible endpoint.++### `openai-account.ts` — ChatGPT OAuth+- `OPENAI_ACCOUNT_BASE_URL = 'https://chatgpt.com/backend-api'`.+- `CODEX_ORIGINATOR = 'codex_cli_rs'` — device-flow origin (matches Codex CLI so backend attributes usage).+- `CODEX_RESPONSES_PATH = '/codex/responses'`, `CODEX_MODELS_PATH = '/codex/models'`.+- `CODEX_REASONING_EFFORT_OPTIONS = ['none','minimal','low','medium','high','xhigh']`.+- `ModelDiscoveryCache` — ETag-cached `/codex/models` response.+- Per-account JSON file under `accountAuthRoot/<id>.json` (refresh tokens).++### `copilot-account.ts`+- Token exchange: `POST https://api.github.com/copilot_internal/v2/token` with `Authorization: Bearer <github_pat>`.+- Caches resolved Copilot token + base URL to `accountAuthRoot/copilot-token.json` with `expiresAt`.+- Reads token, derives base URL via base64-decoding `proxy-ep=` claim in JWT.++### `chat-codex-oauth.ts`+- `ChatCodexOAuth extends BaseChatModel` — implements LangChain v1 chat-model contract.+- Per-session state: `previousPrompt`, `previousResponseId` — supports response-id chaining for efficient multi-turn.+- `CODEX_DEFAULT_INSTRUCTIONS` — system prompt prefix sent on the first turn (Codex identity).++### `tool-schema.ts`+- `normalizeFunctionToolParametersSchema` — turns Zod schemas into OpenAI function-calling JSON schema.++### `agent-provider-capabilities.ts`+- `getReasoningCapability(provider, model)` returns `{ supported, efforts[], defaultEffort?, strategy? }`.+- Strategies: `'custom-openai-account'`, `'openai-responses'`, `'anthropic-thinking'`, `'openrouter-reasoning'`, `'google-thinking'`.+- `buildLangChainReasoningOptions(provider, model, effort)` — translates effort into LangChain options (`{ reasoning, thinking, outputConfig, modelKwargs, useResponsesApi }`).+- `shouldDisableModelStreamingForToolCalling(provider, model)` — for tool-calling models where streaming tool deltas break.++### `llm-config-store.ts` — LlmConfigStore+- File-backed JSON config: `.axcut-data/llm-config.json`.+- API keys stored separately: `.axcut-data/llm-credentials.json` (encrypted? **no — plain JSON**).+- Environment-variable precedence: if `envKeys[i]` is set in `process.env`, it wins over the stored key.+- `getApiKey(provider)` returns the active key (env or stored).++### `utils.ts`+- `withRetry(fn, config)`, `timeoutSignal(ms)`, `CODEX_UPSTREAM_TIMEOUT_MS`, `RETRY_CONFIG`.++---++## 5. Python worker (`py/`)++### `pyproject.toml`+- Python ≥ 3.12 required.+- Dependencies: `faster-whisper>=1.1.1,<2.0.0`, `huggingface-hub>=1.0.0,<2.0.0`, `pydantic>=2.11.0,<3.0.0`, `python-dotenv>=1.1.1,<2.0.0`.++### `axcut_worker/cli.py`+Five subcommands:+- `probe --video <path>` → `{durationSec, video: {codec, width, height, fps}, audio: {codec, sampleRate, channels}}` via `ffprobe`.+- `proxy --video <path> --output <path>` → runs ffmpeg to produce a low-res proxy MP4.+- `transcribe --video <path> --asset-id <id> --dsl-output <dsl> --json-output <json> --model <name> --language <code?>` → runs `faster-whisper` with word timestamps, writes both a custom DSL text format and a JSON payload.+- `export --video <path> --intervals <json> --output <path>` → cuts a single source by intervals.+- `export-sequence --clips <json> --output <path>` → concatenates multiple clips into one MP4.++### `axcut_core/transcribe.py`+- Models: `MODEL_REPOS = { tiny, base, small, medium, large-v3 }` from `Systran/faster-whisper-*` on Hugging Face.+- `transcribe_video(video_path, *, model_name, device, compute_type, language)` → `Transcript`.+- `beam_size=5`, `word_timestamps=True`, `vad_filter=False`.+- Returns pydantic `Transcript` (see models.py).++### `axcut_core/models.py`+Pydantic models mirror the Zod schema but in Python:+- `WordToken (id, segment_id, start, end, text)`+- `Segment (id, kind, start, end, text, words[])`+- `Transcript (source_video, duration, language, kind, edit_prompt, segments[])`+- `DeleteRange (start_word_id, end_word_id, reason)`+- `FollowUpQuestion`, `EditSuggestion`, `EditPlan`+- `KeepInterval (start, end)`++### `axcut_core/dsl.py`+- `write_transcript(path, transcript)` writes a custom plain-text format `AXCUT_TRANSCRIPT v1` with `META`, `SEGMENT`, `WORD`, `ENDSEGMENT`, `SILENCE` lines.+- `read_transcript(path)` round-trips. **This format is the "ingest/export artifact" the README mentions.** Not used by the runtime — only by Python.++### `axcut_core/render.py`+- `create_proxy_video(video_path, output_path)` — ffmpeg command for proxy.+- `render_cut_video(video_path, output_path, keep_intervals)` — ffmpeg concat with negative filter expressions.+- `render_clip_sequence(clips_path, output_path)` — multi-clip sequence.+- `compute_keep_intervals_from_cleaned(source, cleaned)` — derives intervals from a "cleaned" transcript.+- **No high-level effects** (zoom, annotations, blur, cursor). Pure ffmpeg cut/concat. Visual polish is left to a future iteration.++### `axcut_worker/__init__.py` — empty.++---++## 6. Web app (`apps/web/src/`)++### `App.tsx` (top-level — ~1500 lines)+Layout (top-down, all on a single page):+1. **Header** — title, project picker, history dialog toggle, worktree dialog toggle, provider settings toggle, load video dialog.+2. **Status chips** — model status, export status with download button, transcription jobs.+3. **Left sidebar** — ProjectPanel: compositions (recent projects) + files (asset list with drag-source handles).+4. **Center** — VirtualPreview + TranscriptEditor stacked.+5. **Right sidebar** — CurrentTranscriptView (chat panel + suggestions).+6. **Bottom** — TimelinePane with skip ranges, drag-drop assets, clip editing, navigation.+- State from `@tanstack/react-query`: `useQuery(['project', projectId])`, `useMutation` for all ops.+- Local state: `activeSessionId`, `selectedProjectId`, `transcriptLanguage`, `currentTimeSec`, `transcriptModalAssetId`, `sourcePreviewTarget`.+- ~20 modal/dialog components mounted conditionally (history, worktree, provider settings, load video, insert asset, transcript, etc.).++### `components/TimelinePane.tsx` (~1500 lines — longest file in the repo)+The full timeline component. Key features:+- **Clips**: drawn as colored blocks per source, multi-asset layout.+- **Skip ranges**: rendered as gaps between kept segments, with left+right resize handles.+- **Resize modes**:+ - Always-on: skip-handle resize.+ - Pencil-button mode: clip-handle resize (changes `sourceStartSec`/`sourceEndSec`).+- **Pan/zoom** via `NavigatorDragState` (mini-map at top).+- **Asset drop** via HTML5 DnD — sets `pendingAssetInsert` for the InsertAssetDialog.+- **Clip reorder** via `ClipReorderState` (ghost + insert marker).+- **Clip duplicate** via Ctrl+C/V (intercepted at `window.addEventListener('keydown')`).+- **Skip pointer-drag** via `startGlobalPointerDrag` (in `lib/pointer-drag.ts`).+- Calls `onAddSkipRange / onUpdateSkipRange / onRemoveSkipRange / onUpdateClipRange / onDuplicateClip / onMoveClip / onAssetDrop` props.++### `components/VirtualPreview.tsx`+- Two `<video>` elements (`videoARef`, `videoBRef`), crossfade at clip boundary.+- `locateVirtualPosition(clips, virtualTimeSec)` returns `{ clip, clipIndex, virtualTimeSec, sourceTimeSec }`.+- Layer A and layer B swap on clip transitions: when crossing a clip boundary, seek the inactive layer to the next clip's source time, then swap.+- Pending seek queue (`pendingSourceSeekRef`) to avoid race between user seek + clip-boundary seek.+- Preloads next clip's source when within `CLIP_END_LOOKAHEAD_SEC = 0.04` of the end.+- Subscribes to `seekTarget` and `sourcePreviewTarget` props.++### `components/TranscriptEditor.tsx`+- Click a word, shift-click another word → range → "Cut" → `dropWordRange` op.+- "Restore" button → `restore_full_timeline` op.+- Word styling: kept = default, in-skip = red.++### `components/CurrentTranscriptView.tsx`+- Chat panel + suggestions list.+- Renders agent's "operations" (thinking, tool runs) as they stream.+- Markdown rendering for assistant messages (presumably `react-markdown`).++### `components/SuggestionList.tsx`+- Pending suggestions with proposed operation preview; Approve / Reject buttons.++### `components/LlmSetupPanel.tsx`+- The "first-run" provider setup (smaller version of `ProviderSettingsDialog`).++### `components/ProviderSettingsDialog.tsx` (1300+ lines — huge)+- Models screen (per-provider model picker, search, refresh).+- Providers screen (connected provider list).+- Settings screen (edit / add providers).+- Provider-create-select screen (choose which provider to add).+- Provider-form screen (per-provider credentials: API key, base URL, reasoning effort, OAuth device challenge).+- Device challenge UI for OAuth flows (verification URL, user code, copy button).++### Other modals+- `LoadVideoDialog` — recent projects + new-project button.+- `InsertAssetDialog` — when dropping a source on the timeline.+- `TranscriptDialog` — view raw transcript for an asset, regenerate in different language.+- `SessionHistoryDialog` — list, rename, delete sessions.+- `WorktreeDialog` — list/create/remove worktrees (drop in OpenScreen merge).++### `lib/virtual-preview.ts`+Pure-function library used by both React components and server-side timeline math:+- `totalVirtualDuration(clips)` — `clips.at(-1)?.timelineEndSec ?? 0`.+- `clampVirtualTime(clips, value)`.+- `locateVirtualPosition(clips, virtualTimeSec)` — binary search.+- `locateSourcePosition(clips, sourceTimeSec, assetId?, epsilon?)`.+- `resolvePlaybackPosition(clips, currentClip, currentSourceTimeSec, playState)` — `{ inside | next | ended | empty }`.+- `keptWordIdSet(clips)` — for highlighting kept vs. skipped words.+- `selectWordRange(words[], anchorWordId, focusWordId)` — transcript range selection.++### `lib/pointer-drag.ts`+- `startGlobalPointerDrag(target, event, onDelta, onEnd?)` — captures pointer and dispatches `onDelta(dx, dy, event)`.++### `lib/editable-transcript.ts`+- LCS-based deletion algorithm: `deriveEditableTranscriptUpdate(document, editedText)` → returns `{ intervals, deletedWordIds }`.+- Tokenizes by line (`# Clip X` prefixes excluded) → split by whitespace → normalize (`toLocaleLowerCase`, strip non-letter/non-digit punctuation).+- Returns intervals after subtracting the deleted-word ranges.++### `lib/optimistic-timeline.ts`+- Optimistic UI updates for timeline ops.++### `lib/live-run.ts`+- Live-run state for an in-progress agent run (tool-call status, partial deltas).++### Tests+- `lib/{editable-transcript,virtual-preview,optimistic-timeline,live-run}.test.ts` (Vitest).+- `components/{CurrentTranscriptView,TranscriptEditor}.test.ts` (testing-library).+- **No Playwright / browser tests** — everything is jsdom or Node.++---++## 7. Worktree service++Already covered in §2. `WorktreeService` exists for axcut's "agent edits source files in an isolated git worktree" feature, which is **not relevant to a video-editing project**. Drop entirely.++---++## 8. Tests in axcut++- `apps/server/src/services/{document-operations,document-history,agent-session-service,axcut-deep-agent,timeline,chat-service}.test.ts`.+- `apps/server/src/lib/{timeline,document-operations,structured-agent}.test.ts`.+- `apps/server/src/llm/{create-chat-model,llm-config-store}.test.ts`.+- `apps/web/src/components/{CurrentTranscriptView,TranscriptEditor}.test.tsx` + `lib/{editable-transcript,virtual-preview,optimistic-timeline,live-run}.test.ts`.+- `packages/axcut-schema/src/index.test.ts`.+- **No Playwright / browser tests**.+- Total: ~15 test files.++---++## 9. Documentation in axcut++- `README.md` (6759 bytes) — quickstart, architecture, env vars, commands.+- `clip-skip.md` (9597 bytes) — **the conceptual spec** for the clips/skip model. Read when implementing Phase 1.+- `Dockerfile`, `docker-compose.yml`, `.env.example`, `pyproject.toml` — already covered.+- No `AGENTS.md`, no `ROADMAP.md`, no `docs/` folder.++---++## 10. Anything else++### `Dockerfile`, `docker-compose.yml`+- Image installs Python 3.12, Node, ffmpeg, runs `npm install` + `uv pip install -e .`.+- Volumes: `axcut-data` (persisted), `axcut-credentials`, `axcut-cache` (Whisper models).+- Mounts repo at `/workspace` (read-only) so recordings can be imported by absolute path inside the container.+- **For OpenScreen: completely irrelevant** — Electron app, no container.++### `.env.example`+- Common env keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `OPENROUTER_API_KEY`, `OPENAI_COMPATIBLE_API_KEY`, `AXCUT_MODEL_CACHE`, server ports.++### `scripts/`+- `clean-processes.mjs` — kills leftover dev servers.+- `generate-assets.mjs` — generates `assets/generated/logo_full_h_readme.png` (README logo).++### `.kilo/`+- Empty or near-empty. Kilo is an AI-agent IDE config; not relevant.++### Settings & state shape (`LlmConfigSnapshot`)+```ts+{+ ready: boolean,+ source: { homeDir, configPath, credentialsPath, accountAuthRoot },+ stored: { provider, model, baseUrl, reasoningEffort, apiKeyStored },+ effective: { provider, providerLabel, model, baseUrl, reasoningEffort,+ supportsReasoningEffort, apiKeyAvailable, apiKeySource },+ providers: ProviderState[],+ connectedProviders: ProviderState[],+ availableProviders: ProviderState[],+}+```++### `apps/server/src/app.ts`+Fastify server with routes:+- `GET /api/projects` (list), `POST /api/projects` (create).+- `GET /api/projects/:id` (snapshot: document + messages + jobs).+- `POST /api/projects/:id/operations` (apply op).+- `POST /api/projects/:id/timeline/replace` (full replace).+- `POST /api/projects/:id/chat` (run chat turn).+- `POST /api/projects/:id/assets` (add asset by path).+- `GET /api/projects/:id/transcript/:assetId` (raw transcript artifact).+- `POST /api/projects/:id/assets/:assetId/transcribe` (transcription job).+- `POST /api/projects/:id/sessions` (create), `GET` (list), `PATCH` (rename), `DELETE`.+- `POST /api/projects/:id/sessions/:sessionId/checkpoints` (save), `GET` (list), `POST :restore`.+- `POST /api/projects/:id/worktrees` (create), `GET` (list), `POST :select`, `DELETE`.+- `GET /api/llm/providers` (snapshot), `POST /api/llm/providers/:id/connect`, `POST :device/complete`, `POST :select`, `DELETE`, `GET :/models`.+- `GET /api/projects/:id/events` (SSE).+- `POST /api/exports` (enqueue export job).++**For OpenScreen**: replace all of this with `native-bridge:invoke` handlers in the main process. The SSE pub-sub becomes a `webContents.send` event stream. Each axcut service becomes a TypeScript module in `electron/ai-edition/`.\ No newline at end of filediff --git a/docs/architecture/openscreen-inventory.md b/docs/architecture/openscreen-inventory.mdnew file mode 100644index 000000000..d9aacc6ec--- /dev/null+++ b/docs/architecture/openscreen-inventory.md@@ -0,0 +1,707 @@+# OpenScreen Inventory — Merge with Axcut++> Catalog of the OpenScreen codebase at `G:\repos\openscreen\.worktrees\wt-9ce78f24\` as it stands for the AI-edition merge. Path notation is `path:line` relative to the repo root. All file paths are absolute under that worktree.++---++## 1. Recorder pipeline (full lifecycle)++### Window graph+There is **one renderer entry point** (`src/App.tsx:11`) that lazy-loads the window component by `?windowType=…` query param. Four window types are produced:++- `hud-overlay` → `LaunchWindow.tsx:92` (frameless transparent HUD with the record/stop buttons). Created by `electron/windows.ts:87` `createHudOverlayWindow`.+- `source-selector` → `SourceSelector.tsx:16`. Created by `electron/windows.ts:231` `createSourceSelectorWindow`.+- `countdown-overlay` → `CountdownOverlay.tsx`. Created by `electron/windows.ts:275` `createCountdownOverlayWindow`.+- `editor` → `VideoEditor.tsx` (lazy). Created by `electron/windows.ts:168` `createEditorWindow`.++`electron/main.ts:50` sets `RECORDINGS_DIR = path.join(app.getPath("userData"), "recordings")` — this is the canonical on-disk home for media.++### LaunchWindow → SourceSelector flow+- The HUD always opens first (`electron/main.ts:588` `createWindow()` → `createHudOverlayWindow()`).+- When the user clicks the "screen / window" pick, `LaunchWindow.tsx` calls `openSourceSelectorWithPermissionRetry(...)` (defined in `src/components/launch/openSourceSelectorFlow.ts:32`), which calls `window.electronAPI.openSourceSelector()` and, on macOS, retries up to 8× while a `not-determined` Screen Recording permission resolves.+- The main process opens `createSourceSelectorWindow()` (`electron/ipc/handlers.ts:1423`) and the renderer renders `SourceSelector.tsx`. `getSources` (`electron/ipc/handlers.ts:1307`) drives the picker via `desktopCapturer.getSources(...)`. Picking calls `selectSource` IPC (`electron/ipc/handlers.ts:1319`) which closes the selector.++### Source selected → record+- `useScreenRecorder.ts:1527` `toggleRecording()` calls `startRecordCountdown()` (`useScreenRecorder.ts:1040`) which opens the `CountdownOverlay` (`useScreenRecorder.ts:1090`) for a 3-2-1, then routes to one of three branches:+ - Windows + native helper available → `startNativeWindowsRecordingIfAvailable` (`useScreenRecorder.ts:781`).+ - macOS + native helper available → `startNativeMacRecording` (`useScreenRecorder.ts:912`, payload at `:963` with `schemaVersion: 1`).+ - Otherwise → browser `getDisplayMedia` + `MediaRecorder` for screen and webcam (`useScreenRecorder.ts:1163+`).+- The recorder uses a wrapper around `MediaRecorder` defined at `src/hooks/recorderHandle.ts:31` `createRecorderHandle`. With `fileName`, MediaRecorder chunks are streamed to disk via IPC (see §5) so a long recording never buffers the whole video in the renderer.+- Pause/resume restart splits (`useScreenRecorder.ts:1541` `restartRecording`) maintain `accumulatedDurationMs` and `segmentStartedAt` refs (`useScreenRecorder.ts` lines ~22-31) so total duration survives pause gaps.++### Stop → save → switch to editor+- `useScreenRecorder.ts:621` `stopRecording` (held in a ref) branches by transport:+ - **Browser / streaming finalize** — `finalizeRecording` (`:337`): calls `fixWebmDuration` (`@fix-webm-duration/fix`), then `window.electronAPI.storeRecordedSession(...)` (`:369`) with `{ screen: { videoData, fileName }, webcam?: ..., createdAt: recordingId, cursorCaptureMode, durationMs }`. On success calls `setCurrentRecordingSession` (`:391`) then `switchToEditor()` (`:396`).+ - **Native Windows** — `finalizeNativeWindowsRecording` (`:422`): calls `stopNativeWindowsRecording(discard)` and may then call `storeRecordedSession` to merge the webcam blob, then `setCurrentRecordingSession` and `switchToEditor()` (`:503`).+ - **Native macOS** — `finalizeNativeMacRecording` (`:522`): calls `stopNativeMacRecording(discard)` then `attachNativeMacWebcamRecording` (`:582`) to bind the webcam into the session, then `setCurrentRecordingSession` and `switchToEditor()` (`:603`).+- The IPC handler `store-recorded-session` lives at `electron/ipc/handlers.ts:2207` → `storeRecordedSessionFiles` (`:2220`):+ - Resolves final paths via `resolveRecordingOutputPath` (`:270`) → `path.join(RECORDINGS_DIR, parsedPath.base)`.+ - For each track it calls `finalizeRecordingFile` which either finalizes the open stream or writes the buffer (see §5).+ - Patches the WebM `Duration` header on disk when `durationMs` is finite (`:2251-2257`, `electron/recording/webm-duration.ts`).+ - Builds `RecordingSession` (`{ screenVideoPath, webcamVideoPath?, createdAt, cursorCaptureMode? }`) and stores it via `setCurrentRecordingSessionState` (`:1183`).+ - Writes a JSON manifest `<screenFileName>.session.json` next to the WebM (`:2273-2277`).+ - Calls `writePendingCursorTelemetry` (`:2271`) to persist any pending cursor telemetry.+- `setCurrentRecordingSession` and `setCurrentVideoPath` are also exposed individually (`electron/ipc/handlers.ts:2784`, `:2780`).++### What does the editor do with this state?+- On open, `VideoEditor.tsx:540` `loadInitialData` first tries `nativeBridgeClient.project.loadCurrentProjectFile()` (loads the `.openscreen` project file from its last-known path), then falls back to `window.electronAPI.getCurrentRecordingSession()` (`:554`), then `nativeBridgeClient.project.getCurrentVideoPath()` (`:582`). The three are ordered: explicit saved project → just-recorded session → just-recorded single video.+- The recorded files live at `RECORDINGS_DIR/recording-<timestamp>[ -webcam].{webm,mp4}` depending on platform (`electron/ipc/handlers.ts:49` `RECORDING_FILE_PREFIX`, `:1572` for native Windows output naming).++### Where the recording file path lives+- After stop, the canonical paths are:+ - **Last successful recording's screen path** → `app.getPath('userData')/recordings/recording-<id>.webm` (or `.mp4` for native captures).+ - **Main-process session state** → `currentRecordingSession: RecordingSession | null` (`electron/ipc/handlers.ts:358`) and `currentVideoPath: string | null` (`:364`) and `currentProjectPath: string | null` (`:357`).+ - **Renderer "current" view** → mirror via `nativeBridgeClient.project.getCurrentContext()` (`src/native/client.ts:71`) plus the same value fetched through `window.electronAPI.getCurrentRecordingSession()` / `getCurrentVideoPath()`.++### Multiple sequential recordings — what happens today+- **They overwrite the renderer's "current" pointer**, but not the files on disk. Each `stopRecording` calls `setCurrentRecordingSession` / `setCurrentVideoPath` which replaces `currentRecordingSession` / `currentVideoPath` in main (`electron/ipc/handlers.ts:1183`, `:2780`). The editor's `loadInitialData` always reads *the last* one.+- Files keep accumulating in `RECORDINGS_DIR` because file names include a unique `recordingId` (timestamp). There is **no in-app UI to list, append, or manage multiple takes** — `electron/ipc/handlers.ts:2303` `getRecordedVideoPath` does scan the dir to find the latest, but that is only used when no session pointer exists.+- There is **no prompt** before the editor opens, and **no notion of "stay in recorder after Stop"**. Stop → save → `switchToEditor()` is the wired path (all three transports call it). `LaunchWindow.tsx:1008-1018` exposes a single "Open studio" Clapperboard button that also calls `switchToEditor()` manually.+- **Restart** (`useScreenRecorder.ts:1541`) discards the in-progress recording and starts a new one with a fresh `recordingId` — same overwrite-on-stop semantics apply.++### `recordingSession.ts` (`src/lib/recordingSession.ts`, 85 lines)+Pure type module — no runtime behavior. Defines:++- `ProjectMedia { screenVideoPath, webcamVideoPath?, cursorCaptureMode? }` (`recordingSession.ts:1`).+- `CursorCaptureMode = "editable-overlay" | "system"` (`:7`).+- `RecordingSession extends ProjectMedia { createdAt: number }` (`:9`).+- `RecordedVideoAssetInput { fileName: string, videoData: ArrayBuffer }` (`:13`).+- `StoreRecordedSessionInput` — payload from renderer for `store-recorded-session`, includes `durationMs?: number` (`:18`).+- `normalizeProjectMedia`, `normalizeCursorCaptureMode`, `normalizeRecordingSession` — tolerant guards used on every load to drop malformed fields.++### `media-stream.ts`+**There is no `media-stream.ts` file.** The closest is `src/hooks/useScreenRecorder.ts` (1686 lines) which manages screen + webcam MediaStreams; `src/hooks/recorderHandle.ts` wraps `MediaRecorder`. `src/lib/compositeLayout.ts` describes webcam layout math.++---++## 2. Exporter pipeline (full chain)++The exporter pipeline is purely in-browser / in-renderer. The main process only owns the source `MediaRecorder` / native capture and writes the resulting files to disk; once the file is on disk, the renderer reads it (`window.electronAPI.readBinaryFile` via `electron/ipc/handlers.ts:2523`) and feeds it into the exporter.++### Entry points+- `src/lib/exporter/videoExporter.ts` `VideoExporter` class (`:170`) — MP4 / H.264.+- `src/lib/exporter/gifExporter.ts` `GifExporter` class (`:117`) — GIF via `gif.js` worker.+- `src/lib/exporter/index.ts` — barrel re-exporting both.+- Called from `VideoEditor.tsx:1927` (gifExporter) and `VideoEditor.tsx:1979` (VideoExporter).++### Chain (MP4)+1. `VideoExporter.export()` → `exportWithEncoderPreference(prefer-hardware)` (`videoExporter.ts:228`):+ - Loads source metadata via `StreamingVideoDecoder.loadMetadata(videoUrl)` (`:248`).+ - Tries a **source-copy fast path** (`:684` `trySourceCopyFastPath`) — if the source is an MP4 and no trim/zoom/annotation/etc. edits are active, returns the source blob verbatim. Disabled when crop, padding, border radius, shadow, blur, motion blur, webcam overlay, or any time regions are present (`getSourceCopyFastPathBlockers`, `:126-155`).+ - Optionally loads webcam metadata (`:255`).+2. `FrameRenderer` (`frameRenderer.ts:135`) is built with `wallpaper, zoomRegions, showShadow, shadowIntensity, showBlur, motionBlurAmount, borderRadius, padding, cropRegion, cursorRecordingData, cursorScale, …, webcamSize, webcamLayoutPreset, …, annotationRegions, speedRegions, …, cursorTelemetry, cursorClickTimestamps, platform` (`:261-296`). `await renderer.initialize()` creates the Pixi.js `Application`, two canvases (`composite`, `foreground`) plus a `raster` canvas for the Linux read-back path (`:182-279`).+3. `VideoEncoder` (WebCodecs) is configured (`:521` `initializeEncoder`):+ - Codec default `avc1.640033` (`:589`), `latencyMode: "quality"`, `bitrateMode: "variable"`.+ - On Windows it tries `["prefer-software", "prefer-hardware"]`; everywhere else `["prefer-hardware", "prefer-software"]` (`:677-682`).+ - `maxEncodeQueue = 120` (or `32` for software) (`:181`, `:324-327`).+4. `VideoMuxer` (`muxer.ts:13`) wraps `mediabunny`:+ - `Mp4OutputFormat({ fastStart: "in-memory" })` (`:32`).+ - `EncodedVideoPacketSource("avc")` (`:39`).+ - Optional `EncodedAudioPacketSource("aac" | "opus")` chosen at runtime via `AudioProcessor.selectSupportedExportCodecForSource` (`:304`).+5. `streamingDecoder.decodeAll(...)` (`:365`) iterates source frames at the requested `frameRate` honoring `trimRegions` and `speedRegions`. Per frame:+ - Render to Pixi via `renderer.renderFrame(videoFrame, sourceTimestampUs, webcamFrame)` (`:389`).+ - For Linux, force a `getImageData` CPU readback (`:397-412`); otherwise `new VideoFrame(canvas, …)` (`:414`).+ - Throttle via `waitForEncoderQueueSpace` (`:30`) with a 15s stall timer.+ - `encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 })` (`:431`).+ - Webcam frames flow through `TimestampedVideoFrameQueue` (`timestampedVideoFrameQueue.ts`, 75 lines) — webcam decoder runs in parallel (`:330-363`).+6. Encoder output callback (`:528-586`) pushes each chunk into the muxer (`muxer.addVideoChunk`, `:52`) with the first chunk carrying `decoderConfig.description` / `colorSpace`.+7. After decode finishes, encoder is flushed with a 20s timeout (`:469`), then audio is processed via `AudioProcessor.process(...)` (`:497`).+8. `muxer.finalize()` → `Blob({ type: "video/mp4" })` (`:509`, `muxer.ts:72`).++### Compositor layer order (inside `FrameRenderer.renderFrame` at `frameRenderer.ts:374`)+1. Background wallpaper (`compositeCanvas`) — color / linear gradient / image, loaded in `setupBackground` (`:281-372`); blurred with `filter: blur(6px)` when `showBlur` is on (`:978-984`).+2. Pixi.js video stage with zoom camera (`cameraContainer` → `videoContainer`) — sprites the decoded `VideoFrame`, applies zoom (with spring smoothing, see `videoPlayback/zoomSpring.ts`), motion blur, blur filter, mask `roundRect` matching `compositeLayout.screenRect` (`:672-767`). When `Rotation3D` is non-identity, `threeDPass` (`threeDPass.ts`) projects the foreground canvas.+3. Webcam composite (`compositeWithShadows`, `:950`) — drawn into `foregroundCanvas` with mask shape (`rectangle`/`circle`/`square`/`rounded`), shadow from preset, mirroring, reactive scale anchored to a docked corner.+4. Native cursor overlay (`drawNativeCursor`, `:546`) — placed using `getSmoothedCursorPath` (`lib/cursor/cursorPathSmoothing.ts`) for the position and the native cursor sprite from `CursorRecordingData`; motion blur / click bounce / clip-to-bounds applied.+5. Editable cursor from cursor telemetry — same pipeline, reads `config.cursorRecordingData`.+6. Annotations — `renderAnnotations(foregroundCtx, …)` (`annotationRenderer.ts`) draws text / image / figure / blur regions (`frameRenderer.ts:462`).+7. Drop shadow — baked on the flat path (`compositeWithShadows`), re-applied after rotation on the 3D path (`:492-522`).+8. Final readback from `compositeCanvas` (`getCanvas`, `:1100`).++### Output format pipeline+- **MP4** — `mediabunny` (vendor `mediabunny: ^1.40.1`). Fast-start in-memory.+- **GIF** — `gif.js: ^0.2.0` via web worker `gif.js/dist/gif.worker.js` (`gifExporter.ts:25`). `GifExporter` (`:117`) loops `StreamingVideoDecoder.decodeAll` → `FrameRenderer.renderFrame` → `gif.addFrame(canvas, { delay, copy: true })`. GIF is the only non-medibunny exporter.++### Encoder settings+- Default codec `avc1.640033` (High Profile Level 5.1) — `videoExporter.ts:589`.+- Bitrate/width/height computed in `mp4ExportSettings.ts` `calculateMp4ExportSettings`:+ - Quality `medium` → short side 720 px → 10 Mbps (`:106`).+ - Quality `good` → short side 1080 px → 20 Mbps (`:107`).+ - Quality `source` → match source dims → 30/50/80 Mbps depending on pixel count (`:101-104`).+ - Width/height always even (`:17-23`).+- Frame rate passed in via `ExportConfig.frameRate` (set by `VideoEditor.tsx:1979` from `calculateMp4ExportSettings`).+- Aspect ratio is preserved via `calculateSourceDimensions` / `calculateDimensionsForShortSide` (`mp4ExportSettings.ts:39-95`).+- Audio: `AudioProcessor.selectSupportedExportCodecForSource(demuxer)` returns AAC by default, Opus as fallback (`audioEncoder.ts`).++### Exporter tests+- `videoExporter.test.ts` (vitest, jsdom) — unit tests around `isSourceCopyFastPathEligible` / `getSourceCopyFastPathBlockers`.+- `videoExporter.browser.test.ts` — Playwright headless; runs real `VideoExporter` on a fixture WebM.+- `frameRenderer.test.ts` — Pixi-free render logic tests.+- `mp4ExportSettings.test.ts` — bitrate / dimension math.+- `gradientParser.test.ts` — CSS gradient parser used by the wallpaper path.+- `audioEncoder.test.ts` — audio processor units.+- `streamingDecoder.test.ts` — duration validation (`validateDuration`, `shouldFailDecodeEndedEarly`).+- `timestampedVideoFrameQueue.test.ts` — webcam frame queue.+- `gifExporter.test.ts` / `gifExporter.browser.test.ts` — same split for GIF.+- E2E: `tests/e2e/gif-export.spec.ts` (158 lines) launches Electron, loads `tests/fixtures/sample.webm`, exports, and asserts file size > 0.++---++## 3. Project state (current SSOT)++### `src/components/video-editor/types.ts` (433 lines) — every type the editor reads/writes+- `WebcamLayoutPreset` re-exported from `lib/compositeLayout` (`types.ts:1-5`).+- `ZoomDepth = 1|2|3|4|5|6`, `ZoomFocusMode = "manual"|"auto"` (`:3-4`).+- `WebcamSizePreset = number` (10–50, percent of canvas ref dim).+- `WebcamMaskShape = "rectangle"|"circle"|"square"|"rounded"` (`:13`).+- `WebcamPosition { cx, cy }` normalized 0-1 (`:22`).+- `ZoomRegion { id, startMs, endMs, depth, focus: ZoomFocus, focusMode?, rotationPreset?, customScale?, source?: "auto"|"manual" }` (`:71`).+- `Rotation3D { rotationX, rotationY, rotationZ }` + presets `iso/left/right` + `computeRotation3DContainScale` math (`:34-176`).+- `CursorTelemetryPoint { timeMs, cx, cy, interactionType?, cursorType? }` (`:178`).+- `CursorVisualSettings { size, smoothing, motionBlur, clickBounce, clipToBounds }` + defaults (`:195-208`).+- `TrimRegion { id, startMs, endMs }` (`:211`).+- `AnnotationType = "text"|"image"|"figure"|"blur"` + `ArrowDirection`, `FigureData` (`:217-233`).+- `BlurShape`, `BlurType`, `BlurColor`, `BlurData`, `MIN_BLUR_INTENSITY/MAX_BLUR_INTENSITY`, etc. (`:235-254`).+- `AnnotationPosition`, `AnnotationSize`, `AnnotationTextStyle`, `AnnotationTextAnimation`, `AnnotationRegion { id, startMs, endMs, type, content, textContent?, imageContent?, position, size, style, zIndex, annotationSource?: "auto-caption", figureData?, blurData? }` (`:256-303`).+- `DEFAULT_ANNOTATION_POSITION`, `DEFAULT_ANNOTATION_SIZE`, `DEFAULT_ANNOTATION_STYLE`, `DEFAULT_FIGURE_DATA`, `DEFAULT_BLUR_FREEHAND_POINTS`, `DEFAULT_BLUR_DATA` (`:305-352`).+- `CropRegion { x, y, width, height }` normalized 0-1 (`DEFAULT_CROP_REGION = {0,0,1,1}` at `:354-366`).+- `PlaybackSpeed = number` (MIN 0.1, MAX 16), `SpeedRegion { id, startMs, endMs, speed }`, `SPEED_OPTIONS` (`:368-396`).+- `ZOOM_DEPTH_SCALES: Record<ZoomDepth, number>` (1.25x → 5.0x at `:400-407`), `MIN_ZOOM_SCALE/MAX_ZOOM_SCALE` (`:409-410`), `getZoomScale(region)` (`:415-421`).++### `src/components/video-editor/editorDefaults.ts` (99 lines)+- `DEFAULT_SOURCE_DIMENSIONS = { width: 1920, height: 1080 }` (`:23`).+- `DEFAULT_GIF_OUTPUT_DIMENSIONS = { width: 1280, height: 720 }` (`:28`).+- `DEFAULT_EDITOR_APPEARANCE_SETTINGS { shadowIntensity: 0, showBlur: false, motionBlurAmount: 0, borderRadius: 0, showTrimWaveform: true }` (`:33`).+- `DEFAULT_EDITOR_LAYOUT_SETTINGS { padding: 50, aspectRatio: "16:9", cropRegion: {0,0,1,1}, wallpaper: DEFAULT_WALLPAPER }` (`:47`).+- `DEFAULT_WEBCAM_SETTINGS { layoutPreset: "picture-in-picture", maskShape: "rectangle", sizePreset: 25, position: null }` (`:59`).+- `DEFAULT_CURSOR_SETTINGS { show: true, size: 3.0, smoothing: 0.67, motionBlur: 0.35, clickBounce: 2.5, clipToBounds: false, theme: DEFAULT_CURSOR_THEME_ID }` (`:71`).+- `DEFAULT_EXPORT_SETTINGS { quality: "good", format: "mp4" }` (`:81`).+- `DEFAULT_GIF_SETTINGS { frameRate: 15, loop: true, sizePreset: "medium", outputDimensions: 1280x720 }` (`:89`).++### `src/components/video-editor/projectPersistence.ts` (561 lines)+- Defines `ProjectEditorState` (`:67`) with 27 fields including `wallpaper`, `shadowIntensity`, `showBlur`, `motionBlurAmount`, `borderRadius`, `padding`, `cropRegion`, `zoomRegions[]`, `autoZoomEnabled`, `autoFocusAll`, `trimRegions[]`, `speedRegions[]`, `annotationRegions[]`, `aspectRatio`, `webcamLayoutPreset`, `webcamMaskShape`, `webcamMirrored`, `webcamReactiveZoom`, `webcamSizePreset`, `webcamPosition`, `exportQuality`, `exportFormat`, `gifFrameRate`, `gifLoop`, `gifSizePreset`, `cursorTheme`.+- `EditorProjectData { version: number, media?: ProjectMedia, editor: ProjectEditorState, videoPath?: string }` (`:97`).+- `PROJECT_VERSION = 2` (`:65`).+- `createProjectData(media, editor)` (`:536`) → the v2 envelope written to disk.+- `normalizeProjectEditor(editor)` (`:220`) — clamps every field, normalizes wallpaper file URLs (`LEGACY_FILE_WALLPAPER_RE` at `:54`), infers `motionBlurAmount` from legacy `motionBlurEnabled`, etc.+- `toFileUrl(filePath)` / `fromFileUrl(fileUrl)` (`:148` / `:162`) — platform-correct `file://` URL conversion (Windows drive handling).+- `deriveNextId(prefix, ids)` (`:186`) — pure numeric id suffix generator.+- `validateProjectData(candidate)` (`:196`) — required for load.+- `resolveProjectMedia(candidate)` (`:205`) — accepts both the modern `media` envelope and the legacy `videoPath` string.+- `createProjectSnapshot`, `hasProjectUnsavedChanges` (`:547`, `:554`) — JSON-string comparison.++### On-disk format+- File extension `.openscreen` (`PROJECT_FILE_EXTENSION = "openscreen"`, `electron/ipc/handlers.ts:46`).+- JSON: `{ version: 2, media: { screenVideoPath, webcamVideoPath?, cursorCaptureMode? }, editor: ProjectEditorState }`.+- Saved via main-process dialog → `RECORDINGS_DIR` default, but the user can pick anywhere (the path is then remembered as `currentProjectPath`).+- Path validation: `isTrustedProjectPath` (`electron/ipc/handlers.ts:391`) — the renderer can rewrite into the same file path without the save dialog; otherwise dialog appears.+- `loadProjectFileFromPath` (`electron/ipc/handlers.ts:2712`) supports deep-loading a specific `.openscreen` path. A `.session.json` sidecar holds the matching `RecordingSession` (`:1190-1235`).++### IPC contract for save / load+- `native-bridge:invoke` (single channel, typed envelope) hosts the project's save/load RPCs (`src/native/contracts.ts:130-200`):+ - `project.saveProjectFile(payload: { projectData, suggestedName?, existingProjectPath? })` → `ProjectFileResult`.+ - `project.loadProjectFile(payload?: { projectFolder? })` → `ProjectFileResult`.+ - `project.loadCurrentProjectFile()` → re-reads `currentProjectPath`.+ - `project.loadProjectFileFromPath(payload: { path })` → `ProjectFileResult`.+ - `project.setCurrentVideoPath / getCurrentVideoPath / clearCurrentVideoPath`.+ - `project.getCurrentContext` returns `{ currentProjectPath, currentVideoPath }`.+- Legacy aliases still exist on `window.electronAPI` (`electron/preload.ts:182-202`): `saveProjectFile`, `loadProjectFile`, `loadProjectFileFromPath`, `loadCurrentProjectFile`, `setCurrentVideoPath`, `getCurrentVideoPath`, `clearCurrentVideoPath`, `setCurrentRecordingSession`, `getCurrentRecordingSession`. New code is expected to use the bridge (`docs/architecture/native-bridge.md:38`).++### Multiple windows / shared project state+- **Single window at a time carries the editor.** Either the HUD-overlay is open (recording) or the editor window is open (`createEditorWindowWrapper` at `electron/main.ts:385` swaps HUD → editor on first open; `createEditorWindow` runs `win.maximize()`, sets `title: "OpenScreen"`).+- State sharing is via **main-process singletons + bridge calls**:+ - `currentProjectPath`, `currentVideoPath`, `currentRecordingSession` live in `electron/ipc/handlers.ts:357-358`, `:364`. Mutated by IPC, read by `getCurrentContext`.+ - `NativeBridgeStateStore` (`electron/native-bridge/store.ts:24`) holds `{ system, project, cursor }` snapshots for the renderer.+ - The renderer always re-reads on mount (`VideoEditor.tsx:540` `loadInitialData`) — there is **no live pub/sub across windows**. Each window independently fetches its state via `loadCurrentProjectFile` / `getCurrentRecordingSession` / `getCurrentVideoPath`.++---++## 4. Timeline++Files: `src/components/video-editor/timeline/` plus `useAudioPeaks`/`BackgroundWaveform`/`KeyframeMarkers` helpers. Backed by the `dnd-timeline` npm library (`package.json:75`).++### Data model+- All times are **milliseconds** as integers (no floating point rounding). `Span = { start: number, end: number }`, `Range = { start: number, end: number }` (`TimelineEditor.tsx:1` imports).+- The timeline owns **5 stacked rows** (`TimelineEditor.tsx:40-44`):+ - `ZOOM_ROW_ID = "row-zoom"`+ - `TRIM_ROW_ID = "row-trim"`+ - `ANNOTATION_ROW_ID = "row-annotation"`+ - `BLUR_ROW_ID = "row-blur"` (gated by `BLUR_REGIONS_ENABLED` flag, currently `false` in `featureFlags.ts:1`)+ - `SPEED_ROW_ID = "row-speed"`+- Regions on each row are typed `TimelineRenderItem` (`TimelineEditor.tsx:106`) with a per-row `variant`.+- There is also a **keyframe track** (`TimelineEditor.tsx:945`) — opaque time markers stored as `{ id, time }[]`, snap targets during drag/resize. Rendered by `KeyframeMarkers.tsx`.++### Zoom / pan+- `TimelineEditor.tsx:118-153` `calculateAxisScale(visibleRangeMs)` picks an interval (`SCALE_CANDIDATES`) that yields ~12 major markers; ticks subdivide by 5.+- **Pan** is via wheel events without modifier (`TimelineEditor.tsx:707-745` `handleTimelineWheel`); **zoom** is Ctrl/Meta + scroll (`TimelineWrapper.tsx:496-519` `handleRangeChange`).+- Drag-the-playhead past the visible window also pans (`TimelineEditor.tsx:289-372` `PlaybackCursor` `handleMouseMove`).+- `TimelineEditor.tsx:179-184` `createInitialRange(totalMs)` starts at `[0, totalMs]`.+- `TimelineWrapper.tsx:107-131` `clampSpanToBounds` and `:133-161` `clampRange` clamp items + visible range to `[0, totalMs]`.+- `TimelineWrapper.tsx:164-194` `clampToNeighbours` prevents zoom/trim/speed from overlapping.+- `TimelineWrapper.tsx:201-293` `snapSpanToTargets` snaps to region edges, playhead, keyframes, and timeline bounds. Threshold scales with zoom (~1% of visible range, min 50 ms). `:299-311` `inferResizeMode` guesses left vs right resize from pre/post deltas.+- `TimelineWrapper.tsx:39-87` `SnapGuide` paints an amber guide on snap during drag/resize.+- The renderer's spring smoothing (`zoomSpring.ts`) and the preview's transform math (`zoomTransform.ts`) are reused by the exporter so the timeline's camera motion matches what is rendered.++### Trim UX+- Trim is one row in the same DnD lane. The `Item.tsx` template (`:43-184`) renders **left + right end-caps** (`:110-130`, `cursor: "col-resize"`) that act as resize handles. dnd-timeline drives resize from those.+- Two trim regions on the same row **cannot overlap** (`TimelineEditor.tsx:1069-1104` `hasOverlap` enforces it; `clampToNeighbours` re-clamps instead of rejecting when possible).+- Add-trim is via the `Scissors` button (`TimelineEditor.tsx:1515-1523`) or the `addTrim` shortcut (`shortcuts.ts:111` `t`). Default length is `Math.max(1000, totalMs * 0.05)` (`TimelineEditor.tsx:1107`).+- Trim is *also* where the **audio waveform** appears (`BackgroundWaveform.tsx`, peaks from `useAudioPeaks.ts` which spins up `audioPeaksWorker.ts`).++### Zoom / spring / cursor / wallpaper features+- **Spring-smoothed zoom camera**: `zoomSpring.ts` (`createZoomSpringState`, `stepZoomSpring`, `resetZoomSpring`) is consumed by both the preview and the exporter (`frameRenderer.ts:881-898`) so motion is identical in export and preview.+- **Auto-zoom (magic wand)** — `autoZoomEnabled` is editor state (`useEditorHistory.ts:31`). The `WandSparkles` button toggles it (`TimelineEditor.tsx:1489-1501`). When on, `zoomRegionUtils.ts:findDominantRegion` chooses a cursor-follow zoom at run time.+- **Auto-Focus** — `autoFocusAll` (`useEditorHistory.ts:33`), `ScanEye` toggle (`TimelineEditor.tsx:1502-1514`). `cursorFollowUtils.ts:advanceFollowFocus` smooths the focus point.+- **3D rotation** — `zoomRegion.rotationPreset` (`types.ts:46-58`) with three presets (`iso`, `left`, `right`); applied in the exporter's `threeDPass.ts` and as CSS transforms in the preview.+- **Cursor smoothing** — `cursorPathSmoothing.ts` `getSmoothedCursorPath(...)` (used at `frameRenderer.ts:566` and `:569`).+- **Wallpaper** — `wallpaper.ts` `classifyWallpaper` (color / gradient / image) feeds `FrameRenderer.setupBackground` (`frameRenderer.ts:281-372`).+- **Keyframes** — `KeyframeMarkers.tsx`; `addKeyframe` shortcut (`f`, `TimelineEditor.tsx:1245`); add/delete/move wired via `TimelineEditor.tsx:960-982`.++### Multi-video awareness+- **Single video source only.** The timeline holds **time regions** on top of one recording. `useEditorHistory.ts:28-52` shows the `EditorState` has no `assets[]`; there is one `media.screenVideoPath` in `RecordingSession`. `VideoPlayback.tsx` consumes one video at a time. The only thing multiple is the **two tracks of one capture** — the screen and a separate webcam WebM are stacked by the renderer/exporter (see §2 compositor order).+- There is **no notion of multiple clips** in the timeline. Trim regions cut the single source, not a sequence.++### Per-file notes+- `TimelineWrapper.tsx:533-544` returns `TimelineContext` with `autoScroll: { enabled: false }` (horizontal scroll is dnd-timeline-driven).+- `Row.tsx` (34 lines) — single-row lane; `Row` accepts a `background` slot for the waveform overlay and an `isEmpty` hint.+- `Subrow.tsx` (17 lines) — a generic pill-shaped row used by inspector sub-UI; not currently used by the main timeline.+- `Item.module.css` is empty (0 bytes); the timeline Item uses Tailwind + the glass styles in `ItemGlass.module.css` (`zoomEndCap`, `selected`, `glassGreen`, `glassRed`, `glassAmber`, `glassYellow`).+- `TimelineEditor.tsx:1240-1307` — global keydown listener handles all shortcut-bound region adds, Tab cycles overlapping annotations, Delete/Backspace/Ctrl+D removes selected region.+- `BackgroundWaveform.tsx` — audio peaks drawn into the trim row.++---++## 5. Native bridge++### IPC architecture+Two layers:++1. **Ad-hoc `ipcMain.handle / ipcRenderer.invoke`** channels exposed via `window.electronAPI.*` in `electron/preload.ts`. There are ~50 channels (full list in §5 below).+2. **Versioned `native-bridge:invoke` channel** (`src/native/contracts.ts:1`) with `{ domain, action, payload, requestId }` envelopes handled in `electron/ipc/nativeBridge.ts` for system, project, and cursor domains. Renderer SDK at `src/native/client.ts` (`nativeBridgeClient`).++The renderer client (Zustand-free) is `nativeBridgeClient.system|project|cursor` (`src/native/client.ts:52`). Documented at `docs/architecture/native-bridge.md`.++### `electron/main.ts` (589 lines)+- `app.commandLine.appendSwitch` for macOS screen-audio + Linux Wayland (`main.ts:35-48`).+- Single instance lock (`main.ts:116-127`) using both `app.requestSingleInstanceLock()` and `acquireStableInstanceLock()` (`electron/singleInstanceLock.ts`).+- Tray + dynamic menu (`main.ts:304-360`). Tray shows "Stop recording" during a recording; "Open" / "Quit" otherwise.+- Application menu items: `New Project (Cmd/Ctrl+N)`, `Load Project… (Cmd/Ctrl+O)`, `Save Project… (Cmd/Ctrl+S)`, `Save Project As… (Cmd/Ctrl+Shift+S)`, plus Edit/View/Window. `sendEditorMenuAction(channel)` (`:133`) targets the focused editor window or creates one.+- `close` handler with unsaved-changes confirmation flow (`main.ts:395-426`):+ - Editor sets `editorHasUnsavedChanges = true` via `set-has-unsaved-changes` IPC (`main.ts:366`).+ - On close, main asks renderer via `request-close-confirm`; renderer answers with `close-confirm-response = "save" | "discard" | "cancel"`.+ - "save" → main sends `request-save-before-close`; renderer writes then sends `save-before-close-done`.+ - "discard" → main closes via `setImmediate` + `isForceClosing` flag.++### `electron/preload.ts` (293 lines)+- Reads `--asset-base-url=` from `process.argv` (`:11-13`) and exposes it via `contextBridge.exposeInMainWorld("electronAPI", { assetBaseUrl, ... })` (`:15-16`).+- Exposes `invokeNativeBridge<TData>(request)` (`:17-19`) — the single channel the versioned bridge uses.+- Surface area is enumerated below; every other helper is a thin `ipcRenderer.invoke` wrapper.++### `electron/ipc/nativeBridge.ts` (239 lines)+- Versioned (`NATIVE_BRIDGE_VERSION = 1`) request router for `system`, `project`, `cursor` domains.+- Domain services constructed with closures to main-process state:+ - `ProjectService` (`electron/native-bridge/services/projectService.ts:25`).+ - `CursorService` (`electron/native-bridge/services/cursorService.ts:14`).+ - `SystemService` (`electron/native-bridge/services/systemService.ts`).+- Returns `{ ok: true, data, meta } | { ok: false, error: { code, message, retryable }, meta }` envelopes (`contracts.ts:124-126`).+- Error codes: `INVALID_REQUEST | UNSUPPORTED_ACTION | NOT_FOUND | UNAVAILABLE | INTERNAL_ERROR` (`contracts.ts:93-98`).++### Full IPC channel list (from `electron/ipc/handlers.ts` grep + `electron/preload.ts`)+- **HUD / window controls** (`windows.ts`, `main.ts`):+ - `hud-overlay-hide`, `hud-overlay-close`, `hud-overlay-ignore-mouse-events`, `hud-overlay-move-by`, `hud-overlay-set-size` (one-way `ipcMain.on`).+ - `menu-new-project`, `menu-load-project`, `menu-save-project`, `menu-save-project-as`, `menu-import-video` (`preload.ts:202-225`, renderer listeners via `onMenu*`).+ - `hud:setMicrophoneExpanded` (one-way).+ - `set-has-unsaved-changes` (one-way).+ - `request-save-before-close`, `request-close-confirm` (renderer listeners); `save-before-close-done`, `close-confirm-response` (one-way back).+- **Window orchestration** (`handlers.ts:1423-1488`):+ - `get-sources(opts)` → `desktopCapturer.getSources`.+ - `select-source(source)`, `get-selected-source`.+ - `request-camera-access`, `request-screen-access`, `request-native-mac-cursor-access`.+ - `open-source-selector`, `switch-to-editor`, `switch-to-hud`, `start-new-recording`.+ - `countdown-overlay-show`, `countdown-overlay-set-value`, `countdown-overlay-hide`, `countdown-overlay-value` (event).+- **Native capture** (`handlers.ts:1520-2192`):+ - `is-native-windows-capture-available`, `is-native-mac-capture-available`.+ - `start-native-windows-recording(request)`, `pause-native-windows-recording`, `resume-native-windows-recording`, `stop-native-windows-recording(discard?)`.+ - `start-native-mac-recording(request)`, `pause-native-mac-recording`, `resume-native-mac-recording`, `stop-native-mac-recording(discard?)`.+ - `attach-native-mac-webcam-recording(payload)` (`:2141`).+- **Recording storage** (`handlers.ts:2207-2360`):+ - `store-recorded-session(payload)`, `store-recorded-video(data, fileName)`.+ - `open-recording-stream(fileName)`, `append-recording-chunk(fileName, chunk)`, `close-recording-stream(fileName)` (via `recordingStream.ts:95` `registerRecordingStreamHandlers`).+ - `get-recorded-video-path` (scans `RECORDINGS_DIR` for the latest webm).+ - `get-cursor-telemetry(videoPath?)`, `discard-cursor-telemetry(recordingId)`.+ - `set-recording-state(recording, recordingId?, cursorCaptureMode?)`.+ - `get-asset-base-path`.+- **Project / export** (`handlers.ts:2368-2862`):+ - `open-external-url`.+ - `pick-export-save-path(fileName, exportFolder?)`, `write-export-to-path(data, filePath)`.+ - `open-video-file-picker`.+ - `reveal-in-folder`.+ - `read-binary-file(filePath)`, `prepare-preview-audio-track(filePath)`.+ - `set-current-video-path`, `set-current-recording-session`, `get-current-video-path`, `get-current-recording-session`, `clear-current-video-path`.+ - `save-project-file`, `load-project-file`, `load-project-file-from-path`, `load-current-project-file`.+ - `get-platform`, `get-shortcuts`, `save-shortcuts`, `save-diagnostic`.+- **Stop-from-tray** (`handlers.ts:339-341`, `preload.ts:145-148`): main → renderer `stop-recording-from-tray` event.+- **Versioned bridge** (`nativeBridge.ts:124`): single channel `native-bridge:invoke` for system/project/cursor domains above.++### `assetBaseUrl` and file:// access+- `windows.ts:14-17` builds `ASSET_BASE_DIR` (process.resourcesPath in packaged, `public/` in dev) and passes `--asset-base-url=file:///…/` via `webPreferences.additionalArguments`.+- Preload reads it from `process.argv` (`preload.ts:11-13`) and exposes it on `electronAPI.assetBaseUrl`.+- Renderer uses `window.electronAPI.assetBaseUrl` directly:+ - `src/lib/wallpaper.ts` `resolveImageWallpaperUrl(path)` (`:73` and `:204-230` tests).+ - `src/lib/captioning/transcribe.ts:93-94` and `src/lib/captioning/transcribe.worker.ts:48-65` — sets `env.localModelPath = "<assetBaseUrl>/caption-assets/models/"` and `env.backends.onnx.wasm.wasmPaths = "<assetBaseUrl>/caption-assets/ort/"` so transformers.js doesn't try to fetch from the HuggingFace CDN under `file://`.+- **Security boundary:** the renderer can only read paths the main process has explicitly approved. `electron/ipc/handlers.ts:66` `approvedPaths` set; `readBinaryFile` (`handlers.ts:2523`) checks `isPathAllowed` against `RECORDINGS_DIR` and the approved set; `get-asset-base-path` (`handlers.ts:2368`) exposes the packaged resources dir (read-only).++### Screen / audio / webcam capture+- **Screen**: macOS uses `ScreenCaptureKit` via the `OpenScreenScreenCaptureKitHelper` Swift CLI (`electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/main.swift`), Windows uses the WGC CLI (`electron/native/wgc-capture/src/main.cpp`), Linux falls back to browser `getDisplayMedia`. The main process spawns the native CLI as a child process and parses NDJSON output (`:1067-1140` for WGC; `:1727-1869` for SCK). The renderer selects the path via `useScreenRecorder.ts:781` / `:912`.+- **System audio** (macOS): requested via `app.commandLine.appendSwitch("disable-features", "MacCatapLoopbackAudioForScreenShare")` (`main.ts:36`) — uses ScreenCaptureKit audio instead of CoreAudio tap (avoids `NSAudioCaptureUsageDescription`).+- **Microphone audio**: captured by the browser `MediaRecorder` via `getUserMedia({ audio: { deviceId } })` and appended to the screen WebM in `useScreenRecorder.ts:242`.+- **Webcam**: browser `getUserMedia({ video: { deviceId } })` for browser-capture path; native helper uses DirectShow (`dshow_webcam_capture.cpp`). On macOS, webcam is a separate `.mp4` file attached to the session via `attach-native-mac-webcam-recording` (`handlers.ts:2141`). On Windows it can be muxed in directly by the native CLI.+- **Cursor capture**: `useScreenRecorder.ts` offers `cursorCaptureMode = "editable-overlay" | "system"` (`recordingSession.ts:7`). `system` hides the OS cursor and overlays the recorded telemetry; `editable-overlay` keeps the OS cursor visible during recording and overlays the recorded cursor in the editor. `CursorService` (`:14`) reads back from the cursor telemetry file (v2 format, JSON) that the native CLIs write next to the WebM.++### `recordingStream.ts` (`electron/ipc/recordingStream.ts`, 139 lines)+- `RecordingStreamRegistry` (`:11`) — owns open `WriteStream`s keyed by output file name. Methods:+ - `open(fileName, filePath)` (`:19`) — `createWriteStream({ flags: "w" })`, awaits `open` event for fail-fast.+ - `append(fileName, chunk)` (`:45`) — serializes writes so chunks land in arrival order and `close` waits for in-flight writes.+ - `finalize(fileName)` (`:59`) — `ws.end(...)` and remove; returns `true` if the stream was open (so the caller knows the file is already on disk).+ - `discard(fileName, filePath)` (`:75`) — close + `unlink` partial file.+- IPC handlers at `:95` translate the throw-on-failure contract to `{ success, error? }` so renderer callers can fallback to in-memory buffering.++### `globalShortcut.ts` (77 lines)+- Maps `ShortcutBinding` (`src/lib/shortcuts.ts:15`) to Electron `globalShortcut.register(accelerator, callback)` (`:41` `registerOpenAppShortcut`).+- Default binding `Ctrl/Cmd+Shift+O` (`globalShortcut.ts:6`).+- Reads user prefs from `SHORTCUTS_FILE = userData/shortcuts.json` (`globalShortcut.ts:66`) via `loadAndRegisterGlobalShortcut`.+- Only the `openApp` binding is exposed as a global shortcut. All other editor shortcuts are renderer-side via `ShortcutsContext`.++### `windows.ts` (322 lines) — full window list+- `createHudOverlayWindow()` (`:87`) — frameless transparent 600×160 always-on-top, bottom-centred. Reads `--asset-base-url=` from main.+- `createEditorWindow()` (`:168`) — maximized, `hiddenInset` traffic lights on macOS, `webSecurity: false` (relaxed for `file://` access).+- `createSourceSelectorWindow()` (`:231`) — frameless transparent 620×420, always-on-top.+- `createCountdownOverlayWindow()` (`:275`) — fixed 420×260, focusable: false, transparent.+- Coordination: only one `mainWindow` reference exists at a time (`main.ts:83`). On launch the HUD opens; clicking "Open studio" or stopping a recording swaps the HUD for the editor window (`createEditorWindowWrapper` at `main.ts:385`).+- All four windows share the same renderer build and preload (`preload.mjs`) but pick a top-level component by `?windowType=` (see §1).++---++## 6. Captioning pipeline++All under `src/lib/captioning/`. The renderer can transcribe a video's audio in-browser using Whisper via transformers.js, then convert the word/phrase timings into `AnnotationRegion`s.++### Files+- `transcribe.ts` (106 lines) — public entry point.+- `transcribe.worker.ts` (93 lines) — Web Worker that loads transformers.js.+- `transcribeCore.ts` (268 lines) — pure algorithm, no DOM / Workers / Transformers imports.+- `extractMono16k.ts` (159 lines) — `extractMono16kFromVideoUrl`.+- `extractMono16kWebDemuxer.ts` (162 lines) — fallback that uses `web-demuxer` + `AudioDecoder`.+- `leadingSilence.ts` (78 lines) — drops leading silence before Whisper runs.+- `annotationsFromCaptions.ts` (604 lines) — turns `CaptionSegment[]` into `AnnotationRegion[]`.+- `captionConstants.ts` — `MAX_CAPTION_AUDIO_SEC`.+- `index.ts` — barrel.+- `annotationsFromCaptions.test.ts` — unit tests.++### How Whisper runs today+`transcribeMono16kToSegments(samples, options)` (`transcribe.ts:44`):+1. Spawns a module `Worker` from `transcribe.worker.ts` (`:57`).+2. Posts `{ samples, trimRegions, useLocalModels, assetBaseUrl }` (`TranscribeWorkerRequest`, `:18`).+3. Worker (`transcribe.worker.ts:76`):+ - Calls `loadTranscriber({ useLocalModels, assetBaseUrl })` (`:46`).+ - Uses `pipeline("automatic-speech-recognition", "Xenova/whisper-tiny")` from `@xenova/transformers`.+ - With `useLocalModels=true` (file:// packaged app): `env.allowLocalModels=true`, `env.allowRemoteModels=false`, `env.localModelPath = "<assetBaseUrl>/caption-assets/models/"`, `env.backends.onnx.wasm.wasmPaths = "<assetBaseUrl>/caption-assets/ort/"`, `numThreads: 1` (no SharedArrayBuffer under file://).+ - In dev (http://localhost): `env.allowLocalModels=false`, remote CDN fetch.+4. Posts `status` "model" → "transcribe" → `result` (`CaptionSegment[]`) or `error` (`:33`).+5. `withoutNodeVersion` (`transcribe.worker.ts:25`) strips `process.versions.node` before importing Transformers/ORT so Electron workers don't try `require("fs")`.++`runTranscription` in `transcribeCore.ts:184` orchestrates the actual run:+- Tries `word` timestamps first, falls back to `phrase` if empty.+- For each mode, tries `force_full_sequences: true` then `false`; for each pair, retries with `ignoreTrims: true` and post-filters overlapping segments.+- Long audio is split into 12-minute slices (`TRANSCRIBE_SLICE_SAMPLES = 12 * 60 * 16_000`, `:34`).+- Pads short tail slices to `MIN_TRANSCRIBE_SLICE_SAMPLES = 800` so Whisper doesn't return empty (`padTailSliceForTranscribe`, `:43`).+- Dedupes adjacent segments with identical normalized text (`segmentsFromTranscriberChunks`, `:57`).++### Model files+- **Model**: `Xenova/whisper-tiny` (transformers.js ASR pipeline).+- **Storage**: bundled under `caption-assets/` (the `electron-builder.json5:42-46` `extraResources` rule copies `caption-assets/` into the packaged resources dir).+- **Fetch step**: `scripts/fetch-caption-model.mjs` populates `caption-assets/` pre-build.+- **ORT WASM**: bundled in `caption-assets/ort/`.++### Output shape+- `CaptionSegment { startSec: number, endSec: number, text: string }` (`transcribe.ts:3`).+- `TranscribeMono16kResult { segments: CaptionSegment[], granularity: "word" | "phrase" }` (`transcribe.ts:12`).++### Renderer trigger+- `VideoEditor.tsx:2209-2232` `handleGenerateCaptions()`:+ 1. `extractMono16kFromVideoUrl(videoPath, { signal })` (`extractMono16k.ts:110`) — tries `decodeAudioData`, falls back to `extractMonoPcmViaWebDemuxer`.+ 2. `trimLeadingSilenceMono16k(samples)` (`leadingSilence.ts:25`).+ 3. `shiftTrimRegionsMsForCaptionBuffer(trimRegions, trimSec)` (`leadingSilence.ts:66`).+ 4. `transcribeMono16kToSegments(samples, { trimRegions, signal })`.+ 5. `captionSegmentsToAnnotationRegions(segments, …)` (`annotationsFromCaptions.ts:544`).++### Linking to time ranges in the editor+- `annotationsFromCaptions.ts:544` `captionSegmentsToAnnotationRegions` produces `AnnotationRegion[]` with:+ - `startMs`/`endMs` computed from `seg.startSec` / `seg.endSec`.+ - Position / size / style hard-coded to a lower-third bar: `position: { x: 4, y: 86 }` (`:9-13`), `size: { width: 92, height: 12 }`, `style` = white 24px Inter, `annotationSource: "auto-caption"` (`annotationsFromCaptions.ts:300`, `:574-583`).+- `groupTimedCaptionWordsIntoLines` (`:325`) groups word segments into on-screen lines of `minWords=2, maxWords=7`.+- `groupPhraseCaptionSegmentsIntoLines` (`:436`) does the same for phrase granularity.+- `reconcileAutoCaptionTimelineGaps` (`:148`) enforces a min gap between consecutive auto-caption regions.+- `captionSegmentsToAnnotationRegions` is **idempotent and stateless** — the caller is responsible for `startNumericId` and `startZIndex` and merges the new regions with existing ones. `VideoEditor.tsx` uses `maxAnnotationNumericId` / `maxAnnotationZIndex` (`annotationsFromCaptions.ts:592-603`) to keep ids stable.+- **Trim awareness**: `segmentsFromTranscriberChunks` (`transcribeCore.ts:107`) drops any segment that overlaps a `TrimRegion`, so caption ranges never sit inside a cut.++---++## 7. UI primitives++### Radix-based components (`src/components/ui/*`)+All shadcn-style "new-york" presets (`components.json:3`); baseColor `stone`, `tailwind.config.cjs` exposes HSL CSS-variable tokens (`tailwind.config.cjs:41-81`).++| File | Radix package | Notes |+|---|---|---|+| `accordion.tsx` | `@radix-ui/react-accordion` | Forwarded Radix parts. |+| `audio-level-meter.tsx` | (none) | Pure canvas/visual. |+| `button.tsx` | `@radix-ui/react-slot` (for `asChild`) | `class-variance-authority` variants (`:11`). |+| `card.tsx` | (none) | Headless panels. |+| `color-picker.tsx` | `@uiw/react-color-*` | 3rd-party UIW. |+| `content-clamp.tsx` | (none) | Text overflow utility. |+| `dialog.tsx` | `@radix-ui/react-dialog` | Z-index `9999` / `10000`. |+| `dropdown-menu.tsx` | `@radix-ui/react-dropdown-menu` | |+| `input.tsx` | (none) | |+| `item-content.tsx` | (none) | Shared list-item slot. |+| `label.tsx` | (none) | |+| `popover.tsx` | `@radix-ui/react-popover` | |+| `select.tsx` | `@radix-ui/react-select` | Z-index `100000` to sit above dialog (`select.tsx:86`). |+| `slider.tsx` | `@radix-ui/react-slider` | |+| `sonner.tsx` | (none) | Toaster wrapper. |+| `switch.tsx` | `@radix-ui/react-switch` | |+| `tabs.tsx` | `@radix-ui/react-tabs` | |+| `toggle.tsx` | `@radix-ui/react-toggle` | |+| `toggle-group.tsx` | `@radix-ui/react-toggle-group` | |+| `tooltip.tsx` | `@radix-ui/react-tooltip` | |++### Design system+- **Tailwind** (`tailwind.config.cjs`) with CSS-variable theme (`src/index.css:7-61`): `--background`, `--foreground`, `--card`, `--popover`, `--primary`, `--secondary`, `--muted`, `--accent`, `--destructive`, `--border`, `--input`, `--ring`, `--chart-1..5`, `--radius: 0.5rem`. Dark variant at `:35-60`. Editor-specific utilities (`.editor-workspace`, `.editor-preview-panel`, `.editor-timeline-panel`, `.editor-resize-handle`, `.editor-panel-section`, `.editor-control-surface`, `.editor-inspector-shell`) in `src/index.css:77-217`.+- **Brand color**: `#34B27B` (used throughout LaunchWindow / TimelineEditor). Accent `#6C55FF` (playhead). Destructive `#ef4444` (trim).+- **Cursor color tokens**: `glassGreen/glassRed/glassAmber/glassYellow` in `ItemGlass.module.css`.+- **Type ramp**: Inter (default), plus Google Fonts imported via `@import` in `src/index.css:1` (Bebas Neue, Caveat, DM Sans, Fira Code, IBM Plex, Lora, Manrope, Merriweather, Oswald, Permanent Marker, Playfair, Plus Jakarta Sans, Space Grotesk, Sora).+- **No theme provider**; the editor is forced-dark via `index.html` root background `#09090b`.++### Icons+- Primary icon set: **`lucide-react: ^0.545.0`** (`package.json:80`). Used by every UI primitive + the timeline editor (`TimelineEditor.tsx:3-14`, `Item.tsx:3`).+- HUD icons: **`react-icons` (BsPlay, BsPause, BsRecordCircle, FaRegStopCircle, FaFolderOpen, FiMinus, FiX, MdCancel, MdMic, MdMicOff, MdMonitor, MdMouse, MdRestartAlt, MdVideocam, MdVideocamOff, MdVideoFile, MdVolumeOff, MdVolumeUp, RxDragHandleDots2, Languages, Columns3, Rows3, Clapperboard, Check, ChevronDown, ScanEye, WandSparkles, Scissors, MessageSquare, ZoomIn, Gauge, Captions, Captions, Plus, MousePointer2)** — see `LaunchWindow.tsx:1-21` and `TimelineEditor.tsx:3-14`.+- Arrow SVGs (caption arrows): `src/components/video-editor/ArrowSvgs.tsx` (5119 bytes, 8 directions).++### i18n setup+- `src/i18n/config.ts` (30 lines) — `DEFAULT_LOCALE = "en"`, `SUPPORTED_LOCALES = [en, ar, es, fr, it, ja-JP, ko-KR, ru, tr, vi, pt-BR, zh-CN, zh-TW]` (13), `I18N_NAMESPACES = [common, dialogs, editor, launch, settings, shortcuts, timeline]` (7).+- `src/i18n/loader.ts` (125 lines) — `import.meta.glob("./locales/**/*.json", { eager: true })` builds `messages[locale][namespace]`. `translate(locale, namespace, key, vars)` interpolates `{{name}}` placeholders. Missing namespaces are logged but excluded from `availableLocales`.+- `src/contexts/I18nContext.tsx` (192 lines) — provider with `useI18n()` + `useScopedT(namespace)`. Stored in `localStorage[openscreen-locale]`. On change it calls `window.electronAPI?.setLocale?.(newLocale)` which hits the main-process `set-locale` handler (`main.ts:542`) so the application menu re-renders with translated labels.+- Main process i18n (`electron/i18n.ts`, 113 lines — abbreviated `mainT`) covers the application menu and any main-process toasts / dialog labels.++### 13 locales (full list)+`en` (default), `ar`, `es`, `fr`, `it`, `ja-JP`, `ko-KR`, `ru`, `tr`, `vi`, `pt-BR`, `zh-CN`, `zh-TW`. Each locale has 7 namespace JSON files (`common`, `dialogs`, `editor`, `launch`, `settings`, `shortcuts`, `timeline`) under `src/i18n/locales/<locale>/`. Total: 91 locale files.++### Radix collision with axcut patterns+- OpenScreen uses shadcn `new-york` preset with `stone` base color and the standard CSS-variable HSL palette. Axcut uses **the same shadcn `new-york` preset** (per the merge plan references), so primitives like `button`, `dialog`, `popover`, `select`, `dropdown-menu`, `slider`, `tooltip`, `tabs`, `accordion`, `toggle`, `toggle-group`, `switch` should be **drop-in compatible**.+- OpenScreen already uses `@radix-ui/react-popover`, `@radix-ui/react-select`, `@radix-ui/react-dialog`, `@radix-ui/react-tooltip`, `@radix-ui/react-dropdown-menu`, `@radix-ui/react-tabs`, `@radix-ui/react-slider`, `@radix-ui/react-switch`, `@radix-ui/react-accordion`, `@radix-ui/react-toggle`, `@radix-ui/react-toggle-group` — covers the full axcut surface from the plan.+- Custom OpenScreen primitives to watch: `audio-level-meter.tsx` (real-time mic level meter), `color-picker.tsx` (UIW `@uiw/react-color-colorful`), `content-clamp.tsx` (line-clamp wrapper), `item-content.tsx`. None of these are mentioned in the plan, so they are likely unique to OpenScreen.++---++## 8. Settings + preferences++### `src/lib/userPreferences.ts` (145 lines)+Schema:++```ts+interface UserPreferences {+ padding: number; // 0-100, default 50 (DEFAULT_EDITOR_LAYOUT_SETTINGS.padding)+ aspectRatio: AspectRatio; // one of 16:9, 9:16, 1:1, 4:3, 4:5, 16:10, 10:16, native+ exportQuality: ExportQuality; // "medium" | "good" | "source", default "good"+ exportFormat: ExportFormat; // "mp4" | "gif", default "mp4"+ exportFolder: string | null; // remembered folder from save dialog+ projectFolder: string | null; // remembered folder from open-project dialog+ trayLayout: "horizontal" | "vertical"; // HUD layout, default "horizontal"+}+```++- Key `openscreen_user_preferences` in `localStorage`.+- `loadUserPreferences()` (`:59`) parses + clamps + falls back to `DEFAULT_PREFS`.+- `saveUserPreferences(partial)` (`:137`) merges into current and writes.+- `parentDirectoryOf(filePath)` (`:111`) + `getExportFolder()` / `getProjectFolder()` (`:127`, `:132`) helpers used to seed file dialog defaults.+- Auto-save effect in `VideoEditor.tsx:619-623` syncs `padding, aspectRatio, exportQuality, exportFormat` whenever they change.++### Other persisted prefs+- **`shortcuts.json`** (`electron/ipc/handlers.ts:46` `SHORTCUTS_FILE`) — at `userData/shortcuts.json`, the configurable shortcuts (`SHORTCUT_ACTIONS` in `shortcuts.ts:1-12`). Read on launch by `globalShortcut.ts:66` and `ShortcutsContext.tsx:43`; written via `saveShortcuts` IPC (`handlers.ts:2852`).+- **Locale** — `localStorage[openscreen-locale]` (`I18nContext.tsx:104`).+- **System language prompt seen flag** — `localStorage[openscreen-system-language-prompt-seen]` (`I18nContext.tsx:26`).+- **Custom fonts** — `src/lib/customFonts.ts` injects `<style>` into `document.head` (`:79`); no file persistence, but each font family is cached in `document.fonts`.+- **Editor per-project state** — `*.openscreen` files (see §3).+- **Last active project / recording paths** — main-process singletons (`electron/ipc/handlers.ts:357-358`, `:364`).++---++## 9. Shortcuts++`src/lib/shortcuts.ts` (176 lines). Two groups: configurable (`SHORTCUT_ACTIONS`) and fixed (`FIXED_SHORTCUTS`).++### Configurable shortcuts (`SHORTCUT_ACTIONS`, `shortcuts.ts:1-11`)+| Action | Default binding (`DEFAULT_SHORTCUTS`, `:108-118`) | Used by |+|---|---|---|+| `openApp` | `Ctrl/Cmd+Shift+O` | Global `electron.globalShortcut` (open main window). |+| `addZoom` | `Z` | Timeline (`TimelineEditor.tsx:1248`). |+| `addTrim` | `T` | Timeline (`:1251`). |+| `addSpeed` | `S` | Timeline (`:1260`). |+| `addAnnotation` | `A` | Timeline (`:1254`). |+| `addBlur` | `B` | Timeline (`:1257`, gated by `BLUR_REGIONS_ENABLED`). |+| `addKeyframe` | `F` | Timeline (`:1245`). |+| `deleteSelected` | `Ctrl/Cmd+D` | Timeline (`:1286`). |+| `playPause` | `Space` | Not currently bound to a handler in `TimelineEditor` — wired in `PlaybackControls`. |++### Fixed shortcuts (`FIXED_SHORTCUTS`, `shortcuts.ts:32-75`)+- `undo` — `Ctrl+Z`.+- `redo` — `Ctrl+Shift+Z` or `Ctrl+Y`.+- `cycleAnnotationsForward` — `Tab` (handled inline at `TimelineEditor.tsx:1265`).+- `cycleAnnotationsBackward` — `Shift+Tab`.+- `deleteSelectedAlt` — `Delete` / `Backspace`.+- `panTimeline` — `Shift+Ctrl+Scroll` (display only, not enforced).+- `zoomTimeline` — `Ctrl+Scroll` (display only).+- `frameBack` / `frameForward` — `←` / `→`.++### Collision check with axcut (Ctrl+C / Ctrl+V for clip duplicate)+- OpenScreen does **not** bind `Ctrl+C` / `Ctrl+V` to clip duplicate today. `Tab` cycles annotations; `Delete` / `Backspace` / `Ctrl+D` delete selected region.+- However, `Ctrl+C` and `Ctrl+V` are intercepted by Electron's application menu as `Edit > Copy` / `Edit > Paste` (`main.ts:231-233`). In the editor's text inputs these behave normally; in the canvas they would currently go to the system clipboard with no effect (the menu items are wired to native `role: "copy"` / `"paste"`).+- **The merge plan's Ctrl+C / Ctrl+V = duplicate clip will collide** with the existing Edit menu items. The fix is either:+ - Override `role: "copy"` / `role: "paste"` on the menu to send renderer-targeted IPC and have the editor handle them, or+ - Keep the global native copy/paste but bind `Ctrl+Shift+D` / `Ctrl+Shift+V` (or use `Cmd+D` which is already `deleteSelected`) for duplicate.+- `Ctrl+D` is **already bound** to `deleteSelected` (`shortcuts.ts:116`). `findConflict` (`:90`) will reject a duplicate-clip binding on `Ctrl+D` because both are `configurable`. The conflict-detection system at `:90-106` is already in place.++---++## 10. Performance + concurrency++### Web Workers+Three:++| File | Purpose | Spawned by |+|---|---|---|+| `src/lib/captioning/transcribe.worker.ts` | Whisper ASR. | `transcribe.ts:57` `new Worker(new URL("./transcribe.worker.ts", import.meta.url), { type: "module" })`. |+| `src/hooks/audioPeaksWorker.ts` (43 lines) | Computes audio peaks for waveform display. | `useAudioPeaks.ts:21` `new Worker(...)`. |+| `gif.js` worker (`gif.js/dist/gif.worker.js`, external library) | GIF encoding. | `gifExporter.ts:25` via `GIF_WORKER_URL`. |++The caption worker is terminated on completion/abort (`transcribe.ts:67`).++### Pixi.js contexts+- **Preview** — `src/components/video-editor/VideoPlayback.tsx:1027` (creates a `pixi.js` `Application` and mounts the canvas inside the editor preview).+- **Export** — `FrameRenderer.ts:196` creates a separate offscreen Pixi.js app per export (`new Application({ canvas, width, height, backgroundAlpha: 0, antialias: true, resolution: 1, autoDensity: true })`).+- Tests: `vitest.browser.config.ts` runs Playwright with Chromium to render Pixi in jsdom-incompatible code paths (`src/lib/exporter/videoExporter.browser.test.ts`, `src/lib/exporter/gifExporter.browser.test.ts`).++### Main-process concurrency+- **Streams only**: `RecordingStreamRegistry` (`electron/ipc/recordingStream.ts:11`) holds a `Map<fileName, WriteStream>` per open recording. No explicit locking — writes are serialized via the Node `WriteStream` internal queue + an `enqueueWrite` promise chain in the renderer (`recorderHandle.ts:50-67`).+- **Native capture subprocesses**: `electron/ipc/handlers.ts:404-425` holds separate state per platform (`nativeWindowsCaptureProcess`, `nativeMacCaptureProcess`). Single process per platform at a time (rejects parallel start). Spawned via `node:child_process.spawn`.+- **No mutex / lock / queue primitive** in main. Operations are guarded by re-entrancy checks (`activeNativeRecording.finalizing`, `cursorRecordingSession !== null`).++### IPC pub-sub / event bus+- **Native bridge has events** (`NativeBridgeEventName`, `src/native/contracts.ts:230-238`): `project.contextChanged`, `cursor.providerChanged`, `cursor.telemetryLoaded`. The events are *typed* and *advertised* but **no transport is wired** for them today (no `webContents.send` to deliver them; renderer code does not subscribe). They are scaffolding for future use.+- **Implicit pub-sub** via `webContents.send`:+ - `selected-source-changed`, `source-selector-closed`, `countdown-overlay-value`, `stop-recording-from-tray`, `request-close-confirm`, `request-save-before-close`, `main-process-message` (echoes date string back, mostly debug).+ - The renderer subscribes via `on*` callbacks exposed in `preload.ts`.+- **No main-process EventEmitter shared between services** aside from `nativeMacCaptureEvents` (`handlers.ts:51`, used internally for the macOS SCK child process).++---++## 11. Tests++### Inventory (32 test files)+Unit (vitest, jsdom) and browser (Playwright headless Chromium):+- `src/lib/exporter/{videoExporter,videoExporter.browser,frameRenderer,mp4ExportSettings,gradientParser,streamingDecoder,timestampedVideoFrameQueue,audioEncoder,gifExporter,gifExporter.browser}.test.{ts,tsx}` — exporter pipeline.+- `src/lib/{wallpaper,userPreferences,nativeMacRecording,compositeLayout,cursorTelemetryBuffer,blurEffects,annotationTextAnimation}.test.{ts,tsx}` — utility modules.+- `src/lib/captioning/annotationsFromCaptions.test.ts` — caption grouping & spacing.+- `src/lib/cursor/{nativeCursor,cursorPathSmoothing}.test.ts` — cursor telemetry / smoothing.+- `src/lib/__tests__/frameStepNavigation.test.ts` — frame step.+- `src/components/video-editor/{projectPersistence,editorDefaults,customPlaybackSpeed,backgroundImageUpload}.test.{ts,tsx}` — editor state.+- `src/components/launch/{LaunchWindow,SourceSelector}.test.tsx` and `openSourceSelectorFlow.test.ts` — HUD/launch flows.+- `src/hooks/{recorderHandle,useCameraDevices}.test.ts` — recorder + camera devices.+- `src/utils/aspectRatioUtils.test.ts`.+- `src/i18n/__tests__/tutorialHelpTranslations.test.ts`.+- `electron/{singleInstanceLock,ipc/recordingStream}.test.ts` — main process units.+- `src/components/video-editor/videoPlayback/zoomSpring.test.ts`.++### Vitest vs browser-vitest split+- **`vitest.config.ts`** (jsdom env) — 27 unit tests including all editor state, util, caption, cursor, recorder tests.+- **`vitest.browser.config.ts`** (Playwright headless shell, real DOM + Pixi) — only `videoExporter.browser.test.ts` and `gifExporter.browser.test.ts`.+- Split reason: jsdom can't construct `OffscreenCanvas`/`VideoFrame`/WebCodecs needed by the exporter.++### E2E (Playwright, `tests/e2e/`)+- `gif-export.spec.ts` (158 lines) — spawns Electron, loads `tests/fixtures/sample.webm` directly into the editor, exports both mp4 and gif, asserts file size > 0, optionally `ffprobe`s the MP4 if available (`tests/e2e/gif-export.spec.ts:14`).+- `windows-native-checklist.spec.ts` (322 lines) — Windows-specific checklist: launches Electron, exercises the native-bridge RPCs (`system.getCapabilities`, `cursor.getCapabilities`, etc.) to validate the helper availability and capabilities handshake (`tests/e2e/windows-native-checklist.spec.ts:8`).+- Fixtures: `tests/fixtures/sample.webm` (23 KB) and `tests/fixtures/sample-inflated-duration.webm` (1.2 KB) for duration-validation tests.++### Recorder handle tests (`src/hooks/recorderHandle.test.ts`, 264 lines)+Eight tests covering streaming to disk, fallback to in-memory when open fails, fallback when IPC rejects, no truncation when writes are in flight, error propagation from `appendRecordingChunk` (success=false and rejection), buffering without `fileName`, and `discard` semantics.++---++## 12. Build + distribution++### `electron-builder.json5`+- `appId: com.etiennelescot.openscreen`, `productName: Openscreen`, `asar: true`, `asarUnpack: ["**/*.node"]`.+- `extraResources`:+ - `public/wallpapers` → `wallpapers/`.+ - `public/cursors` → `cursors/`.+ - `caption-assets` → `caption-assets/`.+- **mac** — `hardenedRuntime: true`, entitlements `macos.entitlements`, target `dmg` for both `x64` and `arm64`, native helper from `electron/native/bin/darwin-*/*`.+- **linux** — targets `AppImage, deb, pacman`, no native helper.+- **win** — target `nsis` (oneClick: false, allowToChangeInstallationDirectory: true), native helper from `electron/native/bin/win32-*/*`.+- `beforePack: scripts/before-pack.cjs` — fetches the auto-caption model + ORT wasm into `caption-assets/` (idempotent).++### Native helper build scripts+- `scripts/build_macos.sh` (`build:mac` npm script wraps `build:native:mac + tsc + vite build + electron-builder --mac`).+- `scripts/build-macos-screencapturekit-helper.mjs` — invokes `swift build` for `electron/native/screencapturekit` (Swift Package Manager, `Package.swift`).+- `scripts/build-windows-wgc-helper.mjs` — invokes `cmake` for `electron/native/wgc-capture` (`CMakeLists.txt`).+- `scripts/test-windows-wgc-helper.mjs` — helper-level smoke test (5 mode variants).++### `scripts/i18n-check.mjs` (87 lines)+Validates every locale folder has the same key tree as `en/` for all 7 namespaces. Lists missing keys per locale; fails with non-zero exit if any locale is out of sync. Run via `npm run i18n:check` (`package.json:27`).++### Other scripts (`scripts/`)+- `before-pack.cjs` — caption-asset fetch step (above).+- `capture-openscreen-preview.mjs`, `inspect-native-cursor-click-bounce.mjs` — diagnostic / screenshot tools.+- `test-windows-native-cursor.mjs` — native cursor helper smoke test.+- `fetch-caption-model.mjs` — model pre-download.++### Build commands+- `npm run dev` — vite dev server (Electron window opens via `vite-plugin-electron`).+- `npm run build` — full `tsc && vite build && electron-builder`.+- `npm run build-vite` — Vite + tsc only (no packaging), used by Playwright e2e setup.+- `npm run lint` / `npm run format` — Biome 2.4 (`biome.json`, `package.json:24-25`).+- `npm run test` (vitest), `npm run test:browser` (Playwright), `npm run test:e2e` (Playwright e2e).+- `npm run prepare` — `husky` for pre-commit hooks (`lint-staged` runs Biome on staged `*.{ts,tsx,js,jsx,mts,cts,json}`).++---++## 13. Anything else relevant to the merge++### Code that touches "schema" or "document" (potential collisions)+- `useScreenRecorder.ts:963`, `src/lib/nativeMacRecording.ts:7`, `src/lib/nativeMacRecording.ts:53` — native capture **requests** carry `schemaVersion: 1` (`NativeMacRecordingRequest`, `NativeWindowsRecordingRequest`). These are IPC payload schemas, not the project document. If axcut's plan renames or extends these, both sides must move together.+- `ProjectFileResult` (`src/native/contracts.ts:84`) carries `project?: unknown` — the on-disk project JSON is currently passed as `unknown` through the bridge and parsed only in the renderer. The merge plan's `AxcutDocument` will become the **typed** shape; bridge contract stays `unknown`, but renderer + persistence switch.+- `PROJECT_VERSION = 2` (`projectPersistence.ts:65`) — current on-disk schema is v2; the merge plan bumps to v3 with `legacyEditor` preserved.+- `electron-builder.json5:46` already lists `caption-assets` as `extraResources`. The merge plan's "resources/` folder referenced for `apps/server`/`py/axcut-core` does not exist; nothing to deprecate here.++### Plugins / extension points+- **No plugin system in OpenScreen.** All "extension" code paths are hardwired (compositor layers in `FrameRenderer`, IPC channels in `handlers.ts`, Radix UI primitives). The closest thing to extensibility is:+ - `native-bridge:invoke` domain routing — a new domain (`chat`, `agent`) can be added without breaking other domains (`src/native/contracts.ts:130`).+ - `NativeBridgeEventName` (`contracts.ts:230`) declares events for `project.contextChanged`, `cursor.providerChanged`, `cursor.telemetryLoaded` — typed but **not yet wired** (no transport). Adding a transport (e.g. `EventEmitter` or `webContents.send`) is the cleanest place to add the merge plan's "per-project event bus" without inventing a new channel.+ - `getExportFolder` / `getProjectFolder` are the only places user prefs cross into the IPC layer; AI Edition prefs (default provider, default model, reasoning effort per the merge plan §Phase 9) can extend `UserPreferences` cleanly.++### Documentation files (`docs/`)+- `docs/architecture/ai-edition-merge-plan.md` — the merge plan itself.+- `docs/architecture/native-bridge.md` (39 lines) — describes the versioned IPC pattern.+- `docs/tests/writing-tests.md`.+- `docs/testing/windows-native-cursor.md`, `docs/testing/macos-native-cursor.md` — native-helper smoke-test notes.+- `docs/engineering/windows-native-recorder-roadmap.md`, `docs/engineering/macos-native-recorder-roadmap.md`.+- Project root also has `README.md` (7976 bytes), `CONTRIBUTING.md`, `LICENSE`, `AGENTS.md` (the canonical agents guide referenced by merge plan). No other `.md` files in the repo (`grep -r '\.md$' --include=*` returns only those).++### Other notes+- `electron/electron-env.d.ts` (9690 bytes) — the full TypeScript surface of `window.electronAPI` exposed by the preload. This is the authoritative list of legacy ad-hoc IPC and should be cross-checked against the merge plan's new channels (`ai-edition:document:get`, `ai-edition:chat:run`, `ai-edition:sessions:list`, etc.) — none exist yet.+- `RecordingStreamRegistry` (`electron/ipc/recordingStream.ts:11`) is generic enough to host **appending bytes for any streamed IPC payload** — e.g. an axcut asset import that streams a file to disk.+- `assetBaseUrl` plumbing (`electron/preload.ts:11-13` + `src/lib/assetPath.ts` + `src/lib/wallpaper.ts`) is the canonical pattern for shipping bundled assets under `file://`. The merge plan explicitly calls out `transcribe.ts:93-94` as the template to copy when axcut's agent runtime needs to ship models or templates — `transcribe.worker.ts:55-61` shows the matching env-var shape.+- The recorder's `recordingId` is `Date.now()` (`useScreenRecorder.ts:808`, `:1020`), so it's millisecond timestamp + counter — collisions are theoretically possible if two recordings start in the same millisecond on different windows. Not relevant in practice; merge plan's `assets[].id` should generate via `crypto.randomUUID()` like the timeline (`TimelineEditor.tsx:17`).+- `useEditorHistory.ts` (164 lines) holds the undo/redo state machine (80-step ring buffer, `pushState`/`updateState`/`commitState`/`undo`/`redo`/`resetState`). The merge plan's `AxcutDocument.history.revisions[]` will replace this; `pushState` → record a revision, `undo` → restore.+- The `currentRecordingSession` singleton (`handlers.ts:358`) is the closest existing thing to the plan's `activeProject` — it's a single in-flight `RecordingSession`, replaced wholesale on every stop. The plan's per-project model will need an index of all open projects, not just the active one.+- `LICENSE` = MIT; `package.json:5` author/maintainers are listed; `electron-builder.json5:84` sets the linux `maintainer`.diff --git a/docs/axcut-ux-ui-spec.md b/docs/axcut-ux-ui-spec.mdnew file mode 100644index 000000000..66bc809d6--- /dev/null+++ b/docs/axcut-ux-ui-spec.md@@ -0,0 +1,397 @@+# Axcut Web UI — UX/UI Specification++Single-page dark web app at `http://127.0.0.1:5173`. Five-zone resizable grid, no client-side routing, persistent server connection via SSE.++## 1. Layout++CSS grid, full viewport, drag-to-resize on every gutter. Open/closed state for each side panel is persisted in `localStorage`.++```text+┌──────────────────────────────────────────────────────────────────────┐+│ scene-header (56 px) │+├──────────┬───┬─────────────────────────┬───┬─────────────────────────┤+│ │ ↔ │ preview-pane │ ↔ │ transcript-rail │+│ left-rail│ │ │ │ │+│ (tabs + │ │ │ │ │+│ panel) │ │ │ │ │+│ │ │ │ │ │+├──────────┴───┴─────────────────────────┴───┴─────────────────────────┤+│ timeline-resizer (1 px) │+├──────────────────────────────────────────────────────────────────────┤+│ timeline-pane │+└──────────────────────────────────────────────────────────────────────┘+```++- `chatPanelOpen`, `timelinePanelOpen`, `transcriptPanelOpen` — toggle from header.+- Below 980 px viewport, resize handles are disabled (panels stack).+- Chat width default 610 px, transcript width default 360 px, timeline height default 170 px.++---++## 2. Scene Header (top bar)++Left: **project title** (button → click to rename → inline input; Enter saves, Esc cancels, blur saves). Right: **Export** button + **panel toggle group** (hide/show chat, timeline, transcript — icon swaps between panel-open and panel-closed variants).++- Export is disabled if there are no clips, no session token, or an export job is already running.+- Rename error renders inline under the title.++---++## 3. Left Rail — Tabs++Vertical tab strip on the left edge, 74 px wide. Two tabs:++- **Project** (folder icon) — file and composition browser.+- **Axcut** (mascot icon) — chat.++Selecting a tab auto-opens the chat panel if collapsed.++---++## 4. Project Panel (left rail, "Project" tab)++Scrollable. Two sections.++### 4.1 Compositions+- Up to **4 most recently updated** projects listed, sorted by `updatedAt` desc.+- Active project shows a check mark and "active" highlight.+- Header `+` icon opens the **Projects dialog** (see §10.1).++### 4.2 Files+- **Upload** icon triggers hidden `<input type="file" accept="video/*,.mp4,.mov,.m4v,.webm,.mkv">`.+- Read-only **Search** field (placeholder, not wired).+- **File list**: each row = draggable item, label + duration. Shows one of four transcript-status indicators: `pending` (gray dot), `running` (spinner), `complete` (green dot), `failed` (red dot).+- During upload: row replaced by "Uploading video..." status card with spinner.+- **Click** a file → opens Source Transcript modal (§10.4).+- **Drag** a file into the timeline → drops at pointer time, opens Insert Source dialog (§10.3).+- Hover tooltip clarifies drag vs click.+- Upload errors render inline above the list.++---++## 5. Axcut Panel — Chat (left rail, "Axcut" tab)++Three vertical blocks: header, messages (scrollable), composer (sticky).++### 5.1 Chat header+Header row of icon buttons (icon + tooltip; text on hover via `title`):++- **Context pill** — `% context` fill of the model window; tooltip shows prompt tokens / window.+- **Worktree pill** — current worktree branch or path, click opens Worktrees dialog. Only when a session is active.+- **Worktrees button** — same target.+- **Compact context button** — triggers `compact_context`; disabled when no active session, compaction pending, or chat in flight.+- **Settings (gear)** — opens Provider Settings modal, initial screen = "settings".+- **History** — opens Conversation History dialog.+- **New chat** — creates a fresh session and activates it.++Subheader: active session title (or "New conversation"). Read-only.++### 5.2 Messages area+Auto-scroll to bottom while near bottom. Scroll up = manual mode (auto-scroll suspends).++Each message is one of `user | assistant | system`. Renders:+- Role label (`you`, `Axcut`, or system), timestamp.+- Content paragraph.+- Per-message action row (appears on hover):+ - **Rewind** (back arrow) — only on user messages with a checkpoint. Opens a confirmation popover ("Rewind here? Project, conversation, and agent state will be restored." Cancel / Rewind). Sends a rewind request; on success the prompt is pre-filled with the rewound message and live-run state resets.+ - **Copy** — copies message text to clipboard.++Empty state: "No messages in this conversation yet." or, with no project, "Start the server with AXCUT_VIDEO_PATH set to a local video file."++### 5.3 Live-run feed (appended below messages while running)+Cards shown only while the agent is active. Disappears when no run is in flight:+- **Thinking** card — agent's streamed reasoning text (Brain icon).+- **Operation card** — one per tool/operation (Brain / Terminal / Wrench icon + label + status pill `Running`/`Done`/`Error`, optional one-line summary, expandable "Show details" with full body).+- **Context compacted** card — short compaction summary + source tag.+- **Streaming assistant draft** — assistant reply as it streams; ends when the final message arrives.+- **Run indicator** — 9-dot animated bar at the bottom while active.++### 5.4 Composer+- Multi-line textarea (2 rows), placeholder "Describe the edit you want." Resize vertical.+- `Enter` sends, `Shift+Enter` inserts newline.+- **Provider pill** (sliders icon + `provider / model`) — click opens Provider Settings popover; opens on "models" if ready, on "providers" otherwise.+- **Reasoning pill** — only shown when the model supports it; shows current level (e.g. "Reasoning medium"). Click opens the Reasoning popover with the six levels (`none / minimal / low / medium / high / xhigh`).+- "Waiting for the agent response…" muted text while the first byte is pending.+- **Send button** (paper plane) — disabled until there is a project, a session token, a configured LLM, non-empty trimmed text, and no in-flight chat. Icon swaps to a spinner mid-send.+- Inline error message under the form when the chat request fails.++---++## 6. Preview Pane (center)++Two stacked `<video>` layers (A/B) for buffer-and-swap at clip boundaries, plus a controls bar. Renders the **playback timeline** (timeline minus skip ranges).++### 6.1 Video frame+- Layers preload the next clip before its boundary (cross-fade by swapping active layer).+- States shown as overlay text:+ - `loading` — "Loading preview media..."+ - `error` — "Video preview could not be loaded."+ - `idle` / no sources — "Attach a video to start previewing." placeholder.+- Click on the frame toggles play/pause.+- Fullscreen toggle via the controls (button); the frame itself responds to the Fullscreen API.++### 6.2 Controls bar (under frame)+- **Play / Pause** (icon swaps), disabled if no clips or not ready.+- **Restart** — seek to 0.+- **Fullscreen** — enter / exit fullscreen on the frame.+- **Time readout** — `MM:SS.mmm / MM:SS.mmm` (current / total virtual duration).+- **Range slider** — scrub through the virtual duration; thumb progress is color-filled; click jumps, drag scrubs. Disabled until ready.++The current playback position drives the transcript cue highlight, the timeline playhead, and the time readout in the timeline header.++---++## 7. Transcript Rail (right)++Header "Current Transcription". Below, one of three states:+- "No timeline clips yet."+- "No transcript is available for timeline clips yet."+- **ContentEditable transcript view** (one block per clip, in timeline order):+ - Per-clip header: numbered badge, asset label, `Clip N · start - end`.+ - Words rendered as `<span data-word-id>`. Per-word class: `kept | cut`, optional `cue` (current playback position) and `silence` (gap tokens shown as `(0.5s)`).+ - **Kept runs** group kept words; **cut runs** group skipped words and show a hover-revealed trash button (Removes skip).+ - Whole region is `contentEditable` (disabled while `busy`); typing/pasting is blocked; only deletions are meaningful.++### 7.1 Interactions+- **Click a word** → seek preview to that source time; auto-scroll to the cue word if it leaves the viewport.+- **Select a range of words** with the mouse → press `Backspace` or `Delete` (or fire the `deleteContent*` input event) → adds a skip range for those words (only kept words; cross-asset selection is ignored).+- **Backspace/Delete at a collapsed caret** deletes the adjacent kept word (Backward = Backspace, Forward = Delete), producing a one-word skip.+- **Trash button** on a cut run → removes that skip.+- **Caret moves with arrow keys** → preview seeks to the new caret's interpolated time.+- Auto-scroll keeps the cue word visible with a 56 px top/bottom margin.++---++## 8. Timeline Pane (bottom)++Header row + viewport + navigator strip.++### 8.1 Header+- Left: title "Timeline", subtitle `N clips · M skips · total duration`.+- Right:+ - **Scissors button** — toggles "place-skip" mode. While active, hover shows a vertical placement marker; click anywhere in the timeline creates a skip at that source time. Disabled while busy or no clips.+ - Current timeline time, plus "Clip i/N" or "No active clip".++### 8.2 Viewport (scrollable)+Ruler + clip lane + overlays.+- **Ruler** with major/minor ticks; major ticks labelled with `mm:ss.s`.+- **Clip blocks** — one per timeline clip in playback order. Each shows:+ - A skip strip across the top (small dim segments at skip positions).+ - A body with the asset label, `timeline start - end`, and `source start - end`.+ - **Edit (pencil) button** → opens the Clip Edit modal.+- **Clip selection / drag**: pointer-down on a clip starts a drag-to-reorder. Threshold (6 px) before it engages; once dragging, the clip snaps to the nearest drop position with a vertical reorder marker. Releasing dispatches `move_clip`.+- **Click a clip** → selects it (highlight).+- **Hover a skip** → skip-hover-controls appear above the strip with:+ - `‹` resize handle (only if the skip is not pinned to the clip edge).+ - Trash button (remove skip).+ - `›` resize handle.+ - Drag the handles to adjust start/end (`update_skip_range`).+- **Playhead** — vertical line at the current source time.+- **Pending cut marker** — vertical preview line in scissors mode.+- **Reorder marker** — vertical line during drag-to-reorder.++### 8.3 Interactions on the empty surface+- **Click / drag** → scrub (preview seeks on every move).+- **Alt + drag** or **middle-button drag** → pan horizontally when the visible window is narrower than the source duration.+- **Ctrl + wheel** → zoom (in/out by 1.18×), anchored at the cursor X.+- **Drop an asset** (`application/x-axcut-asset`) → opens Insert Source dialog.+- **Wheel** without Ctrl → default page scroll.++### 8.4 Navigator strip (under viewport)+Horizontal overview with skip markers. A draggable window shows the currently visible range:+- Drag the **body** → pan.+- Drag the **left handle** → resize window from the start.+- Drag the **right handle** → resize window from the end.++### 8.5 Clip Edit modal+- Title "Edit clip", subtitle asset label, close (X) button.+- Left: Virtual preview of the source range only.+- Right: start / end / duration readouts, source-range track with draggable handles (start / end), reset / cancel / apply.+- Apply dispatches `update_clip_range` and closes.+- Esc closes the dialog.++---++## 9. Modals & Popovers++All modals: backdrop click closes; Esc closes (where wired).++### 9.1 Projects dialog (LoadVideoDialog)+Opens from the `+` button next to Compositions.+- Left column: "Recent projects" (up to 8, sorted by `updatedAt`); each row shows title + date, active gets "Open" pill.+- Right column: "New project" with description and `+ New project` button. Inline error on failure. New project becomes the active project, dialog closes.++### 9.2 Conversation History dialog+- Lists every session for the active project: title, message count, last-update date.+- Active session shows "Active" pill.+- Per-row: **Rename** (pencil → inline editor → save), **Delete** (trash, disabled if only one session remains).+- Click on the main body switches to that session and closes.++### 9.3 Worktrees dialog+- "Main workspace" entry (the repo checkout) + each available worktree (branch name, full path, "Locked" pill when applicable, "Active" pill when selected).+- **Create** button → `createWorktree`.+- **Select** → activates that worktree.+- Trash → removes (disabled when locked).++### 9.4 Source Transcript modal+- Header: "Source Transcript" + asset label (or artifact filename).+- Top: source-only video preview (full asset range).+- Toolbar: status pill (`Not generated yet / Generating / Generated / Generation failed`), `Detected language: xx`, language selector for regeneration (`auto / en / fr / de / es / it / pt / nl / ja / ko / zh`), **Regenerate transcript** button (spinner while running).+- Body: `<pre>` showing the raw transcript artifact text, with loading state and error copy.+- Closing clears the modal.++### 9.5 Provider Settings — opening surfaces+Same component, two surfaces:+- **Popover** anchored at the provider pill / gear: starts on `models` or `providers` depending on readiness.+- **Modal**: starts on `settings` (from gear) or `provider-form` (from edit).++Screens (deep-linking via `initialScreen`, back-arrow on top-left):+- **Models** — provider label, current model, model search input, scrollable model list (`Active` marker on the selected one). If the saved login is expired, shows **Reconnect**. If a device challenge is open: code card with the user code, copy button (turns into check + "Copied"), "Open login page" external link.+- **Providers** — grid of connected providers; pick one → Models screen. `Provider settings` button at the bottom.+- **Provider Settings (settings screen)** — list of connected providers with per-row edit; `+ Add provider` button.+- **Add Provider (provider-create-select)** — list of available providers; pick one → provider form (create mode).+- **Provider form** — provider label, description (e.g. "Sign in with your ChatGPT account."), Model select (populated when connected; shows "Connect this provider to load…" otherwise), Reasoning effort select (when supported), Base URL input (when required), API key input (password; placeholder notes "Leave blank to keep stored key" when connected). Buttons:+ - `Disconnect` (danger, only when connected).+ - `Connect` / `Update key` / `Start login` / `Reconnect login` (label depends on whether the provider uses OAuth and whether it is connected).+ - `Use provider` (commits the selected model and closes the modal/popover).+ - Device challenge panel appears in-form for OAuth providers, identical to the Models screen card.++Backdrop click on the popover closes; on the modal, click on the backdrop also closes.++### 9.6 Reasoning popover+Anchored at the reasoning pill. Lists the six reasoning-effort options with the current one marked `Active`. Selecting dispatches an update and closes.++### 9.7 Insert Source modal+Triggered by dropping an asset onto the timeline. Header shows source label and insertion time. Three choices:+- **Add before** — insert the whole source before the target clip.+- **Add after** — insert the whole source after the target clip.+- **Split here and insert** — split the target clip at the drop point and insert the source in between.++### 9.8 Rewind confirmation popover+Anchor-below the rewind button. "Rewind here?" + warning copy. Cancel / Rewind.++---++## 10. Status & Feedback Surfaces++### 10.1 Status chips+Inline chips for two jobs:+- **Transcription** — `idle | running | ready | error`; label + detail (e.g. "120 segments · 1840 words · en"); progress fill on the dot.+- **Export** — `idle | running | ready | error`; on `ready` adds a **MP4 download** button (anchored `<a download>`).++### 10.2 File transcript indicators+Four-state dot in the Files list (see §4.2).++### 10.3 Live-run visual signals+Thinking/operation/compaction cards + streaming draft + run indicator (see §5.3).++### 10.4 Errors+- Per-mutation inline error message under the relevant form / button.+- Provider Settings surfaces a `reconnectRequired` banner when the saved credential no longer works.++---++## 11. Conversation Lifecycle (end-to-end flow)++1. User lands on the app → first project auto-selected if any.+2. Empty state: chat shows "Start the server with AXCUT_VIDEO_PATH set to a local video file." if no project; otherwise the chat says "No messages in this conversation yet."+3. If LLM is not configured: send button is disabled, provider pill shows "LLM not configured". User clicks it → Provider Settings popover.+4. User configures a provider (API key or OAuth device flow), selects a model, closes popover.+5. User opens the Project tab → uploads a file (drag-and-drop or button). File appears with `running` indicator; ffmpeg probes + creates proxy + Whisper transcribes.+6. User can switch to the file's transcript modal to inspect / regenerate it.+7. User drags the file into the timeline, or asks the agent to "Add this file to the timeline." Drop → Insert Source dialog → timeline now has a clip.+8. User asks the agent to edit: e.g. "Remove silences and hesitations." → live-run feed streams thinking + operations → final assistant message + applied timeline edits.+9. User reviews transcript; selects words and presses Backspace to add manual skips; drags skip edges in the timeline to fine-tune; clicks the pencil on a clip to retune its source range.+10. User scrubs the preview, watches it, adjusts again.+11. User clicks **Export** → render job queued → progress chip → MP4 download button.+12. User opens History, switches to a previous session, or **Rewinds** to an earlier user message to undo a chain of edits.+13. User closes the panel group via header toggles; positions persist.++---++## 12. Models (LLM Providers)++Configured from the UI; stored credentials live in the `axcut-data` volume (Docker) or `.env` (manual). Source for the live key shown in the provider card (`stored` vs `environment`).++| Provider | Auth | Notes |+|---|---|---|+| OpenAI | API key | Optional base URL for compat. |+| Anthropic | API key | |+| Google (Gemini) | API key | |+| Mistral | API key | |+| OpenRouter | API key | |+| OpenAI-compatible | API key + base URL | Required base URL. |+| GitHub Copilot | OAuth (device flow) | "Sign in with your GitHub account." |+| MiniMax | API key | |+| ChatGPT / OpenAI account | OAuth (device flow) | "Sign in with your ChatGPT account." |++- **Reasoning effort**: shown as a pill next to the provider pill when the active model supports it. Values: `none, minimal, low, medium, high, xhigh`. Selection persists for that provider/model.+- **Device flow** sequence: user clicks Connect → server returns `userCode`, `verificationUri(Complete)`, `intervalMs`, `expiresAt` → UI shows code card → user copies the code, opens the verification URL, approves → UI polls until complete → provider becomes Connected, models load, user picks one.+- **Reconnect**: when the server reports `provider_auth_expired` / `reconnectRequired`, the Models screen shows a **Reconnect** button and the provider-form banner explains that the saved credential no longer works.++---++## 13. Keyboard Shortcuts & Gestures++| Where | Input | Action |+|---|---|---|+| Chat composer | `Enter` | Send message |+| Chat composer | `Shift+Enter` | Newline |+| Transcript view | `Backspace` / `Delete` | Skip selected / adjacent kept word |+| Transcript view | Arrow keys | Move caret → preview seeks |+| Transcript view | `Cmd/Ctrl + A` then type/paste | Blocked (only deletion is allowed) |+| Timeline viewport | Click / drag | Scrub preview |+| Timeline viewport | `Alt` + drag or middle-button drag | Pan |+| Timeline viewport | `Ctrl/Cmd` + wheel | Zoom around cursor |+| Timeline ruler / clip / drop | Drop asset | Open Insert Source dialog |+| Clip block | Drag | Reorder clip |+| Skip strip | Drag `‹` / `›` | Resize skip |+| Skip strip | Hover, click trash | Remove skip |+| Skip strip | Click | (no action; selection is in transcript) |+| Clip edit pencil | Click | Open Clip Edit modal |+| Header toggles | Click | Show/hide chat / timeline / transcript panels |+| Resize gutters | Drag | Resize panels (persisted) |+| Modals | `Esc` / backdrop click | Close |+| Rewind popover | `Esc` / outside click | Cancel |+| Rename title | `Enter` save / `Esc` cancel | Rename project |++---++## 14. Persistence++- Panel open/closed flags and widths/heights: `localStorage` (`axcut.workbench.*`).+- Provider credentials, selected provider/model, reasoning effort: server-side (`.axcut-data` volume) with `.env` override.+- Project state, transcripts, jobs, sessions, checkpoints, worktrees: server-side JSON under `.axcut-data`.+- The UI revalidates on a 5-second poll and via SSE stream (`/api/projects/:id/stream`) for live updates.++---++## 15. Streaming Events (UX-visible effects)++The UI subscribes to the project SSE stream. Visible behaviours:+- `job.progress` / `job.completed` / `job.failed` → status chips and file-list indicators update.+- `project.transcript.updated` → transcript modal reloads, source-transcript query invalidates.+- `project.revision.created` → timeline re-renders (clip / skip changes).+- `preview.ready` → preview reloads the affected layer.+- `agent.message.user / assistant / delta` → messages list and live-run draft update.+- `agent.thinking.delta` → Thinking card text streams.+- `agent.operation` → operation card enters/updates/exits.+- `agent.compaction` → Context-compacted card appears; live-run state resets.+- `agent.checkpoint.*` → rewind availability per user message updates.+- `agent.session.*` → header session title and History list update.++---++## 16. Empty / Failure / Disabled States++- No project → chat empty copy + disabled send; Project panel shows "No compositions yet." / "No files in this project."+- No LLM configured → provider pill says "LLM not configured"; send disabled.+- No clips → timeline shows "No virtual clips yet."; export disabled; preview shows placeholder; transcript shows empty copy.+- Transcription not ready → status chip `Transcription waiting` / `Preparing transcription`; transcript view shows "No transcript is available…".+- Transcription failed → status chip `Transcription failed` + reason; file list shows red dot.+- Export queued / running → button label "Exporting", disabled until the job completes or fails.+- Export failed → status chip `Export failed` + reason.+- Models loading → list shows "Loading models..."; search input disabled.+- Reconnect required → Reconnect button on Models screen; banner in provider form.+- OAuth pending → device challenge card replaces the connect button until complete or expired.+- Drop on empty timeline (no clips) → still opens Insert Source modal, but the three buttons disable when the asset has no probed duration yet.\ No newline at end of filediff --git a/docs/openscreen-ux-ui-spec.md b/docs/openscreen-ux-ui-spec.mdnew file mode 100644index 000000000..891d863b5--- /dev/null+++ b/docs/openscreen-ux-ui-spec.md@@ -0,0 +1,570 @@+# OpenScreen — Complete Front-End UX/UI Specification++This spec covers everything a user can do, see, and trigger from the **renderer (front web app)** of OpenScreen, across all four windows the app loads.++## 1. Application surface++OpenScreen is an Electron + React renderer. The URL `?windowType=...` parameter picks which component the renderer shows. The renderer never boots a multi-page SPA — it is one HTML entrypoint with four top-level React components, lazy-loaded where it matters.++| `?windowType=` | Component | Window type | Purpose |+|---|---|---|---|+| _(unset)_ | Static fallback | Main editor | Renders only an `<h1>OpenScreen</h1>` — boot is treated as broken in this branch |+| `hud-overlay` | `<LaunchWindow>` | Transparent, frameless, mouse-passthrough overlay | Floating recording HUD that lives on top of the user's desktop |+| `source-selector` | `<SourceSelector>` | Glassy modal-style picker | Pick a screen or window to record |+| `countdown-overlay` | `<CountdownOverlay>` | Transparent, frameless | Shows `3 · 2 · 1` over the whole desktop before recording starts |+| `editor` | `<VideoEditor>` + `<ShortcutsConfigDialog>` | Standard BrowserWindow with titlebar | The "Studio": preview, timeline, settings, export |++`<VideoEditor>` itself wraps the lazy `<ShortcutsConfigDialog>` so the shortcuts dialog is code-split behind it. The dialog is mounted globally so it can be opened from the inspector panel via `useShortcuts().openConfig()`.++There is also a tray icon and a global app menu (File / Edit / View / Window) defined in `electron/main.ts`. The renderer reacts to:++- Application menu File submenu → New Project (⌘N), Load Project (⌘O), Save Project (⌘S), Save Project As (⌘⇧S).+- Edit menu: standard Undo / Redo / Cut / Copy / Paste / Select All (handled by Electron's native roles).+- View menu: Reload, Force Reload, DevTools, Actual Size, Zoom In/Out, Toggle Fullscreen.+- Tray context menu: shows **Open** while idle; switches to **Stop Recording** while recording.++A single-instance lock guarantees that double-launching focuses the existing window.++---++## 2. `<LaunchWindow>` — Recording HUD overlay++A draggable, mouse-passthrough glassmorphic pill that lives on top of the desktop. Layout and content are designed for a one-click "hit record" workflow.++### 2.1 Top-level layout++The HUD mounts inside a div with `min-w-0 max-w-full overflow-hidden` and a `body { background: transparent }` override. The bar itself is `fixed bottom-5 left-1/2 -translate-x-1/2`, drag handle to the left, controls in the centre, window controls to the right. The window is mouse-ignored by default (`setHudOverlayIgnoreMouseEvents(true)`); it only becomes interactive when the user hovers a button or opens a popup.++The window auto-resizes to fit content via a `ResizeObserver` and `window.electronAPI.setHudOverlaySize(w, h)`. Padding ensures the shadow isn't clipped and a system-language prompt can pop up above the bar without overlap.++### 2.2 Controls (left → right, horizontal mode is default)++Every control is also vertically stackable — the layout toggle is the first button in the bar (Columns3 / Rows3 icons). The choice is persisted in `localStorage` as `userPreferences.trayLayout`.++1. **Drag handle** — six-dot grip, pointer-captured. Drag moves the HUD overlay (`moveHudOverlayBy`); releases re-ignore mouse events.+2. **Layout toggle** — swaps between horizontal (`Columns3` icon, default) and vertical (`Rows3` icon, `aria-pressed=true` when vertical). Tooltip "Use vertical tray" / "Use horizontal tray".+3. **Source picker button** — screen icon + truncated source name (e.g. "Entire Screen"). Disabled during recording. Opens `<SourceSelector>` window. Selection is mirrored in the bar every 500ms and whenever the source changes (so the label updates without polling the user).+4. **Audio group** — three buttons in a single rounded container:+ - System audio (`MdVolumeUp` / `MdVolumeOff`). Disabled during recording.+ - Microphone (`MdMic` / `MdMicOff`). When enabled and not recording, an **Audio Level Meter** + mic picker pop-up appears above the bar: shows the current mic name (truncated), a `<select>` of all `getUserMedia` microphones, and a 5-bar level meter driven by `useAudioLevelMeter` (FFT analyser, smoothing 0.8). Pop-up collapses on mouse leave / blur.+ - Webcam (`MdVideocam` / `MdVideocamOff`). When enabled and not recording, a webcam pop-up shows the camera label + `<select>` and gracefully handles `Searching…`, `Camera unavailable`, `No camera found` states.+5. **Cursor mode** (only on macOS / Windows, hidden on Linux) — toggles between `editable-overlay` (default, OpenScreen draws a stylised cursor you can theme/edit) and `system` (record OS cursor as-is).+6. **Record/Stop button**:+ - When idle and a source is selected: pill with the red **record** icon, plus the source name on hover.+ - When idle and no source: same pill but greyed, clicking it opens the Source Selector first and then auto-starts recording once a source is picked (`recordAfterSourceSelectionRef`).+ - When recording: red/amber pill with the **stop** icon plus a `mm:ss` elapsed timer (`formatTimePadded`) that ticks up live. Background turns red while running, amber when paused.+7. **Recording-state auxiliary buttons** (only while recording):+ - **Pause/Resume** (`BsPauseCircle` ↔ `BsPlayCircle`) — only shown if `canPauseRecording`.+ - **Restart** (`MdRestartAlt`) — throws away current take and starts fresh.+ - **Cancel** (`MdCancel`) — discards the current take without saving.+8. **Open Studio** (`Clapperboard` icon, hidden during recording) — switches to the editor window via `window.electronAPI.switchToEditor()`.+9. **Language button** (right sidebar) — pill labelled with the current locale short name (e.g. "EN"), opens a portal-rendered language menu above the bar. Each item shows the localized language name with a check next to the current one. Click-outside and `Esc` close it. Width is constrained so it doesn't overflow the desktop. The list of locales is pulled from `getAvailableLocales()`.+10. **Window controls** (far right) — `−` (hide HUD, keeps app running) and `×` (close app).++### 2.3 Hover behaviour++- Hover/pointer-enter on the bar enables mouse events on the overlay (`setHudOverlayIgnoreMouseEvents(false)`).+- Pointer-leave disables them again, except while a popup is open.+- The selected source name refreshes every 500 ms plus on `onSelectedSourceChanged`, so the bar stays in sync if a non-OpenScreen app pops a system picker.++### 2.4 System-language prompt++If the OS locale differs from the current UI locale and hasn't been resolved, a glassy card slides in at `top-8 center`:++- Title: "Use your system language?"+- Body: "We detected X as your system language. Do you want to switch OpenScreen to X?"+- Two buttons: **Keep current language** / **Switch to X**. Both resolve the prompt so it never reappears.++### 2.5 Loading and error states++The HUD itself doesn't have an explicit "loading" state — `useScreenRecorder` handles all of that internally. Errors surface via Sonner toasts triggered from the recorder hook:++- "Camera access is blocked. Enable it in system settings to use the webcam."+- "Microphone access denied. Recording will continue without audio."+- "Camera access denied. Recording will continue without webcam."+- "Webcam disconnected." / "Camera not found."+- "System audio not available. Recording without system audio."+- "Recording permission denied. Please allow screen recording."+- "Allow Accessibility access for OpenScreen, then press record again to start the countdown." (macOS)++### 2.6 Countdown integration++When the user hits Record, the recorder calls `window.electronAPI.showCountdownOverlay(value, runId)` to spawn the `<CountdownOverlay>` window. The HUD doesn't itself render numbers — it just waits for the recorder to flip into the recording state.++---++## 3. `<SourceSelector>` — Pick a screen/window++A separate window (no chrome, glass container) that lists available capture sources. The whole window scrolls.++### 3.1 Layout++- Full-viewport glass container with `min-h-screen`, centred content.+- Top: two **tabs** (grid of cards beneath):+ - **Screens (N)** — `id` starts with `screen:`+ - **Windows (N)** — `id` starts with `window:`+- Each tab shows a 2-column, vertically-scrolling grid of thumbnail cards, fixed height `282px`, `overflow-y-auto`.+- Bottom: a sticky footer with `Cancel` and `Share` buttons (`Share` is disabled until a source is picked).++### 3.2 Source card++Each card is a small `<button>` (renders as a div with role) showing:++- 16:9 thumbnail (320×180 requested from `getSources`).+- Source name + small app icon (only when `appIcon` is non-null).+- When selected: bright green border + check badge in the top-right corner.++Selection is single — clicking another card swaps the selection. Clicking the same card again keeps it selected.++### 3.3 Loading state++While `getSources` resolves, the entire body becomes a centred spinner with the label "Loading sources…".++### 3.4 Empty / failure state++If `getSources` returns zero sources (or rejects), the body becomes a centred card:++- Heading "No screens or windows found".+- Body text either "If you just granted screen recording permission, reload this picker. On macOS you may need to reopen OpenScreen." or the load-failed variant.+- **Reload** button — re-invokes `getSources`.++### 3.5 Window lifetime++The selector is opened via `window.electronAPI.openSourceSelector()`. When it closes, the editor / HUD is notified via `onSourceSelectorClosed` so any "record after pick" intent is cancelled.++---++## 4. `<CountdownOverlay>` — 3·2·1++A separate transparent, frameless, `pointer-events: none` window that overlays the desktop.++- Subscribes to `window.electronAPI.onCountdownOverlayValue((value) => …)`. Renders nothing until the first value arrives.+- The countdown number is rendered at `80px` font weight, centred in a `160×160` dark translucent circle with a heavy text shadow.+- The overlay disappears when the recorder hides it (`hideCountdownOverlay`).++---++## 5. `<VideoEditor>` — Studio++This is the largest UI surface. It opens as a standard Electron BrowserWindow with the macOS-style traffic-light buttons (mac) or the platform default (Windows/Linux) and is laid out as a `flex flex-col h-screen` shell.++### 5.1 Top-level structure++```+┌──────────────────────────────────────────────────────────────────────────┐+│ Top bar (h-11, draggable) — language, new recording, load, save │ (WebkitAppRegion: drag)+├──────────────────────────────────────────────────────────────────────────┤+│ EditorEmptyState (only when no video is loaded) │+│ OR │+│ Resizable panel group (vertical, react-resizable-panels) │+│ ┌─────────────────────────────────────────────────────────────┐ │+│ │ Panel (default 67%, 46–76%) │ │+│ │ ┌─────────────────────────────┬──────────────────────────┐ │ │+│ │ │ editor-preview-zone │ editor-settings-rail │ │ │+│ │ │ • Video preview (Pixi) │ • Mode rail + accordion │ │ │+│ │ │ • Playback controls bar │ panels │ │ │+│ │ └─────────────────────────────┴──────────────────────────┘ │ │+│ └─────────────────────────────────────────────────────────────┘ │+│ ═══════════════ resize handle (h-1 hover-glow pill) ═══════════════ │+│ ┌─────────────────────────────────────────────────────────────┐ │+│ │ Panel (default 33%, 24–54%) — TimelineEditor │ │+│ └─────────────────────────────────────────────────────────────┘ │+├──────────────────────────────────────────────────────────────────────────┤+│ Overlays (z-50 / 60): ExportDialog, UnsavedChangesDialog, etc. │+└──────────────────────────────────────────────────────────────────────────┘+```++There is also a global `<Toaster>` (dark Sonner) mounted at the app root for transient notifications.++### 5.2 Top bar (always visible)++Eleven-pixel-tall bar with `WebkitAppRegion: drag` so the user can move the window; child buttons set `WebkitAppRegion: no-drag`. From left to right:++- **Language picker** (`Languages` icon + `<select>` showing 13 locales: en, ar, es, fr, it, ja-JP, ko-KR, pt-BR, ru, tr, vi, zh-CN, zh-TW). Each option uses its localized native name.+- **New Recording** (`Video` icon + label) — opens a confirmation dialog.+- **Load Project** (`FolderOpen` icon + "Load Project") — file picker via `nativeBridgeClient.project.loadProjectFile`.+- **Save Project** (`Save` icon + "Save Project") — saves in place; if not yet saved, prompts for a path.++The macOS-only traffic-light buttons appear in the top-left (handled by Electron, the language selector leaves `ml-14` on macOS to clear them).++### 5.3 Loading and error screens++While `useEditorHistory` and project IPC are still resolving, the editor shows a centred "Loading video…" label on the `#09090b` background. On a hard load error, the editor shows a destructive-tinted error message + a "Load Project" button.++### 5.4 `<EditorEmptyState>` — Studio dashboard++Renders only when no video is loaded. A drop zone occupies the entire region.++- Logo (64×64, opacity 90).+- Heading "No project open" and description.+- Two stacked buttons:+ - **Import Video File…** — opens `window.electronAPI.openVideoFilePicker` and, on success, calls `setCurrentVideoPath`.+ - **Load Project…** — opens `.openscreen` file picker; on success, restores the project.+- Below: list of supported video formats (MP4, MOV, WebM, MKV, AVI, M4V, WMV) and a small "or drag & drop a .openscreen project file here" hint.++**Drag and drop**: dragging a file over the empty state shows a dashed green overlay with an upload icon and the message "Drop project file to open". The drop handler:++- Accepts only `.openscreen` project files (any other file → "Unsupported Format" dialog).+- Resolves the path via `webUtils.getPathForFile` (Electron 32+).+- Calls `loadProjectFileFromPath` and applies the project on success.+- Any other failure (missing path, IPC error, invalid project) → "Could Not Open File" dialog.++Both dialogs are a small rounded modal with an icon, title, body, and a single Close button. The dialog stays on the last error type even during the close animation so the title doesn't flicker.++### 5.5 Studio workspace (video loaded)++The workspace is a `react-resizable-panels` group. The user drags the handle to rebalance preview vs timeline.++#### 5.5.1 Preview zone (left)++A flexible column with two stacked sub-sections:++1. **Preview canvas** — a Pixi.js canvas wrapped by `<VideoPlayback>`. The canvas aspect ratio follows the chosen `aspectRatio` (`16:9`, `9:16`, `1:1`, `4:3`, `4:5`, `16:10`, `10:16`, or `native`). When `isFullscreen` is true, the preview switches to a `fixed inset-0 z-[99999]` overlay; `Esc` exits fullscreen.++ The preview composite layers (back to front):++ - **Background** (`wallpaper`): image / solid colour / CSS gradient chosen in the settings panel.+ - **Screen video** with crop, border radius, padding, shadow, motion blur, blur (background blur).+ - **Webcam composite** — `picture-in-picture` (draggable bubble), `vertical-stack`, `dual-frame`, or `no-webcam`. PiP can be circular, square, rectangle, or pill-shaped, mirrored, sized 10–50% via slider, and optionally "shrinks on zoom" (reactive scaling).+ - **Animated zoom regions** with spring easing, focus-point tweens, and optional 3D rotation (iso / left / right).+ - **Trim cuts** — played back skipping the trimmed segments.+ - **Speed regions** — clips play at the per-region speed (0.25×–16×).+ - **Cursor** — drawn with theme art, smoothing, motion blur, click bounce; clips to canvas bounds when the toggle is on.+ - **Annotations** — text/image/arrow overlays; mosaics as blur shapes.++ Selecting a region in the timeline selects it on the preview and reveals its resize handles. The selected zoom region can be moved and re-anchored by dragging its focus marker in the preview.++2. **Playback controls** — a centred, full-width `max-w-[760px]` floating pill below the preview:+ - Play/Pause button (round, white when paused, glassy when playing).+ - Current time / total duration labels (`m:ss`).+ - Custom range slider (a transparent `<input type=range>` sits over a green progress bar inside a grey track; round white thumb appears on hover).+ - Fullscreen toggle on the right (changes icon Maximize ↔ Minimize).++#### 5.5.2 Settings rail (right)++Two-column shell: a narrow icon rail on the left, an accordion panel on the right. The rail icon toggles which panel is shown. Icons (top → bottom):++- **Background** (palette) — always visible.+- **Effects** (sliders) — always visible.+- **Layout** (panel-top icon) — only enabled when a webcam video is loaded.+- **Timeline** (brackets icon) — always visible; switches the right column to a small panel for the trim waveform toggle.+- **Cursor** (mouse-pointer-click icon) — appears only when the recording has editable cursor data (editable-overlay + native cursor assets).+- **Crop** (crop icon, outside the panel group) — opens the Crop modal.+- **Export** (download icon, anchored to bottom) — opens the export panel.++When a timeline region is selected, the rail is replaced entirely with the region-specific inspector:++- **Selected zoom**: zoom-level editor.+- **Selected trim**: a single Delete button.+- **Selected speed**: speed editor.+- **Selected annotation**: full annotation editor.+- **Selected blur**: blur editor.++The panel scrolls (`overflow-y-auto custom-scrollbar`). At the bottom sits a footer with three support buttons: **Report Bug**, **Save Diagnostics**, **Star on GitHub** (the bug link opens the GitHub issues page in the OS browser).++##### Panel: Background++Three tabs (Image / Colour / Gradient).++- **Image**: a hidden file input + **Upload Custom** button. Only JPG/JPEG/PNG are accepted (`isSupportedBackgroundImageType`). On success, the image becomes a custom thumbnail in the grid (hover shows a red ✕ to remove). Default wallpapers come from `WALLPAPER_PATHS` and render as 32×32 thumbnails; the active one has a green border + ring.+- **Colour**: opens the `<ColorPicker>` component (Block / Palette / Hue wheel). Updates the `wallpaper` state in real time. A 16-swatch palette is also rendered.+- **Gradient**: a 6-column grid of 24 preset CSS gradients. Click applies.++##### Panel: Effects (Video Effects)++Two columns of rounded "control surfaces":++- **Blur BG** — toggle switch (0/1). Toggles Pixi `BlurFilter`.+- **Motion Blur** — slider 0–1, step 0.01. Live numeric display.+- **Shadow** — slider 0–1, step 0.01. `Math.round(value*100)%` numeric.+- **Roundness** — slider 0–64 px, step 0.5. Numeric in px.+- **Padding** — slider 0–100 %, step 1. Disabled when webcam layout is "vertical-stack".++All sliders commit their value when the user releases the thumb (`onValueCommit`). Some update live (`onValueChange`) — e.g. padding uses `updateState` for the live preview and `commitState` on commit.++##### Panel: Layout (Webcam)++Only visible if a webcam video is present.++- **Preset** dropdown — `picture-in-picture` / `vertical-stack` / `dual-frame` / `no-webcam`. Some entries are filtered based on canvas aspect (e.g. vertical-stack only in portrait, dual-frame only in landscape). Switching presets also clears the saved PiP position unless the new preset is PiP.+- **Mirror Webcam** toggle — visible when preset ≠ no-webcam.+- **Shrink on Zoom (Reactive Webcam)** toggle + info-tooltip — only when preset = PiP.+- **Camera Shape** — four small icon-buttons (rectangle / circle / square / rounded), each rendered as an SVG glyph.+- **Webcam Size** slider — 10–50 %.++The webcam bubble can also be dragged around the canvas (mouse-drag) — the position persists as `webcamPosition`.++##### Panel: Cursor++Only rendered when the recording includes editable cursor assets. Toggles:++- **Show Cursor** — master switch.+- **Clip to Canvas** switch + tooltip.+- **Cursor Style** — a strip of icon buttons, one per bundled theme (Default, Hello Kitty & Watermelon, Among Us Sus Knife & Red Animated, etc.). The first is always the default arrow.+- Four sliders: **Size** (0.5–10), **Smoothing** (0–1), **Motion Blur** (0–1), **Click Bounce** (0–5).++##### Panel: Timeline++A single switch — "Show Audio Waveform on Trim Track". Toggling enables/disables the audio peaks waveform background on the trim row (computed in a worker via `useAudioPeaks`).++##### Panel: Crop (modal)++Launched by the Crop icon. It's a centered modal with `max-w-5xl`, backdrop blur, dark background. Shows the current frame painted to a canvas with a draggable crop rectangle. Controls below the canvas:++- Numeric X/Y/W/H inputs (in pixels).+- **Ratio** dropdown: Free / 16:9 / 9:16 / 4:3 / 3:4 / 1:1 / 21:9. Selecting a preset re-runs the crop with the chosen aspect ratio and toggles the lock state.+- Lock/Unlock aspect toggle button (`Lock` / `Unlock` icons).+- "Done" button.++##### Panel: Export++Visible only in Export mode (the bottom-anchored icon in the rail). Layout:++- **Format toggle** — `MP4` / `GIF` segmented buttons.+- **Quality** (MP4 only) — three segmented buttons: 720p / 1080p / Source. Each button can show an "Upscale" sub-label when the source resolution is below the target. The Source button shows the source short side (e.g. `1080p`) as a sub-label.+- **GIF settings** (GIF only) — two segmented selectors side by side: Frame Rate (15/20/25/30 FPS) and Size (Med/Large/Orig). Below: live dimension readout, plus a **Loop GIF** toggle.+- **Save unsaved export** button — visible only when a previous export failed to write to disk; lets the user pick a location for the cached buffer.+- **Export Video** / **Export GIF** primary button (large, green, full width).++#### 5.5.3 Region-specific inspectors (replacing the right panel when something is selected)++##### Inspector: Selected zoom++- Header chip with the current effective scale (`1.25× / 1.5× / 1.8× / 2.2× / 3.5× / 5×`, or a custom decimal).+- Six depth buttons (same scales as above). Clicking sets depth and snaps the custom slider.+- Custom scale slider (1.0×–5.0×, step 0.01). Releasing commits.+- Focus mode (visible only when cursor telemetry exists) — Manual / Auto segmented toggle. Auto makes the camera follow the cursor. Disabled when the global "Auto-Focus all" toggle is on (locked).+- "Hold to preview zoom effect" button — press-and-hold to render the zoom in the preview at the current time; release reverts.+- Focus Position (visible when focus mode ≠ auto) — two numeric inputs X (%) and Y (%). 0 = leftmost/topmost, 100 = rightmost/bottommost.+- 3D Rotation — three buttons: Iso / Left / Right. Click toggles; click again to clear.+- **Delete Zoom** (red destructive button, full width).++##### Inspector: Selected trim++A single red destructive button "Delete Trim Region".++##### Inspector: Selected speed++- Header chip with the current speed (e.g. `1.5×`).+- Five-column grid of speed presets: 0.25×, 0.5×, 0.75×, 1.25×, 1.5×, 1.75×, 2×, 3×, 4×, 5×.+- Custom speed input — decimal text field; Enter or blur commits. Out-of-range (>16×) shows a toast "Speed can't go higher than 16×".+- **Delete Speed Region** button.++##### Inspector: Selected annotation (`<AnnotationSettingsPanel>`)++Top-level tabs: **Text** / **Image** / **Arrow**.++- **Text** tab: a textarea (5 rows) for the text content, then a 2-column block for:+ - Font Family (selectable from 24 built-in families grouped by category: Classic, Editor, Strong, Typewriter, Deco, Simple, Modern, Clean, plus named families like Inter, Plus Jakarta Sans, Space Grotesk, DM Sans, Sora, Manrope, IBM Plex Sans/Serif/Mono, Playfair Display, Merriweather, Lora, Bebas Neue, Oswald, Caveat, Permanent Marker, Fira Code, plus any user-added custom fonts).+ - Font Size (selectable from `[12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 96, 128]`).+ - "Add Custom Font" button → opens `<AddCustomFontDialog>`: paste a Google Fonts `@import` URL and a display name; on success the font appears in the picker and is auto-applied.+ - Text Animation (selectable from: None, Fade, Rise, Pop, Slide Left, Typewriter, Pulse).+ - Formatting toggle group (Bold / Italic / Underline) — single button per state.+ - Alignment toggle group (Left / Centre / Right).+ - Text Color (Block + palette popover).+ - Background Color (Block + palette + clear-to-transparent).+- **Image** tab: a hidden file input + a tall **Upload Image** button. On success, the image is shown as a preview. Supported: JPG, PNG, GIF, WebP. The text content is replaced with the data URL.+- **Arrow** tab (figure annotations): an 8-button grid of arrow directions (Up, Down, Left, Right, Up-Right, Up-Left, Down-Right, Down-Left). Below: Stroke Width slider 1–6, and an arrow Colour block-picker.++Footer of the annotation inspector: **Duplicate** (copies the region with a slight offset) and **Delete Annotation** (red destructive).++##### Inspector: Selected blur (`<BlurSettingsPanel>`)++Only enabled when the `BLUR_REGIONS_ENABLED` flag is on.++- Shape selector (Rectangle / Oval) — two big icon-buttons.+- Colour selector (White / Black).+- **Mosaic Block Size** slider 4–48 px (display: "X px").+- **Delete Annotation** button.++#### 5.5.4 Timeline++A full-width, full-height panel with a fixed toolbar at the top and a `dnd-timeline`-powered canvas underneath.++##### Toolbar++A single rounded "pill" group containing:++- **+ Zoom** (`ZoomIn` icon, green hint) — adds a zoom region at the playhead.+- **Wand (Auto Zoom)** (`WandSparkles` icon) — toggle. When ON, fresh recordings auto-get suggested zoom regions based on cursor dwell moments. Click again to remove auto-generated zooms.+- **ScanEye (Auto-Focus All)** — toggle. When ON, every zoom follows the cursor; per-zoom focus-mode selectors lock.+- **Scissors (Trim)** — adds a trim region at the playhead. Tooltip "Press T to add trim".+- **Speech bubble (Annotation)** — adds a text annotation at the playhead. Tooltip "Press A to add annotation".+- **Blur icon** (when blur is enabled) — adds a blur region at the playhead. Tooltip "Press B to add blur region".+- **Gauge (Speed)** — adds a speed region at the playhead. Tooltip "Press S to add speed".+- **Captions (waveform-with-text icon)** — opens the Auto Captions dialog. Disabled while a transcription is in flight or when no video URL is available.++Right of the toolbar:++- **Aspect Ratio dropdown** (`ChevronDown` icon + current label) — opens a dropdown menu listing `16:9 / 9:16 / 1:1 / 4:3 / 4:5 / 16:10 / 10:16 / Original (native)`. The check shows the active one. Selecting a portrait/landscape-incompatible webcam preset swaps it back to PiP.+- **Scroll / Ctrl+Scroll hints** — small kbd-style hints for panning/zooming the timeline.++##### Timeline body++A scrollable region containing:++- **Time axis** at the top: major markers (with `m:ss` or `h:mm:ss` labels, fractional digits adapt to zoom) plus minor ticks (5 per major). The current time marker is highlighted in green.+- **Playback cursor**: a vertical purple line (`#6C55FF`) with a diamond handle at the top. Drag it to scrub; it auto-pans the timeline when dragged past either edge and snaps to keyframes within 150 ms. A floating tooltip shows the live time while dragging.+- **Five lanes (top to bottom)**:+ - **Zoom** (`Press Z to add zoom` hint when empty) — glassy green blocks. Hover/select reveals the scale (`1.8×`) and a "cursor-follow" indicator when `focusMode === auto`.+ - **Trim** (`Press T to add trim`) — glassy red blocks. When "Show Audio Waveform on Trim Track" is on, the row's background is a canvas-drawn waveform (computed by an audio-peaks worker).+ - **Annotation** (`Press A to add annotation`) — glassy yellow blocks, labelled with the text preview (truncated to 20 chars + ellipsis), "Image" for image type, or "Annotation" fallback.+ - **Blur** (`Press B to add blur region`, only if BLUR_REGIONS_ENABLED) — same yellow glass with the prefix "Blur".+ - **Speed** (`Press S to add speed`) — glassy amber blocks, labelled `1.5×` etc.++Each block has invisible left/right resize caps (8 px wide, cursor `col-resize`) and a floating tooltip that shows `startMs – endMs` during drag/resize. A 2px amber snap guide appears when an edge is within the snap threshold of another region, playhead, or keyframe.++On drag/resize:++- The drag/resize preview is computed without committing until pointer-up.+- Snap targets are other zoom/trim/speed edges (hard push), annotation/blur edges (soft pull only), playhead, keyframes, 0, total duration.+- Overlap with same-kind regions is clamped to neighbours and rejected if still overlapping.+- Snap threshold scales with zoom (~1% of visible range, minimum 50 ms).++**Keyframes** can be added via the configured shortcut. They render as small yellow diamonds at the top of the timeline (rotated 45°). Click selects, drag moves (clamped to `[0, totalMs]`), `Delete`/`Backspace` removes.++**Zoom controls**:++- **Mouse wheel** — pans horizontally. Auto-pan stops when the timeline is already fully visible.+- **Ctrl/Cmd + Scroll** — zooms in/out (resize the visible range while keeping the cursor anchored).++**Click on empty timeline area** — clears any region selection and seeks to the click X.++**Tab** (when the playhead overlaps multiple annotations) — cycles through overlapping annotations, ordered by `zIndex`. **Shift+Tab** cycles backwards.++### 5.6 Auto Captions dialog++Triggered from the timeline's Captions button. Modal dialog (`max-w-md`):++- Title "Auto captions".+- Description: "Choose roughly how many words each caption shows at once. Timing is spread across the words in that phrase."+- Two labelled selects:+ - **Minimum words per caption** — 1–12.+ - **Maximum words per caption** — 1–12 (kept ≥ min).+- **Cancel** / **Generate** buttons.++While generating, a single Sonner toast keeps updating with phases: "Generating captions from audio…" → "Loading speech model (first use downloads ~75 MB)…" → "Transcribing speech…". On success: "Added N captions." If truncation occurred: "Only the first 240 minutes were transcribed." If nothing was heard: "No speech was detected." If the video has no audio: "This video has no usable audio to transcribe."++Captions are inserted as text annotations with `annotationSource: "auto-caption"`. Edits to one auto-caption's style/position are mirrored onto all its siblings.++### 5.7 Export flow++1. User picks **MP4** or **GIF** in the export panel and hits **Export Video** / **Export GIF**.+2. The editor calls `pickExportSavePath(fileName, getExportFolder())` to open a native save dialog. If the user cancels, the flow stops.+3. The export modal opens (`<ExportDialog>`):+ - Centred rounded modal with the project icon, title (`Exporting Video`/`Exporting GIF`), subtitle "This may take a moment…".+ - A progress block:+ - Header row: "Rendering Frames" (or "Compiling" once frames are done) on the left, percentage on the right.+ - A horizontal progress bar — green with a glow; during the indeterminate compile phase it slides left-to-right.+ - Two info cards: "Format" / "Status" and "currentFrame / totalFrames".+ - **Cancel Export** red destructive button.+ - On success, the modal transitions to "Export Complete", showing the file basename and a **Show in Folder** button. A 2-second timer auto-closes the dialog.+ - On error, the title becomes "Export Failed", a red error block appears with the diagnostic message (Reason / Source / Output dims / fps / Codec / Bitrate / `VideoEncoder` availability), and the **Show in Folder** button is gone.+4. A separate Sonner toast also fires: "Video exported successfully" / "GIF exported successfully", with the file path as description and a **Show in Folder** action. The last-used folder is persisted to `userPreferences.exportFolder`.+5. If the write-to-disk step fails but the encode succeeded, the encoded buffer is cached (`unsavedExport`) and a big purple **Choose Save Location** button appears in the export panel until the user saves or starts another export.++### 5.8 Save / Save As / Load / New++- **Save Project** writes the project (`.openscreen` JSON) via the native save dialog. If the project already has a path, it saves in place. On success, the unsaved-changes flag clears and a toast appears: "Project saved to <path>". On cancel: "Project save canceled". On error: "Failed to save project".+- **Save Project As** always prompts for a new path.+- **Load Project** opens a native file picker, then re-applies the project in the editor.+- **New Project** clears the current video path, resets all undoable and non-undoable editor state, and returns to `<EditorEmptyState>`.+- Any of New / Load initiated with unsaved changes opens `<UnsavedChangesDialog>` with three buttons: **Save & New/Load Project**, **Discard & New/Load Project**, **Cancel**.++### 5.9 Closing the window++Closing the editor window while unsaved-changes is true triggers `<UnsavedChangesDialog>` (`close` variant) with **Save & Close** / **Discard & Close** / **Cancel**. Choices route back to the main process via `sendCloseConfirmResponse("save" | "discard" | "cancel")`.++### 5.10 Keyboard shortcuts (global)++Configurable from the `?` icon next to each panel header (opens `<ShortcutsConfigDialog>`):++| Action | Default | Configurable? |+|---|---|---|+| Open App (global) | `Ctrl/Cmd + Shift + O` | ✅ |+| Add Zoom | `Z` | ✅ |+| Add Trim | `T` | ✅ |+| Add Speed | `S` | ✅ |+| Add Annotation | `A` | ✅ |+| Add Blur (when enabled) | `B` | ✅ |+| Add Keyframe | `K` | ✅ |+| Delete Selected | `Del`/`⌫` | ✅ |+| Play / Pause | `Space` | ✅ |+| Copy Selected Region attributes | configurable | ✅ |+| Paste Region attributes | configurable | ✅ |+| Undo | `Ctrl/Cmd + Z` | fixed |+| Redo | `Ctrl/Cmd + Shift + Z` / `Ctrl/Cmd + Y` | fixed |+| Cycle Annotations Forward | `Tab` | fixed |+| Cycle Annotations Backward | `Shift + Tab` | fixed |+| Delete Selected (alt) | `Del` / `⌫` | fixed |+| Frame Back / Forward | `←` / `→` (60 FPS step, ~16.67 ms) | fixed |+| Pan Timeline | `Shift + Ctrl + Scroll` | fixed |+| Zoom Timeline | `Ctrl + Scroll` | fixed |++The Customise Shortcuts dialog lets the user click a row, press a new binding; conflicts show a swap / cancel action. Reserved (fixed) shortcuts show an error toast: "This shortcut is reserved for 'X' and cannot be reassigned." A "Reset to defaults" button restores everything.++A `?` HelpCircle icon in every settings panel header reveals the shortcut cheat sheet (groups: Configurable, Fixed) on hover, with a link to the customize dialog.++---++## 6. Toasts (Sonner)++Mounted once at the app root. Two main styles:++- **Success/info**: dark green icon, brief text.+- **Error**: red icon, title + optional description.++Frequently used messages:++- Recording error notifications (see §2.5).+- Auto-caption lifecycle (see §5.6).+- Project save/load outcomes.+- Export outcomes.+- Copy/Paste of region attributes ("Zoom attributes copied" / "Zoom attributes pasted").+- "No speech was detected." / "Could not generate captions."+- Speed range error "Speed can't go higher than 16×".+- Region placement errors when the cursor sits inside another region (toast with description).++Each toast supports an `action` button (e.g. "Show in Folder" on export success).++---++## 7. Settings / Preferences persisted++Stored in `localStorage["openscreen_user_preferences"]`:++- `padding` (number 0–100)+- `aspectRatio` (one of the 8 valid aspect ratios)+- `exportQuality` (`medium` / `good` / `source`)+- `exportFormat` (`mp4` / `gif`)+- `exportFolder` (string path)+- `projectFolder` (string path)+- `trayLayout` (`horizontal` / `vertical`)++The renderer also calls into the main process for:++- `saveShortcuts` / `updateGlobalShortcut` (Open App key).+- `revealInFolder(path)` — used after export and on the unsaved-export button.+- `pickExportSavePath`, `writeExportToPath` (file system writes).+- `loadProjectFile` / `loadProjectFileFromPath` / `saveProjectFile` / `loadCurrentProjectFile` / `setCurrentVideoPath` / `clearCurrentVideoPath` — project persistence.+- `getSources` / `selectSource` / `getSelectedSource` / `onSelectedSourceChanged` / `onSourceSelectorClosed` — source picker.+- `showCountdownOverlay` / `hideCountdownOverlay` / `onCountdownOverlayValue` — countdown window.+- `startNativeWindowsRecording` / `pauseNativeWindowsRecording` / `resumeNativeWindowsRecording` / `stopNativeWindowsRecording` / `startNativeMacRecording` / `pauseNativeMacRecording` / `resumeNativeMacRecording` / `stopNativeMacRecording` / `isNativeWindowsCaptureAvailable` / `isNativeMacCaptureAvailable` / `requestNativeMacCursorAccess` / `attachNativeMacWebcamRecording` — native recorder pipeline.+- `getCurrentRecordingSession` / `setCurrentRecordingSession` / `setHasUnsavedChanges` / `onRequestSaveBeforeClose` / `onRequestCloseConfirm` — session handoff between recorder and editor.+- `setHudOverlaySize` / `moveHudOverlayBy` / `setHudOverlayIgnoreMouseEvents` — HUD geometry.+- `requestScreenAccess`, `requestCameraAccess`, `openExternalUrl`, `openVideoFilePicker`, `readBinaryFile`, `saveDiagnostic` — utilities.++---++## 8. i18n++- 13 locale JSON files under `src/i18n/locales/<locale>/` (en, ar, es, fr, it, ja-JP, ko-KR, pt-BR, ru, tr, vi, zh-CN, zh-TW) plus a top-level `common.json` shared across them.+- Each translation namespace: `common`, `launch`, `editor`, `settings`, `timeline`, `dialogs`, `shortcuts`.+- `<I18nProvider>` runs on app boot, detects a system-language suggestion (e.g. `zh-CN` on a Chinese machine) and prompts the user to switch via the system-language prompt. After resolution, the prompt never reappears for the same locale pair.+- All UI strings go through `useScopedT("namespace")`; the locale is read by both the renderer and the Electron main process (`electron/i18n.ts`), so menu items stay in sync.++---++## 9. Status summary++If you want a one-paragraph mental model: OpenScreen's front-end is two cooperating surfaces — a **HUD overlay** that captures content (sources, audio, mic, webcam, cursor mode, record/stop/pause/restart/cancel, language, tray layout, minimised window) and a **Studio editor** built around a resizable preview + inspector + timeline that lets the user cut, zoom, speed-change, annotate, blur, theme the cursor, set background/wallpaper/padding/shadow/border-radius/motion-blur, aspect-ratio, crop, layout the webcam (PiP/double/side-by-side/no-webcam), draw auto-captions from audio, save/load `.openscreen` projects, and export to MP4 (720p/1080p/Source) or GIF (15–30 fps, three sizes, optional loop) — all keyboard-driven, fully undoable, with a per-region Copy/Paste clipboard, customisable shortcuts, and 13 locales.\ No newline at end of filediff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.tsnew file mode 100644index 000000000..2a007ce46--- /dev/null+++ b/electron/ai-edition/chat-service.ts@@ -0,0 +1,96 @@+// In-memory chat service. ponytail: no SQLite, no LangGraph, no checkpoints+// for Phase 6 scaffolding. Stores messages per project in a Map. The actual+// LLM call goes through `llm-call.ts` (no LangChain dep — direct fetch to+// the provider's /chat/completions endpoint).+//+// Phase 8 upgrades this to SQLite-backed sessions with checkpoint restore.++import { v4 as uuidv4 } from "uuid";+import type { AiEditionChatMessage, AiEditionChatResult } from "../../src/native/contracts";+import { type ChatMessage, callLlm } from "./llm-call";+import type { LlmConfigStore } from "./llm-config-store";+import { PROVIDER_DEFINITIONS } from "./provider-registry";++const messagesByProject = new Map<string, AiEditionChatMessage[]>();++const SYSTEM_PROMPT =+ "You are an AI video editor. The user is editing a recording in OpenScreen. " ++ "Help them cut silences, tighten pacing, add captions, and rewrite titles. " ++ "Be concise, action-oriented, and reference the timeline or transcript by time when relevant.";++export async function runChat(+ projectId: string,+ message: string,+ llmConfig: LlmConfigStore,+): Promise<AiEditionChatResult> {+ const config = llmConfig.getConfig();+ if (!config) {+ return {+ success: false,+ error: "No LLM provider configured. Open Settings → AI to configure.",+ };+ }++ const def = PROVIDER_DEFINITIONS.find((d) => d.id === config.provider);+ if (!def) {+ return { success: false, error: `Unknown provider: ${config.provider}` };+ }++ const apiKey = llmConfig.getApiKey(def.id, def.envKeys);+ if (!apiKey && def.authKind === "api-key") {+ return {+ success: false,+ error: `No API key for ${def.label}. Add one in Settings → AI.`,+ };+ }++ const history = messagesByProject.get(projectId) ?? [];+ const userMessage: AiEditionChatMessage = {+ id: uuidv4(),+ role: "user",+ content: message,+ createdAt: new Date().toISOString(),+ };+ history.push(userMessage);+ messagesByProject.set(projectId, history);++ const llmMessages: ChatMessage[] = [+ { role: "system", content: SYSTEM_PROMPT },+ ...history.slice(-20).map((m) => ({ role: m.role, content: m.content })),+ ];++ const result = await callLlm({+ provider: config.provider,+ model: config.model,+ apiKey: apiKey ?? "",+ baseUrl: config.baseUrl,+ reasoningEffort: config.reasoningEffort,+ messages: llmMessages,+ });++ if (!result.success || !result.content) {+ return { success: false, error: result.error ?? "Empty response from model." };+ }++ const assistantMessage: AiEditionChatMessage = {+ id: uuidv4(),+ role: "assistant",+ content: result.content,+ createdAt: new Date().toISOString(),+ };+ history.push(assistantMessage);+ messagesByProject.set(projectId, history);++ return {+ success: true,+ assistantMessage,+ };+}++export async function getChatHistory(projectId: string): Promise<AiEditionChatMessage[]> {+ return messagesByProject.get(projectId) ?? [];+}++export function clearChatHistory(projectId: string): void {+ messagesByProject.delete(projectId);+}diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsnew file mode 100644index 000000000..765e7e884--- /dev/null+++ b/electron/ai-edition/document-service.test.ts@@ -0,0 +1,194 @@+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { DocumentNotFoundError, DocumentService, ProjectFileError } from "./document-service";++async function makeTempDir(): Promise<string> {+ const base = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-ai-edition-"));+ return base;+}++describe("DocumentService", () => {+ let tempDir: string;+ let service: DocumentService;++ beforeEach(async () => {+ tempDir = await makeTempDir();+ service = new DocumentService(tempDir);+ });++ afterEach(async () => {+ await fs.rm(tempDir, { recursive: true, force: true });+ });++ describe("createProject", () => {+ it("creates a v3 doc with the given title and writes it to disk", async () => {+ const doc = await service.createProject("Demo Project");+ expect(doc.schemaVersion).toBe(3);+ expect(doc.project.title).toBe("Demo Project");+ expect(doc.project.id).toMatch(/^proj_/);+ expect(doc.assets).toEqual([]);++ const filePath = path.join(tempDir, `${doc.project.id}.axcut`);+ const raw = await fs.readFile(filePath, "utf8");+ expect(JSON.parse(raw)).toMatchObject({+ schemaVersion: 3,+ project: { title: "Demo Project" },+ });+ });++ it("falls back to 'Untitled Project' for empty titles", async () => {+ const doc = await service.createProject(" ");+ expect(doc.project.title).toBe("Untitled Project");+ });+ });++ describe("getProject", () => {+ it("returns the doc by id", async () => {+ const created = await service.createProject("Round trip");+ const fetched = await service.getProject(created.project.id);+ expect(fetched.project.id).toBe(created.project.id);+ });++ it("throws DocumentNotFoundError for missing projects", async () => {+ await expect(service.getProject("proj_does-not-exist")).rejects.toBeInstanceOf(+ DocumentNotFoundError,+ );+ });++ it("rejects project ids with path-traversal characters", async () => {+ await expect(service.getProject("../etc/passwd")).rejects.toBeInstanceOf(ProjectFileError);+ await expect(service.getProject("proj/with/slash")).rejects.toBeInstanceOf(ProjectFileError);+ });+ });++ describe("listProjects", () => {+ it("returns summaries sorted by updatedAt desc", async () => {+ const a = await service.createProject("A");+ await new Promise((r) => setTimeout(r, 5));+ const b = await service.createProject("B");+ const summaries = await service.listProjects();+ expect(summaries.map((s) => s.id)).toEqual([b.project.id, a.project.id]);+ expect(summaries[0]?.title).toBe("B");+ });++ it("skips files that fail to parse rather than throwing", async () => {+ const a = await service.createProject("OK");+ await fs.writeFile(path.join(tempDir, "garbage.axcut"), "not json", "utf8");+ const summaries = await service.listProjects();+ expect(summaries.map((s) => s.id)).toEqual([a.project.id]);+ });+ });++ describe("addAsset", () => {+ it("appends a video asset and sets primaryAssetId on the first add", async () => {+ const doc = await service.createProject("P");+ const updated = await service.addAsset(doc.project.id, {+ path: "/tmp/screen.mp4",+ label: "Screen",+ });+ expect(updated.assets).toHaveLength(1);+ const asset = updated.assets[0];+ expect(asset?.kind).toBe("video");+ expect(asset?.originalPath).toBe("/tmp/screen.mp4");+ expect(asset?.label).toBe("Screen");+ expect(updated.project.primaryAssetId).toBe(asset?.id);+ });++ it("resolves relative paths against the cwd", async () => {+ const doc = await service.createProject("P");+ const updated = await service.addAsset(doc.project.id, { path: "recording.webm" });+ expect(path.isAbsolute(updated.assets[0]?.originalPath ?? "")).toBe(true);+ });++ it("rejects unsupported video extensions", async () => {+ const doc = await service.createProject("P");+ await expect(+ service.addAsset(doc.project.id, { path: "/tmp/audio.mp3" }),+ ).rejects.toBeInstanceOf(ProjectFileError);+ });++ it("preserves primaryAssetId when adding a second asset", async () => {+ const doc = await service.createProject("P");+ const first = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });+ const after = await service.addAsset(doc.project.id, { path: "/tmp/b.mp4" });+ expect(after.project.primaryAssetId).toBe(first.project.primaryAssetId);+ expect(after.assets).toHaveLength(2);+ });+ });++ describe("removeAsset", () => {+ it("removes the asset and cascades clips + skipRanges", async () => {+ const doc = await service.createProject("P");+ const withAsset = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });+ const assetId = withAsset.assets[0]?.id;+ expect(assetId).toBeTruthy();++ // Manually add a clip + skipRange so we can verify cascade+ const docWithTimeline = await service.saveProject({+ ...withAsset,+ timeline: {+ ...withAsset.timeline,+ clips: [+ {+ id: "clip_1",+ assetId,+ sourceStartSec: 0,+ timelineStartSec: 0,+ timelineEndSec: 1,+ wordRefs: [],+ origin: "system",+ },+ ],+ skipRanges: [+ {+ id: "skip_1",+ assetId,+ startSec: 0,+ endSec: 1,+ origin: "user",+ },+ ],+ },+ });++ const after = await service.removeAsset(docWithTimeline.project.id, assetId ?? "");+ expect(after.assets).toHaveLength(0);+ expect(after.timeline.clips).toHaveLength(0);+ expect(after.timeline.skipRanges).toHaveLength(0);+ expect(after.project.primaryAssetId).toBeUndefined();+ });++ it("reassigns primaryAssetId when removing the primary", async () => {+ const doc = await service.createProject("P");+ const a = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });+ const b = await service.addAsset(doc.project.id, { path: "/tmp/b.mp4" });+ const primaryId = a.project.primaryAssetId;+ expect(primaryId).toBeTruthy();+ const after = await service.removeAsset(doc.project.id, primaryId ?? "");+ expect(after.project.primaryAssetId).toBe(b.assets[1]?.id);+ });++ it("throws when removing a missing asset", async () => {+ const doc = await service.createProject("P");+ await expect(service.removeAsset(doc.project.id, "asset_x")).rejects.toBeInstanceOf(+ ProjectFileError,+ );+ });+ });++ describe("deleteProject", () => {+ it("removes the .axcut file", async () => {+ const doc = await service.createProject("Bye");+ await service.deleteProject(doc.project.id);+ await expect(service.getProject(doc.project.id)).rejects.toBeInstanceOf(+ DocumentNotFoundError,+ );+ });++ it("is a no-op when the file doesn't exist", async () => {+ await expect(service.deleteProject("proj_never-existed")).resolves.toBeUndefined();+ });+ });+});diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.tsnew file mode 100644index 000000000..31d842eeb--- /dev/null+++ b/electron/ai-edition/document-service.ts@@ -0,0 +1,227 @@+// DocumentService — main-process owner of v3 AxcutDocument projects.+// Persists one .axcut JSON per project under userData/projects/. Slim port of+// axcut's apps/server/src/services/document-service.ts (no separate paths.ts —+// uses app.getPath("userData") directly; no Python probe_media — assets carry+// only path metadata, duration is filled in by the renderer).+//+// ponytail: Phase 1 surface area is intentionally narrow (list / get / create+// / save / addAsset / removeAsset). ops/history/agent runtime land in Phase 6.++import fs from "node:fs/promises";+import path from "node:path";+import { createId } from "../../src/lib/ai-edition/document/ids";+import {+ type AxcutAsset,+ type AxcutDocument,+ createEmptyDocument,+ documentSchema,+} from "../../src/lib/ai-edition/schema";++const PROJECT_FILE_EXTENSION = ".axcut";++export interface ProjectSummary {+ id: string;+ title: string;+ updatedAt: string;+ assetCount: number;+}++export interface AddAssetInput {+ path: string;+ label?: string;+}++export class DocumentNotFoundError extends Error {+ constructor(public readonly projectId: string) {+ super(`Project not found: ${projectId}`);+ this.name = "DocumentNotFoundError";+ }+}++export class ProjectFileError extends Error {+ constructor(+ message: string,+ public readonly projectId?: string,+ ) {+ super(message);+ this.name = "ProjectFileError";+ }+}++const SUPPORTED_VIDEO_EXTENSIONS = new Set([+ ".mp4",+ ".mov",+ ".m4v",+ ".webm",+ ".mkv",+ ".avi",+ ".wmv",+]);++function isSupportedVideoPath(filePath: string): boolean {+ const ext = path.extname(filePath).toLowerCase();+ return SUPPORTED_VIDEO_EXTENSIONS.has(ext);+}++function safeProjectId(raw: string): string {+ // ponytail: project ids are uuid-prefixed strings (e.g. "proj_<uuid>"). Reject+ // anything that smells like path traversal before we ever touch the disk.+ if (!/^[A-Za-z0-9_-]+$/.test(raw)) {+ throw new ProjectFileError(`Invalid project id: ${raw}`);+ }+ return raw;+}++export class DocumentService {+ private readonly projectsRoot: string;++ constructor(projectsRoot: string) {+ this.projectsRoot = projectsRoot;+ }++ async ensureProjectsDir(): Promise<void> {+ await fs.mkdir(this.projectsRoot, { recursive: true });+ }++ private fileFor(projectId: string): string {+ const safe = safeProjectId(projectId);+ return path.join(this.projectsRoot, `${safe}${PROJECT_FILE_EXTENSION}`);+ }++ async listProjects(): Promise<ProjectSummary[]> {+ await this.ensureProjectsDir();+ const entries = await fs.readdir(this.projectsRoot);+ const axcutFiles = entries.filter((name) => name.endsWith(PROJECT_FILE_EXTENSION));+ const summaries: ProjectSummary[] = [];+ for (const name of axcutFiles) {+ const filePath = path.join(this.projectsRoot, name);+ try {+ const raw = await fs.readFile(filePath, "utf8");+ const parsed = documentSchema.parse(JSON.parse(raw));+ summaries.push({+ id: parsed.project.id,+ title: parsed.project.title,+ updatedAt: parsed.project.updatedAt,+ assetCount: parsed.assets.length,+ });+ } catch (error) {+ // ponytail: skip unreadable files rather than failing the whole list.+ // A future migration pass can recover them.+ console.warn(`[ai-edition] failed to read ${filePath}:`, error);+ }+ }+ summaries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));+ return summaries;+ }++ async getProject(projectId: string): Promise<AxcutDocument> {+ const filePath = this.fileFor(projectId);+ try {+ const raw = await fs.readFile(filePath, "utf8");+ return documentSchema.parse(JSON.parse(raw));+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {+ throw new DocumentNotFoundError(projectId);+ }+ throw new ProjectFileError(+ `Failed to read project ${projectId}: ${error instanceof Error ? error.message : String(error)}`,+ projectId,+ );+ }+ }++ async createProject(title: string): Promise<AxcutDocument> {+ await this.ensureProjectsDir();+ const projectId = createId("proj");+ const doc = createEmptyDocument({+ projectId,+ title: title?.trim() || "Untitled Project",+ });+ await this.writeProject(doc);+ return doc;+ }++ async saveProject(document: AxcutDocument): Promise<AxcutDocument> {+ const parsed = documentSchema.parse(document);+ const stamped: AxcutDocument = {+ ...parsed,+ project: { ...parsed.project, updatedAt: new Date().toISOString() },+ };+ await this.writeProject(stamped);+ return stamped;+ }++ async deleteProject(projectId: string): Promise<void> {+ const filePath = this.fileFor(projectId);+ try {+ await fs.unlink(filePath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {+ throw error;+ }+ }+ }++ async addAsset(projectId: string, input: AddAssetInput): Promise<AxcutDocument> {+ const doc = await this.getProject(projectId);+ if (!input.path) {+ throw new ProjectFileError("Asset path is required.", projectId);+ }+ if (!isSupportedVideoPath(input.path)) {+ throw new ProjectFileError(+ `Unsupported video extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_VIDEO_EXTENSIONS].join(", ")})`,+ projectId,+ );+ }+ const absolutePath = path.isAbsolute(input.path) ? input.path : path.resolve(input.path);+ const asset: AxcutAsset = {+ id: createId("asset"),+ kind: "video",+ label: input.label?.trim() || path.basename(absolutePath),+ originalPath: absolutePath,+ };+ const next: AxcutDocument = {+ ...doc,+ assets: [...doc.assets, asset],+ project: {+ ...doc.project,+ ...(doc.project.primaryAssetId ? {} : { primaryAssetId: asset.id }),+ updatedAt: new Date().toISOString(),+ },+ };+ return this.saveProject(next);+ }++ async removeAsset(projectId: string, assetId: string): Promise<AxcutDocument> {+ const doc = await this.getProject(projectId);+ if (!doc.assets.some((a) => a.id === assetId)) {+ throw new ProjectFileError(`Asset ${assetId} not found in project ${projectId}.`, projectId);+ }+ const assets = doc.assets.filter((a) => a.id !== assetId);+ const primaryAssetId =+ doc.project.primaryAssetId === assetId+ ? (assets[0]?.id ?? undefined)+ : doc.project.primaryAssetId;+ const next: AxcutDocument = {+ ...doc,+ assets,+ timeline: {+ ...doc.timeline,+ clips: doc.timeline.clips.filter((c) => c.assetId !== assetId),+ skipRanges: doc.timeline.skipRanges.filter((r) => r.assetId !== assetId),+ },+ project: {+ ...doc.project,+ primaryAssetId,+ updatedAt: new Date().toISOString(),+ },+ };+ return this.saveProject(next);+ }++ private async writeProject(doc: AxcutDocument): Promise<void> {+ await this.ensureProjectsDir();+ const filePath = this.fileFor(doc.project.id);+ await fs.writeFile(filePath, JSON.stringify(doc, null, 2), "utf8");+ }+}diff --git a/electron/ai-edition/llm-call.ts b/electron/ai-edition/llm-call.tsnew file mode 100644index 000000000..2847b656a--- /dev/null+++ b/electron/ai-edition/llm-call.ts@@ -0,0 +1,170 @@+// Real LLM call via fetch — no LangChain dependency. Supports the+// OpenAI-compatible `/chat/completions` endpoint (OpenAI, Mistral,+// OpenRouter, openai-compatible). Anthropic and OAuth providers stay+// stubbed for now and return a clear "not yet implemented" error.+//+// ponytail: keep this file small and dependency-free so it works in both+// Electron and the browser-mode shim. Streaming is not supported in this+// pass — the chat panel does request/response.++import { PROVIDER_DEFINITIONS, type ProviderDefinition } from "./provider-registry";++export interface ChatMessage {+ role: "system" | "user" | "assistant";+ content: string;+}++export interface CallLlmOptions {+ provider: string;+ model: string;+ apiKey: string;+ baseUrl?: string;+ reasoningEffort?: string;+ messages: ChatMessage[];+}++export interface CallLlmResult {+ success: boolean;+ content?: string;+ error?: string;+}++const REASONING_BY_PROVIDER: Record<string, "low" | "medium" | "high"> = {+ low: "low",+ medium: "medium",+ high: "high",+};++function findProvider(id: string): ProviderDefinition | undefined {+ return PROVIDER_DEFINITIONS.find((p) => p.id === id);+}++function defaultBaseUrl(providerId: string): string {+ switch (providerId) {+ case "openai":+ return "https://api.openai.com/v1";+ case "anthropic":+ return "https://api.anthropic.com/v1";+ case "google":+ return "https://generativelanguage.googleapis.com/v1beta";+ case "mistral":+ return "https://api.mistral.ai/v1";+ case "openrouter":+ return "https://openrouter.ai/api/v1";+ default:+ return "https://api.openai.com/v1";+ }+}++export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {+ const def = findProvider(opts.provider);+ if (!def) {+ return { success: false, error: `Unknown provider: ${opts.provider}` };+ }+ if (!opts.apiKey && def.authKind === "api-key") {+ return { success: false, error: `Missing API key for ${def.label}` };+ }+ // OAuth + PAT providers are not yet wired. Return a clear error.+ if (def.authKind === "oauth-device") {+ return {+ success: false,+ error: `Provider "${def.label}" uses OAuth — device-flow is not implemented yet.`,+ };+ }+ if (def.authKind === "pat") {+ return {+ success: false,+ error: `Provider "${def.label}" uses a personal access token — wire it via env var.`,+ };+ }++ // Anthropic has its own /v1/messages endpoint with a different schema.+ // Wire it separately so the OpenAI-compatible path stays small.+ if (opts.provider === "anthropic") {+ return callAnthropic(opts);+ }++ const baseUrl = (opts.baseUrl || def.baseUrl || defaultBaseUrl(opts.provider)).replace(+ /\/+$/,+ "",+ );+ const url = `${baseUrl}/chat/completions`;++ const body: Record<string, unknown> = {+ model: opts.model || def.defaultModel,+ messages: opts.messages,+ };+ if (def.supportsReasoningEffort && opts.reasoningEffort) {+ body.reasoning_effort = REASONING_BY_PROVIDER[opts.reasoningEffort] ?? opts.reasoningEffort;+ }++ try {+ const res = await fetch(url, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${opts.apiKey}`,+ },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ const text = await res.text();+ return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };+ }+ const json = (await res.json()) as {+ choices?: Array<{ message?: { content?: string } }>;+ };+ const content = json.choices?.[0]?.message?.content;+ if (!content) {+ return { success: false, error: "Empty response from model." };+ }+ return { success: true, content };+ } catch (err) {+ return { success: false, error: err instanceof Error ? err.message : String(err) };+ }+}++async function callAnthropic(opts: CallLlmOptions): Promise<CallLlmResult> {+ const baseUrl = (opts.baseUrl || defaultBaseUrl("anthropic")).replace(/\/+$/, "");+ const url = `${baseUrl}/messages`;+ const systemMessage = opts.messages.find((m) => m.role === "system")?.content;+ const conversation = opts.messages+ .filter((m) => m.role !== "system")+ .map((m) => ({ role: m.role, content: m.content }));++ const body: Record<string, unknown> = {+ model: opts.model || "claude-haiku-4-5",+ max_tokens: 1024,+ messages: conversation,+ };+ if (systemMessage) body.system = systemMessage;+ if (opts.reasoningEffort === "high") {+ body.thinking = { type: "enabled", budget_tokens: 4096 };+ }++ try {+ const res = await fetch(url, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "x-api-key": opts.apiKey,+ "anthropic-version": "2023-06-01",+ },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ const text = await res.text();+ return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };+ }+ const json = (await res.json()) as {+ content?: Array<{ type: string; text?: string }>;+ };+ const text = json.content?.find((b) => b.type === "text")?.text;+ if (!text) {+ return { success: false, error: "Empty response from Anthropic." };+ }+ return { success: true, content: text };+ } catch (err) {+ return { success: false, error: err instanceof Error ? err.message : String(err) };+ }+}diff --git a/electron/ai-edition/llm-config-store.ts b/electron/ai-edition/llm-config-store.tsnew file mode 100644index 000000000..d7e0c50ec--- /dev/null+++ b/electron/ai-edition/llm-config-store.ts@@ -0,0 +1,92 @@+// LLM credential + config storage using Electron's safeStorage (OS keychain).+// Per locked decision 4: no plain JSON for credentials.+//+// ponytail: the config (provider, model, baseUrl, reasoningEffort) lives in+// a plain JSON file; the API keys live in safeStorage-encrypted bytes. Env+// vars override stored keys (same precedence as axcut).++import { readFileSync } from "node:fs";+import fs from "node:fs/promises";+import path from "node:path";+import { safeStorage } from "electron";++export interface LlmConfig {+ provider: string;+ model: string;+ baseUrl?: string;+ reasoningEffort?: string;+}++export interface LlmCredentials {+ [providerId: string]: string;+}++export class LlmConfigStore {+ private readonly configPath: string;+ private readonly credentialsPath: string;+ private config: LlmConfig | null = null;+ private credentials: LlmCredentials = {};++ constructor(userDataPath: string) {+ this.configPath = path.join(userDataPath, "llm-config.json");+ this.credentialsPath = path.join(userDataPath, "llm-credentials.enc");+ this.loadSync();+ }++ private loadSync(): void {+ try {+ const raw = readFileSync(this.configPath, "utf8");+ this.config = JSON.parse(raw);+ } catch {+ this.config = null;+ }+ try {+ const encrypted = readFileSync(this.credentialsPath);+ if (safeStorage.isEncryptionAvailable()) {+ const decrypted = safeStorage.decryptString(encrypted);+ this.credentials = JSON.parse(decrypted);+ }+ } catch {+ this.credentials = {};+ }+ }++ async load(): Promise<void> {+ this.loadSync();+ }++ getConfig(): LlmConfig | null {+ return this.config;+ }++ async setConfig(config: LlmConfig): Promise<void> {+ this.config = config;+ await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), "utf8");+ }++ getApiKey(providerId: string, envKeys: string[]): string | null {+ for (const envKey of envKeys) {+ const envValue = process.env[envKey];+ if (envValue) return envValue;+ }+ return this.credentials[providerId] ?? null;+ }++ async setApiKey(providerId: string, apiKey: string): Promise<void> {+ this.credentials[providerId] = apiKey;+ await this.saveCredentials();+ }++ async removeApiKey(providerId: string): Promise<void> {+ delete this.credentials[providerId];+ await this.saveCredentials();+ }++ private async saveCredentials(): Promise<void> {+ if (!safeStorage.isEncryptionAvailable()) {+ throw new Error("safeStorage is not available on this platform.");+ }+ const encrypted = safeStorage.encryptString(JSON.stringify(this.credentials));+ await fs.writeFile(this.credentialsPath, encrypted);+ }+}diff --git a/electron/ai-edition/provider-registry.ts b/electron/ai-edition/provider-registry.tsnew file mode 100644index 000000000..b9f458f08--- /dev/null+++ b/electron/ai-edition/provider-registry.ts@@ -0,0 +1,87 @@+// Provider definitions for the AI features layer. Static data — no runtime+// deps. Mirrors axcut's apps/server/src/llm/provider-registry.ts.+//+// ponytail: the full provider set (10 providers in axcut). Each entry carries+// enough metadata for the ProviderSettingsDialog to render without hitting the+// network. Actual model creation (create-chat-model) needs @langchain/* deps.++export interface ProviderDefinition {+ id: string;+ label: string;+ defaultModel: string;+ authKind: "api-key" | "oauth-device" | "pat";+ supportsReasoningEffort: boolean;+ envKeys: string[];+ baseUrl?: string;+}++export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [+ {+ id: "anthropic",+ label: "Claude API",+ defaultModel: "claude-haiku-4-5",+ authKind: "api-key",+ supportsReasoningEffort: true,+ envKeys: ["ANTHROPIC_API_KEY"],+ },+ {+ id: "openai",+ label: "OpenAI API",+ defaultModel: "gpt-4o",+ authKind: "api-key",+ supportsReasoningEffort: true,+ envKeys: ["OPENAI_API_KEY"],+ },+ {+ id: "google",+ label: "Gemini API",+ defaultModel: "gemini-2.5-flash",+ authKind: "api-key",+ supportsReasoningEffort: true,+ envKeys: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],+ },+ {+ id: "mistral",+ label: "Mistral API",+ defaultModel: "mistral-large-latest",+ authKind: "api-key",+ supportsReasoningEffort: false,+ envKeys: ["MISTRAL_API_KEY"],+ },+ {+ id: "openrouter",+ label: "OpenRouter",+ defaultModel: "anthropic/claude-3.5-sonnet",+ authKind: "api-key",+ supportsReasoningEffort: true,+ envKeys: ["OPENROUTER_API_KEY"],+ baseUrl: "https://openrouter.ai/api/v1",+ },+ {+ id: "openai-compatible",+ label: "OpenAI-compatible endpoint",+ defaultModel: "",+ authKind: "api-key",+ supportsReasoningEffort: false,+ envKeys: ["OPENAI_COMPATIBLE_API_KEY"],+ },+ {+ id: "openai-oauth",+ label: "ChatGPT (OAuth)",+ defaultModel: "gpt-4o",+ authKind: "oauth-device",+ supportsReasoningEffort: true,+ envKeys: [],+ },+ {+ id: "copilot-proxy",+ label: "GitHub Copilot",+ defaultModel: "gpt-4o",+ authKind: "pat",+ supportsReasoningEffort: true,+ envKeys: ["GITHUB_TOKEN", "GH_TOKEN"],+ },+];++export const REASONING_EFFORT_OPTIONS = ["none", "minimal", "low", "medium", "high"] as const;+export type ReasoningEffort = (typeof REASONING_EFFORT_OPTIONS)[number];diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex f954fc99e..75cc695c7 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -208,7 +208,14 @@ interface Window {getCurrentVideoPath: () => Promise<{ success: boolean; path?: string }>;getCurrentRecordingSession: () => Promise<{success: boolean;- session?: import("../src/lib/recordingSession").RecordingSession;+ session?: RecordingSession | null;+ canceled?: boolean;+ }>;+ findRecordingCamera: (videoPath: string) => Promise<{+ success: boolean;+ webcamVideoPath?: string;+ offsetMs?: number;+ error?: string;}>;readBinaryFile: (filePath: string) => Promise<{success: boolean;diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 852250ec4..d399aa349 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -35,6 +35,9 @@ import type {ProjectFileResult,ProjectPathResult,} from "../../src/native/contracts";+import { clearChatHistory, getChatHistory, runChat } from "../ai-edition/chat-service";+import { DocumentService } from "../ai-edition/document-service";+import { LlmConfigStore } from "../ai-edition/llm-config-store";import { mainLogBuffer } from "../diagnostics/main-log-buffer";import { mainT } from "../i18n";import { RECORDINGS_DIR } from "../main";@@ -2308,6 +2311,36 @@ export function registerIpcHandlers();}+ // ponytail: MediaRecorder occasionally produces a 0-byte file on Windows+ // when the display stream is captured but no frames are produced (the+ // streaming WriteStream was opened but never received any chunks). Detect+ // the bad file here so the recording fails loudly instead of opening the+ // editor on a file the <video> element can't decode. The WebM EBML header+ // alone is ~33 bytes; 1KB rules out a header-only file with no frames.+ const MIN_VALID_BYTES = 1024;+ try {+ const screenStat = await fs.stat(screenVideoPath);+ if (screenStat.size < MIN_VALID_BYTES) {+ await fs.unlink(screenVideoPath).catch(() => undefined);+ if (webcamVideoPath) {+ await fs.unlink(webcamVideoPath).catch(() => undefined);+ }+ return {+ success: false,+ message: `Screen recording is empty (${screenStat.size} bytes). The screen capture did not produce any frames — this can happen on Windows when the display source changes during recording. Try recording again.`,+ };+ }+ } catch (statError) {+ // file missing is fatal; any other stat error is non-fatal, the+ // editor will surface the load error on its own.+ if ((statError as NodeJS.ErrnoException).code === "ENOENT") {+ return {+ success: false,+ message: "Screen recording file is missing on disk.",+ };+ }+ }+// Streamed files lack the WebM Duration header (renderer no longer holds the// blob), so patch on disk for the editor's seek bar and timeline. Best-effort,// independent per file, so they run together.@@ -2937,6 +2970,43 @@ export function registerIpcHandlers(: { success: false };});+ // ponytail: returns the webcam path (if any) for a given screen video by+ // reading its sibling session.json — drives the cameraTrack auto-link on+ // `addAsset` in the new editor's project store.+ ipcMain.handle(+ "find-recording-camera",+ async (+ _event,+ videoPath: string,+ ): Promise<{+ success: boolean;+ webcamVideoPath?: string;+ offsetMs?: number;+ error?: string;+ }> => {+ try {+ const normalized = normalizeVideoSourcePath(videoPath);+ if (!normalized || !isPathAllowed(normalized)) {+ return { success: false, error: "Video path has not been approved" };+ }+ const session = await loadRecordedSessionForVideoPath(normalized);+ if (!session?.webcamVideoPath) {+ return { success: false, error: "No camera attached to this recording" };+ }+ return {+ success: true,+ webcamVideoPath: session.webcamVideoPath,+ offsetMs: 0,+ };+ } catch (err) {+ return {+ success: false,+ error: err instanceof Error ? err.message : String(err),+ };+ }+ },+ );+async function setCurrentVideoPath(path: string): Promise<ProjectPathResult> {const normalizedPath = normalizeVideoSourcePath(path);if (!normalizedPath || !isPathAllowed(normalizedPath)) {@@ -3066,5 +3136,12 @@ export function registerIpcHandlers(normalizeVideoSourcePath(videoPath ?? currentVideoPath),loadCursorRecordingData: readCursorRecordingFile,loadCursorTelemetry: readCursorTelemetryFile,+ getAiEditionDocuments: () =>+ new DocumentService(path.join(app.getPath("userData"), "projects")),+ getAiEditionLlmConfig: () => new LlmConfigStore(app.getPath("userData")),+ runAiEditionChat: (projectId, message) =>+ runChat(projectId, message, new LlmConfigStore(app.getPath("userData"))),+ getAiEditionChatHistory: (projectId) => getChatHistory(projectId),+ clearAiEditionChatHistory: (projectId: string) => clearChatHistory(projectId),});}diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex 2669300a9..73febea2a 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -9,8 +9,10 @@ import {type ProjectFileResult,type ProjectPathResult,} from "../../src/native/contracts";+import type { DocumentService } from "../ai-edition/document-service";import type { CursorTelemetryLoadResult } from "../native-bridge/cursor/adapter";import { TelemetryCursorAdapter } from "../native-bridge/cursor/telemetryCursorAdapter";+import { AiEditionService } from "../native-bridge/services/aiEditionService";import { CursorService } from "../native-bridge/services/cursorService";import { ProjectService } from "../native-bridge/services/projectService";import { SystemService } from "../native-bridge/services/systemService";@@ -37,6 +39,16 @@ export interface NativeBridgeContext {videoPath: string,) => Promise<import("../../src/native/contracts").CursorRecordingData>;loadCursorTelemetry: (videoPath: string) => Promise<CursorTelemetryLoadResult>;+ getAiEditionDocuments: () => DocumentService;+ getAiEditionLlmConfig: () => import("../ai-edition/llm-config-store").LlmConfigStore;+ runAiEditionChat: (+ projectId: string,+ message: string,+ ) => Promise<import("../../src/native/contracts").AiEditionChatResult>;+ getAiEditionChatHistory: (+ projectId: string,+ ) => Promise<import("../../src/native/contracts").AiEditionChatMessage[]>;+ clearAiEditionChatHistory: (projectId: string) => void;}function normalizePlatform(platform: NodeJS.Platform): NativePlatform {@@ -120,6 +132,13 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {getAssetBasePath: context.resolveAssetBasePath,getCursorCapabilities: () => cursorService.getCapabilities(),});+ const aiEditionService = new AiEditionService({+ documents: context.getAiEditionDocuments(),+ llmConfig: context.getAiEditionLlmConfig(),+ runChat: context.runAiEditionChat,+ getChatHistory: context.getAiEditionChatHistory,+ clearChatHistory: context.clearAiEditionChatHistory,+ });ipcMain.handle(NATIVE_BRIDGE_CHANNEL, async (_, request: unknown) => {if (!isBridgeRequest(request)) {@@ -220,6 +239,92 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {}}+ case "aiEdition": {+ const action = request.action as string;+ switch (request.action) {+ case "document.listProjects":+ return createSuccessResponse(requestId, await aiEditionService.listProjects());+ case "document.get":+ return createSuccessResponse(+ requestId,+ await aiEditionService.get(request.payload.projectId),+ );+ case "document.create":+ return createSuccessResponse(+ requestId,+ await aiEditionService.create(request.payload?.title),+ );+ case "document.save":+ return createSuccessResponse(+ requestId,+ await aiEditionService.save(request.payload.document),+ );+ case "document.delete":+ return createSuccessResponse(+ requestId,+ await aiEditionService.deleteProject(request.payload.projectId),+ );+ case "document.addAsset":+ return createSuccessResponse(+ requestId,+ await aiEditionService.addAsset(+ request.payload.projectId,+ request.payload.path,+ request.payload.label,+ ),+ );+ case "document.removeAsset":+ return createSuccessResponse(+ requestId,+ await aiEditionService.removeAsset(+ request.payload.projectId,+ request.payload.assetId,+ ),+ );+ case "llm.getSnapshot":+ return createSuccessResponse(requestId, await aiEditionService.llmGetSnapshot());+ case "llm.setConfig":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmSetConfig(request.payload.config),+ );+ case "llm.setApiKey":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmSetApiKey(+ request.payload.providerId,+ request.payload.apiKey,+ ),+ );+ case "llm.removeApiKey":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmRemoveApiKey(request.payload.providerId),+ );+ case "chat.run":+ return createSuccessResponse(+ requestId,+ await aiEditionService.chatRun(request.payload.projectId, request.payload.message),+ );+ case "chat.history":+ return createSuccessResponse(+ requestId,+ await aiEditionService.chatHistory(request.payload.projectId),+ );+ case "chat.clear":+ return createSuccessResponse(+ requestId,+ await aiEditionService.chatClear(request.payload.projectId),+ );+ default:+ return createErrorResponse(+ requestId,+ "UNSUPPORTED_ACTION",+ `Unsupported aiEdition action: ${action}`,+ );+ }+ }+default:return createErrorResponse(requestId,diff --git a/electron/main.ts b/electron/main.tsindex 12ce817fc..7d8c2a748 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -547,6 +547,14 @@ appReady?.then(async () => {session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {const source = getSelectedDesktopSource();+ // ponytail: diagnostic for the 0-byte screen-recording bug. Log what+ // we're handing to the renderer so we can see if the source is stale+ // or the handler is returning an empty payload.+ console.info(+ `[display-media] videoRequested=${request.videoRequested} ` ++ `audioRequested=${request.audioRequested} ` ++ `source=${source ? `${source.id} (${source.name})` : "(none)"}`,+ );if (!request.videoRequested || !source) {callback({});return;@@ -560,6 +568,22 @@ appReady?.then(async () => {{ useSystemPicker: false },);+ // ponytail: forward renderer console.warn/error to main-process stdout so+ // recorder diagnostics (which fire in the renderer) show up next to the+ // main-process logs in `npm run dev` output. Without this, the+ // `[recorder:...]` lines from recorderHandle.ts are only visible in+ // DevTools. One-time wire; no per-message cost beyond a single IPC hop.+ const logChannels = ["log", "warn", "error"] as const;+ for (const channel of logChannels) {+ ipcMain.on(`renderer-console-${channel}`, (_event, ...args) => {+ const text = args+ .map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg)))+ .join(" ");+ const stream = channel === "error" ? process.stderr : process.stdout;+ stream.write(`[renderer:${channel}] ${text}\n`);+ });+ }+// Request mic permission now. Screen Recording is requested lazily from the// source-picker action so its prompt isn't hidden behind the selector window.if (process.platform === "darwin") {diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsnew file mode 100644index 000000000..afb816cd5--- /dev/null+++ b/electron/native-bridge/services/aiEditionService.ts@@ -0,0 +1,147 @@+import { documentSchema } from "../../../src/lib/ai-edition/schema";+import type {+ AiEditionAssetResult,+ AiEditionChatMessage,+ AiEditionChatResult,+ AiEditionDocumentResult,+ AiEditionLlmConfig,+ AiEditionLlmSnapshot,+ AiEditionProjectSummary,+} from "../../../src/native/contracts";+import type { DocumentService } from "../../ai-edition/document-service";+import type { LlmConfigStore } from "../../ai-edition/llm-config-store";+import { PROVIDER_DEFINITIONS } from "../../ai-edition/provider-registry";++export interface AiEditionServiceOptions {+ documents: DocumentService;+ llmConfig: LlmConfigStore;+ runChat: (projectId: string, message: string) => Promise<AiEditionChatResult>;+ getChatHistory: (projectId: string) => Promise<AiEditionChatMessage[]>;+ clearChatHistory: (projectId: string) => void;+}++export class AiEditionService {+ constructor(private readonly options: AiEditionServiceOptions) {}++ async listProjects(): Promise<AiEditionProjectSummary[]> {+ return this.options.documents.listProjects();+ }++ async get(projectId: string): Promise<AiEditionDocumentResult> {+ try {+ const document = await this.options.documents.getProject(projectId);+ return { success: true, document };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }++ async create(title?: string): Promise<AiEditionDocumentResult> {+ try {+ const document = await this.options.documents.createProject(title ?? "");+ return { success: true, document };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }++ async save(document: unknown): Promise<AiEditionDocumentResult> {+ try {+ const parsed = documentSchema.parse(document);+ const saved = await this.options.documents.saveProject(parsed);+ return { success: true, document: saved };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }++ async deleteProject(projectId: string): Promise<AiEditionDocumentResult> {+ try {+ await this.options.documents.deleteProject(projectId);+ return { success: true };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }++ async addAsset(projectId: string, path: string, label?: string): Promise<AiEditionAssetResult> {+ const document = await this.options.documents.addAsset(projectId, { path, label });+ const assetId = document.project.primaryAssetId ?? document.assets.at(-1)?.id ?? "";+ return { assetId, document };+ }++ async removeAsset(projectId: string, assetId: string): Promise<AiEditionAssetResult> {+ const document = await this.options.documents.removeAsset(projectId, assetId);+ return { assetId, document };+ }++ async llmGetSnapshot(): Promise<AiEditionLlmSnapshot> {+ const config = this.options.llmConfig.getConfig();+ const connectedProviders: string[] = [];+ for (const def of PROVIDER_DEFINITIONS) {+ const key = this.options.llmConfig.getApiKey(def.id, def.envKeys);+ if (key) connectedProviders.push(def.id);+ }+ return {+ config,+ connectedProviders,+ availableProviders: PROVIDER_DEFINITIONS.map((d) => ({+ id: d.id,+ label: d.label,+ authKind: d.authKind,+ })),+ };+ }++ async llmSetConfig(config: AiEditionLlmConfig): Promise<AiEditionDocumentResult> {+ try {+ await this.options.llmConfig.setConfig(config);+ return { success: true };+ } catch (error) {+ return { success: false, error: error instanceof Error ? error.message : String(error) };+ }+ }++ async llmSetApiKey(providerId: string, apiKey: string): Promise<AiEditionDocumentResult> {+ try {+ await this.options.llmConfig.setApiKey(providerId, apiKey);+ return { success: true };+ } catch (error) {+ return { success: false, error: error instanceof Error ? error.message : String(error) };+ }+ }++ async llmRemoveApiKey(providerId: string): Promise<AiEditionDocumentResult> {+ try {+ await this.options.llmConfig.removeApiKey(providerId);+ return { success: true };+ } catch (error) {+ return { success: false, error: error instanceof Error ? error.message : String(error) };+ }+ }++ async chatRun(projectId: string, message: string): Promise<AiEditionChatResult> {+ return this.options.runChat(projectId, message);+ }++ async chatHistory(projectId: string): Promise<AiEditionChatMessage[]> {+ return this.options.getChatHistory(projectId);+ }++ async chatClear(projectId: string): Promise<{ success: boolean }> {+ this.options.clearChatHistory(projectId);+ return { success: true };+ }+}diff --git a/electron/preload.ts b/electron/preload.tsindex f02a2ccd2..b1e8d4e17 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -174,6 +174,9 @@ contextBridge.exposeInMainWorld("electronAPI", {getCurrentRecordingSession: () => {return ipcRenderer.invoke("get-current-recording-session");},+ findRecordingCamera: (videoPath: string) => {+ return ipcRenderer.invoke("find-recording-camera", videoPath);+ },readBinaryFile: (filePath: string) => {return ipcRenderer.invoke("read-binary-file", filePath);},@@ -302,4 +305,10 @@ contextBridge.exposeInMainWorld("electronAPI", {sendCloseConfirmResponse: (choice: "save" | "discard" | "cancel") => {ipcRenderer.send("close-confirm-response", choice);},+ // ponytail: forward renderer console output to main-process stdout so+ // recorder diagnostics land next to the main-process logs in dev output.+ // One-way fire-and-forget; we deliberately don't await the IPC.+ rendererConsole: (channel: "log" | "warn" | "error", args: unknown[]) => {+ ipcRenderer.send(`renderer-console-${channel}`, ...args);+ },});diff --git a/package-lock.json b/package-lock.jsonindex b34ad429d..3876357a8 100644--- a/package-lock.json+++ b/package-lock.json@@ -52,7 +52,9 @@"tailwind-merge": "^3.5.0","tailwindcss-animate": "^1.0.7","uuid": "^13.0.0",- "web-demuxer": "^4.0.0"+ "web-demuxer": "^4.0.0",+ "zod": "^3.23.8",+ "zustand": "^5.0.8"},"devDependencies": {"@actions/core": "^3.0.1",@@ -12453,6 +12455,44 @@"funding": {"url": "https://github.com/sponsors/sindresorhus"}+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zustand": {+ "version": "5.0.14",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.14.tgz",+ "integrity": "sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }}}}diff --git a/package.json b/package.jsonindex 02f778efc..de703ff3a 100644--- a/package.json+++ b/package.json@@ -98,7 +98,9 @@"tailwind-merge": "^3.5.0","tailwindcss-animate": "^1.0.7","uuid": "^13.0.0",- "web-demuxer": "^4.0.0"+ "web-demuxer": "^4.0.0",+ "zod": "^3.23.8",+ "zustand": "^5.0.8"},"devDependencies": {"@actions/core": "^3.0.1",diff --git a/src/App.tsx b/src/App.tsxindex 35749408c..dacf83d55 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,4 +1,9 @@import { lazy, Suspense, useEffect, useState } from "react";+import "./styles/design-tokens.css";+import { installBrowserShims } from "./native/browserShim";++installBrowserShims();+import { CountdownOverlay } from "./components/launch/CountdownOverlay.tsx";import { LaunchWindow } from "./components/launch/LaunchWindow";import { NotesWindow } from "./components/launch/NotesWindow.tsx";@@ -9,7 +14,11 @@ import { useScopedT } from "./contexts/I18nContext";import { ShortcutsProvider } from "./contexts/ShortcutsContext";import { loadAllCustomFonts } from "./lib/customFonts";-const VideoEditor = lazy(() => import("./components/video-editor/VideoEditor"));+const VideoEditorEntry = lazy(() =>+ import("./components/ai-edition/AiEditionShell").then((module) => ({+ default: module.default,+ })),+);const ShortcutsConfigDialog = lazy(() =>import("./components/video-editor/ShortcutsConfigDialog").then((module) => ({default: module.ShortcutsConfigDialog,@@ -98,7 +107,7 @@ export default function App() {</div>}>- <VideoEditor />+ <VideoEditorEntry /><ShortcutsConfigDialog /></Suspense></ShortcutsProvider>diff --git a/src/components/ai-edition/AiEditionShell.tsx b/src/components/ai-edition/AiEditionShell.tsxnew file mode 100644index 000000000..72d5d7a75--- /dev/null+++ b/src/components/ai-edition/AiEditionShell.tsx@@ -0,0 +1,12 @@+import { NewEditorShell } from "./NewEditorShell";++// ponytail: the new editor is the default for all users (merge plan §0 — the+// new editing model is NOT opt-in). AI_FEATURES_ENABLED gates only the+// LLM/agent UI (chat panel, provider settings) which mounts inside+// NewEditorShell when the flag is true. The legacy VideoEditor is deprecated.++export function AiEditionOrLegacy() {+ return <NewEditorShell />;+}++export default AiEditionOrLegacy;diff --git a/src/components/ai-edition/Bottombar.tsx b/src/components/ai-edition/Bottombar.tsxnew file mode 100644index 000000000..67a8e79a4--- /dev/null+++ b/src/components/ai-edition/Bottombar.tsx@@ -0,0 +1,437 @@+import {+ ChevronDown,+ FileText,+ MessageSquare,+ Scissors,+ Timer,+ WandSparkles,+ ZoomIn,+} from "lucide-react";+import { useState } from "react";+import type { AnnotationRegion } from "@/components/video-editor/types";+import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { ASPECT_RATIOS, type AspectRatio } from "@/utils/aspectRatioUtils";+import styles from "./NewEditorShell.module.css";+import { TimelinePane } from "./TimelinePane";++type RegionKind = "zoom" | "skip" | "annotation" | "speed";++interface RegionHandle {+ kind: RegionKind;+ id: string;+}++interface BottombarProps {+ clips: AxcutClip[];+ currentTimeSec: number;+ sourceDurationSec: number;+ onPreviewSource: (sec: number) => void;+ onReplaceTimeline: (+ intervals: Array<{ startSec: number; endSec: number }>,+ reason: string,+ ) => void;+ // Region operations (from useTimeline)+ zoomRegions: AxcutDocument["zoomRanges"];+ skipRanges: AxcutDocument["timeline"]["skipRanges"];+ annotationRegions: AnnotationRegion[];+ speedRegions: Array<{ id: string; startMs: number; endMs: number; speed: number }>;+ selection: RegionHandle | null;+ hasDoc: boolean;+ onAddZoom: () => void;+ onAddSkip: () => void;+ onAddAnnotation: () => void;+ onAddSpeed: () => void;+ onSelectRegion: (kind: RegionKind, id: string) => void;+ onRemoveRegion: (kind: RegionKind, id: string) => void;+ onCaptions: () => void;+}++const RATIO_LABELS: Record<AspectRatio, string> = {+ "16:9": "16:9",+ "9:16": "9:16",+ "1:1": "1:1",+ "4:3": "4:3",+ "4:5": "4:5",+ "16:10": "16:10",+ "10:16": "10:16",+ native: "Original",+};++function formatMs(ms: number): string {+ const sec = ms / 1000;+ const m = Math.floor(sec / 60);+ const s = (sec % 60).toFixed(1);+ return `${m}:${s.padStart(4, "0")}`;+}++export function Bottombar({+ clips,+ currentTimeSec,+ sourceDurationSec,+ onPreviewSource,+ onReplaceTimeline,+ zoomRegions,+ annotationRegions,+ speedRegions,+ selection,+ hasDoc,+ onAddZoom,+ onAddSkip,+ onAddAnnotation,+ onAddSpeed,+ onSelectRegion,+ onRemoveRegion,+ onCaptions,+}: BottombarProps) {+ const { settings, set } = useEditorSettings();+ const [ratioOpen, setRatioOpen] = useState(false);+ return (+ <footer className={styles.bottombar} aria-label="Timeline and properties">+ <section+ style={{ minWidth: 0, display: "grid", gridTemplateRows: "auto 1fr auto", minHeight: 0 }}+ >+ <header className={styles.timelineHead}>+ <div className={styles.viewTools} role="toolbar" aria-label="View tools">+ <VtBtn label="Add zoom" title="Add zoom (Z)" onClick={onAddZoom} disabled={!hasDoc}>+ <ZoomIn size={17} />+ </VtBtn>+ <VtBtn+ label="Auto focus"+ title="Auto focus on for all zoom"+ on={settings.autoFocusAll}+ onClick={() => {+ void set({ autoFocusAll: !settings.autoFocusAll });+ }}+ >+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.75"+ strokeLinecap="round"+ strokeLinejoin="round"+ width={17}+ height={17}+ >+ <path d="M4 8V4h4" />+ <path d="M16 4h4v4" />+ <path d="M4 16v4h4" />+ <path d="M16 20h4v-4" />+ <path d="M6 12c1.5-2.2 3.6-3.4 6-3.4s4.5 1.2 6 3.4c-1.5 2.2-3.6 3.4-6 3.4S7.5 14.2 6 12z" />+ <circle cx="12" cy="12" r="1.6" />+ </svg>+ </VtBtn>+ <VtBtn label="Trim" title="Press T to add trim" onClick={onAddSkip} disabled={!hasDoc}>+ <Scissors size={17} />+ </VtBtn>+ <VtBtn+ label="Annotation"+ title="Press A to add annotation"+ onClick={onAddAnnotation}+ disabled={!hasDoc}+ >+ <MessageSquare size={17} />+ </VtBtn>+ <VtBtn+ label="Speed"+ title="Press S to add speed"+ onClick={onAddSpeed}+ disabled={!hasDoc}+ >+ <Timer size={17} />+ </VtBtn>+ <VtBtn label="Captions" title="Auto captions" onClick={onCaptions} disabled={!hasDoc}>+ <FileText size={17} />+ </VtBtn>+ <VtBtn label="Magic" title="Auto zoom suggestions" disabled>+ <WandSparkles size={17} />+ </VtBtn>+ <div style={{ position: "relative" }}>+ <button+ type="button"+ className={styles.ratio}+ onClick={() => setRatioOpen((v) => !v)}+ aria-haspopup="menu"+ aria-expanded={ratioOpen}+ >+ <span>{RATIO_LABELS[settings.aspectRatio]}</span>+ <ChevronDown size={10} className="caret" />+ </button>+ {ratioOpen ? (+ <div+ role="menu"+ style={{+ position: "absolute",+ top: "calc(100% + 4px)",+ left: 0,+ minWidth: 120,+ background: "var(--surface)",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ boxShadow: "var(--elev-pop)",+ padding: 4,+ zIndex: 60,+ }}+ >+ {ASPECT_RATIOS.map((r) => (+ <button+ type="button"+ key={r}+ role="menuitem"+ style={menuItemStyle(r === settings.aspectRatio)}+ disabled={!hasDoc}+ onClick={() => {+ void set({ aspectRatio: r });+ setRatioOpen(false);+ }}+ >+ {RATIO_LABELS[r]}+ </button>+ ))}+ </div>+ ) : null}+ </div>+ </div>+ <div className={styles.hintRow}>+ <span className={styles.hint}>+ <span className={styles.kbd}>Scroll</span>+ <span>Pan</span>+ </span>+ <span className={styles.hint}>+ <span className={styles.kbd}>Ctrl</span>+ <span className={styles.kbd}>+ Scroll</span>+ <span>Zoom</span>+ </span>+ </div>+ </header>+ <div className={styles.timelineBody}>+ {/* Region lane rows */}+ <div+ style={{+ padding: "4px var(--sp-4) 0",+ display: "flex",+ flexDirection: "column",+ gap: 4,+ flexShrink: 0,+ }}+ >+ {zoomRegions.length > 0 ? (+ <LaneRow+ label="Zoom"+ kind="zoom"+ items={zoomRegions.map((z) => ({+ id: z.id,+ startMs: z.startMs,+ endMs: z.endMs,+ label: `${getZoomLabel(z)}`,+ }))}+ selection={selection}+ onSelect={onSelectRegion}+ onRemove={onRemoveRegion}+ />+ ) : null}+ {annotationRegions.length > 0 ? (+ <LaneRow+ label="Annotations"+ kind="annotation"+ items={annotationRegions.map((a) => ({+ id: a.id,+ startMs: a.startMs,+ endMs: a.endMs,+ label: a.content?.slice(0, 30) || "Annotation",+ }))}+ selection={selection}+ onSelect={onSelectRegion}+ onRemove={onRemoveRegion}+ />+ ) : null}+ {speedRegions.length > 0 ? (+ <LaneRow+ label="Speed"+ kind="speed"+ items={speedRegions.map((s) => ({+ id: s.id,+ startMs: s.startMs,+ endMs: s.endMs,+ label: `${s.speed}×`,+ }))}+ selection={selection}+ onSelect={onSelectRegion}+ onRemove={onRemoveRegion}+ />+ ) : null}+ </div>+ <div className="timelinePaneWrap" style={{ flex: 1, minHeight: 0, overflow: "hidden" }}>+ <TimelinePane+ clips={clips}+ currentTimeSec={currentTimeSec}+ sourceDurationSec={sourceDurationSec}+ onPreviewSource={onPreviewSource}+ onReplaceTimeline={onReplaceTimeline}+ />+ </div>+ </div>+ <div className={styles.zoombar} role="group" aria-label="Zoom range">+ <div className={styles.zoomTrack}>+ <div className={styles.zoomFill} aria-hidden />+ </div>+ </div>+ </section>+ </footer>+ );+}++function VtBtn({+ label,+ title,+ onClick,+ on,+ disabled,+ children,+}: {+ label: string;+ title: string;+ onClick?: () => void;+ on?: boolean;+ disabled?: boolean;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ className={`${styles.vtBtn} ${on ? styles.isOn : ""}`}+ aria-label={label}+ aria-pressed={on}+ title={title}+ onClick={onClick}+ disabled={disabled}+ >+ {children}+ </button>+ );+}++function LaneRow({+ label,+ kind,+ items,+ selection,+ onSelect,+ onRemove,+}: {+ label: string;+ kind: RegionKind;+ items: Array<{ id: string; startMs: number; endMs: number; label: string }>;+ selection: RegionHandle | null;+ onSelect: (kind: RegionKind, id: string) => void;+ onRemove: (kind: RegionKind, id: string) => void;+}) {+ return (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: 8,+ height: 30,+ }}+ >+ <span+ style={{+ font: "600 10px/1 var(--font-mono)",+ color: "var(--meta)",+ letterSpacing: "0.04em",+ textTransform: "uppercase",+ minWidth: 48,+ flexShrink: 0,+ }}+ >+ {label}+ </span>+ {items.map((item) => {+ const isSel = selection?.kind === kind && selection?.id === item.id;+ return (+ <button+ type="button"+ key={item.id}+ onClick={() => onSelect(kind, item.id)}+ title={`${formatMs(item.startMs)}–${formatMs(item.endMs)}`}+ style={{+ display: "inline-flex",+ alignItems: "center",+ gap: 6,+ padding: "3px 8px",+ borderRadius: "var(--r-md)",+ border: `1px solid ${isSel ? "var(--accent)" : "var(--border-soft)"}`,+ background: isSel ? "var(--accent-soft)" : "var(--surface-2)",+ color: isSel ? "var(--accent)" : "var(--fg-2)",+ font: "500 11px/1 var(--font-mono)",+ letterSpacing: "0.02em",+ cursor: "pointer",+ whiteSpace: "nowrap",+ }}+ >+ <span style={{ maxWidth: 140, overflow: "hidden", textOverflow: "ellipsis" }}>+ {item.label}+ </span>+ <span style={{ color: "var(--meta)", fontSize: 10 }}>{formatMs(item.startMs)}</span>+ <button+ type="button"+ aria-label="Delete"+ title="Delete (Del)"+ onClick={(e) => {+ e.stopPropagation();+ onRemove(kind, item.id);+ }}+ style={{+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ width: 16,+ height: 16,+ borderRadius: "var(--r-xs)",+ border: 0,+ background: "var(--danger-soft)",+ color: "var(--danger)",+ fontSize: 10,+ fontWeight: 600,+ cursor: "pointer",+ opacity: isSel ? 1 : 0,+ }}+ >+ ×+ </button>+ </button>+ );+ })}+ </div>+ );+}++function getZoomLabel(z: { depth: number; customScale?: number }): string {+ if (z.customScale) return `${z.customScale.toFixed(1)}×`;+ const scales: Record<number, string> = {+ 1: "1.25×",+ 2: "1.5×",+ 3: "1.8×",+ 4: "2.2×",+ 5: "3.5×",+ 6: "5×",+ };+ return scales[z.depth] ?? "1.8×";+}++function menuItemStyle(active: boolean): React.CSSProperties {+ return {+ display: "block",+ width: "100%",+ textAlign: "left",+ padding: "6px 10px",+ border: 0,+ background: active ? "var(--accent-wash)" : "transparent",+ color: "var(--fg-2)",+ borderRadius: "var(--r-sm)",+ cursor: "pointer",+ font: "500 12px var(--font-body)",+ };+}diff --git a/src/components/ai-edition/ChatPanel.tsx b/src/components/ai-edition/ChatPanel.tsxnew file mode 100644index 000000000..6af48e496--- /dev/null+++ b/src/components/ai-edition/ChatPanel.tsx@@ -0,0 +1,114 @@+import { Send } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { nativeBridgeClient } from "@/native/client";+import type { AiEditionChatMessage } from "@/native/contracts";++export function ChatPanel() {+ const projectId = useProjectStore((s) => s.projectId);+ const [messages, setMessages] = useState<AiEditionChatMessage[]>([]);+ const [input, setInput] = useState("");+ const [busy, setBusy] = useState(false);+ const scrollRef = useRef<HTMLDivElement | null>(null);++ const loadHistory = useCallback(async () => {+ if (!projectId) return;+ try {+ const history = await nativeBridgeClient.aiEdition.chatHistory(projectId);+ setMessages(history);+ } catch {+ // ponytail: silent+ }+ }, [projectId]);++ useEffect(() => {+ void loadHistory();+ }, [loadHistory]);++ useEffect(() => {+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });+ }, []);++ const handleSend = useCallback(async () => {+ if (!projectId || !input.trim() || busy) return;+ const text = input.trim();+ setInput("");+ setBusy(true);+ try {+ const result = await nativeBridgeClient.aiEdition.chatRun(projectId, text);+ if (result.success && result.assistantMessage) {+ setMessages((prev) => [...prev, result.assistantMessage!]);+ } else {+ toast.error(result.error ?? "Chat failed");+ }+ } catch (err) {+ toast.error("Chat failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ }, [projectId, input, busy]);++ return (+ <aside className="w-full h-full flex flex-col overflow-hidden">+ <header className="px-4 py-3 border-b border-white/[0.06]">+ <h2 className="text-[10px] font-semibold tracking-[0.1em] uppercase text-white/40">+ AI Chat+ </h2>+ </header>+ <div+ ref={scrollRef}+ className="flex-1 min-h-0 overflow-y-auto px-3 py-3 flex flex-col gap-2 custom-scrollbar"+ >+ {messages.length === 0 && (+ <div className="flex flex-col items-center gap-3 text-center py-6">+ <div className="flex items-center justify-center w-12 h-12 rounded-2xl bg-white/[0.05] ring-1 ring-white/10">+ <Send className="h-5 w-5 text-white/40" />+ </div>+ <p className="text-[12px] text-white/45 max-w-[220px] leading-relaxed">+ Ask the AI to edit your video — e.g. "remove silences" or "cut the first 10 seconds".+ </p>+ </div>+ )}+ {messages.map((msg) => (+ <div+ key={msg.id}+ className={`max-w-[90%] px-3 py-2 rounded-xl text-[12.5px] leading-relaxed ${+ msg.role === "user"+ ? "self-end bg-[#34B27B] text-white rounded-br-sm"+ : "self-start bg-white/[0.06] text-white/90 rounded-bl-sm"+ }`}+ >+ {msg.content}+ </div>+ ))}+ </div>+ <div className="px-3 py-2 border-t border-white/[0.06] flex items-center gap-1.5">+ <input+ className="flex-1 px-3 py-2 rounded-md bg-white/[0.04] border border-white/[0.06] text-[12px] text-white/85 placeholder:text-white/30 outline-none focus:border-[#34B27B]/50 focus:bg-white/[0.06]"+ placeholder="Type a message…"+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void handleSend();+ }+ }}+ disabled={busy || !projectId}+ />+ <button+ type="button"+ className="flex items-center justify-center w-8 h-8 rounded-md bg-[#34B27B] hover:bg-[#2d9e6c] active:bg-[#27885c] text-white transition-colors disabled:opacity-40"+ onClick={handleSend}+ disabled={busy || !input.trim() || !projectId}+ title="Send"+ >+ <Send size={14} />+ </button>+ </div>+ </aside>+ );+}diff --git a/src/components/ai-edition/CursorPreviewLayer.module.css b/src/components/ai-edition/CursorPreviewLayer.module.cssnew file mode 100644index 000000000..8237d3aef--- /dev/null+++ b/src/components/ai-edition/CursorPreviewLayer.module.css@@ -0,0 +1,34 @@+/* Cursor preview layer. Transparent overlay that hosts a Pixi canvas ++ a native-cursor <img>. The Pixi canvas is appended by the component on+ mount; the <img> is positioned via translate3d in the same coordinate+ space as the <video>, so cursor + video always align. */++.layer {+ position: absolute;+ inset: 0;+ z-index: 2;+ pointer-events: none;+ overflow: hidden;+}++.layer[data-clip="off"] {+ overflow: visible;+}++.nativeCursorClip {+ position: absolute;+ inset: 0;+ pointer-events: none;+}++.nativeCursor {+ position: absolute;+ top: 0;+ left: 0;+ image-rendering: -webkit-optimize-contrast;+ image-rendering: crisp-edges;+ will-change: transform, filter;+ user-select: none;+ -webkit-user-drag: none;+ display: none;+}diff --git a/src/components/ai-edition/CursorPreviewLayer.test.tsx b/src/components/ai-edition/CursorPreviewLayer.test.tsxnew file mode 100644index 000000000..b6edf4a22--- /dev/null+++ b/src/components/ai-edition/CursorPreviewLayer.test.tsx@@ -0,0 +1,216 @@+import "@testing-library/jest-dom";+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { CursorPreviewLayer } from "./CursorPreviewLayer";++const bridgeMocks = vi.hoisted(() => ({+ getRecordingData: vi.fn(),+ getTelemetry: vi.fn(),+}));++class StubResizeObserver {+ private callback: ResizeObserverCallback;+ private target: Element | null = null;+ constructor(callback: ResizeObserverCallback) {+ this.callback = callback;+ }+ observe(target: Element) {+ this.target = target;+ return undefined;+ }+ unobserve() {+ return undefined;+ }+ disconnect() {+ return undefined;+ }+}++vi.mock("@/native/client", () => ({+ nativeBridgeClient: {+ cursor: {+ getRecordingData: bridgeMocks.getRecordingData,+ getTelemetry: bridgeMocks.getTelemetry,+ },+ },+}));++vi.mock("@/lib/cursor/pixiCursorRenderer", () => ({+ DEFAULT_CURSOR_CONFIG: { dotRadius: 28, smoothingFactor: 0, motionBlur: 0, clickBounce: 1 },+ preloadCursorAssets: vi.fn(async () => undefined),+ PixiCursorOverlay: class {+ public container = { label: "" };+ // ponytail: no-op stubs — the test asserts on the React boundary,+ // not on Pixi internals.+ update() {+ /* no-op */+ }+ setDotRadius() {+ /* no-op */+ }+ setSmoothingFactor() {+ /* no-op */+ }+ setMotionBlur() {+ /* no-op */+ }+ setClickBounce() {+ /* no-op */+ }+ reset() {+ /* no-op */+ }+ destroy() {+ /* no-op */+ }+ },+}));++vi.mock("pixi.js", () => ({+ Application: class {+ public canvas = document.createElement("canvas");+ public stage = { addChild: vi.fn() };+ public ticker = { maxFPS: 60 };+ public renderer = {};+ // ponytail: no-op stubs — the test asserts on the React boundary,+ // not on Pixi internals.+ async init() {+ /* no-op */+ }+ destroy() {+ /* no-op */+ }+ },+ Container: class {},+}));++const SAMPLE_DOC = {+ schemaVersion: 3,+ project: {+ id: "proj_test",+ title: "Test",+ createdAt: "2026-06-25T10:00:00.000Z",+ updatedAt: "2026-06-25T10:00:00.000Z",+ },+ assets: [],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRegions: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+};++function renderWithVideo(): { host: HTMLDivElement; video: HTMLVideoElement } {+ const stage = document.createElement("div");+ const video = document.createElement("video");+ stage.appendChild(video);+ document.body.appendChild(stage);+ vi.spyOn(video, "getBoundingClientRect").mockReturnValue({+ x: 0,+ y: 0,+ width: 1920,+ height: 1080,+ top: 0,+ right: 1920,+ bottom: 1080,+ left: 0,+ toJSON: () => "",+ });++ const host = document.createElement("div");+ stage.appendChild(host);+ act(() => {+ render(+ <CursorPreviewLayer videoPath="/tmp/recording.mp4" currentTimeSec={0.5} isPlaying={false} />,+ { container: host },+ );+ });+ return { host: stage, video };+}++describe("CursorPreviewLayer (shared)", () => {+ beforeEach(() => {+ Object.defineProperty(window, "ResizeObserver", {+ writable: true,+ value: StubResizeObserver,+ });+ useProjectStore.getState().clear();+ useProjectStore.setState({+ projectId: "proj_test",+ document: SAMPLE_DOC,+ revision: 1,+ status: "ready",+ error: null,+ sourceDurationSec: 0,+ currentTimeSec: 0,+ dirty: false,+ lastSavedAt: new Date(),+ });+ for (const mock of Object.values(bridgeMocks)) {+ mock.mockReset();+ }+ });++ afterEach(() => {+ cleanup();+ document.body.innerHTML = "";+ });++ it("renders nothing when videoPath is null", () => {+ bridgeMocks.getRecordingData.mockResolvedValue(null);+ bridgeMocks.getTelemetry.mockResolvedValue([]);+ const host = document.createElement("div");+ document.body.appendChild(host);+ act(() => {+ render(<CursorPreviewLayer videoPath={null} currentTimeSec={0} isPlaying={false} />, {+ container: host,+ });+ });+ expect(host.querySelector("img")).toBeNull();+ });++ it("queries the native bridge for cursor data when videoPath is set", async () => {+ bridgeMocks.getRecordingData.mockImplementation(async () => null);+ bridgeMocks.getTelemetry.mockImplementation(async () => []);+ renderWithVideo();++ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(bridgeMocks.getRecordingData).toHaveBeenCalledWith("/tmp/recording.mp4");+ expect(bridgeMocks.getTelemetry).toHaveBeenCalledWith("/tmp/recording.mp4");+ });++ it("hides the native cursor <img> when settings.cursorShow is false", async () => {+ bridgeMocks.getRecordingData.mockImplementation(async () => null);+ bridgeMocks.getTelemetry.mockImplementation(async () => []);+ const document = useProjectStore.getState().document;+ useProjectStore.setState({+ document: { ...document!, legacyEditor: { cursorShow: false } },+ });+ const { host } = renderWithVideo();++ // ponytail: let the rAF tick fire + flush.+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 16));+ });++ const img = host.querySelector("img");+ expect(img).toBeTruthy();+ expect((img as HTMLImageElement).style.display).toBe("none");+ });+});diff --git a/src/components/ai-edition/CursorPreviewLayer.tsx b/src/components/ai-edition/CursorPreviewLayer.tsxnew file mode 100644index 000000000..7a4d70a5f--- /dev/null+++ b/src/components/ai-edition/CursorPreviewLayer.tsx@@ -0,0 +1,440 @@+// Shared cursor preview layer for the editor.+//+// Renders the cursor on top of a <video> element. Uses the same cursor+// assets, smoothing, click bounce, motion blur, and themed native cursor+// bitmaps as the legacy editor's Pixi-based path. Reads cursor visual+// config from `useEditorSettings`.+//+// The cursor data lives in `src/lib/cursor/` so both editors share the+// same `PixiCursorOverlay` class: the new editor mounts this component as+// a sibling of the <video>, and the legacy editor drives the same+// `PixiCursorOverlay` directly from inside its existing Pixi stage+// (which carries the additional zoom / crop / 3D transform math).++import { Application, Container } from "pixi.js";+import { useEffect, useMemo, useRef, useState } from "react";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { getSmoothedCursorPath } from "@/lib/cursor/cursorPathSmoothing";+import {+ createNativeCursorMotionBlurState,+ getNativeCursorClickBounceProgress,+ getNativeCursorClickBounceScale,+ getNativeCursorMotionBlurPx,+ hasNativeCursorRecordingData,+ resolveInterpolatedNativeCursorFrame,+ resolveNativeCursorRenderAsset,+} from "@/lib/cursor/nativeCursor";+import {+ DEFAULT_CURSOR_CONFIG,+ PixiCursorOverlay,+ preloadCursorAssets,+} from "@/lib/cursor/pixiCursorRenderer";+import { useCursorRecordingData } from "@/native/hooks/useCursorRecordingData";+import { useCursorTelemetry } from "@/native/hooks/useCursorTelemetry";+import styles from "./CursorPreviewLayer.module.css";++interface CursorPreviewLayerProps {+ videoPath: string | null;+ currentTimeSec: number;+ isPlaying: boolean;+}++export function CursorPreviewLayer({+ videoPath,+ currentTimeSec,+ isPlaying,+}: CursorPreviewLayerProps) {+ const { settings } = useEditorSettings();+ const { data: cursorRecordingData } = useCursorRecordingData(videoPath);+ const { samples: cursorTelemetry } = useCursorTelemetry(videoPath);++ const hasNativeCursor = useMemo(+ () => hasNativeCursorRecordingData(cursorRecordingData),+ [cursorRecordingData],+ );++ // Layer ref — the DOM <div> that hosts the Pixi canvas + native-cursor+ // <img>. Sized to the <video> via ResizeObserver; both editors mount the+ // layer as a sibling of the <video> so the measurements line up.+ const layerRef = useRef<HTMLDivElement | null>(null);+ const [size, setSize] = useState({ width: 0, height: 0 });++ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run when videoPath changes so the observer re-attaches to the new <video>.+ useEffect(() => {+ const layer = layerRef.current;+ if (!layer) return;+ const video = layer.parentElement?.querySelector("video");+ if (!video) return;+ const update = () => {+ const rect = video.getBoundingClientRect();+ setSize({ width: rect.width, height: rect.height });+ };+ update();+ const ro = new ResizeObserver(update);+ ro.observe(video);+ window.addEventListener("resize", update);+ return () => {+ ro.disconnect();+ window.removeEventListener("resize", update);+ };+ }, [videoPath]);++ // Pixi application + cursor overlay lifecycle. The app is created once+ // per videoPath and torn down on swap. The overlay is created after+ // cursor assets finish loading (otherwise it'd throw on missing assets).+ const appRef = useRef<Application | null>(null);+ const overlayRef = useRef<PixiCursorOverlay | null>(null);+ const [pixiReady, setPixiReady] = useState(false);+ const appMountedRef = useRef<HTMLDivElement | null>(null);++ // biome-ignore lint/correctness/useExhaustiveDependencies: re-create on videoPath so the Pixi stage tracks the current asset.+ useEffect(() => {+ if (!videoPath) {+ setPixiReady(false);+ return;+ }+ const host = layerRef.current;+ if (!host) return;+ let mounted = true;+ let app: Application | null = null;++ (async () => {+ let enabled = true;+ try {+ await preloadCursorAssets();+ } catch {+ enabled = false;+ }+ if (!mounted) return;+ if (!enabled) {+ setPixiReady(false);+ return;+ }+ app = new Application();+ await app.init({+ width: size.width || 1,+ height: size.height || 1,+ backgroundAlpha: 0,+ antialias: true,+ resolution: window.devicePixelRatio || 1,+ autoDensity: true,+ });+ if (!mounted) {+ app.destroy(true, { children: true, texture: true, textureSource: true });+ return;+ }+ app.ticker.maxFPS = 60;+ host.appendChild(app.canvas);+ appRef.current = app;+ appMountedRef.current = host;++ const overlay = new PixiCursorOverlay({+ dotRadius: DEFAULT_CURSOR_CONFIG.dotRadius * settings.cursor.size,+ smoothingFactor: settings.cursor.smoothing,+ motionBlur: settings.cursor.motionBlur,+ clickBounce: settings.cursor.clickBounce,+ });+ overlay.container.label = "cursor-overlay";+ app.stage.addChild(overlay.container as Container);+ overlayRef.current = overlay;+ setPixiReady(true);+ })();++ return () => {+ mounted = false;+ setPixiReady(false);+ if (overlayRef.current) {+ overlayRef.current.destroy();+ overlayRef.current = null;+ }+ if (app && app.renderer) {+ const canvas = app.canvas;+ if (canvas.parentElement === host) host.removeChild(canvas);+ app.destroy(true, { children: true, texture: true, textureSource: true });+ }+ appRef.current = null;+ appMountedRef.current = null;+ };+ // ponytail: settings.* are read inside the async init only on+ // mount; live updates go through the rAF tick + the live-update+ // effect below.+ }, [videoPath]);++ // Live-update the overlay's config when the panel sliders move. The+ // effect is debounced via the rAF tick — the smoothing slider in+ // particular benefits from resetting the spring state.+ useEffect(() => {+ const overlay = overlayRef.current;+ if (!overlay) return;+ overlay.setDotRadius(DEFAULT_CURSOR_CONFIG.dotRadius * settings.cursor.size);+ overlay.setSmoothingFactor(settings.cursor.smoothing);+ overlay.setMotionBlur(settings.cursor.motionBlur);+ overlay.setClickBounce(settings.cursor.clickBounce);+ overlay.reset();+ }, [+ settings.cursor.size,+ settings.cursor.smoothing,+ settings.cursor.motionBlur,+ settings.cursor.clickBounce,+ ]);++ // Native cursor (DOM <img>) refs.+ const imageRef = useRef<HTMLImageElement | null>(null);+ const clipRef = useRef<HTMLDivElement | null>(null);+ const motionBlurStateRef = useRef(createNativeCursorMotionBlurState());+ const lastImageIdRef = useRef<string | null>(null);++ // rAF tick — drives both the Pixi overlay (telemetry cursor) and the+ // native cursor DOM <img> (recorded cursor). Reads the latest refs+ // inside the tick so React state churn doesn't restart the loop.+ const timeRef = useRef(currentTimeSec);+ const playingRef = useRef(isPlaying);+ const showCursorRef = useRef(settings.cursorShow);+ const cursorThemeRef = useRef(settings.cursorTheme);+ const sizeRef = useRef(size);+ const hasNativeRef = useRef(hasNativeCursor);+ const recordingDataRef = useRef(cursorRecordingData);+ const telemetryRef = useRef(cursorTelemetry);+ const smoothingRef = useRef(settings.cursor.smoothing);+ const clickBounceRef = useRef(settings.cursor.clickBounce);+ const cursorSizeRef = useRef(settings.cursor.size);+ const cursorMotionBlurRef = useRef(settings.cursor.motionBlur);+ const cursorClipToBoundsRef = useRef(settings.cursor.clipToBounds);++ useEffect(() => {+ timeRef.current = currentTimeSec;+ }, [currentTimeSec]);+ useEffect(() => {+ playingRef.current = isPlaying;+ }, [isPlaying]);+ useEffect(() => {+ showCursorRef.current = settings.cursorShow;+ }, [settings.cursorShow]);+ useEffect(() => {+ cursorThemeRef.current = settings.cursorTheme;+ }, [settings.cursorTheme]);+ useEffect(() => {+ sizeRef.current = size;+ }, [size]);+ useEffect(() => {+ hasNativeRef.current = hasNativeCursor;+ }, [hasNativeCursor]);+ useEffect(() => {+ recordingDataRef.current = cursorRecordingData;+ }, [cursorRecordingData]);+ useEffect(() => {+ telemetryRef.current = cursorTelemetry;+ }, [cursorTelemetry]);+ useEffect(() => {+ smoothingRef.current = settings.cursor.smoothing;+ }, [settings.cursor.smoothing]);+ useEffect(() => {+ clickBounceRef.current = settings.cursor.clickBounce;+ }, [settings.cursor.clickBounce]);+ useEffect(() => {+ cursorSizeRef.current = settings.cursor.size;+ }, [settings.cursor.size]);+ useEffect(() => {+ cursorMotionBlurRef.current = settings.cursor.motionBlur;+ }, [settings.cursor.motionBlur]);+ useEffect(() => {+ cursorClipToBoundsRef.current = settings.cursor.clipToBounds;+ }, [settings.cursor.clipToBounds]);++ // rAF loop is restarted only when the Pixi app mounts (or unmounts).+ useEffect(() => {+ if (!pixiReady) return;+ let raf = 0;+ const tick = () => {+ raf = window.requestAnimationFrame(tick);+ const overlay = overlayRef.current;+ if (!overlay) return;+ const timeMs = timeRef.current * 1000;+ const viewport = { x: 0, y: 0, ...sizeRef.current };+ const samples = hasNativeRef.current ? [] : telemetryRef.current;+ overlay.update(samples, timeMs, viewport, showCursorRef.current, !playingRef.current);+ };+ raf = window.requestAnimationFrame(tick);+ return () => window.cancelAnimationFrame(raf);+ }, [pixiReady]);++ // Native cursor DOM <img> tick — separate from the Pixi tick because+ // this layer doesn't depend on the Pixi app mount.+ useEffect(() => {+ if (!videoPath) return;+ let raf = 0;+ const tick = () => {+ raf = window.requestAnimationFrame(tick);+ renderNativeCursorFrame({+ hasNativeCursor: hasNativeRef.current,+ recordingData: recordingDataRef.current,+ telemetry: telemetryRef.current,+ timeMs: timeRef.current * 1000,+ isPlaying: playingRef.current,+ size: sizeRef.current,+ cursorSize: cursorSizeRef.current,+ cursorSmoothing: smoothingRef.current,+ cursorClickBounce: clickBounceRef.current,+ cursorMotionBlur: cursorMotionBlurRef.current,+ cursorTheme: cursorThemeRef.current,+ cursorClipToBounds: cursorClipToBoundsRef.current,+ showCursor: showCursorRef.current,+ imageRef,+ clipRef,+ lastImageIdRef,+ motionBlurStateRef,+ });+ };+ raf = window.requestAnimationFrame(tick);+ return () => window.cancelAnimationFrame(raf);+ }, [videoPath]);++ if (!videoPath) return null;++ return (+ <div+ ref={layerRef}+ className={styles.layer}+ data-clip={settings.cursor.clipToBounds ? "on" : "off"}+ >+ <div ref={clipRef} className={styles.nativeCursorClip}>+ <img ref={imageRef} alt="" className={styles.nativeCursor} draggable={false} />+ </div>+ </div>+ );+}++interface NativeCursorFrameInputs {+ hasNativeCursor: boolean;+ recordingData: ReturnType<typeof useCursorRecordingData>["data"];+ telemetry: ReturnType<typeof useCursorTelemetry>["samples"];+ timeMs: number;+ isPlaying: boolean;+ size: { width: number; height: number };+ cursorSize: number;+ cursorSmoothing: number;+ cursorClickBounce: number;+ cursorMotionBlur: number;+ cursorTheme: string;+ cursorClipToBounds: boolean;+ showCursor: boolean;+ imageRef: React.MutableRefObject<HTMLImageElement | null>;+ clipRef: React.MutableRefObject<HTMLDivElement | null>;+ lastImageIdRef: React.MutableRefObject<string | null>;+ motionBlurStateRef: React.MutableRefObject<ReturnType<typeof createNativeCursorMotionBlurState>>;+}++function renderNativeCursorFrame(inputs: NativeCursorFrameInputs) {+ const {+ hasNativeCursor,+ recordingData,+ telemetry,+ timeMs,+ isPlaying,+ size,+ cursorSize,+ cursorSmoothing,+ cursorClickBounce,+ cursorMotionBlur,+ cursorTheme,+ cursorClipToBounds,+ showCursor,+ imageRef,+ clipRef,+ lastImageIdRef,+ motionBlurStateRef,+ } = inputs;++ const imageEl = imageRef.current;+ const clipEl = clipRef.current;+ const hide = () => {+ if (imageEl) imageEl.style.display = "none";+ if (clipEl) clipEl.style.clipPath = "none";+ };++ if (!showCursor || size.width <= 0 || size.height <= 0) {+ hide();+ return;+ }++ if (!hasNativeCursor || !recordingData) {+ // ponytail: telemetry-only fallback. Draw a synthetic dot at the+ // smoothed path. The Pixi overlay already does this with the+ // bundled SVG art; the DOM <img> is the no-native path used in+ // legacy recordings (no cursor bitmaps captured).+ const samples = telemetry;+ if (samples.length === 0) {+ hide();+ return;+ }+ const path = getSmoothedCursorPath(+ { version: 1, provider: "none", samples: samples as never, assets: [] },+ cursorSmoothing,+ );+ const pos = path?.sampleAt(timeMs);+ if (!pos || !imageEl) {+ hide();+ return;+ }+ const radius = Math.max(4, 28 * Math.max(0, cursorSize));+ const x = pos.cx * size.width;+ const y = pos.cy * size.height;+ if (lastImageIdRef.current !== "fallback-dot") {+ imageEl.src =+ "data:image/svg+xml;utf8," ++ encodeURIComponent(+ `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><circle cx="16" cy="16" r="14" fill="#ff4040" stroke="#fff" stroke-width="2"/></svg>`,+ );+ lastImageIdRef.current = "fallback-dot";+ }+ imageEl.style.display = "block";+ imageEl.style.width = `${radius * 2}px`;+ imageEl.style.height = `${radius * 2}px`;+ imageEl.style.transform = `translate3d(${x - radius}px, ${y - radius}px, 0)`;+ imageEl.style.filter = "none";+ return;+ }++ const frame = resolveInterpolatedNativeCursorFrame(recordingData, timeMs);+ if (!frame) {+ hide();+ return;+ }+ const pos = getSmoothedCursorPath(recordingData, cursorSmoothing)?.sampleAt(timeMs);+ const displaySample = pos ? { ...frame.sample, cx: pos.cx, cy: pos.cy } : frame.sample;+ const renderAsset = resolveNativeCursorRenderAsset(frame.asset, 1, displaySample, cursorTheme);+ const bounceProgress = getNativeCursorClickBounceProgress(recordingData, timeMs);+ const scale =+ Math.max(0, cursorSize) * getNativeCursorClickBounceScale(cursorClickBounce, bounceProgress);+ const x = displaySample.cx * size.width;+ const y = displaySample.cy * size.height;+ const motionBlurPx = isPlaying+ ? getNativeCursorMotionBlurPx({+ motionBlur: cursorMotionBlur,+ point: { x, y },+ state: motionBlurStateRef.current,+ timeMs,+ })+ : 0;++ if (imageEl) {+ if (lastImageIdRef.current !== renderAsset.id) {+ imageEl.src = renderAsset.imageDataUrl;+ lastImageIdRef.current = renderAsset.id;+ }+ imageEl.style.display = "block";+ imageEl.style.width = `${renderAsset.width * scale}px`;+ imageEl.style.height = `${renderAsset.height * scale}px`;+ imageEl.style.transform = `translate3d(${x - renderAsset.hotspotX * scale}px, ${+ y - renderAsset.hotspotY * scale+ }px, 0)`;+ imageEl.style.filter = motionBlurPx > 0 ? `blur(${motionBlurPx.toFixed(2)}px)` : "none";+ }+ if (clipEl) {+ if (!cursorClipToBounds) {+ clipEl.style.clipPath = "none";+ } else {+ clipEl.style.clipPath = `inset(0 0 0 0)`;+ }+ }+}diff --git a/src/components/ai-edition/EditorEmptyState.test.tsx b/src/components/ai-edition/EditorEmptyState.test.tsxnew file mode 100644index 000000000..de66e22e9--- /dev/null+++ b/src/components/ai-edition/EditorEmptyState.test.tsx@@ -0,0 +1,235 @@+import "@testing-library/jest-dom";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { EditorEmptyState } from "./EditorEmptyState";++const bridgeMocks = vi.hoisted(() => ({+ create: vi.fn(),+ save: vi.fn(),+ addAsset: vi.fn(),+ loadProjectFile: vi.fn(),+ loadProjectFileFromPath: vi.fn(),+ getPathForFile: vi.fn(),+ openVideoFilePicker: vi.fn(),+}));++const sampleDoc = vi.hoisted(() => ({+ schemaVersion: 3,+ project: {+ id: "proj_test",+ title: "Test",+ createdAt: "2026-06-25T10:00:00.000Z",+ updatedAt: "2026-06-25T10:00:00.000Z",+ },+ assets: [],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRegions: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+}));++function setupElectronApi() {+ Object.assign(window, {+ electronAPI: {+ openVideoFilePicker: bridgeMocks.openVideoFilePicker,+ loadProjectFile: bridgeMocks.loadProjectFile,+ loadProjectFileFromPath: bridgeMocks.loadProjectFileFromPath,+ getPathForFile: bridgeMocks.getPathForFile,+ },+ });+}++vi.mock("@/native/client", () => ({+ nativeBridgeClient: {+ aiEdition: {+ create: bridgeMocks.create,+ save: bridgeMocks.save,+ addAsset: bridgeMocks.addAsset,+ },+ },+}));++vi.mock("@/lib/ai-edition/document/migrate", () => ({+ migrateProjectDataToAxcutDocument: (project: unknown) => ({+ ...sampleDoc,+ project: {+ ...sampleDoc.project,+ id: (project as { id?: string })?.id ?? "migrated",+ },+ }),+}));++describe("EditorEmptyState (new editor)", () => {+ beforeEach(() => {+ useProjectStore.getState().clear();+ setupElectronApi();+ for (const mock of Object.values(bridgeMocks)) {+ mock.mockReset();+ }+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it("shows the import button when a project is loaded but has no asset", () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ sourceDurationSec: 0,+ currentTimeSec: 0,+ dirty: false,+ lastSavedAt: new Date(),+ });++ render(<EditorEmptyState hasProject={true} />);++ expect(screen.getByText(/add a video to get started/i)).toBeInTheDocument();+ // ponytail: no "Open project" button when a project is already loaded —+ // the import button does the job.+ expect(screen.queryByText(/open project/i)).not.toBeInTheDocument();+ });++ it("shows both import + open-project buttons when no project is loaded", () => {+ render(<EditorEmptyState hasProject={false} />);++ expect(screen.getByText(/no project open/i)).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /new project \+ import video/i }),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /open project/i })).toBeInTheDocument();+ });++ it("imports a video: file picker → addAsset on the existing project", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ sourceDurationSec: 0,+ currentTimeSec: 0,+ dirty: false,+ lastSavedAt: new Date(),+ });+ bridgeMocks.openVideoFilePicker.mockResolvedValue({+ success: true,+ path: "/tmp/recording.mp4",+ });+ bridgeMocks.addAsset.mockResolvedValue({+ assetId: "asset_1",+ document: {+ ...sampleDoc,+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "recording.mp4",+ originalPath: "/tmp/recording.mp4",+ },+ ],+ project: { ...sampleDoc.project, primaryAssetId: "asset_1" },+ },+ });++ render(<EditorEmptyState hasProject={true} />);++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /import video/i }));+ });++ await waitFor(() => {+ expect(bridgeMocks.openVideoFilePicker).toHaveBeenCalledTimes(1);+ // The store's addAsset signs projectId as the first arg.+ expect(bridgeMocks.addAsset).toHaveBeenCalledWith(+ "proj_test",+ "/tmp/recording.mp4",+ "recording.mp4",+ );+ });+ });++ it("creates a project when importing with no project loaded", async () => {+ bridgeMocks.create.mockResolvedValue({ success: true, document: sampleDoc });+ bridgeMocks.openVideoFilePicker.mockResolvedValue({+ success: true,+ path: "/tmp/recording.mp4",+ });+ bridgeMocks.addAsset.mockResolvedValue({+ assetId: "asset_1",+ document: sampleDoc,+ });++ render(<EditorEmptyState hasProject={false} />);++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /new project \+ import video/i }));+ });++ await waitFor(() => {+ expect(bridgeMocks.create).toHaveBeenCalledTimes(1);+ expect(bridgeMocks.addAsset).toHaveBeenCalledWith(+ "proj_test",+ "/tmp/recording.mp4",+ "recording.mp4",+ );+ });+ });++ it("opens a .openscreen project file via the load button", async () => {+ bridgeMocks.loadProjectFile.mockResolvedValue({+ success: true,+ project: { id: "loaded", title: "Loaded" },+ });+ bridgeMocks.save.mockResolvedValue({ success: true, document: sampleDoc });++ render(<EditorEmptyState hasProject={false} />);++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /open project/i }));+ });++ await waitFor(() => {+ expect(bridgeMocks.loadProjectFile).toHaveBeenCalledTimes(1);+ expect(bridgeMocks.save).toHaveBeenCalledTimes(1);+ });+ });++ it("shows the unsupported-format dialog when a non-.openscreen file is dropped", async () => {+ render(<EditorEmptyState hasProject={false} />);++ const file = new File([new Uint8Array([0, 1, 2])], "recording.mp4", { type: "video/mp4" });+ const dropZone = screen.getByText(/no project open/i).parentElement?.parentElement+ ?.parentElement as HTMLElement;+ expect(dropZone).toBeTruthy();++ // ponytail: jsdom doesn't ship `DataTransfer`, so the file list is a+ // plain array on a stand-in. React's `files` getter on dataTransfer+ // is what the component reads.+ fireEvent.drop(dropZone, {+ dataTransfer: { files: [file] },+ });++ await waitFor(() => {+ expect(screen.getByText(/unsupported format/i)).toBeInTheDocument();+ });+ });+});diff --git a/src/components/ai-edition/EditorEmptyState.tsx b/src/components/ai-edition/EditorEmptyState.tsxnew file mode 100644index 000000000..f9c34e622--- /dev/null+++ b/src/components/ai-edition/EditorEmptyState.tsx@@ -0,0 +1,238 @@+// Empty state for the new editor's preview.+//+// Mirrors the legacy `EditorEmptyState` (import video + load project + drag+// drop) but on top of the project store: a "no project" branch offers+// `createProject` + `loadProject`, and a "has project, no asset" branch offers+// the file picker + load (for the rare user who already has a .openscreen+// project without media attached).+//+// ponytail: keeps the existing copy from the legacy component and the same+// drag/drop affordance, but the actions map to project-store operations+// rather than the legacy `nativeBridgeClient.project.*` ones. The two editor+// shells will collapse once we have a single render path; until then the+// "open screen" feature lives here in the new UX and in the legacy+// `EditorEmptyState.tsx` for the deprecated editor.++import { AlertCircle, Film, FolderOpen, Upload, X } from "lucide-react";+import { useCallback, useRef, useState } from "react";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { nativeBridgeClient } from "@/native";+import styles from "./NewEditorShell.module.css";++type DropError = "unsupported-format" | "load-failed" | null;++interface EditorEmptyStateProps {+ /** True when a project exists (so the copy becomes "add a video" not "no project"). */+ hasProject: boolean;+ /** Show the file dialog (Open Video) and a Load Project button when no project is loaded. */+ showLoadProjectButton?: boolean;+}++export function EditorEmptyState({+ hasProject,+ showLoadProjectButton = true,+}: EditorEmptyStateProps) {+ const [isDraggingOver, setIsDraggingOver] = useState(false);+ const [dropError, setDropError] = useState<DropError>(null);+ const lastDropErrorRef = useRef<Exclude<DropError, null>>("unsupported-format");+ if (dropError !== null) {+ lastDropErrorRef.current = dropError;+ }++ const createProject = useProjectStore((s) => s.createProject);+ const addAsset = useProjectStore((s) => s.addAsset);+ const loadProject = useProjectStore((s) => s.loadProject);++ const ensureProject = useCallback(async (): Promise<string | null> => {+ const existing = useProjectStore.getState().projectId;+ if (existing) return existing;+ const doc = await createProject(`Project ${new Date().toLocaleString()}`);+ return doc.project.id;+ }, [createProject]);++ const handleImportVideo = useCallback(async () => {+ const result = await window.electronAPI?.openVideoFilePicker?.();+ if (!result || result.canceled || !result.success || !result.path) return;+ try {+ const projectId = await ensureProject();+ if (!projectId) return;+ const label = result.path.split(/[\\/]/).pop() || "Recording";+ await addAsset(result.path, label);+ } catch (err) {+ setDropError("load-failed");+ // ponytail: surface as a console message only — the dialog above+ // already tells the user something went wrong.+ console.error("Failed to import video", err);+ }+ }, [addAsset, ensureProject]);++ const handleLoadProject = useCallback(async () => {+ try {+ const result = await window.electronAPI?.loadProjectFile?.();+ if (!result?.success || !result.project) return;+ // ponytail: legacy v2 projects round-trip through the migrator.+ // The bridge expects a v3 AxcutDocument.+ const migrated = migrateProjectDataToAxcutDocument(result.project as never);+ const saved = await nativeBridgeClient.aiEdition.save(migrated);+ if (saved.success && saved.document) {+ await loadProject(migrated.project.id);+ } else {+ setDropError("load-failed");+ }+ } catch {+ setDropError("load-failed");+ }+ }, [loadProject]);++ const handleDragOver = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ if (e.dataTransfer.items.length > 0) {+ setIsDraggingOver(true);+ }+ }, []);++ const handleDragLeave = useCallback((e: React.DragEvent) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node)) {+ setIsDraggingOver(false);+ }+ }, []);++ const handleDrop = useCallback(+ async (e: React.DragEvent) => {+ e.preventDefault();+ setIsDraggingOver(false);+ const files = Array.from(e.dataTransfer.files);+ if (files.length === 0) return;+ const projectFile = files.find((f) => f.name.endsWith(".openscreen"));+ if (!projectFile) {+ setDropError("unsupported-format");+ return;+ }+ let filePath: string;+ try {+ filePath = window.electronAPI?.getPathForFile(projectFile) ?? "";+ } catch {+ setDropError("load-failed");+ return;+ }+ if (!filePath) {+ setDropError("load-failed");+ return;+ }+ const result = await window.electronAPI?.loadProjectFileFromPath?.(filePath);+ if (!result?.success || !result.project) {+ setDropError("load-failed");+ return;+ }+ try {+ const migrated = migrateProjectDataToAxcutDocument(result.project as never);+ const saved = await nativeBridgeClient.aiEdition.save(migrated);+ if (saved.success && saved.document) {+ await loadProject(migrated.project.id);+ } else {+ setDropError("load-failed");+ }+ } catch {+ setDropError("load-failed");+ }+ },+ [loadProject],+ );++ return (+ <div+ className={styles.previewEmptyDrop}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ {isDraggingOver ? (+ <div className={styles.previewEmptyDropOverlay}>+ <Upload className={styles.previewEmptyDropIcon} />+ <p className={styles.previewEmptyDropLabel}>Drop a .openscreen project file</p>+ </div>+ ) : null}++ <Dialog open={dropError !== null} onOpenChange={(open) => !open && setDropError(null)}>+ <DialogContent className={styles.previewEmptyDialog}>+ <DialogHeader className={styles.previewEmptyDialogHeader}>+ <div className={styles.previewEmptyDialogHeaderInner}>+ <img+ src="./openscreen.png"+ alt=""+ aria-hidden="true"+ className={styles.previewEmptyDialogLogo}+ />+ <DialogTitle className={styles.previewEmptyDialogTitle}>+ {lastDropErrorRef.current === "unsupported-format"+ ? "Unsupported format"+ : "Could not open project"}+ </DialogTitle>+ </div>+ </DialogHeader>+ <div className={styles.previewEmptyDialogBody}>+ <div className={styles.previewEmptyDialogIcon}>+ <AlertCircle className={styles.previewEmptyDialogAlertIcon} />+ </div>+ <p className={styles.previewEmptyDialogMessage}>+ {lastDropErrorRef.current === "unsupported-format"+ ? "Only .openscreen project files are supported. Drop a recording to import it, or use the buttons above."+ : "We couldn't read that project file. Try re-opening it from the file picker."}+ </p>+ </div>+ <button+ type="button"+ onClick={() => setDropError(null)}+ className={styles.previewEmptyDialogClose}+ >+ <X className={styles.previewEmptyDialogCloseIcon} />+ Close+ </button>+ </DialogContent>+ </Dialog>++ <div className={styles.previewEmptyInner}>+ <img src="./openscreen.png" alt="" aria-hidden="true" className={styles.previewEmptyLogo} />+ <div className={styles.previewEmptyHeading}>+ <h2 className={styles.previewEmptyTitle}>+ {hasProject ? "Add a video to get started" : "No project open"}+ </h2>+ <p className={styles.previewEmptyDescription}>+ {hasProject+ ? "Import a recording to begin editing."+ : "Create a new project or open an existing one."}+ </p>+ </div>+ <div className={styles.previewEmptyActions}>+ <button+ type="button"+ onClick={() => void handleImportVideo()}+ className={styles.previewEmptyPrimaryButton}+ >+ <Film className={styles.previewEmptyButtonIcon} />+ {hasProject ? "Import video" : "New project + import video"}+ </button>+ {showLoadProjectButton && !hasProject ? (+ <button+ type="button"+ onClick={() => void handleLoadProject()}+ className={styles.previewEmptySecondaryButton}+ >+ <FolderOpen className={styles.previewEmptyButtonIcon} />+ Open project+ </button>+ ) : null}+ </div>+ <p className={styles.previewEmptyHint}>+ Supported formats: MP4, MOV, WebM, MKV, AVI, M4V, WMV.+ </p>+ <p className={styles.previewEmptyDragHint}>+ <Upload className={styles.previewEmptyDragHintIcon} />+ Or drop a .openscreen project file here.+ </p>+ </div>+ </div>+ );+}diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsxnew file mode 100644index 000000000..396511cf3--- /dev/null+++ b/src/components/ai-edition/ExportDialog.tsx@@ -0,0 +1,541 @@+// Export dialog for the new editor. Wires together:+// 1. pickExportSavePath (native save dialog)+// 2. exportAxcutDocument (renders frames + muxes mp4/gif)+// 3. writeExportToPath (writes the resulting buffer to disk)+//+// Format/quality/GIF options live in the dialog's local state. The+// legacy `ExportDialog` (in components/video-editor) is the rich version+// used by the legacy VideoEditor; this one is a compact surface tuned for+// the new shell's modal style.++import { Download, FileVideo, Loader2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import {+ type DocumentExportOptions,+ exportAxcutDocument,+} from "@/lib/ai-edition/exporter/documentExporter";+import type { AxcutDocument } from "@/lib/ai-edition/schema";+import {+ type ExportFormat,+ type ExportProgress,+ type ExportQuality,+ GIF_FRAME_RATES,+ GIF_SIZE_PRESETS,+ type GifFrameRate,+ type GifSizePreset,+} from "@/lib/exporter";+import { nativeBridgeClient } from "@/native/client";+import { ModalShell } from "./Modals";+import styles from "./NewEditorShell.module.css";++type Phase = "idle" | "configuring" | "rendering" | "writing" | "done" | "error";++const QUALITY_OPTIONS: Array<{+ value: ExportQuality;+ label: string;+ hint: string;+}> = [+ { value: "medium", label: "720p", hint: "Smaller file" },+ { value: "good", label: "1080p", hint: "Recommended" },+ { value: "source", label: "Source", hint: "Match recording" },+];++interface ExportDialogProps {+ open: boolean;+ onClose: () => void;+ document: AxcutDocument | null;+}++export function ExportDialog({ open, onClose, document }: ExportDialogProps) {+ const [format, setFormat] = useState<ExportFormat>("mp4");+ const [quality, setQuality] = useState<ExportQuality>("good");+ const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(15);+ const [gifSize, setGifSize] = useState<GifSizePreset>("medium");+ const [gifLoop, setGifLoop] = useState(true);+ const [phase, setPhase] = useState<Phase>("idle");+ const [progress, setProgress] = useState<ExportProgress | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [savedPath, setSavedPath] = useState<string | null>(null);+ const cancelRef = useRef<{ cancel: () => void } | null>(null);++ useEffect(() => {+ if (!open) {+ setPhase("idle");+ setProgress(null);+ setError(null);+ setSavedPath(null);+ cancelRef.current = null;+ }+ }, [open]);++ const handleClose = () => {+ if (phase === "rendering" || phase === "writing") return;+ onClose();+ };++ const handleStart = async () => {+ if (!document) return;+ const asset =+ document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];+ if (!asset) {+ setError("Add a video before exporting.");+ setPhase("error");+ return;+ }++ const safeName = (document.project.title || "OpenScreen")+ .replace(/[^a-z0-9-_]+/gi, "_")+ .replace(/^_+|_+$/g, "")+ .slice(0, 60);+ const suggested = `${safeName || "export"}${format === "gif" ? ".gif" : ".mp4"}`;++ setPhase("configuring");+ setError(null);+ setProgress(null);+ setSavedPath(null);++ let pickedPath: string | undefined;+ try {+ const picker = await window.electronAPI?.pickExportSavePath?.(suggested);+ pickedPath = picker && "path" in picker ? picker.path : undefined;+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setPhase("error");+ return;+ }+ if (!pickedPath) {+ setPhase("idle");+ return;+ }++ setPhase("rendering");+ const options: DocumentExportOptions = {+ format,+ quality,+ gifFrameRate,+ gifLoop,+ gifSizePreset: gifSize,+ sourceWidth: asset.video?.width,+ sourceHeight: asset.video?.height,+ onProgress: (p) => setProgress(p),+ };++ try {+ const result = await exportAxcutDocument(document, options);+ if (!result.success || !result.blob) {+ throw new Error(result.error ?? "Export failed");+ }+ setPhase("writing");+ const arrayBuffer = await result.blob.arrayBuffer();+ const writeResult = await window.electronAPI?.writeExportToPath?.(arrayBuffer, pickedPath);+ if (!writeResult?.success) {+ throw new Error(writeResult?.error ?? "Failed to write file");+ }+ setSavedPath(pickedPath);+ setPhase("done");+ toast.success(`${format === "gif" ? "GIF" : "Video"} exported`, {+ description: pickedPath,+ action: {+ label: "Show in folder",+ onClick: () => {+ void window.electronAPI?.revealInFolder?.(pickedPath);+ },+ },+ });+ // Touch the bridge so it stays referenced even when export+ // is invoked from a non-Electron shim.+ void nativeBridgeClient.aiEdition.llmGetSnapshot;+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setPhase("error");+ toast.error("Export failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ };++ const isBusy = phase === "rendering" || phase === "writing" || phase === "configuring";+ const pct = progress?.percentage ?? 0;+ const gifSizeLabel = GIF_SIZE_PRESETS[gifSize].label;++ return (+ <ModalShell+ open={open}+ onClose={handleClose}+ title="Export"+ subtitle="Render the timeline to a file"+ >+ <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "1fr 1fr",+ gap: 8,+ }}+ >+ <FormatToggle+ active={format === "mp4"}+ label="MP4"+ icon={<FileVideo size={18} />}+ onClick={() => setFormat("mp4")}+ disabled={isBusy}+ />+ <FormatToggle+ active={format === "gif"}+ label="GIF"+ icon={<Download size={18} />}+ onClick={() => setFormat("gif")}+ disabled={isBusy}+ />+ </div>++ {format === "mp4" ? (+ <section>+ <div+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ marginBottom: 8,+ }}+ >+ Quality+ </div>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>+ {QUALITY_OPTIONS.map((q) => (+ <button+ type="button"+ key={q.value}+ disabled={isBusy}+ onClick={() => setQuality(q.value)}+ style={{+ display: "flex",+ flexDirection: "column",+ gap: 2,+ padding: "10px 12px",+ border: `1px solid ${quality === q.value ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 10,+ background: quality === q.value ? "var(--accent-wash)" : "var(--surface)",+ color: "var(--fg-2)",+ cursor: "pointer",+ font: "500 13px/1 var(--font-body)",+ }}+ >+ <span style={{ color: "var(--fg)", fontWeight: 600 }}>{q.label}</span>+ <span style={{ font: "500 11px var(--font-body)", color: "var(--muted)" }}>+ {q.hint}+ </span>+ </button>+ ))}+ </div>+ </section>+ ) : (+ <section style={{ display: "flex", flexDirection: "column", gap: 12 }}>+ <div>+ <div+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ marginBottom: 8,+ }}+ >+ Frame rate+ </div>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>+ {GIF_FRAME_RATES.map((r) => (+ <button+ type="button"+ key={r.value}+ disabled={isBusy}+ onClick={() => setGifFrameRate(r.value)}+ style={segStyle(gifFrameRate === r.value)}+ >+ {r.value} FPS+ </button>+ ))}+ </div>+ </div>+ <div>+ <div+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ marginBottom: 8,+ }}+ >+ Size+ </div>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>+ {(Object.keys(GIF_SIZE_PRESETS) as GifSizePreset[]).map((s) => (+ <button+ type="button"+ key={s}+ disabled={isBusy}+ onClick={() => setGifSize(s)}+ style={segStyle(gifSize === s)}+ >+ {GIF_SIZE_PRESETS[s].label}+ </button>+ ))}+ </div>+ </div>+ <div className={styles.paneRow} style={{ margin: 0 }}>+ <span className="label">Loop GIF</span>+ <button+ type="button"+ className={`${styles.toggle} ${gifLoop ? styles.isOn : ""}`}+ aria-pressed={gifLoop}+ disabled={isBusy}+ onClick={() => setGifLoop((v) => !v)}+ />+ </div>+ <div+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ letterSpacing: "0.04em",+ }}+ >+ {gifFrameRate} FPS · {gifSizeLabel} · {gifLoop ? "Loop on" : "Loop off"}+ </div>+ </section>+ )}++ <ProgressBlock+ phase={phase}+ progress={progress}+ error={error}+ pct={pct}+ savedPath={savedPath}+ />++ <div+ style={{+ display: "flex",+ justifyContent: "flex-end",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={handleClose}+ disabled={isBusy}+ >+ {phase === "done" ? "Close" : "Cancel"}+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={handleStart}+ disabled={isBusy || !document}+ >+ {isBusy ? (+ <>+ <Loader2 size={14} className="animate-spin" />+ {phase === "rendering"+ ? "Rendering…"+ : phase === "writing"+ ? "Saving…"+ : "Starting…"}+ </>+ ) : (+ <>+ <Download size={14} />+ Export {format === "gif" ? "GIF" : "MP4"}+ </>+ )}+ </button>+ </div>+ </div>+ </ModalShell>+ );+}++function FormatToggle({+ active,+ label,+ icon,+ onClick,+ disabled,+}: {+ active: boolean;+ label: string;+ icon: React.ReactNode;+ onClick: () => void;+ disabled?: boolean;+}) {+ return (+ <button+ type="button"+ disabled={disabled}+ onClick={onClick}+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ gap: 8,+ padding: "12px 16px",+ border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 10,+ background: active ? "var(--accent-wash)" : "var(--surface)",+ color: active ? "var(--accent-on)" : "var(--fg-2)",+ cursor: "pointer",+ font: "600 14px/1 var(--font-body)",+ }}+ >+ {icon}+ {label}+ </button>+ );+}++function ProgressBlock({+ phase,+ progress,+ error,+ pct,+ savedPath,+}: {+ phase: Phase;+ progress: ExportProgress | null;+ error: string | null;+ pct: number;+ savedPath: string | null;+}) {+ if (phase === "idle" || phase === "configuring") {+ return (+ <div+ style={{+ padding: "16px",+ border: "1px solid var(--border)",+ borderRadius: 10,+ background: "var(--surface-1)",+ color: "var(--muted)",+ font: "500 12px var(--font-body)",+ textAlign: "center",+ }}+ >+ Pick a format and press Export to start.+ </div>+ );+ }+ if (phase === "done") {+ return (+ <div+ style={{+ padding: "16px",+ border: "1px solid var(--brand)",+ borderRadius: 10,+ background: "var(--success-soft)",+ color: "var(--fg-2)",+ font: "500 12px var(--font-body)",+ }}+ >+ Saved to <span style={{ fontFamily: "var(--font-mono)" }}>{savedPath}</span>+ </div>+ );+ }+ if (phase === "error") {+ return (+ <div+ style={{+ padding: "16px",+ border: "1px solid var(--danger)",+ borderRadius: 10,+ background: "var(--danger-soft)",+ color: "var(--danger)",+ font: "500 12px var(--font-body)",+ }}+ >+ {error ?? "Export failed."}+ </div>+ );+ }+ const current = progress?.currentFrame ?? 0;+ const total = progress?.totalFrames ?? 0;+ const eta = progress?.estimatedTimeRemaining ?? 0;+ return (+ <div+ style={{+ padding: "12px 14px",+ border: "1px solid var(--border)",+ borderRadius: 10,+ background: "var(--surface-1)",+ display: "flex",+ flexDirection: "column",+ gap: 8,+ }}+ >+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <span style={{ font: "500 12px var(--font-body)", color: "var(--fg-2)" }}>+ {phase === "writing" ? "Writing file…" : "Rendering frames"}+ </span>+ <span+ style={{+ font: "500 12px/1 var(--font-mono)",+ color: "var(--brand)",+ }}+ >+ {Math.round(pct)}%+ </span>+ </div>+ <div+ style={{+ position: "relative",+ height: 8,+ background: "var(--surface-3)",+ borderRadius: 999,+ overflow: "hidden",+ }}+ >+ <div+ style={{+ position: "absolute",+ inset: 0,+ width: `${Math.max(0, Math.min(100, pct))}%`,+ background: "var(--brand)",+ transition: "width 200ms var(--ease)",+ }}+ />+ </div>+ <div+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ letterSpacing: "0.04em",+ }}+ >+ {total > 0+ ? `${current} / ${total} frames · ETA ${Math.max(0, Math.round(eta))}s`+ : "Preparing encoder…"}+ </div>+ </div>+ );+}++function segStyle(active: boolean): React.CSSProperties {+ return {+ padding: "8px 10px",+ border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 8,+ background: active ? "var(--brand)" : "var(--bg)",+ color: active ? "var(--accent-on)" : "var(--fg-2)",+ cursor: "pointer",+ font: "500 12px/1 var(--font-body)",+ };+}diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsxnew file mode 100644index 000000000..ffa646cca--- /dev/null+++ b/src/components/ai-edition/LeftPanel.tsx@@ -0,0 +1,699 @@+import { Film, Loader2, MessageSquare, Plus, Search, X } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { AI_FEATURES_ENABLED } from "@/components/video-editor/featureFlags";+import type { AxcutAsset } from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { nativeBridgeClient } from "@/native/client";+import type { AiEditionLlmConfig } from "@/native/contracts";+import { ChatHistoryModal, SourceTranscriptModal } from "./Modals";+import styles from "./NewEditorShell.module.css";+import { ProviderSettings } from "./ProviderSettings";++export type LeftTab = "chat" | "media";++function formatTranscriptText(t: unknown): string {+ if (!t || typeof t !== "object") return "";+ const obj = t as Record<string, unknown>;+ const segments = (obj.segments as Array<Record<string, unknown>>) ?? [];+ if (segments.length === 0) return "";+ return segments+ .map((s, i) => {+ const start = s.startSec ?? s.start ?? "?";+ const end = s.endSec ?? s.end ?? "?";+ const text = s.text ?? "";+ return `[${i + 1}] ${start}s–${end}s: ${text}`;+ })+ .join("\n");+}++const THUMB_PALETTE = ["thumbRed", "thumbGreen", "thumbAmber", "thumbCyan"] as const;++function formatTimecode(sec: number | undefined): string {+ if (!sec || !Number.isFinite(sec)) return "0:00:00.0";+ const h = Math.floor(sec / 3600);+ const m = Math.floor((sec % 3600) / 60);+ const s = (sec % 60).toFixed(1);+ return `${h}:${m.toString().padStart(2, "0")}:${s.padStart(3, "0")}`;+}++function formatSize(bytes: number | undefined): string {+ // ponytail: AxcutAsset has no size field yet — always em-dash.+ if (!bytes || !Number.isFinite(bytes)) return "—";+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(0)} MB`;+ return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;+}++function basename(path: string): string {+ return path.split(/[\\/]/).pop() ?? path;+}++function MediaList({+ assets,+ onOpenTranscript,+ transcriptReadyIds,+ assetStatuses,+}: {+ assets: AxcutAsset[];+ onOpenTranscript?: (asset: AxcutAsset) => void;+ transcriptReadyIds?: Set<string>;+ assetStatuses?: Record<string, "pending" | "running" | "failed">;+}) {+ if (assets.length === 0) {+ return (+ <p+ style={{+ font: "400 12px var(--font-body)",+ color: "var(--muted)",+ padding: "16px var(--sp-4)",+ textAlign: "center",+ lineHeight: 1.5,+ }}+ >+ No media in this project yet. Import a video below.+ </p>+ );+ }+ return (+ <ul className={styles.mediaList}>+ {assets.map((asset, i) => {+ const label = asset.label || basename(asset.originalPath);+ const tc = formatTimecode(asset.durationSec);+ const size = formatSize(undefined);+ const palette = THUMB_PALETTE[i % THUMB_PALETTE.length];+ const isReady = transcriptReadyIds?.has(asset.id);+ const status = isReady ? "complete" : (assetStatuses?.[asset.id] ?? "idle");++ return (+ <li+ className={styles.mediaCard}+ key={asset.id}+ title={asset.originalPath}+ draggable+ onDragStart={(e) => {+ e.dataTransfer.setData("application/x-axcut-asset", asset.id);+ e.dataTransfer.effectAllowed = "copy";+ }}+ >+ <button+ type="button"+ style={{+ display: "flex",+ flexDirection: "column",+ border: 0,+ background: "none",+ padding: 0,+ cursor: "pointer",+ font: "inherit",+ textAlign: "left",+ width: "100%",+ }}+ onClick={() => onOpenTranscript?.(asset)}+ >+ <div className={`${styles.thumb} ${styles[palette]}`} aria-hidden>+ <Film size={22} />+ </div>+ <div className={styles.mediaMeta}>+ <div className={styles.name}>{label}</div>+ <div className={styles.row}>+ <span+ style={{+ width: 8,+ height: 8,+ borderRadius: "50%",+ background:+ status === "complete"+ ? "var(--success)"+ : status === "running"+ ? "var(--accent)"+ : status === "pending"+ ? "#f59e0b"+ : status === "failed"+ ? "var(--danger)"+ : "var(--dim)",+ boxShadow:+ status === "complete"+ ? "0 0 0 3px var(--success-soft)"+ : status === "running"+ ? "0 0 0 3px rgba(16, 185, 129, 0.2)"+ : status === "pending"+ ? "0 0 0 3px rgba(245, 158, 11, 0.2)"+ : status === "failed"+ ? "0 0 0 3px rgba(239, 68, 68, 0.2)"+ : "none",+ flexShrink: 0,+ }}+ aria-label={+ status === "complete"+ ? "Transcript ready"+ : status === "running"+ ? "Transcribing"+ : status === "pending"+ ? "Pending transcription"+ : status === "failed"+ ? "Transcription failed"+ : "No transcript"+ }+ />+ <span className={styles.timecode}>{tc}</span>+ <span className={styles.size}>{size}</span>+ </div>+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ );+}++export function MediaPane({+ assetStatuses,+}: {+ assetStatuses?: Record<string, "pending" | "running" | "failed">;+}) {+ const projectId = useProjectStore((s) => s.projectId);+ const document = useProjectStore((s) => s.document);+ const addAsset = useProjectStore((s) => s.addAsset);+ const [query, setQuery] = useState("");+ const [busy, setBusy] = useState(false);+ const [srcTranscriptAsset, setSrcTranscriptAsset] = useState<AxcutAsset | null>(null);++ const handleImport = async () => {+ if (!projectId) {+ toast.error("Open a project first");+ return;+ }+ const picker = await window.electronAPI?.openVideoFilePicker();+ if (!picker?.success || !picker.path) return;+ setBusy(true);+ try {+ await addAsset(picker.path);+ toast.success(`Added ${basename(picker.path)}`);+ } catch (err) {+ toast.error("Could not add asset", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ };++ const filtered = (document?.assets ?? []).filter((a) => {+ if (!query) return true;+ const text = `${a.label} ${a.originalPath}`.toLowerCase();+ return text.includes(query.toLowerCase());+ });++ return (+ <aside className={styles.panel}>+ <header className={styles.panelHead}>+ <h2>Media</h2>+ </header>+ <div style={{ padding: "10px var(--sp-3) 8px" }}>+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: 8,+ padding: "6px 10px",+ background: "var(--surface-warm)",+ border: "1px solid var(--border-soft)",+ borderRadius: "var(--r-md)",+ color: "var(--meta)",+ }}+ >+ <Search size={14} />+ <input+ type="text"+ placeholder="Search…"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ style={{+ flex: 1,+ border: 0,+ background: "transparent",+ outline: "none",+ font: "13px var(--font-body)",+ color: "var(--fg)",+ }}+ />+ {query ? (+ <button+ type="button"+ onClick={() => setQuery("")}+ aria-label="Clear search"+ style={{+ background: "transparent",+ border: 0,+ color: "var(--meta)",+ cursor: "pointer",+ }}+ >+ <X size={12} />+ </button>+ ) : null}+ </div>+ </div>+ <div className={styles.panelBody} style={{ padding: "4px var(--sp-3) 8px" }}>+ <MediaList+ assets={filtered}+ onOpenTranscript={setSrcTranscriptAsset}+ transcriptReadyIds={new Set(document?.transcripts?.map((t) => t.assetId) ?? [])}+ assetStatuses={assetStatuses}+ />+ </div>+ <button+ type="button"+ className={styles.importBtn}+ onClick={handleImport}+ disabled={!projectId || busy}+ >+ <Plus size={14} />+ Import media+ </button>+ {document?.transcript ? (+ <div+ style={{+ margin: "0 var(--sp-3) 8px",+ padding: "6px 10px",+ borderRadius: 999,+ background: "var(--success-soft)",+ color: "var(--success)",+ font: "500 11px/1 var(--font-mono)",+ letterSpacing: "0.04em",+ display: "inline-flex",+ alignItems: "center",+ gap: 6,+ }}+ >+ <span+ style={{+ width: 6,+ height: 6,+ borderRadius: "50%",+ background: "var(--success)",+ }}+ />+ TRANSCRIPT READY+ </div>+ ) : null}+ <SourceTranscriptModal+ open={srcTranscriptAsset !== null}+ onClose={() => setSrcTranscriptAsset(null)}+ assetLabel={srcTranscriptAsset?.label ?? ""}+ assetPath={srcTranscriptAsset?.originalPath ?? ""}+ tcFormatted={formatTimecode(srcTranscriptAsset?.durationSec)}+ transcriptText={+ srcTranscriptAsset && document?.transcripts+ ? (() => {+ const t = document.transcripts.find((t) => t.assetId === srcTranscriptAsset.id);+ return t ? formatTranscriptText(t) : null;+ })()+ : null+ }+ />+ </aside>+ );+}++export function LeftPanel({+ active,+ assetStatuses,+}: {+ active: LeftTab;+ assetStatuses?: Record<string, "pending" | "running" | "failed">;+}) {+ return active === "chat" && AI_FEATURES_ENABLED ? (+ <ChatStripPanel />+ ) : (+ <MediaPane assetStatuses={assetStatuses} />+ );+}++function ChatStripPanel() {+ const projectId = useProjectStore((s) => s.projectId);+ const [messages, setMessages] = useState<Array<{ role: string; content: string; time?: string }>>(+ [],+ );+ const [input, setInput] = useState("");+ const [busy, setBusy] = useState(false);+ const [llmConfig, setLlmConfig] = useState<AiEditionLlmConfig | null>(null);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [chatsOpen, setChatsOpen] = useState(false);+ const [sessionNum, setSessionNum] = useState(1);+ const scrollRef = useRef<HTMLDivElement | null>(null);++ const refreshLlm = useCallback(async () => {+ try {+ const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();+ setLlmConfig(snap.config);+ } catch {+ // ponytail: silent+ }+ }, []);++ useEffect(() => {+ void refreshLlm();+ }, [refreshLlm]);++ useEffect(() => {+ if (!projectId) return;+ void (async () => {+ try {+ const history = await nativeBridgeClient.aiEdition.chatHistory(projectId);+ setMessages(history.map((m) => ({ role: m.role, content: m.content, time: m.createdAt })));+ } catch {+ // ponytail: silent — shim mode or missing project+ }+ })();+ }, [projectId]);++ useEffect(() => {+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });+ });++ const send = async () => {+ if (!projectId || !input.trim() || busy) return;+ const text = input.trim();+ setInput("");+ setBusy(true);+ try {+ const result = await nativeBridgeClient.aiEdition.chatRun(projectId, text);+ setMessages((prev) => [+ ...prev,+ { role: "user", content: text, time: new Date().toLocaleTimeString() },+ ]);+ const assistant = result.assistantMessage;+ if (result.success && assistant) {+ setMessages((prev) => [+ ...prev,+ {+ role: "assistant",+ content: assistant.content,+ time: new Date().toLocaleTimeString(),+ },+ ]);+ } else {+ toast.error(result.error ?? "Chat failed");+ }+ } catch (err) {+ toast.error("Chat failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ };++ const modelLabel = llmConfig+ ? `${llmConfig.provider} / ${llmConfig.model}`+ : "Configure AI Model";+ const reasoningLabel =+ llmConfig?.reasoningEffort && llmConfig.reasoningEffort !== "none"+ ? `Reasoning ${llmConfig.reasoningEffort}`+ : null;++ const newChat = useCallback(async () => {+ setMessages([]);+ setSessionNum((n) => n + 1);+ if (projectId) {+ try {+ await nativeBridgeClient.aiEdition.chatClear(projectId);+ } catch {+ // ponytail: silent — shim mode or no-op+ }+ }+ }, [projectId]);++ return (+ <aside className={styles.panel}>+ <div className={styles.chatStrip}>+ <div className={styles.chatStripRow}>+ <span className={styles.ctxPill}>+ <span className={styles.d} aria-hidden />+ 0% context+ </span>+ <span className={styles.stripActions}>+ <button type="button" title="Compact" aria-label="Compact">+ <svg+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M 6 6 L 12 10 L 18 6" />+ <path d="M 4 12 L 20 12" />+ <path d="M 6 18 L 12 14 L 18 18" />+ </svg>+ </button>+ <button+ type="button"+ title="AI settings"+ aria-label="AI settings"+ onClick={() => setSettingsOpen(true)}+ >+ <svg+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <circle cx="12" cy="12" r="3" />+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />+ </svg>+ </button>+ </span>+ <span className={styles.stripActions}>+ <button+ type="button"+ title="History"+ aria-label="History"+ onClick={() => setChatsOpen(true)}+ >+ <svg+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />+ <path d="M3 3v5h5" />+ <path d="M12 7v5l4 2" />+ </svg>+ </button>+ <button+ type="button"+ title="New conversation"+ aria-label="New conversation"+ onClick={newChat}+ >+ <svg+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />+ <path d="M12 7v6" />+ <path d="M9 10h6" />+ </svg>+ </button>+ </span>+ </div>+ <div className={styles.chatHint}>Describe the edit you want…</div>+ </div>++ <div className={styles.panelBody} ref={scrollRef}>+ {messages.length === 0 ? (+ <p+ style={{+ font: "400 12px var(--font-body)",+ color: "var(--muted)",+ padding: "24px var(--sp-4)",+ textAlign: "center",+ lineHeight: 1.5,+ }}+ >+ No messages yet. Ask the agent to cut silences, tighten pauses, or add captions.+ </p>+ ) : (+ <>+ {messages.map((m, i) => (+ <div className={styles.msg} key={i}>+ <div className={styles.msgHead}>+ <span className={styles.msgAuthor}>+ {m.role === "user" ? "You" : "OpenScreen"}+ </span>+ {m.time ? (+ <span+ className="right"+ style={{ font: "500 10px/1 var(--font-mono)", color: "var(--muted)" }}+ >+ {m.time}+ </span>+ ) : null}+ </div>+ <div className={styles.msgBubble}>{m.content}</div>+ </div>+ ))}+ {busy ? (+ <div className={styles.msg} aria-live="polite">+ <div className={styles.msgHead}>+ <span className={styles.msgAuthor}>OpenScreen</span>+ </div>+ <div+ className={styles.msgBubble}+ style={{ color: "var(--muted)", fontStyle: "italic" }}+ >+ <Loader2+ size={12}+ className="animate-spin"+ style={{ marginRight: 6, verticalAlign: "middle" }}+ />+ Thinking…+ </div>+ </div>+ ) : null}+ </>+ )}+ </div>++ <div className={styles.chatInput}>+ <textarea+ placeholder="Describe the edit you want."+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void send();+ }+ }}+ />+ <div className="actions">+ <button+ type="button"+ className={styles.modelPicker}+ aria-label="AI settings"+ onClick={() => setSettingsOpen(true)}+ >+ <svg+ width={12}+ height={12}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <line x1="3" y1="6" x2="21" y2="6" />+ <line x1="3" y1="12" x2="21" y2="12" />+ <line x1="3" y1="18" x2="21" y2="18" />+ </svg>+ <span>{modelLabel}</span>+ {reasoningLabel ? (+ <span className="chip">+ <span className="d" />+ {reasoningLabel}+ </span>+ ) : null}+ </button>+ <button+ type="button"+ className={styles.sendBtn}+ title="Send (Enter)"+ aria-label="Send"+ onClick={send}+ disabled={busy || !input.trim()}+ >+ <svg+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <line x1="22" y1="2" x2="11" y2="13" />+ <polygon points="22 2 15 22 11 13 2 9 22 2" />+ </svg>+ </button>+ </div>+ </div>+ <ProviderSettings+ open={settingsOpen}+ onClose={() => {+ setSettingsOpen(false);+ void refreshLlm();+ }}+ />+ <ChatHistoryModal+ open={chatsOpen}+ onClose={() => setChatsOpen(false)}+ sessions={[+ {+ id: `session_${sessionNum}`,+ title: `Session ${sessionNum}`,+ messageCount: messages.length,+ createdAt: new Date().toISOString(),+ },+ ]}+ activeSessionId={`session_${sessionNum}`}+ onSelect={() => setChatsOpen(false)}+ onNew={newChat}+ />+ </aside>+ );+}++const RAIL_BUTTONS: Array<{ id: LeftTab; label: string; icon: React.ElementType }> = [+ ...(AI_FEATURES_ENABLED ? [{ id: "chat" as LeftTab, label: "Chat", icon: MessageSquare }] : []),+ { id: "media", label: "Media", icon: Film },+];++export function LeftRail({+ active,+ onChange,+}: {+ active: LeftTab;+ onChange: (id: LeftTab) => void;+}) {+ return (+ <aside className={`${styles.rail} ${styles.leftRail}`} aria-label="Left tools">+ {RAIL_BUTTONS.map(({ id, label, icon: Icon }) => (+ <button+ type="button"+ key={id}+ title={label}+ aria-label={label}+ aria-pressed={active === id}+ onClick={() => onChange(id)}+ >+ <Icon size={18} />+ </button>+ ))}+ </aside>+ );+}diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsxnew file mode 100644index 000000000..e5f04b75c--- /dev/null+++ b/src/components/ai-edition/Modals.tsx@@ -0,0 +1,1050 @@+import { AlertTriangle, Crop, FolderOpen, FolderPlus, Plus, X } from "lucide-react";+import { type ReactNode, useEffect, useState } from "react";+import type { CropRegion } from "@/components/video-editor/types";+import styles from "./NewEditorShell.module.css";++interface BaseModalProps {+ open: boolean;+ onClose: () => void;+}++function useEscape(open: boolean, onClose: () => void) {+ useEffect(() => {+ if (!open) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [open, onClose]);+}++export function ModalShell({+ open,+ onClose,+ title,+ subtitle,+ wide,+ children,+}: BaseModalProps & {+ title: string;+ subtitle?: string;+ wide?: boolean;+ children: ReactNode;+}) {+ useEscape(open, onClose);+ if (!open) return null;+ return (+ <div+ className={`${styles.modal} ${open ? styles.isOpen : ""}`}+ role="dialog"+ aria-modal="true"+ aria-labelledby="modal-title"+ >+ <div className={styles.modalBackdrop} aria-hidden onClick={onClose} />+ <div className={`${styles.modalCard} ${wide ? styles.wide : ""}`}>+ <header className={styles.modalHead}>+ <div>+ <h2 id="modal-title">{title}</h2>+ {subtitle ? <p>{subtitle}</p> : null}+ </div>+ <button+ type="button"+ className={styles.closeBtn}+ onClick={onClose}+ title="Close"+ aria-label="Close"+ >+ <X size={18} />+ </button>+ </header>+ <div className={styles.modalBody}>{children}</div>+ </div>+ </div>+ );+}++interface ProjectItem {+ id: string;+ title: string;+ updatedAt: string;+}++interface OpenProjectModalProps extends BaseModalProps {+ projects: ProjectItem[];+ activeProjectId: string | null;+ onSelect: (id: string) => void;+ onBrowse: () => void;+}++export function OpenProjectModal({+ open,+ onClose,+ projects,+ activeProjectId,+ onSelect,+ onBrowse,+}: OpenProjectModalProps) {+ const [query, setQuery] = useState("");+ const filtered = projects.filter((p) => p.title.toLowerCase().includes(query.toLowerCase()));+ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Open project"+ subtitle="Pick up an existing project or browse your files"+ wide+ >+ <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>+ <FolderOpen size={14} style={{ color: "var(--muted)" }} />+ <input+ type="search"+ placeholder="Search projects…"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ style={{+ flex: 1,+ height: 36,+ padding: "0 12px",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ background: "var(--surface)",+ color: "var(--fg)",+ font: "400 13px/1 var(--font-body)",+ outline: "none",+ }}+ />+ </div>+ <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 12 }}>+ {filtered.length === 0 ? (+ <p style={{ color: "var(--muted)", fontSize: 12, padding: 16, textAlign: "center" }}>+ No projects match "{query}".+ </p>+ ) : (+ filtered.map((p) => {+ const isActive = p.id === activeProjectId;+ return (+ <button+ type="button"+ key={p.id}+ onClick={() => {+ onSelect(p.id);+ onClose();+ }}+ style={{+ display: "grid",+ gridTemplateColumns: "36px 1fr auto",+ alignItems: "center",+ gap: 12,+ padding: "10px 12px",+ border: "none",+ borderRadius: "var(--r-md)",+ background: isActive ? "var(--accent-wash)" : "transparent",+ boxShadow: isActive ? "inset 0 0 0 1px var(--accent)" : "none",+ color: "var(--fg)",+ cursor: "pointer",+ textAlign: "left",+ font: "inherit",+ }}+ >+ <div+ style={{+ width: 36,+ height: 36,+ borderRadius: "var(--r-sm)",+ background: "linear-gradient(135deg, var(--brand-lo), var(--brand))",+ display: "grid",+ placeItems: "center",+ color: "var(--accent-on)",+ }}+ >+ <FolderOpen size={18} />+ </div>+ <div style={{ minWidth: 0 }}>+ <div+ style={{+ font: "500 13px/1.3 var(--font-body)",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {p.title}+ </div>+ <div+ style={{+ font: "400 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ marginTop: 2,+ }}+ >+ id: {p.id.slice(0, 8)}+ </div>+ </div>+ <span+ style={{+ font: "400 11px/1 var(--font-mono)",+ color: "var(--meta)",+ whiteSpace: "nowrap",+ }}+ >+ {new Date(p.updatedAt).toLocaleDateString()}+ </span>+ </button>+ );+ })+ )}+ </div>+ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <span style={{ fontSize: 12, color: "var(--muted)" }}>+ <kbd+ style={{+ font: "500 11px/1 var(--font-mono)",+ padding: "2px 6px",+ borderRadius: 4,+ background: "var(--surface-2)",+ border: "1px solid var(--border)",+ color: "var(--fg)",+ }}+ >+ ↑↓+ </kbd>{" "}+ to navigate ·{" "}+ <kbd+ style={{+ font: "500 11px/1 var(--font-mono)",+ padding: "2px 6px",+ borderRadius: 4,+ background: "var(--surface-2)",+ border: "1px solid var(--border)",+ color: "var(--fg)",+ }}+ >+ Enter+ </kbd>{" "}+ to open+ </span>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={() => {+ onBrowse();+ onClose();+ }}+ >+ <FolderOpen size={14} />+ Browse files…+ </button>+ </div>+ </ModalShell>+ );+}++type Template = "blank" | "screen-recording" | "import" | "template";++interface NewProjectModalProps extends BaseModalProps {+ onCreate: (title: string) => void;+}++export function NewProjectModal({ open, onClose, onCreate }: NewProjectModalProps) {+ const [title, setTitle] = useState("Untitled project");+ const [template, setTemplate] = useState<Template>("blank");+ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="New project"+ subtitle="Choose a starting point and give it a name"+ >+ <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>+ <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>+ <label+ htmlFor="np-name"+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ }}+ >+ Project name+ </label>+ <input+ id="np-name"+ type="text"+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ style={{+ height: 36,+ padding: "0 12px",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ background: "var(--surface)",+ color: "var(--fg)",+ font: "400 13px/1 var(--font-body)",+ }}+ />+ </div>++ <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>+ <label+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ }}+ >+ Starting point+ </label>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(2, 1fr)",+ gap: 8,+ }}+ >+ <TemplateCell+ icon={<FolderPlus size={18} />}+ title="Blank project"+ desc="Empty timeline, ready to import"+ active={template === "blank"}+ onClick={() => setTemplate("blank")}+ />+ <TemplateCell+ icon={<Crop size={18} />}+ title="Screen recording"+ desc="Start system capture"+ active={template === "screen-recording"}+ onClick={() => setTemplate("screen-recording")}+ />+ <TemplateCell+ icon={<Plus size={18} />}+ title="Import media"+ desc="Video, audio, images from disk"+ active={template === "import"}+ onClick={() => setTemplate("import")}+ />+ <TemplateCell+ icon={<Crop size={18} />}+ title="From template"+ desc="Predefined storyboard"+ active={template === "template"}+ onClick={() => setTemplate("template")}+ />+ </div>+ </div>++ <div+ style={{+ display: "flex",+ justifyContent: "flex-end",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onClose}+ >+ Cancel+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={() => {+ onCreate(title.trim() || "Untitled project");+ onClose();+ }}+ >+ <Plus size={14} />+ Create project+ </button>+ </div>+ </div>+ </ModalShell>+ );+}++function TemplateCell({+ icon,+ title,+ desc,+ active,+ onClick,+}: {+ icon: ReactNode;+ title: string;+ desc: string;+ active: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ style={{+ display: "flex",+ flexDirection: "column",+ alignItems: "flex-start",+ gap: 8,+ padding: 12,+ border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,+ borderRadius: "var(--r-md)",+ background: active ? "var(--accent-wash)" : "var(--surface)",+ boxShadow: active ? "0 0 0 1px var(--accent)" : "none",+ color: "var(--fg)",+ cursor: "pointer",+ textAlign: "left",+ font: "inherit",+ }}+ >+ <span+ style={{+ width: 36,+ height: 36,+ borderRadius: "var(--r-sm)",+ background: active ? "var(--accent)" : "var(--surface-2)",+ color: active ? "var(--accent-on)" : "var(--muted)",+ display: "grid",+ placeItems: "center",+ }}+ >+ {icon}+ </span>+ <span style={{ font: "500 13px/1.3 var(--font-body)" }}>{title}</span>+ <span style={{ font: "400 11px/1.4 var(--font-body)", color: "var(--muted)" }}>{desc}</span>+ </button>+ );+}++interface CropModalProps extends BaseModalProps {+ initialRegion: CropRegion;+ onApply: (region: CropRegion) => void;+}++const CROP_RATIOS: Array<{ value: string; label: string; ratio: number | null }> = [+ { value: "free", label: "Free", ratio: null },+ { value: "16:9", label: "16:9", ratio: 16 / 9 },+ { value: "9:16", label: "9:16", ratio: 9 / 16 },+ { value: "1:1", label: "1:1", ratio: 1 },+ { value: "4:3", label: "4:3", ratio: 4 / 3 },+ { value: "3:4", label: "3:4", ratio: 3 / 4 },+ { value: "21:9", label: "21:9", ratio: 21 / 9 },+];++function detectRatio(r: CropRegion): string {+ const candidates = CROP_RATIOS.filter((c) => c.ratio !== null);+ const ratio = r.width === 0 ? 0 : r.height / r.width;+ for (const c of candidates) {+ if (c.ratio === null) continue;+ if (Math.abs(ratio - c.ratio) < 0.01) return c.value;+ }+ return "free";+}++export function CropModal({ open, onClose, initialRegion, onApply }: CropModalProps) {+ const [xPct, setXPct] = useState(0);+ const [yPct, setYPct] = useState(0);+ const [wPct, setWPct] = useState(100);+ const [hPct, setHPct] = useState(100);+ const [ratio, setRatio] = useState("free");++ // ponytail: sync local form state to the document region every time the+ // modal opens. Doesn't run on every doc change — `open` is the trigger.+ useEffect(() => {+ if (!open) return;+ setXPct(Math.round(initialRegion.x * 100));+ setYPct(Math.round(initialRegion.y * 100));+ setWPct(Math.round(initialRegion.width * 100));+ setHPct(Math.round(initialRegion.height * 100));+ setRatio(detectRatio(initialRegion));+ }, [open, initialRegion]);++ const handleRatioChange = (next: string) => {+ setRatio(next);+ const candidate = CROP_RATIOS.find((c) => c.value === next);+ if (candidate?.ratio && wPct > 0) {+ const newH = Math.round(wPct * candidate.ratio);+ setHPct(Math.min(100, Math.max(1, newH)));+ }+ };++ const handleApply = () => {+ const next: CropRegion = {+ x: Math.max(0, Math.min(1, xPct / 100)),+ y: Math.max(0, Math.min(1, yPct / 100)),+ width: Math.max(0.01, Math.min(1, wPct / 100)),+ height: Math.max(0.01, Math.min(1, hPct / 100)),+ };+ onApply(next);+ onClose();+ };++ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Crop video"+ subtitle="Drag on each side to adjust the crop area"+ >+ <div+ style={{+ position: "relative",+ aspectRatio: "16 / 9",+ background: "linear-gradient(135deg, #16171d, #16171d)",+ borderRadius: "var(--r-md)",+ border: "1px solid var(--border)",+ overflow: "hidden",+ }}+ >+ <div+ style={{+ position: "absolute",+ left: `${xPct}%`,+ top: `${yPct}%`,+ width: `${wPct}%`,+ height: `${hPct}%`,+ border: "1.5px solid var(--fg)",+ borderRadius: 4,+ boxShadow: "0 0 0 9999px rgba(22,23,29,0.55)",+ cursor: "move",+ }}+ />+ </div>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(5, auto) 1fr auto",+ gap: 10,+ alignItems: "end",+ }}+ >+ <CropField label="X" value={xPct} onChange={setXPct} />+ <CropField label="Y" value={yPct} onChange={setYPct} />+ <CropField label="W" value={wPct} onChange={setWPct} />+ <CropField label="H" value={hPct} onChange={setHPct} />+ <div className={styles.field} style={{ minWidth: 96 }}>+ <label>Ratio</label>+ <select value={ratio} onChange={(e) => handleRatioChange(e.target.value)}>+ {CROP_RATIOS.map((r) => (+ <option key={r.value} value={r.value}>+ {r.label}+ </option>+ ))}+ </select>+ </div>+ <span+ style={{+ font: "500 11px/1 var(--font-mono)",+ color: "var(--muted)",+ alignSelf: "center",+ }}+ >+ {wPct}% × {hPct}%+ </span>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ style={{ height: 36, padding: "0 20px" }}+ onClick={handleApply}+ >+ Done+ </button>+ </div>+ </ModalShell>+ );+}++function CropField({+ label,+ value,+ onChange,+}: {+ label: string;+ value: number;+ onChange: (n: number) => void;+}) {+ return (+ <div className={styles.field}>+ <label>{label}</label>+ <input+ type="number"+ value={value}+ min={0}+ max={100}+ onChange={(e) => onChange(Number(e.target.value))}+ />+ </div>+ );+}++export type UnsavedChoice = "save" | "discard" | "cancel";++interface UnsavedChangesModalProps extends BaseModalProps {+ action: "close" | "new" | "open" | "record";+ busy?: boolean;+ onChoose: (choice: UnsavedChoice) => void;+}++const ACTION_COPY: Record<UnsavedChangesModalProps["action"], { title: string; body: string }> = {+ close: {+ title: "Save changes before closing?",+ body: "Your project has unsaved changes. Save them now, discard them, or stay in the editor.",+ },+ new: {+ title: "Save changes before creating a new project?",+ body: "The current project has unsaved changes. Save them first, discard them, or cancel.",+ },+ open: {+ title: "Save changes before opening another project?",+ body: "The current project has unsaved changes. Save them first, discard them, or cancel.",+ },+ record: {+ title: "Save changes before starting a new recording?",+ body: "The current project has unsaved changes. Save them first, discard them, or cancel.",+ },+};++export function UnsavedChangesModal({+ open,+ onClose,+ action,+ busy,+ onChoose,+}: UnsavedChangesModalProps) {+ const copy = ACTION_COPY[action];+ return (+ <ModalShell open={open} onClose={onClose} title={copy.title} subtitle={copy.body}>+ <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>+ <span+ style={{+ display: "grid",+ placeItems: "center",+ width: 32,+ height: 32,+ borderRadius: 8,+ background: "var(--warn-soft)",+ color: "var(--warn)",+ }}+ >+ <AlertTriangle size={16} />+ </span>+ <div+ style={{+ font: "500 12px var(--font-body)",+ color: "var(--fg-2)",+ }}+ >+ The current project has not been saved to disk yet.+ </div>+ </div>+ <div+ style={{+ display: "flex",+ justifyContent: "flex-end",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={() => onChoose("cancel")}+ disabled={busy}+ >+ Cancel+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={() => onChoose("discard")}+ disabled={busy}+ >+ Discard+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={() => onChoose("save")}+ disabled={busy}+ >+ {busy ? "Saving…" : "Save & continue"}+ </button>+ </div>+ </ModalShell>+ );+}++export interface InsertSourceModalProps extends BaseModalProps {+ assetLabel: string;+ canAddBefore: boolean;+ canAddAfter: boolean;+ canSplit: boolean;+ onAddBefore: () => void;+ onAddAfter: () => void;+ onSplit: () => void;+}++export function InsertSourceModal({+ open,+ onClose,+ assetLabel,+ canAddBefore,+ canAddAfter,+ canSplit,+ onAddBefore,+ onAddAfter,+ onSplit,+}: InsertSourceModalProps) {+ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Insert source"+ subtitle={`Where to place "${assetLabel}" on the timeline?`}+ >+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>+ <button+ type="button"+ disabled={!canAddBefore}+ onClick={onAddBefore}+ style={{+ padding: "12px 16px",+ border: "1px solid var(--border)",+ borderRadius: 10,+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 13px/1.2 var(--font-body)",+ cursor: canAddBefore ? "pointer" : "not-allowed",+ textAlign: "left",+ opacity: canAddBefore ? 1 : 0.5,+ }}+ >+ <strong>Add before</strong>+ <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>+ Insert the whole source before the target clip.+ </div>+ </button>+ <button+ type="button"+ disabled={!canAddAfter}+ onClick={onAddAfter}+ style={{+ padding: "12px 16px",+ border: "1px solid var(--border)",+ borderRadius: 10,+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 13px/1.2 var(--font-body)",+ cursor: canAddAfter ? "pointer" : "not-allowed",+ textAlign: "left",+ opacity: canAddAfter ? 1 : 0.5,+ }}+ >+ <strong>Add after</strong>+ <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>+ Insert the whole source after the target clip.+ </div>+ </button>+ <button+ type="button"+ disabled={!canSplit}+ onClick={onSplit}+ style={{+ padding: "12px 16px",+ border: "1px solid var(--border)",+ borderRadius: 10,+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 13px/1.2 var(--font-body)",+ cursor: canSplit ? "pointer" : "not-allowed",+ textAlign: "left",+ opacity: canSplit ? 1 : 0.5,+ }}+ >+ <strong>Split here and insert</strong>+ <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>+ Split the target clip at the drop point and insert the source in between.+ </div>+ </button>+ </div>+ </ModalShell>+ );+}++export interface SourceTranscriptModalProps extends BaseModalProps {+ assetLabel: string;+ assetPath: string;+ tcFormatted: string;+ transcriptText: string | null;+}++export function SourceTranscriptModal({+ open,+ onClose,+ assetLabel,+ tcFormatted,+ transcriptText,+}: SourceTranscriptModalProps) {+ return (+ <ModalShell open={open} onClose={onClose} title="Source transcript" subtitle={assetLabel} wide>+ <div style={{ display: "flex", gap: 12, marginBottom: 12, flexWrap: "wrap" }}>+ <span+ style={{+ padding: "4px 10px",+ borderRadius: 999,+ background: "var(--success-soft)",+ color: "var(--success)",+ font: "500 12px var(--font-body)",+ border: "1px solid color-mix(in srgb, var(--success) 22%, transparent)",+ }}+ >+ {transcriptText ? "Generated" : "Not generated yet"}+ </span>+ <span+ style={{+ font: "500 12px/1.4 var(--font-mono)",+ color: "var(--muted)",+ alignSelf: "center",+ }}+ >+ {tcFormatted}+ </span>+ </div>+ {transcriptText ? (+ <pre+ style={{+ margin: 0,+ padding: "14px 16px",+ borderRadius: "var(--r-md)",+ border: "1px solid var(--border)",+ background: "var(--surface-warm)",+ font: "400 12px/1.55 var(--font-mono)",+ color: "var(--fg)",+ whiteSpace: "pre",+ overflow: "auto",+ maxHeight: "40vh",+ }}+ >+ {transcriptText}+ </pre>+ ) : (+ <div+ style={{+ padding: 32,+ textAlign: "center",+ color: "var(--muted)",+ font: "500 13px var(--font-body)",+ }}+ >+ Transcribe the asset first using the Transcript pane on the right.+ </div>+ )}+ </ModalShell>+ );+}++interface CaptionsModalProps extends BaseModalProps {+ minWords: number;+ maxWords: number;+ onMinWords: (n: number) => void;+ onMaxWords: (n: number) => void;+ onGenerate: () => void;+}++export function AutoCaptionsModal({+ open,+ onClose,+ minWords,+ maxWords,+ onMinWords,+ onMaxWords,+ onGenerate,+}: CaptionsModalProps) {+ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Auto captions"+ subtitle="Choose roughly how many words each caption shows at once. Timing is spread across the words in that phrase."+ >+ <div style={{ display: "flex", gap: 12 }}>+ <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1 }}>+ <label+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ }}+ >+ Min words per caption+ </label>+ <select+ value={minWords}+ onChange={(e) => onMinWords(Number(e.target.value))}+ style={{+ padding: "8px 10px",+ border: "1px solid var(--border)",+ borderRadius: "6px",+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 13px var(--font-body)",+ }}+ >+ {Array.from({ length: 12 }, (_, i) => i + 1).map((n) => (+ <option key={n} value={n}>+ {n} word{n === 1 ? "" : "s"}+ </option>+ ))}+ </select>+ </div>+ <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1 }}>+ <label+ style={{+ font: "500 11px/1 var(--font-body)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ color: "var(--muted)",+ }}+ >+ Max words per caption+ </label>+ <select+ value={maxWords}+ onChange={(e) => onMaxWords(Number(e.target.value))}+ style={{+ padding: "8px 10px",+ border: "1px solid var(--border)",+ borderRadius: "6px",+ background: "var(--surface)",+ color: "var(--fg-2)",+ font: "500 13px var(--font-body)",+ }}+ >+ {Array.from({ length: 12 }, (_, i) => i + 1).map((n) => (+ <option key={n} value={n} disabled={n < minWords}>+ {n} word{n === 1 ? "" : "s"}+ </option>+ ))}+ </select>+ </div>+ </div>+ <div+ style={{+ display: "flex",+ justifyContent: "flex-end",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button type="button" className={`${styles.btn} ${styles.btnSecondary}`} onClick={onClose}>+ Cancel+ </button>+ <button type="button" className={`${styles.btn} ${styles.btnPrimary}`} onClick={onGenerate}>+ Generate+ </button>+ </div>+ </ModalShell>+ );+}++export interface ChatHistoryModalProps extends BaseModalProps {+ sessions: Array<{ id: string; title: string; messageCount: number; createdAt: string }>;+ activeSessionId: string | null;+ onSelect: (id: string) => void;+ onNew: () => void;+}++export function ChatHistoryModal({+ open,+ onClose,+ sessions,+ activeSessionId,+ onSelect,+ onNew: _onNew,+}: ChatHistoryModalProps) {+ void _onNew;+ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Conversation history"+ subtitle="Switch or create sessions"+ >+ {sessions.length === 0 ? (+ <div+ style={{+ padding: 16,+ textAlign: "center",+ color: "var(--muted)",+ font: "500 13px var(--font-body)",+ }}+ >+ No conversations yet.+ </div>+ ) : (+ <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>+ {sessions.map((s) => {+ const isActive = s.id === activeSessionId;+ return (+ <button+ type="button"+ key={s.id}+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ padding: "10px 12px",+ border: `1px solid ${isActive ? "var(--accent)" : "var(--border-soft)"}`,+ borderRadius: 8,+ background: isActive ? "var(--accent-wash)" : "var(--surface)",+ color: "var(--fg-2)",+ cursor: "pointer",+ font: "500 13px var(--font-body)",+ textAlign: "left",+ width: "100%",+ }}+ onClick={() => {+ onSelect(s.id);+ onClose();+ }}+ >+ <span style={{ fontWeight: isActive ? 600 : 500 }}>{s.title}</span>+ <span style={{ font: "500 11px/1 var(--font-mono)", color: "var(--muted)" }}>+ {s.messageCount} msgs · {new Date(s.createdAt).toLocaleDateString()}+ </span>+ </button>+ );+ })}+ </div>+ )}+ <div+ style={{+ display: "flex",+ justifyContent: "flex-end",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button type="button" className={`${styles.btn} ${styles.btnSecondary}`} onClick={onClose}>+ Close+ </button>+ </div>+ </ModalShell>+ );+}diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssnew file mode 100644index 000000000..6c53184ec--- /dev/null+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -0,0 +1,1668 @@+/* Editor shell — 4-row grid: titlebar · workbench · handle · bottombar.+ * Mirrors design/openscreen-editor.html. Tokens come from+ * src/styles/design-tokens.css (light + dark via :root[data-theme="dark"]). */++.app {+ display: grid;+ grid-template-rows: var(--titlebar-h) 1fr var(--handle-h) var(--bottom-h);+ height: 100vh;+ min-width: 1024px;+ background: var(--bg);+ color: var(--fg);+ font-family: var(--font-body);+ font-size: var(--fs-app);+ line-height: 1.5;+ overflow: hidden;+ user-select: none;+}++.app[data-collapse~="left"] {+ --panel-w-left: 0px;+}+.app[data-collapse~="left"] .leftRail,+.app[data-collapse~="left"] .leftPanel,+.app[data-collapse~="left"] .handleLeft {+ display: none;+}++.app[data-collapse~="right"] {+ --panel-w-right: 0px;+}+.app[data-collapse~="right"] .rightStack,+.app[data-collapse~="right"] .rightRail,+.app[data-collapse~="right"] .handleRight {+ display: none;+}++.app[data-collapse~="bottom"] {+ --bottom-h: 0px;+}+.app[data-collapse~="bottom"] .bottombar {+ display: none;+}+.app[data-collapse~="bottom"] .handleBottom {+ display: none;+}++/* ─── titlebar ──────────────────────────────────────────────────── */+.titlebar {+ display: flex;+ align-items: center;+ gap: var(--sp-3);+ padding-inline: var(--sp-4);+ background: var(--bg);+ border-bottom: 1px solid var(--border-soft);+ min-width: 0;+ /* ponytail: make the titlebar the drag region in Electron. The buttons+ * opt out via inline -webkit-app-region: no-drag (see Titlebar.tsx). */+ -webkit-app-region: drag;+ app-region: drag;+}+.titlebar button,+.titlebar input,+.titlebar select,+.titlebar textarea,+.titlebar .langSel,+.titlebar .recorderBtn {+ -webkit-app-region: no-drag;+ app-region: no-drag;+}+.titlebar .lights {+ display: inline-flex;+ gap: 6px;+ margin-right: var(--sp-3);+}+.titlebar .lights span {+ width: 11px;+ height: 11px;+ border-radius: 50%;+ border: 1px solid var(--overlay-border);+}+.titlebar .lights .r { background: var(--light-red); }+.titlebar .lights .y { background: var(--light-yellow); }+.titlebar .lights .g { background: var(--light-green); }++.titlebar .brand {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-family: var(--font-display);+ font-size: var(--fs-title);+ font-weight: 500;+ letter-spacing: -0.005em;+ color: var(--fg);+}+.titlebar .brandMark {+ width: 18px;+ height: 18px;+ border-radius: 5px;+ background: var(--accent);+ display: grid;+ place-items: center;+ color: var(--accent-on);+ font: 600 11px/1 var(--font-display);+}+.titlebar .sep {+ width: 1px;+ height: 16px;+ background: var(--border);+}+.titlebar .project {+ display: inline-flex;+ align-items: center;+ gap: var(--sp-2);+ font-size: var(--fs-app);+ color: var(--muted);+ min-width: 0;+}+.titlebar .projectName {+ color: var(--fg-2);+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ max-width: 280px;+ background: transparent;+ border: 0;+ padding: 2px 6px;+ border-radius: var(--r-sm);+ cursor: text;+ font: inherit;+ -webkit-app-region: no-drag;+ app-region: no-drag;+}+.titlebar .projectName:hover:not(:disabled) {+ background: var(--surface-3);+}+.titlebar .projectInput {+ background: var(--surface);+ color: var(--fg);+ border: 1px solid var(--accent);+ border-radius: var(--r-sm);+ padding: 2px 6px;+ font: 500 13px var(--font-body);+ outline: none;+ min-width: 200px;+ max-width: 360px;+ -webkit-app-region: no-drag;+ app-region: no-drag;+}+.titlebar .saved {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-family: var(--font-mono);+ font-size: var(--fs-app-sm);+ color: var(--muted);+}+.titlebar .saved .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--success);+}+.titlebar .projActions {+ display: inline-flex;+ align-items: center;+ gap: var(--sp-1);+ margin-right: var(--sp-1);+}+.titlebar .right {+ margin-left: auto;+ display: inline-flex;+ align-items: center;+ gap: var(--sp-1);+}+.titlebar .iconBtn {+ width: 28px;+ height: 28px;+ display: grid;+ place-items: center;+ border-radius: var(--r-sm);+ color: var(--muted);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.titlebar .iconBtn:hover {+ background: var(--surface-3);+ color: var(--fg);+}+.titlebar .iconBtn[aria-pressed="true"] {+ background: var(--accent-soft);+ color: var(--accent);+}+.titlebar .langSel {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 26px;+ padding: 0 6px;+ background: transparent;+ border: 1px solid var(--border-soft);+ border-radius: var(--r-md);+ color: var(--fg-2);+ font: 500 var(--fs-app)/1 var(--font-display);+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), border-color var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.titlebar .langSel:hover {+ background: var(--surface-3);+ border-color: var(--border);+ color: var(--fg);+}+.titlebar .recorderBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 26px;+ padding: 0 10px 0 8px;+ border-radius: var(--r-md);+ background: var(--accent-soft);+ color: var(--accent);+ border: 1px solid color-mix(in oklch, var(--accent) 22%, transparent);+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+ font: 500 var(--fs-app-sm)/1 var(--font-display);+ letter-spacing: 0.01em;+ cursor: pointer;+}+.titlebar .recorderBtn:hover {+ background: color-mix(in oklch, var(--accent) 18%, var(--surface-3));+}++/* ─── workbench — 7 columns: rail · panel · handle · preview · handle · stack · rail */+.workbench {+ display: grid;+ grid-template-columns:+ var(--rail-w)+ var(--panel-w-left)+ var(--handle-w)+ 1fr+ var(--handle-w)+ var(--panel-w-right)+ var(--rail-w);+ min-height: 0;+ background: var(--bg);+ overflow: hidden;+}+.workbench > * {+ min-height: 0;+}+.workbench > * + * {+ border-left: 1px solid var(--border-soft);+}++/* ─── rails — vertical icon strips ─────────────────────────────── */+.rail {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--sp-1);+ padding: var(--sp-2) 0;+ background: var(--bg);+ min-width: 0;+}+.rail button {+ width: 36px;+ height: 36px;+ display: grid;+ place-items: center;+ border-radius: var(--r-md);+ color: var(--muted);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+ position: relative;+}+.rail button:hover {+ background: var(--surface-3);+ color: var(--fg);+}+.rail button[aria-pressed="true"] {+ color: var(--accent);+ background: var(--accent-soft);+}+.rail button[aria-pressed="true"]::before {+ content: "";+ position: absolute;+ left: -8px;+ top: 8px;+ bottom: 8px;+ width: 3px;+ border-radius: 2px;+ background: var(--accent);+}+.rail .sepH {+ width: 24px;+ height: 1px;+ background: var(--border);+ margin: var(--sp-1) 0;+}++/* ─── panels (chat, transcript, etc.) ──────────────────────────── */+.panel {+ display: grid;+ grid-template-rows: auto 1fr auto;+ min-width: 0;+ min-height: 0;+ background: var(--bg);+ overflow: hidden;+}+.panelHead {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ padding: var(--sp-3) var(--sp-4);+ border-bottom: 1px solid var(--border-soft);+ min-height: 44px;+}+.panelHead h2 {+ margin: 0;+ font-family: var(--font-display);+ font-size: 14px;+ font-weight: 500;+ letter-spacing: -0.005em;+ color: var(--fg);+}+.panelHead .right {+ margin-left: auto;+ display: inline-flex;+ gap: var(--sp-1);+}+.panelHead .iconBtn {+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ border-radius: var(--r-sm);+ color: var(--meta);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.panelHead .iconBtn:hover {+ background: var(--surface-3);+ color: var(--fg-2);+}+.panelBody {+ overflow-y: auto;+ padding: var(--sp-3) var(--sp-4);+ scrollbar-width: thin;+ scrollbar-color: var(--border) transparent;+ min-height: 0;+}+.panelBody::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}+.panelBody::-webkit-scrollbar-thumb {+ background: var(--border);+ border-radius: 4px;+}+.panelBody::-webkit-scrollbar-thumb:hover {+ background: var(--border-hi);+}++/* ─── resize handles ───────────────────────────────────────────── */+.handle {+ background: transparent;+ position: relative;+ z-index: 2;+ transition: background var(--motion-fast) var(--ease);+ cursor: col-resize;+}+.handleRow {+ cursor: row-resize;+ grid-column: 1 / -1;+ border-bottom: 1px solid var(--border);+}+.handle:hover,+.handle.isDragging {+ background: var(--surface-2);+}+.handle::before,+.handle::after {+ content: "";+ position: absolute;+ background: var(--dim);+ border-radius: 1px;+ opacity: 0.45;+ transition: opacity var(--motion-fast) var(--ease);+ pointer-events: none;+}+.handleCol::before,+.handleCol::after {+ left: 50%;+ width: 1px;+ height: 14px;+ transform: translateX(-50%);+}+.handleCol::before { top: calc(50% - 16px); }+.handleCol::after { top: calc(50% + 2px); }+.handleRow::before,+.handleRow::after {+ top: 50%;+ height: 1px;+ width: 14px;+ transform: translateY(-50%);+}+.handleRow::before { left: calc(50% - 16px); }+.handleRow::after { left: calc(50% + 2px); }+.handle:hover::before,+.handle:hover::after,+.handle.isDragging::before,+.handle.isDragging::after {+ opacity: 1;+}+.handle.isDragging {+ background: var(--accent-soft);+}++/* ─── preview area ─────────────────────────────────────────────── */+.previewWrap {+ display: grid;+ grid-template-rows: 1fr auto;+ background: var(--surface-1);+ min-width: 0;+ min-height: 0;+ position: relative;+}+.previewCanvas {+ position: relative;+ display: grid;+ place-items: center;+ overflow: hidden;+ padding: var(--sp-5);+ min-height: 0;+}+.previewFrame {+ position: relative;+ aspect-ratio: 16 / 9;+ max-width: 100%;+ max-height: 100%;+ width: 100%;+ min-width: 0;+ min-height: 0;+ background:+ radial-gradient(ellipse at 50% 35%,+ var(--scene-sky-hi) 0%,+ var(--scene-sky-mid) 35%,+ var(--scene-foliage) 70%,+ var(--scene-foliage-d) 100%);+ /* ponytail: don't make the canvas itself a rounded card — the video /+ camera apply their own border-radius for content clipping. A square+ canvas blends into the editor chrome; the wallpaper is the visible+ area, but no "frame around the canvas" effect. */+ border-radius: 0;+ overflow: hidden;+ display: grid;+ place-items: center;+}+.videoStage {+ position: relative;+ display: grid;+ place-items: center;+ min-width: 0;+ min-height: 0;+ overflow: visible;+ z-index: 1;+}+.screenStage {+ position: absolute;+ overflow: hidden;+ z-index: 1;+ display: flex;+}+.screenStage > .container,+.screenStage > div > .container {+ width: 100%;+ height: 100%;+}+.previewEmpty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ color: var(--muted);+ font-size: var(--fs-app);+}+.previewEmpty strong { color: var(--fg-2); }++/* ─── preview empty state (no project / no asset) ───────────────── */+.previewEmptyDrop {+ position: relative;+ width: 100%;+ height: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+}+.previewEmptyDropOverlay {+ position: absolute;+ inset: 0;+ z-index: 10;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--sp-2);+ border: 2px dashed var(--primary, #34B27B);+ background: color-mix(in srgb, var(--primary, #34B27B) 10%, transparent);+ border-radius: var(--r-sm);+ pointer-events: none;+}+.previewEmptyDropIcon {+ width: 40px;+ height: 40px;+ color: var(--primary, #34B27B);+}+.previewEmptyDropLabel {+ font-size: var(--fs-app);+ font-weight: 600;+ color: var(--primary, #34B27B);+}+.previewEmptyInner {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--sp-4);+ padding: var(--sp-5);+ text-align: center;+ max-width: 28rem;+}+.previewEmptyLogo {+ width: 64px;+ height: 64px;+ border-radius: var(--r-md);+ opacity: 0.9;+}+.previewEmptyHeading {+ display: flex;+ flex-direction: column;+ gap: var(--sp-1);+}+.previewEmptyTitle {+ margin: 0;+ font-size: 1.25rem;+ font-weight: 600;+ color: var(--fg-2);+}+.previewEmptyDescription {+ margin: 0;+ font-size: 0.875rem;+ color: var(--muted);+ line-height: 1.5;+}+.previewEmptyActions {+ display: flex;+ flex-direction: column;+ gap: var(--sp-2);+ width: 100%;+ max-width: 18rem;+}+.previewEmptyPrimaryButton {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--sp-2);+ padding: var(--sp-3) var(--sp-4);+ border-radius: var(--r-sm);+ background: var(--primary, #34B27B);+ color: #fff;+ border: none;+ font-weight: 500;+ font-size: 0.875rem;+ cursor: pointer;+ transition: background-color 120ms ease;+}+.previewEmptyPrimaryButton:hover {+ filter: brightness(0.95);+}+.previewEmptySecondaryButton {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--sp-2);+ padding: var(--sp-3) var(--sp-4);+ border-radius: var(--r-sm);+ background: var(--card);+ color: var(--fg-2);+ border: 1px solid var(--border);+ font-weight: 500;+ font-size: 0.875rem;+ cursor: pointer;+ transition: background-color 120ms ease;+}+.previewEmptySecondaryButton:hover {+ background: var(--accent, rgba(255, 255, 255, 0.06));+}+.previewEmptyButtonIcon {+ width: 16px;+ height: 16px;+}+.previewEmptyHint {+ margin: 0;+ font-size: 0.75rem;+ color: var(--muted-foreground, rgba(255, 255, 255, 0.5));+}+.previewEmptyDragHint {+ display: flex;+ align-items: center;+ gap: var(--sp-1);+ margin: 0;+ font-size: 0.75rem;+ color: var(--muted-foreground, rgba(255, 255, 255, 0.4));+}+.previewEmptyDragHintIcon {+ width: 12px;+ height: 12px;+}+.previewEmptyDialog {+ max-width: 24rem;+ padding: var(--sp-5);+ background: var(--bg);+ border: 1px solid var(--border);+}+.previewEmptyDialogHeader {+ margin-bottom: var(--sp-3);+}+.previewEmptyDialogHeaderInner {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+}+.previewEmptyDialogLogo {+ width: 36px;+ height: 36px;+ border-radius: var(--r-sm);+ flex-shrink: 0;+}+.previewEmptyDialogTitle {+ font-size: 1rem;+ font-weight: 600;+ color: var(--fg-2);+ line-height: 1.2;+}+.previewEmptyDialogBody {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--sp-2);+ margin-bottom: var(--sp-4);+ text-align: center;+}+.previewEmptyDialogIcon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 40px;+ border-radius: 9999px;+ background: var(--card);+ border: 1px solid var(--border);+}+.previewEmptyDialogAlertIcon {+ width: 20px;+ height: 20px;+ color: var(--muted);+}+.previewEmptyDialogMessage {+ margin: 0;+ font-size: 0.875rem;+ color: var(--muted);+ line-height: 1.5;+}+.previewEmptyDialogClose {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--sp-1);+ width: 100%;+ padding: var(--sp-2) var(--sp-3);+ border-radius: var(--r-sm);+ background: var(--card);+ color: var(--fg-2);+ border: 1px solid var(--border);+ font-size: 0.875rem;+ font-weight: 500;+ cursor: pointer;+}+.previewEmptyDialogCloseIcon {+ width: 14px;+ height: 14px;+}+.previewPip {+ position: absolute;+ right: var(--sp-3);+ bottom: var(--sp-3);+ width: 120px;+ aspect-ratio: 16 / 9;+ border-radius: var(--r-sm);+ background: linear-gradient(135deg, var(--pip-bg-1) 0%, var(--pip-bg-2) 50%, var(--pip-bg-3) 100%);+ border: 2px solid var(--bg);+ box-shadow: var(--elev-card);+ overflow: hidden;+ display: grid;+ place-items: center;+ color: var(--overlay-text);+ font-family: var(--font-mono);+ font-size: 9px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+}+.previewBadge {+ position: absolute;+ top: var(--sp-3);+ right: var(--sp-3);+ padding: 4px 8px;+ border-radius: var(--r-xs);+ background: var(--overlay-light);+ color: var(--fg);+ font-family: var(--font-mono);+ font-size: 10px;+ letter-spacing: 0.02em;+ font-weight: 500;+ backdrop-filter: blur(8px);+}+.bgBlur {+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 0;+ transform: scale(1.06);+}+.previewFrame > .screenStage > video,+.previewFrame > .screenStage > div > video {+ position: relative;+ z-index: 1;+}+.pipCircle {+ border-radius: 9999px !important;+}+.pipSquare {+ border-radius: 0 !important;+}+.pipRounded {+ border-radius: 18px !important;+}++/* Webcam overlay: real <video> driven by the cameraTrack. The slot is+ transparent so clip-path / border-radius carve the camera without leaving+ a rectangular placeholder peeking through. */+.webcamSlot {+ background: transparent;+ overflow: hidden;+ z-index: 2;+ display: flex;+}+.webcamSlot .webcamVideo {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.previewTimecode {+ position: absolute;+ top: var(--sp-3);+ left: var(--sp-3);+ padding: 4px 8px;+ border-radius: var(--r-xs);+ background: var(--overlay-dark);+ color: var(--bg);+ font-family: var(--font-mono);+ font-size: 11px;+ letter-spacing: 0.02em;+}++/* ─── transport bar ────────────────────────────────────────────── */+.transport {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ padding: var(--sp-2) var(--sp-4);+ background: var(--bg);+ border-top: 1px solid var(--border-soft);+}+.transport .tbtn {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border-radius: var(--r-sm);+ color: var(--fg-2);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.transport .tbtn:hover {+ background: var(--surface-3);+ color: var(--fg);+}+.transport .tbtn.play {+ width: 36px;+ height: 36px;+ background: var(--fg);+ color: var(--bg);+ border-radius: 50%;+}+.transport .tbtn.play:hover {+ background: var(--fg-2);+}+.transport .time {+ font-family: var(--font-mono);+ font-size: var(--fs-app-sm);+ color: var(--fg);+ letter-spacing: 0.02em;+ min-width: 96px;+ text-align: center;+}+.transport .time .sep { color: var(--meta); margin-inline: 4px; }+.transport .time .total { color: var(--muted); }+.transport .spacer { flex: 1; }++/* ─── right panel-stack (one pane visible at a time) ──────────── */+.rightStack {+ grid-column: 6;+ display: grid;+ min-width: 0;+ min-height: 0;+ background: var(--bg);+}+.pane {+ display: none;+ grid-template-rows: auto 1fr;+ min-height: 0;+}+.pane.isActive {+ display: grid;+}+.paneHead {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ padding: 12px var(--sp-4);+ border-bottom: 1px solid var(--border-soft);+ min-height: 44px;+}+.paneHead h2 {+ margin: 0;+ font-family: var(--font-display);+ font-size: 14px;+ font-weight: 500;+ letter-spacing: -0.005em;+ color: var(--fg);+}+.paneBody {+ overflow-y: auto;+ padding: 12px var(--sp-4);+ scrollbar-width: thin;+ scrollbar-color: var(--border) transparent;+ min-height: 0;+}++/* ─── pane tabs (sub-nav inside a pane) ───────────────────────── */+.paneTabs {+ display: flex;+ gap: 2px;+ padding: 3px;+ margin: 12px var(--sp-4);+ background: var(--surface-warm);+ border-radius: 10px;+}+.paneTabs button {+ flex: 1;+ padding: 7px 10px;+ border: 0;+ background: transparent;+ border-radius: 7px;+ font: 500 var(--fs-app-sm)/1 var(--font-body);+ color: var(--muted);+ cursor: pointer;+ transition: background 150ms ease, color 150ms ease;+}+.paneTabs button.isActive {+ background: var(--brand);+ color: var(--accent-on);+ box-shadow: 0 1px 2px rgba(22, 23, 29, 0.12);+}+.paneSection { display: none; }+.paneSection.isActive { display: block; }++/* ─── pane rows (label + control) ─────────────────────────────── */+.paneRow {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 12px 14px;+ margin: 8px var(--sp-4);+ border: 1px solid var(--border);+ border-radius: 10px;+ background: var(--bg);+}+.paneRow .label { font: 500 var(--fs-app) var(--font-body); color: var(--fg-2); }+.paneRow .info { color: var(--meta); font-size: var(--fs-app-sm); margin-left: 4px; }+.sectionLabel {+ font: 500 var(--fs-app-sm) var(--font-body);+ color: var(--fg-2);+ margin: 4px var(--sp-4) 8px;+}+.uploadBtn {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ margin: 0 var(--sp-4) 12px;+ padding: 12px;+ border: 1px dashed var(--border);+ border-radius: 10px;+ background: var(--bg);+ color: var(--muted);+ font: 500 var(--fs-app-sm) var(--font-body);+ cursor: pointer;+}+.uploadBtn:hover { border-color: var(--success); color: var(--success); }+.field {+ display: grid;+ grid-template-columns: 80px 1fr;+ align-items: center;+ gap: 8px;+ padding: 4px var(--sp-4);+}+.field label {+ font: 500 var(--fs-app-sm) var(--font-body);+ color: var(--muted);+}+.field select,+.field input {+ width: 100%;+ padding: 6px 8px;+ font: 400 var(--fs-app-sm) var(--font-body);+ color: var(--fg-2);+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: 6px;+ outline: none;+}+.field select:focus,+.field input:focus { border-color: var(--brand); }++/* ─── bg thumb grid ────────────────────────────────────────────── */+.bgGrid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 8px;+ padding: 0 var(--sp-4) var(--sp-4);+}+.bgThumb {+ aspect-ratio: 1/1;+ border-radius: 10px;+ border: 1px solid transparent;+ cursor: pointer;+ transition: transform 150ms ease, border-color 150ms ease;+ background: var(--surface-2);+}+.bgThumb:hover { transform: translateY(-1px); }+.bgThumb.isActive {+ border-color: var(--brand);+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--brand), transparent 70%);+}++/* ─── toggle (switch) ──────────────────────────────────────────── */+.toggle {+ width: 36px;+ height: 20px;+ border: 0;+ padding: 0;+ background: var(--border);+ border-radius: 9999px;+ position: relative;+ cursor: pointer;+ transition: background 150ms ease;+ flex-shrink: 0;+}+.toggle::after {+ content: "";+ position: absolute;+ top: 2px;+ left: 2px;+ width: 16px;+ height: 16px;+ background: var(--accent-on);+ border-radius: 50%;+ box-shadow: 0 1px 3px rgba(22, 23, 29, 0.2);+ transition: transform 150ms ease;+}+.toggle.isOn { background: var(--brand); }+.toggle.isOn::after { transform: translateX(16px); }++/* ─── slider cell (effect) ─────────────────────────────────────── */+.sliderGrid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 10px;+ padding: 0 var(--sp-4) var(--sp-4);+}+.sliderCell {+ border: 1px solid var(--border);+ border-radius: 10px;+ background: var(--bg);+ padding: 10px 12px;+ display: grid;+ grid-template-rows: auto auto;+ gap: 8px;+}+.sliderCell .head { display: flex; align-items: center; gap: 6px; }+.sliderCell .label { font: 500 11px var(--font-body); color: var(--fg-2); }+.sliderCell .val { font: 500 11px var(--font-mono); color: var(--brand); margin-left: auto; }+.sliderCell input[type=range] {+ width: 100%;+ height: 4px;+ background: var(--border);+ border-radius: 2px;+ outline: none;+ -webkit-appearance: none;+ cursor: pointer;+}+.sliderCell input[type=range]::-webkit-slider-thumb {+ -webkit-appearance: none;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--brand);+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--brand), transparent 80%);+ cursor: pointer;+}+.sliderCell input[type=range]::-moz-range-thumb {+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--brand);+ border: 0;+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--brand), transparent 80%);+ cursor: pointer;+}+.sliderCell.full { grid-column: 1 / -1; }++/* ─── cursor style grid ────────────────────────────────────────── */+.cursorGrid {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: 6px;+ padding: 0 var(--sp-4) var(--sp-4);+}+.cursorCell {+ aspect-ratio: 1/1;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--bg);+ display: grid;+ place-items: center;+ cursor: pointer;+ transition: border-color 150ms ease, box-shadow 150ms ease;+ color: var(--muted);+}+.cursorCell:hover { border-color: var(--border-hi); color: var(--fg-2); }+.cursorCell.isActive {+ border-color: var(--brand);+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--brand), transparent 75%);+}++/* ─── chat strip + input ───────────────────────────────────────── */+.chatStrip {+ padding: var(--sp-3) var(--sp-4) var(--sp-2);+ border-bottom: 1px solid var(--border-soft);+ background: var(--bg);+}+.chatStripRow {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ margin-bottom: 6px;+}+.ctxPill {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 3px 9px 3px 7px;+ border-radius: var(--r-pill);+ background: var(--success-soft);+ color: var(--success);+ font-family: var(--font-mono);+ font-size: 10.5px;+ font-weight: 500;+ letter-spacing: 0.02em;+}+.ctxPill .d {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--success);+}+.stripActions {+ margin-left: auto;+ display: inline-flex;+ gap: 2px;+}+.stripActions button {+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ border-radius: var(--r-sm);+ color: var(--meta);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.stripActions button:hover {+ background: var(--surface-3);+ color: var(--fg-2);+}+.chatHint {+ font-size: var(--fs-app-sm);+ color: var(--muted);+ letter-spacing: 0.005em;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.msg { margin-bottom: var(--sp-3); }+.msgHead {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ padding: 0 var(--sp-1);+ margin-bottom: var(--sp-1);+}+.msgAuthor {+ font-family: var(--font-mono);+ font-size: 10px;+ letter-spacing: 0.08em;+ color: var(--meta);+ text-transform: uppercase;+}+.msgHead .right {+ margin-left: auto;+ display: inline-flex;+ gap: 2px;+}+.msgHead .right button {+ width: 22px;+ height: 22px;+ display: grid;+ place-items: center;+ border-radius: var(--r-xs);+ color: var(--meta);+ background: transparent;+ border: 0;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease);+}+.msgHead .right button:hover {+ background: var(--surface-3);+ color: var(--fg-2);+}+.msgBubble {+ padding: var(--sp-3) var(--sp-4);+ border-radius: var(--r-md);+ background: var(--bg);+ border: 1px solid var(--border);+ font-size: var(--fs-app);+ color: var(--fg-2);+ line-height: 1.5;+}+.msgBubble .msgAuthor { color: var(--accent); }++.chatInput {+ padding: var(--sp-3) var(--sp-4);+ border-top: 1px solid var(--border-soft);+ background: var(--bg);+}+.chatInput textarea {+ width: 100%;+ min-height: 64px;+ resize: none;+ padding: var(--sp-3);+ border-radius: var(--r-md);+ border: 1px solid var(--border);+ background: var(--bg);+ font-family: var(--font-body);+ font-size: var(--fs-app);+ line-height: 1.5;+ color: var(--fg);+ outline: none;+ transition: border-color var(--motion-fast) var(--ease), box-shadow var(--motion-fast) var(--ease);+}+.chatInput textarea::placeholder { color: var(--meta); }+.chatInput textarea:focus {+ border-color: var(--accent);+ box-shadow: var(--focus-ring);+}+.chatInput .actions {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ margin-top: var(--sp-2);+}+.modelPicker {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 4px 5px 10px;+ border-radius: var(--r-pill);+ background: var(--surface-2);+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--fg-2);+ letter-spacing: 0.01em;+ cursor: pointer;+ transition: background var(--motion-fast) var(--ease);+ border: 0;+}+.modelPicker:hover { background: var(--surface-3); }+.modelPicker .chip {+ padding: 3px 8px;+ border-radius: var(--r-pill);+ background: var(--success-soft);+ color: var(--success);+ font-size: 10.5px;+ font-weight: 500;+ letter-spacing: 0.01em;+ display: inline-flex;+ align-items: center;+ gap: 4px;+}+.modelPicker .chip .d {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--success);+}+.sendBtn {+ margin-left: auto;+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: transparent;+ color: var(--fg);+ border: 0;+ cursor: pointer;+ transition: color var(--motion-fast) var(--ease), transform var(--motion-fast) var(--ease);+}+.sendBtn:hover { color: var(--accent); transform: scale(1.05); }+.sendBtn:disabled { opacity: 0.4; cursor: not-allowed; }++/* ─── transcript pane content ─────────────────────────────────── */+.transcriptClipHead {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 0 4px 4px;+ border-bottom: 1px solid var(--border-soft);+ margin-bottom: 8px;+}+.transcriptClipHead .badge {+ width: 22px;+ height: 22px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: var(--brand-soft);+ color: var(--brand);+ border-radius: var(--r-sm);+ font: 700 12px/1 var(--font-mono);+ flex-shrink: 0;+}+.transcriptClipHead .title {+ font: 600 var(--fs-app)/1.2 var(--font-body);+ color: var(--fg);+ margin: 0;+ padding: 0;+}+.transcriptClipHead .sub {+ font: 400 11px/1.3 var(--font-mono);+ color: var(--muted);+ margin-top: 2px;+}+.transcriptFlow {+ margin: 0;+ padding: 0 4px;+ font: 400 var(--fs-app-lg)/1.65 var(--font-body);+ color: var(--fg);+ text-wrap: pretty;+}+.transcriptFlow .tc {+ display: inline-block;+ margin: 0 4px;+ padding: 1px 6px;+ background: transparent;+ color: var(--brand);+ border-radius: var(--r-sm);+ font: 500 11px/1.4 var(--font-mono);+ vertical-align: middle;+ white-space: nowrap;+}+.transcriptFlow .filler {+ display: inline-block;+ padding: 1px 6px;+ margin: 0 1px;+ background: var(--danger-soft);+ color: var(--danger);+ border-radius: var(--r-sm);+ font-weight: 500;+}++/* ─── bottombar / timeline ─────────────────────────────────────── */+.bottombar {+ display: grid;+ grid-template-columns: 1fr;+ min-height: 0;+ background: var(--bg);+ overflow: hidden;+}+.timelineHead {+ display: flex;+ align-items: center;+ gap: var(--sp-2);+ padding: var(--sp-2) var(--sp-4);+ border-bottom: 1px solid var(--border-soft);+ min-height: 40px;+}+.timelineHead .viewTools {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 3px;+ background: var(--surface-2);+ border: 1px solid var(--border-soft);+ border-radius: var(--r-sm);+}+.timelineHead .vtBtn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 30px;+ height: 30px;+ padding: 0;+ border: 0;+ background: transparent;+ color: var(--muted);+ border-radius: var(--r-xs);+ cursor: pointer;+ transition: color 0.12s ease, background 0.12s ease;+}+.timelineHead .vtBtn:hover { color: var(--fg); background: var(--surface); }+.timelineHead .vtBtn.isOn { color: var(--accent); background: var(--accent-wash); }+.timelineHead .ratio {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ height: 30px;+ padding: 0 10px;+ font-family: var(--font-mono);+ font-size: var(--fs-app-sm);+ color: var(--muted);+ letter-spacing: 0.02em;+ background: transparent;+ border: 0;+ border-left: 1px solid var(--border-soft);+ margin-left: 4px;+ cursor: pointer;+ border-radius: 0 var(--r-sm) var(--r-sm) 0;+}+.timelineHead .ratio:hover { color: var(--fg); }+.timelineHead .hintRow {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: var(--sp-4);+}+.timelineHead .hint {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-family: var(--font-display);+ font-size: 11.5px;+ color: var(--muted);+ letter-spacing: 0.005em;+}+.timelineHead .hint .kbd {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ height: 20px;+ padding: 0 7px;+ font-family: var(--font-mono);+ font-size: 10.5px;+ font-weight: 500;+ color: var(--accent);+ background: var(--accent-soft);+ border: 1px solid color-mix(in oklch, var(--accent) 24%, transparent);+ border-radius: var(--r-xs);+ letter-spacing: 0.02em;+ white-space: nowrap;+}+.timelineBody {+ display: flex;+ flex-direction: column;+ min-height: 0;+ flex: 1;+ overflow: hidden;+}+.timelineBody :global(.timelinePaneWrap) {+ flex: 1;+ min-height: 0;+ overflow: hidden;+}+.zoombar {+ padding: 4px var(--sp-4) 8px;+ background: var(--bg);+ flex-shrink: 0;+ border-top: 1px solid var(--border-soft);+}+.zoombar .zoomTrack {+ position: relative;+ height: 18px;+ width: 100%;+}+.zoombar .zoomFill {+ position: absolute;+ top: 50%;+ transform: translateY(-50%);+ left: 0;+ width: 100%;+ height: 6px;+ background: var(--accent);+ border-radius: 3px;+ pointer-events: none;+}++/* ─── modals ───────────────────────────────────────────────────── */+.modal {+ position: fixed;+ inset: 0;+ display: none;+ z-index: 100;+}+.modal.isOpen { display: block; }+.modalBackdrop {+ position: absolute;+ inset: 0;+ background: rgba(22, 23, 29, 0.55);+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+}+.modalCard {+ position: relative;+ width: min(960px, 92vw);+ max-height: 88vh;+ margin: 6vh auto 0;+ background: var(--bg);+ border: 1px solid var(--border);+ border-radius: var(--r-lg);+ box-shadow: 0 24px 60px rgba(22, 23, 29, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ color: var(--fg);+}+.modalCard.wide { width: min(720px, 92vw); }+.modalHead {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ padding: 20px 24px 12px;+ gap: 16px;+}+.modalHead h2 {+ margin: 0;+ font: 600 20px/1.3 var(--font-display);+ color: var(--fg);+}+.modalHead p {+ margin: 4px 0 0;+ font: 400 var(--fs-app)/1.5 var(--font-body);+ color: var(--muted);+}+.modalHead .closeBtn {+ width: 28px;+ height: 28px;+ display: grid;+ place-items: center;+ border-radius: var(--r-sm);+ color: var(--muted);+ background: transparent;+ border: 0;+ cursor: pointer;+}+.modalHead .closeBtn:hover { background: var(--surface-3); color: var(--fg); }+.modalBody {+ padding: 8px 24px 24px;+ display: flex;+ flex-direction: column;+ gap: 20px;+ overflow: auto;+}++.btn {+ height: 32px;+ padding: 0 14px;+ border-radius: var(--r-md);+ font: 500 var(--fs-app)/1 var(--font-body);+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ transition: background var(--motion-fast) var(--ease), border-color var(--motion-fast) var(--ease);+}+.btnSecondary {+ background: var(--surface);+ color: var(--fg);+ border: 1px solid var(--border);+}+.btnSecondary:hover { background: var(--surface-warm); border-color: var(--border-hi); }+.btnPrimary {+ background: var(--accent);+ color: var(--accent-on);+ border: 1px solid var(--accent);+}+.btnPrimary:hover { background: var(--brand-lo); }+.btnPrimary:disabled {+ background: var(--surface-2);+ border-color: var(--border);+ color: var(--muted);+ cursor: not-allowed;+}++/* ─── media card (left panel media list) ───────────────────────── */+.mediaList {+ list-style: none;+ padding: 0;+ margin: 0;+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.mediaCard {+ display: flex;+ flex-direction: column;+ border-radius: var(--r-md);+ overflow: hidden;+ border: 1px solid var(--border-soft);+ background: var(--bg);+ cursor: pointer;+ transition: border-color var(--motion-fast) var(--ease);+}+.mediaCard:hover { border-color: var(--brand); }+.mediaCard .thumb {+ aspect-ratio: 16 / 9;+ display: flex;+ align-items: center;+ justify-content: center;+ color: rgba(255, 255, 255, 0.95);+}+.thumbRed { background: var(--danger); }+.thumbGreen { background: var(--success); }+.thumbAmber { background: var(--warn); }+.thumbCyan { background: var(--accent); }+.mediaMeta {+ padding: 8px 10px 10px;+ background: var(--surface-2);+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.mediaMeta .name {+ font: var(--fs-app) var(--font-body);+ color: var(--fg);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.mediaMeta .row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}+.mediaMeta .timecode { font: 11px var(--font-mono); color: var(--muted); }+.mediaMeta .size { font: 11px var(--font-body); color: var(--muted); }++.importBtn {+ margin: 8px var(--sp-3) 12px;+ padding: 10px 12px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: var(--sp-2);+ border: 1px dashed var(--border-hi);+ border-radius: var(--r-md);+ background: transparent;+ color: var(--muted);+ font: var(--fs-app) var(--font-body);+ font-weight: 500;+ cursor: pointer;+}+.importBtn:hover { background: var(--surface-warm); color: var(--fg); border-color: var(--accent); }++/* Custom range slider / progress bar */+.scrubBar {+ flex: 1;+ max-width: 400px;+ position: relative;+ height: 24px;+ display: flex;+ align-items: center;+ cursor: pointer;+}+.scrubTrack {+ position: absolute;+ left: 0;+ right: 0;+ height: 4px;+ background: var(--border);+ border-radius: 9999px;+ overflow: hidden;+}+.scrubProgress {+ height: 100%;+ background: var(--accent);+ border-radius: 9999px;+}+.scrubInput {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ opacity: 0;+ cursor: pointer;+ z-index: 10;+ margin: 0;+}+.scrubThumb {+ position: absolute;+ width: 10px;+ height: 10px;+ background: #ffffff;+ border-radius: 50%;+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);+ pointer-events: none;+ transform: translate(-50%, -50%);+ top: 50%;+ opacity: 0;+ transition: transform 100ms ease, opacity 100ms ease;+}+.scrubBar:hover .scrubThumb {+ opacity: 1;+ transform: translate(-50%, -50%) scale(1.2);+}diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxnew file mode 100644index 000000000..f7ffc323e--- /dev/null+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -0,0 +1,990 @@+import { EyeOff, Film, Sparkles } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import type { EditorProjectData } from "@/components/video-editor/projectPersistence";+import { toFileUrl } from "@/components/video-editor/projectPersistence";+import type { CropRegion } from "@/components/video-editor/types";+import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";+import { transcribeAsset } from "@/lib/ai-edition/document/transcribe";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { useUndoRedoShortcuts } from "@/lib/ai-edition/store/undo";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { useTimeline } from "@/lib/ai-edition/store/useTimeline";+import { nativeBridgeClient } from "@/native";+import type { AiEditionProjectSummary } from "@/native/contracts";+import { Bottombar } from "./Bottombar";+import { ExportDialog } from "./ExportDialog";+import { LeftPanel, LeftRail, type LeftTab } from "./LeftPanel";+import {+ AutoCaptionsModal,+ CropModal,+ InsertSourceModal,+ NewProjectModal,+ OpenProjectModal,+ UnsavedChangesModal,+ type UnsavedChoice,+} from "./Modals";+import styles from "./NewEditorShell.module.css";+import { Preview } from "./Preview";+import { RightPanelStack } from "./RightPanelStack";+import type { RightPaneId } from "./RightPanes";+import { Titlebar } from "./Titlebar";++interface SeekTarget {+ timeSec: number;+ isSource?: boolean;+ requestId: number;+}++const COLLAPSE_INITIAL = {+ left: false,+ right: true,+ bottom: false,+};++export function NewEditorShell() {+ const document = useProjectStore((s) => s.document);+ const projectId = useProjectStore((s) => s.projectId);+ const sourceDurationSec = useProjectStore((s) => s.sourceDurationSec);+ const currentTimeSec = useProjectStore((s) => s.currentTimeSec);+ const dirty = useProjectStore((s) => s.dirty);+ const lastSavedAt = useProjectStore((s) => s.lastSavedAt);+ const createProject = useProjectStore((s) => s.createProject);+ const addAsset = useProjectStore((s) => s.addAsset);+ const replaceTimeline = useProjectStore((s) => s.replaceTimeline);+ const setTranscript = useProjectStore((s) => s.setTranscript);+ const setCurrentTime = useProjectStore((s) => s.setCurrentTime);+ const setSourceDuration = useProjectStore((s) => s.setSourceDuration);+ const loadProject = useProjectStore((s) => s.loadProject);+ const saveDocument = useProjectStore((s) => s.saveDocument);+ const markClean = useProjectStore((s) => s.markClean);++ const [seekTarget, setSeekTarget] = useState<SeekTarget | null>(null);+ const [isTranscribing, setIsTranscribing] = useState(false);+ const [assetStatuses, setAssetStatuses] = useState<+ Record<string, "pending" | "running" | "failed">+ >({});+ const [, setVideoElement] = useState<HTMLVideoElement | null>(null);+ const [leftTab, setLeftTab] = useState<LeftTab>("media");+ const [rightPane, setRightPane] = useState<RightPaneId>("background");+ const [leftCollapsed, setLeftCollapsed] = useState(COLLAPSE_INITIAL.left);+ const [rightCollapsed, setRightCollapsed] = useState(COLLAPSE_INITIAL.right);+ const [bottomCollapsed, setBottomCollapsed] = useState(COLLAPSE_INITIAL.bottom);+ const [openProjectOpen, setOpenProjectOpen] = useState(false);+ const [newProjectOpen, setNewProjectOpen] = useState(false);+ const [cropOpen, setCropOpen] = useState(false);+ const [exportOpen, setExportOpen] = useState(false);+ const [unsavedPrompt, setUnsavedPrompt] = useState<{+ action: "new" | "open" | "record";+ resolve: (choice: UnsavedChoice) => void;+ } | null>(null);+ const { settings: editorSettings, set: setEditorSettings } = useEditorSettings();+ const tl = useTimeline();+ useUndoRedoShortcuts(() => {+ // ponytail: placeholder, wire when undo stack merges with history+ });+ const [captionsOpen, setCaptionsOpen] = useState(false);+ const [captionsMinW, setCaptionsMinW] = useState(2);+ const [captionsMaxW, setCaptionsMaxW] = useState(7);+ const [insertAssetId, setInsertAssetId] = useState<string | null>(null);+ const [projectSummaries, setProjectSummaries] = useState<AiEditionProjectSummary[]>([]);+ const seekSeqRef = useRef(0);+ const initRef = useRef(false);++ const promptUnsaved = useCallback(+ (action: "new" | "open" | "record"): Promise<UnsavedChoice> => {+ if (!dirty) return Promise.resolve("discard");+ return new Promise<UnsavedChoice>((resolve) => {+ setUnsavedPrompt({ action, resolve });+ });+ },+ [dirty],+ );++ const primaryAssetPath =+ document?.assets.find((a) => a.id === document.project.primaryAssetId)?.originalPath ?? null;+ void primaryAssetPath;+ const clips: AxcutClip[] = document?.timeline.clips ?? [];+ const hasProject = Boolean(document);+ const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;+ const project = document?.project+ ? {+ id: document.project.id,+ title: document.project.title,+ updatedAt: new Date().toISOString(),+ }+ : null;++ // refresh project list when the Open Project modal is open+ useEffect(() => {+ if (!openProjectOpen) return;+ void (async () => {+ try {+ const next = await nativeBridgeClient.aiEdition.listProjects();+ setProjectSummaries(next);+ } catch {+ // ponytail: silent+ }+ })();+ }, [openProjectOpen]);++ // Auto-load project recording session on mount+ useEffect(() => {+ if (initRef.current) return;+ initRef.current = true;+ void (async () => {+ if (!window.electronAPI) return;+ try {+ const result = await window.electronAPI.getCurrentRecordingSession();+ if (!result.success || !result.session?.screenVideoPath) return;+ const screenPath = result.session.screenVideoPath;+ const label = screenPath.split(/[\\/]/).pop() || "Recording";+ await createProject(`Recording ${new Date().toLocaleString()}`);+ await addAsset(screenPath, label);+ toast.success("Recording added to a new project");+ } catch (err) {+ toast.error("Could not auto-create project from recording", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ })();+ }, [addAsset, createProject]);++ // Warn on close when dirty+ useEffect(() => {+ const onBeforeUnload = (e: BeforeUnloadEvent) => {+ if (useProjectStore.getState().dirty) {+ e.preventDefault();+ e.returnValue = "";+ }+ };+ window.addEventListener("beforeunload", onBeforeUnload);+ return () => window.removeEventListener("beforeunload", onBeforeUnload);+ }, []);++ // Electron close interception+ useEffect(() => {+ if (!window.electronAPI) return;++ // 1. Sync dirty state to Electron main process+ window.electronAPI.setHasUnsavedChanges(dirty);+ }, [dirty]);++ useEffect(() => {+ if (!window.electronAPI) return;++ // 2. Handle request-close-confirm from Electron+ const unsubCloseConfirm = window.electronAPI.onRequestCloseConfirm(() => {+ void (async () => {+ const choice = await promptUnsaved("new"); // Use "new" as a generic action for close+ if (choice === "discard") {+ window.electronAPI.sendCloseConfirmResponse("discard");+ } else if (choice === "save") {+ window.electronAPI.sendCloseConfirmResponse("save");+ } else {+ window.electronAPI.sendCloseConfirmResponse("cancel");+ }+ })();+ });++ // 3. Handle request-save-before-close from Electron+ const unsubSaveBeforeClose = window.electronAPI.onRequestSaveBeforeClose(async () => {+ const doc = useProjectStore.getState().document;+ if (doc) {+ try {+ await saveDocument(doc);+ return true;+ } catch {+ toast.error("Failed to save before closing");+ return false;+ }+ }+ return true;+ });++ return () => {+ unsubCloseConfirm?.();+ unsubSaveBeforeClose?.();+ };+ }, [promptUnsaved, saveDocument]);++ const videoSources = useMemo(() => {+ if (!document) return [];+ return document.assets.map((asset) => ({+ id: asset.id,+ src: toFileUrl(asset.originalPath),+ label: asset.label,+ }));+ }, [document]);++ const handleLoadedMetadata = useCallback(+ (durationSec: number) => {+ setSourceDuration(durationSec);+ if (document && document.assets.length > 0 && document.timeline.clips.length === 0) {+ const asset =+ document.assets.find((a) => a.id === document.project.primaryAssetId) ??+ document.assets[0];+ if (asset) {+ void replaceTimeline(+ [{ startSec: 0, endSec: durationSec }],+ "Auto-created full-duration clip",+ );+ }+ }+ },+ [document, replaceTimeline, setSourceDuration],+ );++ const handleSeek = useCallback(+ (timeSec: number) => {+ setCurrentTime(timeSec);+ setSeekTarget({ timeSec, isSource: false, requestId: ++seekSeqRef.current });+ },+ [setCurrentTime],+ );++ const handleTimeChange = useCallback(+ (timeSec: number) => {+ setCurrentTime(timeSec);+ },+ [setCurrentTime],+ );++ const handleReplaceTimeline = useCallback(+ (intervals: Array<{ startSec: number; endSec: number }>, reason: string) => {+ void replaceTimeline(intervals, reason);+ },+ [replaceTimeline],+ );++ const handleTranscribe = useCallback(async () => {+ if (!document || !document.project.primaryAssetId) return;+ const assetId = document.project.primaryAssetId;+ setIsTranscribing(true);+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "running" }));+ try {+ const transcript = await transcribeAsset(document, assetId, {+ onStatus: (s) => toast.loading(`Transcribing: ${s}`, { id: "transcribe" }),+ });+ toast.dismiss("transcribe");+ await setTranscript(transcript);+ setRightPane("transcript");+ toast.success("Transcript ready");+ setAssetStatuses((prev) => {+ const next = { ...prev };+ delete next[assetId];+ return next;+ });+ } catch (err) {+ toast.dismiss("transcribe");+ toast.error("Transcription failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "failed" }));+ } finally {+ setIsTranscribing(false);+ }+ }, [document, setTranscript]);++ const handleLoadLegacyProject = useCallback(async () => {+ try {+ const result = await window.electronAPI?.loadProjectFile();+ if (!result?.success || !result.project) return;+ const legacy = result.project as EditorProjectData;+ const migrated = migrateProjectDataToAxcutDocument(legacy);+ const saved = await nativeBridgeClient.aiEdition.save(migrated);+ if (saved.success && saved.document) {+ await loadProject(migrated.project.id);+ toast.success("Legacy project migrated and loaded");+ } else {+ toast.error(saved.error ?? "Failed to save migrated project");+ }+ } catch (err) {+ toast.error("Could not load project", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ }, [loadProject]);++ const handleDropWordRange = useCallback(+ async (startSec: number, endSec: number) => {+ if (!document) return;+ const { subtractInterval, timelineIntervals: getIntervals } = await import(+ "@/lib/ai-edition/document/timeline"+ );+ const intervals = getIntervals(document);+ const next = subtractInterval(intervals, { startSec, endSec });+ await replaceTimeline(+ next,+ `Dropped word range ${startSec.toFixed(1)}s-${endSec.toFixed(1)}s`,+ );+ },+ [document, replaceTimeline],+ );++ const handleSelectProject = useCallback(+ async (id: string) => {+ try {+ await loadProject(id);+ } catch (err) {+ toast.error("Could not open project", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [loadProject],+ );++ const handleCreateProject = useCallback(+ async (title: string) => {+ try {+ await createProject(title);+ } catch (err) {+ toast.error("Could not create project", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [createProject],+ );++ const handleSave = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ try {+ await saveDocument(doc);+ toast.success("Project saved");+ } catch (err) {+ toast.error("Save failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ }, [saveDocument]);++ const handleSaveAs = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ try {+ const result = await nativeBridgeClient.aiEdition.save(doc);+ if (!result.success || !result.document) {+ throw new Error(result.error ?? "Failed to save project");+ }+ const title = window.prompt("Save project as", doc.project.title);+ if (!title || title === doc.project.title) {+ markClean();+ toast.success("Project saved");+ return;+ }+ const renamed = { ...doc, project: { ...doc.project, title } };+ await saveDocument(renamed);+ toast.success(`Saved as "${title}"`);+ } catch (err) {+ toast.error("Save failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ }, [markClean, saveDocument]);++ const handleRenameProject = useCallback(+ async (title: string) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ if (title === doc.project.title) return;+ try {+ await saveDocument({ ...doc, project: { ...doc.project, title } });+ } catch (err) {+ toast.error("Rename failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [saveDocument],+ );++ const handleConfirmUnsaved = useCallback(+ (choice: UnsavedChoice) => {+ if (!unsavedPrompt) return;+ const { action, resolve } = unsavedPrompt;+ setUnsavedPrompt(null);+ // ponytail: resolve the action when the user picks save / discard.+ // The "continue with action" path is handled below in handleNewRecording /+ // the open-project branch. We resolve the promise once the work is done+ // (or cancelled).+ void (async () => {+ if (choice === "cancel") {+ resolve("cancel");+ return;+ }+ if (choice === "save") {+ const doc = useProjectStore.getState().document;+ if (doc) {+ try {+ await saveDocument(doc);+ } catch {+ resolve("cancel");+ return;+ }+ }+ }+ if (action === "record") {+ void window.electronAPI?.startNewRecording?.();+ }+ resolve(choice);+ })();+ },+ [saveDocument, unsavedPrompt],+ );++ const handleNewRecording = useCallback(async () => {+ const choice = await promptUnsaved("record");+ if (choice !== "cancel") {+ void window.electronAPI?.startNewRecording?.();+ }+ }, [promptUnsaved]);++ const handleReturnToRecorder = useCallback(() => {+ void window.electronAPI?.switchToHud?.();+ }, []);++ const handleExport = useCallback(() => {+ if (!hasAsset) {+ toast.info("Add a video to the project before exporting.");+ return;+ }+ setExportOpen(true);+ }, [hasAsset]);++ const handlePreviewSource = useCallback((sec: number) => {+ setSeekTarget({ timeSec: sec, isSource: true, requestId: ++seekSeqRef.current });+ }, []);++ const handleOpenSettings = useCallback(() => {+ toast.info(+ "Open the right rail to access Background, Effects, Layout, Cursor, and Timeline settings.",+ );+ }, []);++ const pasteRegion = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const { pasteClipboard } = await import("@/lib/ai-edition/store/regionClipboard");+ const clip = pasteClipboard();+ if (!clip) return;+ const timeMs = Math.round(currentTimeSec * 1000);+ const region = { ...clip.region, id: crypto.randomUUID() };+ if (clip.kind === "zoom") {+ const zoom = region as unknown as (typeof doc.zoomRanges)[number];+ const duration = zoom.endMs - zoom.startMs;+ zoom.startMs = timeMs;+ zoom.endMs = timeMs + duration;+ await saveDocument({ ...doc, zoomRanges: [...doc.zoomRanges, zoom] });+ } else if (clip.kind === "annotation") {+ const annotation = region as unknown as (typeof doc.annotations)[number];+ const duration = annotation.endMs - annotation.startMs;+ annotation.startMs = timeMs;+ annotation.endMs = timeMs + duration;+ await saveDocument({ ...doc, annotations: [...doc.annotations, annotation] });+ } else if (clip.kind === "speed") {+ const speedRegions =+ (doc.legacyEditor as { speedRegions?: Array<Record<string, unknown>> })?.speedRegions ?? [];+ const speed = region as unknown as (typeof speedRegions)[number];+ const duration = Number(speed.endMs) - Number(speed.startMs);+ speed.startMs = timeMs;+ speed.endMs = timeMs + duration;+ await saveDocument({+ ...doc,+ legacyEditor: {+ ...doc.legacyEditor,+ speedRegions: [...speedRegions, speed],+ },+ });+ }+ toast.success("Region pasted");+ }, [currentTimeSec, saveDocument]);++ const handleCopyRegion = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc || !tl.selection) return;+ const { copyRegion } = await import("@/lib/ai-edition/store/regionClipboard");+ const region =+ tl.selection.kind === "zoom"+ ? doc.zoomRanges.find((z) => z.id === tl.selection?.id)+ : tl.selection.kind === "annotation"+ ? (doc.annotations as unknown[]).find(+ (a) => (a as { id: string }).id === tl.selection?.id,+ )+ : ((doc.legacyEditor as { speedRegions?: unknown[] } | null)?.speedRegions ?? []).find(+ (s) => (s as { id: string }).id === tl.selection?.id,+ );+ if (region) {+ copyRegion({+ kind: tl.selection.kind === "skip" ? "zoom" : tl.selection.kind,+ region: region as Record<string, unknown>,+ });+ toast.success("Region copied");+ }+ }, [tl]);++ const handleDropOnTimeline = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ const assetId = e.dataTransfer.getData("application/x-axcut-asset");+ if (assetId) setInsertAssetId(assetId);+ }, []);++ const handleInsertBefore = useCallback(async () => {+ if (!insertAssetId) return;+ setInsertAssetId(null);+ await tl.addClipBefore(insertAssetId);+ }, [insertAssetId, tl]);++ const handleInsertAfter = useCallback(async () => {+ if (!insertAssetId) return;+ setInsertAssetId(null);+ await tl.addClipAfter(insertAssetId);+ }, [insertAssetId, tl]);++ const handleInsertSplit = useCallback(async () => {+ if (!insertAssetId) return;+ setInsertAssetId(null);+ await tl.splitAndInsert(insertAssetId, currentTimeSec);+ }, [insertAssetId, currentTimeSec, tl]);++ const handleCaptions = useCallback(() => {+ if (!document?.project.primaryAssetId) {+ toast.info("Add a video to the project before generating captions.");+ return;+ }+ setCaptionsOpen(true);+ }, [document]);++ const handleGenerateCaptions = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const assetId = doc.project.primaryAssetId;+ if (!assetId) {+ toast.error("Add a video to the project before generating captions.");+ return;+ }++ setCaptionsOpen(false);+ try {+ let transcript = doc.transcript;+ if (!transcript) {+ toast.loading("Transcribing first…", { id: "captions-gen" });+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "running" }));+ try {+ transcript = await transcribeAsset(doc, assetId, {+ onStatus: (s) => toast.loading(`Transcribing: ${s}`, { id: "captions-gen" }),+ });+ toast.dismiss("captions-gen");+ await setTranscript(transcript);+ setAssetStatuses((prev) => {+ const next = { ...prev };+ delete next[assetId];+ return next;+ });+ } catch (err) {+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "failed" }));+ throw err;+ }+ }++ const { captionSegmentsToAnnotationRegions } = await import(+ "@/lib/captioning/annotationsFromCaptions"+ );+ toast.loading("Generating captions…", { id: "captions-gen" });+ const segments =+ ((transcript as Record<string, unknown>).segments as Array<Record<string, unknown>>) ?? [];+ const { regions } = captionSegmentsToAnnotationRegions(+ segments as never,+ doc.annotations.length + 1,+ doc.annotations.length + 1,+ {+ minWordsPerCaption: captionsMinW,+ maxWordsPerCaption: captionsMaxW,+ timestampGranularity: "word",+ },+ );+ const latestDoc = useProjectStore.getState().document ?? doc;+ const next = {+ ...latestDoc,+ annotations: [...latestDoc.annotations, ...(regions as never)],+ };+ await saveDocument(next);+ toast.dismiss("captions-gen");+ toast.success(`Added ${regions.length} captions`);+ } catch (err) {+ toast.dismiss("captions-gen");+ toast.error("Caption generation failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ }, [captionsMinW, captionsMaxW, saveDocument, setTranscript]);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLInputElement) return;+ if (e.target instanceof HTMLElement && e.target.isContentEditable) return;+ const ctrl = e.ctrlKey || e.metaKey;+ if (ctrl && e.key === "s") {+ e.preventDefault();+ void handleSave();+ return;+ }+ if (ctrl && e.key === "n") {+ e.preventDefault();+ void (async () => {+ const choice = await promptUnsaved("new");+ if (choice === "cancel") return;+ if (choice === "save") {+ const doc = useProjectStore.getState().document;+ if (doc) {+ try {+ await saveDocument(doc);+ } catch {+ return;+ }+ }+ }+ setNewProjectOpen(true);+ })();+ return;+ }+ if (ctrl && e.key === "o") {+ e.preventDefault();+ void (async () => {+ const choice = await promptUnsaved("open");+ if (choice === "cancel") return;+ if (choice === "save") {+ const doc = useProjectStore.getState().document;+ if (doc) {+ try {+ await saveDocument(doc);+ } catch {+ return;+ }+ }+ }+ setOpenProjectOpen(true);+ })();+ return;+ }+ if (!hasProject && e.key !== "?") return;+ if (ctrl && e.key === "z") return;+ if (e.key === "?" || (e.shiftKey && e.key === "/")) {+ e.preventDefault();+ window.dispatchEvent(new CustomEvent("openscreen:open-shortcuts"));+ return;+ }+ if (ctrl && e.key.toLowerCase() === "c" && tl.selection) {+ e.preventDefault();+ void handleCopyRegion();+ return;+ }+ if (ctrl && e.key.toLowerCase() === "v") {+ e.preventDefault();+ void pasteRegion();+ return;+ }+ if (e.key === " ") {+ const v = window.document.querySelector("video");+ if (v) {+ e.preventDefault();+ if (v.paused) {+ void v.play();+ } else {+ v.pause();+ }+ }+ return;+ }+ if (e.key === "Delete" || e.key === "Backspace") {+ if (tl.selection) {+ e.preventDefault();+ void tl.removeRegion(tl.selection.kind, tl.selection.id);+ }+ return;+ }+ switch (e.key.toLowerCase()) {+ case "z":+ if (!ctrl) {+ e.preventDefault();+ void tl.addZoom();+ }+ break;+ case "t":+ e.preventDefault();+ void tl.addSkip();+ break;+ case "a":+ e.preventDefault();+ void tl.addAnnotation();+ break;+ case "s":+ e.preventDefault();+ void tl.addSpeed();+ break;+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [hasProject, handleCopyRegion, handleSave, pasteRegion, tl, promptUnsaved, saveDocument]);++ const collapseAttr = useMemo(() => {+ const list: string[] = [];+ if (leftCollapsed) list.push("left");+ if (rightCollapsed) list.push("right");+ if (bottomCollapsed) list.push("bottom");+ return list.join(" ");+ }, [leftCollapsed, rightCollapsed, bottomCollapsed]);++ return (+ <div className={styles.app} data-collapse={collapseAttr || undefined}>+ <Titlebar+ project={project}+ dirty={dirty}+ lastSavedAt={lastSavedAt}+ canExport={hasAsset}+ leftCollapsed={leftCollapsed}+ rightCollapsed={rightCollapsed}+ bottomCollapsed={bottomCollapsed}+ actions={{+ openProject: () => setOpenProjectOpen(true),+ newProject: () => setNewProjectOpen(true),+ save: () => void handleSave(),+ saveAs: () => void handleSaveAs(),+ newRecording: () => void handleNewRecording(),+ recorder: handleReturnToRecorder,+ export: handleExport,+ toggleLeft: () => setLeftCollapsed((v) => !v),+ toggleRight: () => setRightCollapsed((v) => !v),+ toggleBottom: () => setBottomCollapsed((v) => !v),+ openSettings: handleOpenSettings,+ renameProject: handleRenameProject,+ }}+ />++ <main+ className={styles.workbench}+ onDragOver={(e) => {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }}+ onDrop={handleDropOnTimeline}+ >+ {/* Left rail */}+ <LeftRail active={leftTab} onChange={setLeftTab} />++ {/* Left content panel */}+ {!leftCollapsed ? (+ <div className={styles.leftPanel}>+ <LeftPanel active={leftTab} assetStatuses={assetStatuses} />+ </div>+ ) : null}++ {/* Resize handle: left */}+ <div+ className={`${styles.handle} ${styles.handleCol} ${styles.handleLeft}`}+ aria-label="Resize left panel"+ onPointerDown={(e) => startResize(e, "left")}+ />++ {/* Preview center */}+ <Preview+ hasProject={hasProject}+ hasAsset={hasAsset}+ videoSources={videoSources}+ clips={clips}+ seekTarget={seekTarget}+ onTimeChange={handleTimeChange}+ onSeek={handleSeek}+ onLoadedMetadata={handleLoadedMetadata}+ onVideoElement={setVideoElement}+ currentTimeSec={currentTimeSec}+ />++ {/* Resize handle: right */}+ <div+ className={`${styles.handle} ${styles.handleCol} ${styles.handleRight}`}+ aria-label="Resize right panel"+ onPointerDown={(e) => startResize(e, "right")}+ />++ {/* Right panel stack + rail */}+ {!rightCollapsed ? (+ <RightPanelStack+ active={rightPane}+ onChange={setRightPane}+ onCrop={() => setCropOpen(true)}+ transcript={document?.transcript ?? null}+ clips={clips}+ currentTimeSec={currentTimeSec}+ onSeek={handleSeek}+ onDropWordRange={handleDropWordRange}+ onTranscribe={handleTranscribe}+ canTranscribe={hasAsset}+ isTranscribing={isTranscribing}+ selection={tl.selection}+ onClearSelection={tl.clearSelection}+ onRemoveSelection={(kind, id) => void tl.removeRegion(kind, id)}+ />+ ) : (+ <aside className={`${styles.rail} ${styles.rightRail}`} aria-label="Right tools">+ <RightRailCompact onChange={setRightPane} onCrop={() => setCropOpen(true)} />+ </aside>+ )}+ </main>++ {/* Resize handle: bottom */}+ <div+ className={`${styles.handle} ${styles.handleRow} ${styles.handleBottom}`}+ aria-label="Resize timeline"+ onPointerDown={(e) => startResize(e, "bottom")}+ />++ {/* Bottom timeline */}+ {!bottomCollapsed ? (+ <Bottombar+ clips={clips}+ currentTimeSec={currentTimeSec}+ sourceDurationSec={sourceDurationSec}+ onPreviewSource={handlePreviewSource}+ onReplaceTimeline={handleReplaceTimeline}+ zoomRegions={tl.zoomRegions}+ skipRanges={tl.skipRanges}+ annotationRegions={tl.annotationRegions}+ speedRegions={tl.speedRegions}+ selection={tl.selection}+ hasDoc={tl.hasDoc}+ onAddZoom={() => void tl.addZoom()}+ onAddSkip={() => void tl.addSkip()}+ onAddAnnotation={() => void tl.addAnnotation()}+ onAddSpeed={() => void tl.addSpeed()}+ onSelectRegion={(kind, id) => tl.selectRegion(kind, id)}+ onRemoveRegion={(kind, id) => void tl.removeRegion(kind, id)}+ onCaptions={handleCaptions}+ />+ ) : null}++ {/* Modals */}+ <OpenProjectModal+ open={openProjectOpen}+ onClose={() => setOpenProjectOpen(false)}+ projects={projectSummaries}+ activeProjectId={projectId}+ onSelect={handleSelectProject}+ onBrowse={handleLoadLegacyProject}+ />+ <NewProjectModal+ open={newProjectOpen}+ onClose={() => setNewProjectOpen(false)}+ onCreate={handleCreateProject}+ />+ <CropModal+ open={cropOpen}+ onClose={() => setCropOpen(false)}+ initialRegion={editorSettings.cropRegion}+ onApply={(region: CropRegion) => void setEditorSettings({ cropRegion: region })}+ />+ <UnsavedChangesModal+ open={unsavedPrompt !== null}+ onClose={() => {+ unsavedPrompt?.resolve("cancel");+ setUnsavedPrompt(null);+ }}+ action={unsavedPrompt?.action ?? "new"}+ onChoose={handleConfirmUnsaved}+ />+ <ExportDialog open={exportOpen} onClose={() => setExportOpen(false)} document={document} />+ <AutoCaptionsModal+ open={captionsOpen}+ onClose={() => setCaptionsOpen(false)}+ minWords={captionsMinW}+ maxWords={captionsMaxW}+ onMinWords={setCaptionsMinW}+ onMaxWords={setCaptionsMaxW}+ onGenerate={handleGenerateCaptions}+ />+ <InsertSourceModal+ open={insertAssetId !== null}+ onClose={() => setInsertAssetId(null)}+ assetLabel={document?.assets.find((a) => a.id === insertAssetId)?.label ?? ""}+ canAddBefore+ canAddAfter+ canSplit={document !== null}+ onAddBefore={() => void handleInsertBefore()}+ onAddAfter={() => void handleInsertAfter()}+ onSplit={() => void handleInsertSplit()}+ />+ </div>+ );+}++function RightRailCompact({+ onChange,+ onCrop,+}: {+ onChange: (id: RightPaneId) => void;+ onCrop: () => void;+}) {+ const buttons: Array<{ id: RightPaneId; label: string; icon: React.ElementType }> = [+ { id: "background", label: "Background", icon: Sparkles },+ { id: "effects", label: "Video effects", icon: Film },+ ];+ return (+ <>+ {buttons.map(({ id, label, icon: Icon }) => (+ <button+ type="button"+ key={id}+ title={label}+ aria-label={label}+ onClick={() => onChange(id)}+ >+ <Icon size={18} />+ </button>+ ))}+ <button type="button" title="Crop" aria-label="Crop" onClick={onCrop}>+ <EyeOff size={18} />+ </button>+ </>+ );+}++function startResize(e: React.PointerEvent<HTMLDivElement>, axis: "left" | "right" | "bottom") {+ e.preventDefault();+ const target = e.currentTarget;+ target.setPointerCapture(e.pointerId);+ target.classList.add(styles.isDragging);+ document.body.style.cursor = axis === "bottom" ? "row-resize" : "col-resize";++ const root = document.documentElement;+ const varName =+ axis === "left" ? "--panel-w-left" : axis === "right" ? "--panel-w-right" : "--bottom-h";+ const min = axis === "bottom" ? 140 : 200;+ const cap = axis === "bottom" ? 0.65 : 0.55;+ const max = axis === "bottom" ? window.innerHeight * cap : window.innerWidth * cap;+ const startVal = parseFloat(getComputedStyle(root).getPropertyValue(varName)) || 0;+ const startX = e.clientX;+ const startY = e.clientY;++ const onMove = (ev: PointerEvent) => {+ let next: number;+ if (axis === "left") next = startVal + (ev.clientX - startX);+ else if (axis === "right") next = startVal - (ev.clientX - startX);+ else next = startVal + (startY - ev.clientY);+ next = Math.max(min, Math.min(next, max));+ root.style.setProperty(varName, `${next}px`);+ };+ const onUp = () => {+ target.classList.remove(styles.isDragging);+ document.body.style.cursor = "";+ target.removeEventListener("pointermove", onMove);+ target.removeEventListener("pointerup", onUp);+ target.removeEventListener("pointercancel", onUp);+ };+ target.addEventListener("pointermove", onMove);+ target.addEventListener("pointerup", onUp);+ target.addEventListener("pointercancel", onUp);+}diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsxnew file mode 100644index 000000000..c79329ace--- /dev/null+++ b/src/components/ai-edition/Preview.tsx@@ -0,0 +1,260 @@+import { Maximize2, Pause, Play, Repeat, SkipBack, SkipForward } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { EditorEmptyState } from "./EditorEmptyState";+import styles from "./NewEditorShell.module.css";+import { PreviewCanvas } from "./PreviewCanvas";++interface PreviewProps {+ hasProject: boolean;+ hasAsset: boolean;+ videoSources: import("./VirtualPreview").VideoSource[];+ clips: AxcutClip[];+ seekTarget: { timeSec: number; requestId: number } | null;+ onTimeChange: (sec: number) => void;+ onSeek: (sec: number) => void;+ onLoadedMetadata: (sec: number) => void;+ onVideoElement: (el: HTMLVideoElement | null) => void;+ currentTimeSec: number;+}++function formatTC(sec: number): string {+ if (!sec || !Number.isFinite(sec) || sec < 0) sec = 0;+ const m = Math.floor(sec / 60);+ const s = (sec % 60).toFixed(1);+ return `${m}:${s.padStart(4, "0")}`;+}++export function Preview({+ hasProject,+ hasAsset,+ videoSources,+ clips,+ seekTarget,+ onTimeChange,+ onSeek,+ onLoadedMetadata,+ onVideoElement,+ currentTimeSec,+}: PreviewProps) {+ const [playing, setPlaying] = useState(false);+ const [loop, setLoop] = useState(false);+ const [videoEl, setVideoEl] = useState<HTMLVideoElement | null>(null);+ // ponytail: when the <video> fails to load (e.g. truncated recording+ // from a bad MediaRecorder capture), swap to the empty state so the+ // user can import a different file instead of staring at a broken+ // preview. Resets when the active source changes (asset path).+ const [videoError, setVideoError] = useState(false);+ const activeSourceKey = videoSources[0]?.src ?? null;+ const previousSourceKeyRef = useRef<string | null>(null);+ useEffect(() => {+ if (previousSourceKeyRef.current !== activeSourceKey) {+ previousSourceKeyRef.current = activeSourceKey;+ setVideoError(false);+ }+ }, [activeSourceKey]);++ const handleVideoElement = useCallback(+ (el: HTMLVideoElement | null) => {+ setVideoEl(el);+ onVideoElement(el);+ },+ [onVideoElement],+ );++ const togglePlay = useCallback(() => {+ if (!videoEl) return;+ if (videoEl.paused) {+ void videoEl.play();+ } else {+ videoEl.pause();+ }+ }, [videoEl]);++ // ponytail: mirror the real video element's play state instead of+ // maintaining an optimistic local flag that drifts after play() rejects+ // or when VirtualPreview pauses/ends.+ useEffect(() => {+ const el = videoEl;+ if (!el) return;+ const onPlay = () => setPlaying(true);+ const onPause = () => setPlaying(false);+ const onEnded = () => setPlaying(false);+ el.addEventListener("play", onPlay);+ el.addEventListener("pause", onPause);+ el.addEventListener("ended", onEnded);+ setPlaying(!el.paused);+ return () => {+ el.removeEventListener("play", onPlay);+ el.removeEventListener("pause", onPause);+ el.removeEventListener("ended", onEnded);+ };+ }, [videoEl]);++ const handlePrevClip = useCallback(() => {+ if (clips.length === 0) return;+ // ponytail: navigate in virtual timeline space, not source-media time.+ let prevStart = 0;+ for (let i = clips.length - 1; i >= 0; i--) {+ const c = clips[i];+ if (c.timelineEndSec <= currentTimeSec - 0.1) {+ prevStart = c.timelineStartSec;+ break;+ }+ }+ onSeek(prevStart);+ onTimeChange(prevStart);+ }, [clips, currentTimeSec, onSeek, onTimeChange]);++ const handleNextClip = useCallback(() => {+ if (clips.length === 0) return;+ const next = clips.find((c) => c.timelineStartSec > currentTimeSec + 0.1);+ if (!next) return;+ onSeek(next.timelineStartSec);+ onTimeChange(next.timelineStartSec);+ }, [clips, currentTimeSec, onSeek, onTimeChange]);++ const handleLoop = useCallback(() => {+ setLoop((v) => {+ const next = !v;+ if (videoEl) videoEl.loop = next;+ return next;+ });+ }, [videoEl]);++ const expand = useCallback(() => {+ const el = videoEl?.parentElement;+ if (!el) return;+ if (document.fullscreenElement) {+ void document.exitFullscreen();+ } else {+ void el.requestFullscreen?.();+ }+ }, [videoEl]);++ const { settings: editorSettings } = useEditorSettings();+ const aspectRatioLabel = editorSettings.aspectRatio;++ return (+ <section className={styles.previewWrap} aria-label="Video preview">+ <div className={styles.previewCanvas}>+ {hasProject && hasAsset && !videoError ? (+ <PreviewCanvas+ videoSources={videoSources}+ clips={clips}+ seekTarget={seekTarget}+ onTimeChange={onTimeChange}+ onSeek={onSeek}+ onLoadedMetadata={onLoadedMetadata}+ onVideoElement={handleVideoElement}+ currentTimeSec={currentTimeSec}+ onVideoError={() => setVideoError(true)}+ />+ ) : (+ <EditorEmptyState hasProject={hasProject} />+ )}+ {hasProject && hasAsset ? (+ <span className={styles.previewTimecode}>{formatTC(currentTimeSec)}</span>+ ) : null}+ {hasProject && hasAsset ? (+ <span className={styles.previewBadge}>+ {editorSettings.cursorShow ? "Cursor on" : "Cursor off"} · {aspectRatioLabel} · 60 fps+ </span>+ ) : null}+ </div>+ <div className={styles.transport} role="toolbar" aria-label="Playback controls">+ <button+ type="button"+ className={`${styles.tbtn} ${styles.play}`}+ title="Play / Pause (Space)"+ aria-label="Play / Pause"+ data-playing={playing}+ onClick={togglePlay}+ >+ {playing ? (+ <Pause size={14} fill="currentColor" />+ ) : (+ <Play size={14} fill="currentColor" />+ )}+ </button>+ <button+ type="button"+ className={styles.tbtn}+ title="Previous clip"+ aria-label="Previous clip"+ onClick={handlePrevClip}+ >+ <SkipBack size={14} />+ </button>+ <button+ type="button"+ className={styles.tbtn}+ title="Next clip"+ aria-label="Next clip"+ onClick={handleNextClip}+ >+ <SkipForward size={14} />+ </button>+ <button+ type="button"+ className={styles.tbtn}+ title="Loop"+ aria-label="Loop"+ aria-pressed={loop}+ onClick={handleLoop}+ >+ <Repeat size={14} />+ </button>+ <button+ type="button"+ className={styles.tbtn}+ title="Fullscreen"+ aria-label="Fullscreen"+ onClick={expand}+ >+ <Maximize2 size={14} />+ </button>+ {(() => {+ const virtualDurationSec = clips.reduce(+ (acc, c) => acc + (c.timelineEndSec - c.timelineStartSec),+ 0,+ );+ const progress = virtualDurationSec ? (currentTimeSec / virtualDurationSec) * 100 : 0;+ return (+ <>+ <span className={styles.time}>+ <span>{formatTC(currentTimeSec)}</span>+ <span className={styles.sep}>/</span>+ <span className={styles.total}>{formatTC(virtualDurationSec)}</span>+ </span>+ <div className={styles.scrubBar}>+ <div className={styles.scrubTrack}>+ <div className={styles.scrubProgress} style={{ width: `${progress}%` }} />+ </div>+ <input+ type="range"+ min={0}+ max={virtualDurationSec || 1}+ step={0.01}+ value={Math.min(currentTimeSec, virtualDurationSec || 1)}+ onChange={(e) => {+ onSeek(Number(e.target.value));+ }}+ className={styles.scrubInput}+ aria-label="Seek video"+ />+ <div+ className={styles.scrubThumb}+ style={{+ left: `${progress}%`,+ }}+ />+ </div>+ </>+ );+ })()}+ </div>+ </section>+ );+}diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxnew file mode 100644index 000000000..7bd8a7afc--- /dev/null+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -0,0 +1,345 @@+// CSS-driven canvas shell that wraps the active source video with the+// editor's background, frame, and overlay settings.+//+// ponytail: mouse-driven overlays (cursor, zoom, annotations) and motion blur+// still render through the legacy canvas preview pipeline for export. The+// shared source of truth is `useEditorSettings`, so toggling a slider here+// updates both the live preview and the eventual render.+//+// Architecture (matches the legacy `compositeLayout.computeCompositeLayout`):+// .previewFrame → canvas (wallpaper bg + blurred copy behind the+// video when showBlur is on; never receives padding+// from the slider directly).+// .screenStage → active source video; positioned/sized by the+// composite-layout math (PiP/dual/stack/no-cam).+// Carries the drop-shadow that gives the active+// recording its lifted look.+// .webcamSlot → live WebcamOverlay container; positioned/sized+// by the same math.+// .bgBlur → blurred wallpaper peeking around the video.+//+// The composite layout is computed from `.previewFrame`'s actual rendered+// size (via ResizeObserver), so the camera + screen both resize correctly+// as the user resizes the workbench.++import type { PointerEvent as ReactPointerEvent } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import type { WebcamLayoutPreset, WebcamMaskShape } from "@/components/video-editor/types";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import {+ computeCompositeLayout,+ getWebcamLayoutCssBoxShadow,+ type WebcamCompositeLayout,+} from "@/lib/compositeLayout";+import { getCssClipPath } from "@/lib/webcamMaskShapes";+import styles from "./NewEditorShell.module.css";+import { type VideoSource, VirtualPreview } from "./VirtualPreview";+import { WebcamOverlay } from "./WebcamOverlay";++interface PreviewCanvasProps {+ videoSources: VideoSource[];+ clips: AxcutClip[];+ seekTarget: { timeSec: number; requestId: number } | null;+ onTimeChange: (sec: number) => void;+ onSeek: (sec: number) => void;+ onLoadedMetadata: (sec: number) => void;+ onVideoElement: (el: HTMLVideoElement | null) => void;+ currentTimeSec: number;+ onVideoError?: () => void;+}++const SCREEN_SOURCE_SIZE = { width: 1920, height: 1080 };+// ponytail: live preview defaults until the camera <video> reports its real+// dimensions via loadedmetadata. 4:3 is the legacy default — typical webcams+// capture at 1.33, and using a 16:9 default collapses vertical-stack to a+// degenerate full-bleed camera with 0px screen height.+const WEBCAM_SOURCE_SIZE = { width: 960, height: 720 };++export function PreviewCanvas(props: PreviewCanvasProps) {+ const { settings, setLive, commit } = useEditorSettings();+ const frameRef = useRef<HTMLDivElement | null>(null);+ const webcamSlotRef = useRef<HTMLDivElement | null>(null);+ const [canvasSize, setCanvasSize] = useState({ width: 1280, height: 720 });++ useEffect(() => {+ const el = frameRef.current;+ if (!el) return;+ const update = () =>+ setCanvasSize({+ width: el.clientWidth || 1280,+ height: el.clientHeight || 720,+ });+ update();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const layout = useMemo(() => {+ const preset = settings.webcamLayoutPreset as WebcamLayoutPreset;+ const mask = settings.webcamMaskShape as WebcamMaskShape;+ // ponytail: padding shrinks the available content area for ALL layouts+ // (PiP/dual/stack) so the screen doesn't fill the canvas edge-to-edge.+ // In vertical-stack this caps the camera strip height: at padding=0 the+ // camera reaches 40% of canvas; at padding=50 it falls to ~32%;+ // at padding=100 the screen takes even more.+ const paddingFit = clamp(1 - (clamp(settings.padding, 0, 100) / 100) * 0.4, 0.4, 1);+ const maxContentSize = {+ width: Math.round(canvasSize.width * paddingFit),+ height: Math.round(canvasSize.height * paddingFit),+ };+ return computeCompositeLayout({+ canvasSize,+ maxContentSize,+ screenSize: SCREEN_SOURCE_SIZE,+ webcamSize: settings.webcamLayoutPreset === "no-webcam" ? null : WEBCAM_SOURCE_SIZE,+ layoutPreset: preset,+ webcamSizePreset: settings.webcamSizePreset,+ // ponytail: PiP webcam is grabbable. Pass through the user's+ // position so the layout math places it at the dragged spot, not+ // the legacy default. Dual-frame / vertical-stack / no-webcam ignore+ // it (their preset definitions hardcode their own placement).+ webcamPosition: preset === "picture-in-picture" ? settings.webcamPosition : null,+ webcamMaskShape: mask,+ });+ }, [+ canvasSize,+ settings.webcamLayoutPreset,+ settings.webcamMaskShape,+ settings.webcamSizePreset,+ settings.webcamPosition,+ settings.padding,+ ]);++ const frameStyle = useMemo(() => buildFrameStyle(settings), [settings]);+ const blurStyle = useMemo(() => buildBlurStyle(settings), [settings]);+ const screenStyle = useMemo(+ () => buildScreenStyle(layout, settings, canvasSize),+ [layout, settings, canvasSize],+ );+ const webcamStyle = useMemo(+ () => buildWebcamStyle(layout, settings, canvasSize),+ [layout, settings, canvasSize],+ );+ const [isPlaying, setIsPlaying] = useState(false);+ const handleVideoElement = useMemo(() => props.onVideoElement, [props.onVideoElement]);+ const relayIsPlaying = (el: HTMLVideoElement | null) => {+ handleVideoElement(el);+ setIsPlaying(!el?.paused);+ };+ const relayProps = { ...props, onVideoElement: relayIsPlaying };++ const handleWebcamPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (settings.webcamLayoutPreset !== "picture-in-picture") return;+ if (isPlaying) return;+ const slot = webcamSlotRef.current;+ if (!slot) return;+ const slotRect = slot.getBoundingClientRect();+ const frameRect = frameRef.current?.getBoundingClientRect();+ if (!frameRect) return;+ event.preventDefault();+ event.stopPropagation();+ const offsetX = event.clientX - (slotRect.left + slotRect.width / 2);+ const offsetY = event.clientY - (slotRect.top + slotRect.height / 2);+ slot.setPointerCapture(event.pointerId);++ const handleMove = (e: PointerEvent) => {+ const frameNow = frameRef.current?.getBoundingClientRect();+ if (!frameNow) return;+ const cx = clamp01((e.clientX - offsetX - frameNow.left) / frameNow.width);+ const cy = clamp01((e.clientY - offsetY - frameNow.top) / frameNow.height);+ setLive({ webcamPosition: { cx, cy } });+ };+ const handleUp = () => {+ slot.removeEventListener("pointermove", handleMove);+ slot.removeEventListener("pointerup", handleUp);+ slot.removeEventListener("pointercancel", handleUp);+ try {+ slot.releasePointerCapture(event.pointerId);+ } catch {+ // pointer already released+ }+ void commit();+ };+ slot.addEventListener("pointermove", handleMove);+ slot.addEventListener("pointerup", handleUp);+ slot.addEventListener("pointercancel", handleUp);+ };++ const isPipGrab = settings.webcamLayoutPreset === "picture-in-picture";++ return (+ <div ref={frameRef} className={styles.previewFrame} style={frameStyle}>+ <div className={styles.bgBlur} style={blurStyle} aria-hidden />+ {layout?.screenRect ? (+ <div className={styles.screenStage} style={screenStyle}>+ <VirtualPreview {...relayProps} videoStyle={videoBorderRadiusStyle(settings)} />+ </div>+ ) : null}+ {layout?.webcamRect ? (+ <div+ ref={webcamSlotRef}+ className={styles.webcamSlot}+ style={{+ ...webcamStyle,+ cursor: isPipGrab && !isPlaying ? "grab" : "default",+ touchAction: "none",+ }}+ onPointerDown={isPipGrab ? handleWebcamPointerDown : undefined}+ aria-label="Webcam preview (drag to reposition)"+ >+ <WebcamOverlay+ clips={props.clips}+ currentTimeSec={props.currentTimeSec}+ onTimeChange={props.onTimeChange}+ isPlaying={isPlaying}+ borderRadius={layout.webcamRect.borderRadius}+ webcamMaskShape={settings.webcamMaskShape}+ layoutPreset={settings.webcamLayoutPreset}+ />+ </div>+ ) : null}+ </div>+ );+}++// Canvas: wallpaper only — no padding, no shadow.+function buildFrameStyle(+ settings: ReturnType<typeof useEditorSettings>["settings"],+): React.CSSProperties {+ const wallpaper = settings.wallpaper;+ const isImageWallpaper = wallpaper.startsWith("/wallpapers/") || wallpaper.startsWith("data:");+ const isColor = wallpaper.startsWith("#");+ const isGradient =+ wallpaper.startsWith("linear-") ||+ wallpaper.startsWith("radial-") ||+ wallpaper.startsWith("conic-");++ if (isImageWallpaper) {+ return {+ backgroundImage: `url(${wallpaper})`,+ backgroundSize: "cover",+ backgroundPosition: "center",+ backgroundRepeat: "no-repeat",+ };+ }+ if (isColor) return { backgroundColor: wallpaper };+ return {+ backgroundImage: isGradient ? wallpaper : undefined,+ backgroundSize: "cover",+ };+}++// Screen stage: rectangle from the composite layout, converted to percentages+// of the canvas. NO borderRadius on the container — the rounded corners are+// applied on the <video> itself so they actually clip the video content+// rather than drawing a border around it. Box-shadow follows the user's+// `shadowIntensity` setting only — at intensity 0 the stage is flat so it+// bleeds into the canvas cleanly.+function buildScreenStyle(+ layout: WebcamCompositeLayout | null,+ settings: ReturnType<typeof useEditorSettings>["settings"],+ canvasSize: { width: number; height: number },+): React.CSSProperties {+ if (!layout?.screenRect) return { display: "none" };+ const r = layout.screenRect;+ const shadow = settings.shadowIntensity+ ? `0 ${4 + settings.shadowIntensity * 20}px ${16 + settings.shadowIntensity * 36}px rgba(0,0,0,${0.18 + settings.shadowIntensity * 0.45})`+ : undefined;+ void layout.screenBorderRadius;+ void settings.borderRadius;+ return {+ position: "absolute",+ left: `${(r.x / canvasSize.width) * 100}%`,+ top: `${(r.y / canvasSize.height) * 100}%`,+ width: `${(r.width / canvasSize.width) * 100}%`,+ height: `${(r.height / canvasSize.height) * 100}%`,+ overflow: "hidden",+ display: "flex",+ boxShadow: shadow,+ };+}++function videoBorderRadiusStyle(+ settings: ReturnType<typeof useEditorSettings>["settings"],+): React.CSSProperties {+ return { borderRadius: `${settings.borderRadius}px` };+}++// Webcam slot: full composite-layout rect with mask shape + shadow. NO+// borderRadius here — the rounded corners live on the <video> inside so they+// actually clip the camera content rather than drawing a frame around it.+function buildWebcamStyle(+ layout: WebcamCompositeLayout | null,+ settings: ReturnType<typeof useEditorSettings>["settings"],+ canvasSize: { width: number; height: number },+): React.CSSProperties {+ if (!layout?.webcamRect) return { display: "none" };+ const r = layout.webcamRect;+ const mask = settings.webcamMaskShape as WebcamMaskShape;+ const clipPath = getCssClipPath(mask);+ const base: React.CSSProperties = {+ position: "absolute",+ left: `${(r.x / canvasSize.width) * 100}%`,+ top: `${(r.y / canvasSize.height) * 100}%`,+ width: `${(r.width / canvasSize.width) * 100}%`,+ height: `${(r.height / canvasSize.height) * 100}%`,+ overflow: "hidden",+ display: "flex",+ background: "transparent",+ boxShadow: getWebcamLayoutCssBoxShadow(settings.webcamLayoutPreset as WebcamLayoutPreset),+ };+ void r.borderRadius;+ void mask;+ return clipPath ? { ...base, clipPath } : base;+}++// Blurred wallpaper copy. Hidden when showBlur is off.+function buildBlurStyle(+ settings: ReturnType<typeof useEditorSettings>["settings"],+): React.CSSProperties {+ if (!settings.showBlur) return { display: "none" };+ const wallpaper = settings.wallpaper;+ const isImageWallpaper = wallpaper.startsWith("/wallpapers/") || wallpaper.startsWith("data:");+ const isColor = wallpaper.startsWith("#");+ const isGradient =+ wallpaper.startsWith("linear-") ||+ wallpaper.startsWith("radial-") ||+ wallpaper.startsWith("conic-");++ if (isImageWallpaper) {+ return {+ backgroundImage: `url(${wallpaper})`,+ backgroundSize: "cover",+ backgroundPosition: "center",+ filter: "blur(28px)",+ opacity: 1,+ };+ }+ if (isColor) {+ return {+ backgroundColor: wallpaper,+ filter: "blur(28px)",+ opacity: 1,+ };+ }+ if (isGradient) {+ return {+ background: wallpaper,+ backgroundSize: "cover",+ filter: "blur(28px)",+ opacity: 1,+ };+ }+ return { display: "none" };+}++function clamp(v: number, min: number, max: number): number {+ return Math.min(Math.max(v, min), max);+}++function clamp01(v: number, min = 0, max = 1): number {+ return clamp(v, min, max);+}diff --git a/src/components/ai-edition/ProjectPanel.tsx b/src/components/ai-edition/ProjectPanel.tsxnew file mode 100644index 000000000..d2f8243f9--- /dev/null+++ b/src/components/ai-edition/ProjectPanel.tsx@@ -0,0 +1,225 @@+import { Film, FolderOpen, Plus, Trash2 } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import { toast } from "sonner";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { nativeBridgeClient } from "@/native/client";+import type { AiEditionProjectSummary } from "@/native/contracts";++function basename(path: string): string {+ return path.split(/[\\/]/).pop() ?? path;+}++function formatRelative(iso: string): string {+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return "";+ const delta = Date.now() - then;+ if (delta < 60_000) return "just now";+ if (delta < 3_600_000) return `${Math.floor(delta / 60_000)}m ago`;+ if (delta < 86_400_000) return `${Math.floor(delta / 3_600_000)}h ago`;+ return new Date(iso).toLocaleDateString();+}++const TOOLBAR_BTN =+ "flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-white/50 hover:text-white/90 hover:bg-white/[0.08] transition-all duration-150 text-[11px] font-medium disabled:opacity-40 disabled:pointer-events-none";++export function ProjectPanel() {+ const projectId = useProjectStore((s) => s.projectId);+ const document = useProjectStore((s) => s.document);+ const createProject = useProjectStore((s) => s.createProject);+ const loadProject = useProjectStore((s) => s.loadProject);+ const addAsset = useProjectStore((s) => s.addAsset);+ const removeAsset = useProjectStore((s) => s.removeAsset);++ const [summaries, setSummaries] = useState<AiEditionProjectSummary[]>([]);+ const [newTitle, setNewTitle] = useState("");+ const [busy, setBusy] = useState(false);++ const refreshList = useCallback(async () => {+ try {+ const next = await nativeBridgeClient.aiEdition.listProjects();+ setSummaries(next);+ } catch {+ // ponytail: silent — the panel still works for the active project+ }+ }, []);++ useEffect(() => {+ void refreshList();+ }, [refreshList]);++ const handleCreate = useCallback(async () => {+ setBusy(true);+ try {+ await createProject(newTitle || "Untitled Project");+ setNewTitle("");+ await refreshList();+ } catch (err) {+ toast.error("Could not create project", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ }, [createProject, newTitle, refreshList]);++ const handleSelect = useCallback(+ async (id: string) => {+ setBusy(true);+ try {+ await loadProject(id);+ } finally {+ setBusy(false);+ }+ },+ [loadProject],+ );++ const handleAddAsset = useCallback(async () => {+ if (!projectId) {+ toast.error("Open a project first");+ return;+ }+ const picker = await window.electronAPI?.openVideoFilePicker();+ if (!picker?.success || !picker.path) return;+ setBusy(true);+ try {+ await addAsset(picker.path);+ toast.success(`Added ${basename(picker.path)}`);+ } catch (err) {+ toast.error("Could not add asset", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ }, [addAsset, projectId]);++ const handleRemoveAsset = useCallback(+ async (assetId: string, label: string) => {+ if (!confirm(`Remove asset "${label}"?`)) return;+ try {+ await removeAsset(assetId);+ } catch (err) {+ toast.error("Could not remove asset", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [removeAsset],+ );++ return (+ <aside className="w-full h-full flex flex-col overflow-hidden">+ <header className="px-4 py-3 border-b border-white/[0.06]">+ <h2 className="text-[10px] font-semibold tracking-[0.1em] uppercase text-white/40">+ Projects+ </h2>+ </header>++ <div className="px-3 py-2 border-b border-white/[0.06]">+ <div className="flex items-center gap-1.5">+ <input+ placeholder="New project title"+ value={newTitle}+ onChange={(e) => setNewTitle(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void handleCreate();+ }}+ className="flex-1 px-2.5 py-1.5 rounded-md bg-white/[0.04] border border-white/[0.06] text-[12px] text-white/85 placeholder:text-white/30 outline-none focus:border-[#34B27B]/50 focus:bg-white/[0.06]"+ />+ <button+ type="button"+ className="flex items-center justify-center w-7 h-7 rounded-md bg-[#34B27B] hover:bg-[#2d9e6c] active:bg-[#27885c] text-white transition-colors disabled:opacity-40"+ onClick={handleCreate}+ disabled={busy}+ title="Create project"+ >+ <Plus size={14} />+ </button>+ </div>+ </div>++ <div className="flex-1 min-h-0 overflow-y-auto px-2 py-2 custom-scrollbar">+ {summaries.length === 0 && (+ <p className="text-[11px] text-white/35 px-2 py-3 text-center leading-relaxed">+ No projects yet — create one above.+ </p>+ )}+ {summaries.map((summary) => {+ const isActive = summary.id === projectId;+ return (+ <button+ type="button"+ key={summary.id}+ className={`w-full text-left px-2.5 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-white/[0.08] ring-1 ring-[#34B27B]/30" : "hover:bg-white/[0.04]"}`}+ onClick={() => void handleSelect(summary.id)}+ >+ <div className="flex items-center gap-2 mb-1">+ <FolderOpen size={12} className={isActive ? "text-[#34B27B]" : "text-white/40"} />+ <span className="text-[12px] font-medium text-white/90 truncate">+ {summary.title}+ </span>+ </div>+ <div className="flex items-center justify-between pl-5 text-[10px] text-white/40">+ <span>+ {summary.assetCount} asset{summary.assetCount === 1 ? "" : "s"}+ </span>+ <span>{formatRelative(summary.updatedAt)}</span>+ </div>+ </button>+ );+ })}+ </div>++ <div className="border-t border-white/[0.06]">+ <header className="px-4 py-3 flex items-center justify-between">+ <h2 className="text-[10px] font-semibold tracking-[0.1em] uppercase text-white/40">+ Assets+ </h2>+ <button+ type="button"+ className={TOOLBAR_BTN}+ onClick={handleAddAsset}+ disabled={!projectId || busy}+ title="Add video asset"+ >+ <Film size={12} />+ Add+ </button>+ </header>+ <div className="px-2 pb-3 max-h-48 overflow-y-auto custom-scrollbar">+ {!document && (+ <p className="text-[11px] text-white/35 px-2 py-2 text-center leading-relaxed">+ Open a project to see its assets.+ </p>+ )}+ {document && document.assets.length === 0 && (+ <p className="text-[11px] text-white/35 px-2 py-2 text-center leading-relaxed">+ No assets yet.+ </p>+ )}+ {document?.assets.map((asset) => (+ <div+ key={asset.id}+ className="flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-white/[0.04] group"+ >+ <Film size={12} className="text-white/40 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="text-[11px] font-medium text-white/85 truncate">{asset.label}</div>+ <div className="text-[10px] text-white/35 truncate">{asset.originalPath}</div>+ </div>+ <button+ type="button"+ className="flex items-center justify-center w-6 h-6 rounded text-white/30 opacity-0 group-hover:opacity-100 hover:text-red-400 hover:bg-white/[0.06] transition-all"+ onClick={() => void handleRemoveAsset(asset.id, asset.label)}+ title={`Remove ${asset.label}`}+ >+ <Trash2 size={12} />+ </button>+ </div>+ ))}+ </div>+ </div>+ </aside>+ );+}diff --git a/src/components/ai-edition/ProviderSettings.tsx b/src/components/ai-edition/ProviderSettings.tsxnew file mode 100644index 000000000..4cbaa42a0--- /dev/null+++ b/src/components/ai-edition/ProviderSettings.tsx@@ -0,0 +1,513 @@+// Provider Settings popover/modal for the new editor's chat strip.+//+// UI: list of provider cards (the 8 from provider-registry.ts). On select, a+// detail form opens for the picked provider: API key input, model select,+// baseUrl (for openai-compatible), reasoning effort (if supported). Save+// commits the config + key to the LLMConfigStore via the native bridge.++import { Check, KeyRound, Loader2, X } from "lucide-react";+import { useEffect, useState } from "react";+import { toast } from "sonner";+import { nativeBridgeClient } from "@/native/client";+import type { AiEditionLlmConfig, AiEditionLlmSnapshot } from "@/native/contracts";+import {+ PROVIDER_DEFINITIONS,+ type ProviderDefinition,+ REASONING_EFFORT_OPTIONS,+} from "../../../electron/ai-edition/provider-registry";+import { ModalShell } from "./Modals";+import styles from "./NewEditorShell.module.css";++type Mode = "list" | "form";++interface ProviderSettingsProps {+ open: boolean;+ onClose: () => void;+}++export function ProviderSettings({ open, onClose }: ProviderSettingsProps) {+ const [snapshot, setSnapshot] = useState<AiEditionLlmSnapshot | null>(null);+ const [mode, setMode] = useState<Mode>("list");+ const [active, setActive] = useState<ProviderDefinition | null>(null);+ const [apiKey, setApiKey] = useState("");+ const [config, setConfig] = useState<AiEditionLlmConfig | null>(null);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ if (!open) return;+ void (async () => {+ try {+ const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();+ setSnapshot(snap);+ if (snap.config) {+ setConfig(snap.config);+ }+ } catch (err) {+ toast.error("Could not load AI settings", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ })();+ }, [open]);++ const handlePick = (def: ProviderDefinition) => {+ setActive(def);+ setApiKey("");+ setConfig((prev) => {+ const base: AiEditionLlmConfig = prev ?? { provider: def.id, model: def.defaultModel };+ return {+ provider: def.id,+ model: base.provider === def.id ? base.model : def.defaultModel,+ baseUrl: base.provider === def.id ? base.baseUrl : def.baseUrl,+ reasoningEffort: base.provider === def.id ? base.reasoningEffort : undefined,+ };+ });+ setMode("form");+ };++ const handleSave = async () => {+ if (!active || !config) return;+ setBusy(true);+ try {+ if (apiKey && active.authKind === "api-key") {+ await nativeBridgeClient.aiEdition.llmSetApiKey(active.id, apiKey);+ }+ await nativeBridgeClient.aiEdition.llmSetConfig(config);+ toast.success(`${active.label} configured`);+ const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();+ setSnapshot(snap);+ setMode("list");+ setActive(null);+ setApiKey("");+ } catch (err) {+ toast.error("Save failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ };++ const handleDisconnect = async () => {+ if (!active) return;+ setBusy(true);+ try {+ await nativeBridgeClient.aiEdition.llmRemoveApiKey(active.id);+ toast.success(`${active.label} disconnected`);+ const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();+ setSnapshot(snap);+ } catch (err) {+ toast.error("Disconnect failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusy(false);+ }+ };++ const connected = new Set(snapshot?.connectedProviders ?? []);++ return (+ <ModalShell+ open={open}+ onClose={() => {+ if (busy) return;+ onClose();+ setMode("list");+ setActive(null);+ setApiKey("");+ }}+ title="AI settings"+ subtitle="Choose a provider. Credentials are stored in the OS keychain (safeStorage)."+ wide+ >+ {mode === "list" ? (+ <ProviderList+ connected={connected}+ activeProvider={snapshot?.config?.provider ?? null}+ onPick={handlePick}+ />+ ) : active ? (+ <ProviderForm+ def={active}+ isConnected={connected.has(active.id)}+ apiKey={apiKey}+ setApiKey={setApiKey}+ config={config}+ setConfig={setConfig}+ busy={busy}+ onBack={() => {+ if (busy) return;+ setMode("list");+ setActive(null);+ setApiKey("");+ }}+ onSave={handleSave}+ onDisconnect={handleDisconnect}+ />+ ) : null}+ </ModalShell>+ );+}++function ProviderList({+ connected,+ activeProvider,+ onPick,+}: {+ connected: Set<string>;+ activeProvider: string | null;+ onPick: (def: ProviderDefinition) => void;+}) {+ return (+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(2, 1fr)",+ gap: 8,+ }}+ >+ {PROVIDER_DEFINITIONS.map((def) => {+ const isConnected = connected.has(def.id);+ const isActive = def.id === activeProvider;+ return (+ <button+ key={def.id}+ type="button"+ onClick={() => onPick(def)}+ style={{+ display: "flex",+ flexDirection: "column",+ gap: 6,+ padding: 12,+ border: `1px solid ${isActive ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 10,+ background: isActive ? "var(--accent-wash)" : "var(--surface)",+ color: "var(--fg-2)",+ cursor: "pointer",+ textAlign: "left",+ font: "500 13px/1.2 var(--font-body)",+ }}+ >+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 8,+ }}+ >+ <span style={{ color: "var(--fg)", fontWeight: 600 }}>{def.label}</span>+ {isConnected ? (+ <span+ style={{+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ padding: "2px 8px",+ borderRadius: 999,+ background: "var(--success-soft)",+ color: "var(--success)",+ font: "500 10px/1 var(--font-mono)",+ letterSpacing: "0.04em",+ }}+ >+ <Check size={10} />+ CONNECTED+ </span>+ ) : (+ <span+ style={{+ padding: "2px 8px",+ borderRadius: 999,+ background: "var(--surface-2)",+ color: "var(--muted)",+ font: "500 10px/1 var(--font-mono)",+ letterSpacing: "0.04em",+ }}+ >+ {authLabel(def.authKind)}+ </span>+ )}+ </div>+ <span+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ letterSpacing: "0.02em",+ }}+ >+ {def.defaultModel || "—"}+ </span>+ </button>+ );+ })}+ </div>+ );+}++function authLabel(kind: ProviderDefinition["authKind"]): string {+ switch (kind) {+ case "api-key":+ return "API KEY";+ case "oauth-device":+ return "OAUTH";+ case "pat":+ return "TOKEN";+ }+}++function ProviderForm({+ def,+ isConnected,+ apiKey,+ setApiKey,+ config,+ setConfig,+ busy,+ onBack,+ onSave,+ onDisconnect,+}: {+ def: ProviderDefinition;+ isConnected: boolean;+ apiKey: string;+ setApiKey: (v: string) => void;+ config: AiEditionLlmConfig | null;+ setConfig: (c: AiEditionLlmConfig | null) => void;+ busy: boolean;+ onBack: () => void;+ onSave: () => void;+ onDisconnect: () => void;+}) {+ return (+ <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <button+ type="button"+ className={styles.iconBtn}+ title="Back"+ aria-label="Back"+ onClick={onBack}+ >+ <X size={16} />+ </button>+ <span style={{ font: "600 14px var(--font-body)", color: "var(--fg)" }}>{def.label}</span>+ <button+ type="button"+ className={styles.iconBtn}+ title="Close"+ aria-label="Close"+ onClick={onBack}+ >+ <X size={16} />+ </button>+ </div>++ <Field label="Model">+ <input+ type="text"+ value={config?.model ?? def.defaultModel}+ placeholder={def.defaultModel}+ onChange={(e) =>+ setConfig({+ ...(config ?? { provider: def.id, model: def.defaultModel }),+ model: e.target.value,+ })+ }+ />+ </Field>++ {def.authKind === "api-key" ? (+ <Field+ label="API key"+ hint={isConnected ? "Leave blank to keep the stored key." : undefined}+ >+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: 6,+ padding: "6px 8px 6px 10px",+ border: "1px solid var(--border)",+ borderRadius: 6,+ background: "var(--surface)",+ }}+ >+ <KeyRound size={14} style={{ color: "var(--meta)" }} />+ <input+ type="password"+ value={apiKey}+ placeholder={isConnected ? "••••••" : "sk-…"}+ onChange={(e) => setApiKey(e.target.value)}+ style={{+ flex: 1,+ border: 0,+ outline: "none",+ background: "transparent",+ font: "500 12px var(--font-mono)",+ color: "var(--fg-2)",+ }}+ />+ </div>+ </Field>+ ) : (+ <Field label="Authentication" hint={authHint(def)}>+ <div+ style={{+ padding: "8px 10px",+ border: "1px solid var(--border)",+ borderRadius: 6,+ background: "var(--surface-2)",+ color: "var(--muted)",+ font: "500 12px var(--font-body)",+ }}+ >+ {authKindLabel(def.authKind)} — connect flow not implemented yet.+ </div>+ </Field>+ )}++ {(def.id === "openai-compatible" || def.baseUrl) && (+ <Field label="Base URL" hint="Leave blank to use the provider's default.">+ <input+ type="text"+ value={config?.baseUrl ?? def.baseUrl ?? ""}+ placeholder={def.baseUrl ?? "https://…"}+ onChange={(e) =>+ setConfig({+ ...(config ?? { provider: def.id, model: def.defaultModel }),+ baseUrl: e.target.value || undefined,+ })+ }+ />+ </Field>+ )}++ {def.supportsReasoningEffort ? (+ <Field label="Reasoning effort">+ <select+ value={config?.reasoningEffort ?? "none"}+ onChange={(e) =>+ setConfig({+ ...(config ?? { provider: def.id, model: def.defaultModel }),+ reasoningEffort: e.target.value,+ })+ }+ >+ {REASONING_EFFORT_OPTIONS.map((r: string) => (+ <option key={r} value={r}>+ {r}+ </option>+ ))}+ </select>+ </Field>+ ) : null}++ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ gap: 8,+ paddingTop: 12,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ {isConnected ? (+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onDisconnect}+ disabled={busy}+ >+ Disconnect+ </button>+ ) : (+ <span />+ )}+ <div style={{ display: "flex", gap: 8 }}>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onBack}+ disabled={busy}+ >+ Cancel+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={onSave}+ disabled={busy || !config}+ >+ {busy ? (+ <>+ <Loader2 size={14} className="animate-spin" />+ Saving…+ </>+ ) : (+ "Save & use"+ )}+ </button>+ </div>+ </div>+ </div>+ );+}++function Field({+ label,+ hint,+ children,+}: {+ label: string;+ hint?: string;+ children: React.ReactNode;+}) {+ return (+ <div className={styles.field}>+ <label>+ {label}+ {hint ? (+ <span+ style={{+ display: "block",+ font: "500 10px/1.2 var(--font-mono)",+ color: "var(--muted)",+ letterSpacing: "0.04em",+ textTransform: "uppercase",+ marginTop: 2,+ }}+ >+ {hint}+ </span>+ ) : null}+ </label>+ {children}+ </div>+ );+}++function authKindLabel(kind: ProviderDefinition["authKind"]): string {+ switch (kind) {+ case "oauth-device":+ return "OAuth device flow";+ case "pat":+ return "Personal access token";+ case "api-key":+ return "API key";+ }+}++function authHint(def: ProviderDefinition): string {+ if (def.envKeys.length > 0) {+ return `Set ${def.envKeys.join(" or ")} in your environment.`;+ }+ return "Connect flow coming soon.";+}diff --git a/src/components/ai-edition/RightPanelStack.tsx b/src/components/ai-edition/RightPanelStack.tsxnew file mode 100644index 000000000..ad37787ab--- /dev/null+++ b/src/components/ai-edition/RightPanelStack.tsx@@ -0,0 +1,448 @@+import {+ Brackets,+ Crop,+ LayoutPanelTop,+ MousePointerClick,+ Palette,+ Sliders,+ Sparkles,+ Trash2,+} from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import type {+ AxcutAnnotationRegion,+ AxcutClip,+ AxcutDocument,+ AxcutTranscript,+} from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import styles from "./NewEditorShell.module.css";+import {+ BackgroundPane,+ CursorPane,+ LayoutPane,+ type RightPaneId,+ TimelinePaneBody,+ TranscriptPane,+ VideoEffectsPane,+} from "./RightPanes";++type RegionKind = "zoom" | "skip" | "annotation" | "speed";++interface RegionHandle {+ kind: RegionKind;+ id: string;+}++interface RightPanelStackProps {+ active: RightPaneId;+ onChange: (id: RightPaneId) => void;+ onCrop: () => void;+ transcript: AxcutTranscript | null;+ clips: AxcutClip[];+ currentTimeSec: number;+ onSeek: (sec: number) => void;+ onDropWordRange: (start: number, end: number) => void;+ onTranscribe: () => void;+ canTranscribe: boolean;+ isTranscribing: boolean;+ selection?: RegionHandle | null;+ onClearSelection?: () => void;+ onRemoveSelection?: (kind: RegionKind, id: string) => void;+}++const RAIL_BUTTONS: Array<{+ id: RightPaneId;+ label: string;+ icon: React.ElementType;+}> = [+ { id: "background", label: "Background", icon: Palette },+ { id: "effects", label: "Video effects", icon: Sliders },+ { id: "layout", label: "Layout", icon: LayoutPanelTop },+ { id: "cursor", label: "Cursor", icon: MousePointerClick },+ { id: "timeline", label: "Timeline", icon: Brackets },+ { id: "transcript", label: "Transcription", icon: Sparkles },+];++export function RightPanelStack({+ active,+ onChange,+ onCrop,+ transcript,+ clips,+ currentTimeSec,+ onSeek,+ onDropWordRange,+ onTranscribe,+ canTranscribe,+ isTranscribing,+ selection,+ onClearSelection,+ onRemoveSelection,+}: RightPanelStackProps) {+ const document = useProjectStore((s) => s.document);++ // Region inspector+ if (selection && onClearSelection && onRemoveSelection && document) {+ return (+ <RegionInspector+ document={document}+ selection={selection}+ onClear={onClearSelection}+ onRemove={onRemoveSelection}+ />+ );+ }++ return (+ <>+ <div className={`${styles.rightStack}`}>+ {active === "background" ? <BackgroundPane /> : null}+ {active === "transcript" ? (+ <TranscriptPane+ transcript={transcript}+ clips={clips}+ currentTimeSec={currentTimeSec}+ onSeek={onSeek}+ onDropWordRange={onDropWordRange}+ onTranscribe={onTranscribe}+ canTranscribe={canTranscribe}+ isTranscribing={isTranscribing}+ />+ ) : null}+ {active === "effects" ? <VideoEffectsPane /> : null}+ {active === "layout" ? <LayoutPane /> : null}+ {active === "cursor" ? <CursorPane /> : null}+ {active === "timeline" ? <TimelinePaneBody /> : null}+ </div>+ <aside className={`${styles.rail} ${styles.rightRail}`} aria-label="Right tools">+ {RAIL_BUTTONS.map(({ id, label, icon: Icon }) => (+ <button+ type="button"+ key={id}+ title={label}+ aria-label={label}+ aria-pressed={active === id}+ onClick={() => onChange(id)}+ >+ <Icon size={18} />+ </button>+ ))}+ <span className={styles.sepH} aria-hidden />+ <button type="button" title="Crop video" aria-label="Crop video" onClick={onCrop}>+ <Crop size={18} />+ </button>+ </aside>+ </>+ );+}++function RegionInspector({+ document,+ selection,+ onClear,+ onRemove,+}: {+ document: AxcutDocument;+ selection: RegionHandle;+ onClear: () => void;+ onRemove: (kind: RegionKind, id: string) => void;+}) {+ const setDocument = useProjectStore((s) => s.setDocument);+ const saveDocument = useProjectStore((s) => s.saveDocument);++ const region =+ selection.kind === "zoom"+ ? document.zoomRanges.find((z) => z.id === selection.id)+ : selection.kind === "annotation"+ ? document.annotations.find((a) => a.id === selection.id)+ : selection.kind === "speed"+ ? (+ (document.legacyEditor as { speedRegions?: Array<{ id: string; speed: number }> })+ ?.speedRegions ?? []+ ).find((s) => s.id === selection.id)+ : null;++ const depthNames = ["1.25×", "1.5×", "1.8×", "2.2×", "3.5×", "5×"];+ const currentDepth =+ selection.kind === "zoom" ? ((region as { depth?: number })?.depth ?? 3) - 1 : 0;++ // ponytail: keep rapid text edits in local state and flush on blur so we+ // don't push an undo snapshot per keystroke.+ const annot =+ region && selection.kind === "annotation" ? (region as AxcutAnnotationRegion) : null;+ const annotText = annot?.textContent || annot?.content || "";+ const [textDraft, setTextDraft] = useState(annotText);+ useEffect(() => {+ setTextDraft(annotText);+ }, [annotText]);+ const flushText = useCallback(() => {+ if (!annot) return;+ if (textDraft === (annot.textContent || annot.content || "")) return;+ const next = document.annotations.map((a) =>+ a.id === selection.id ? { ...a, textContent: textDraft, content: textDraft } : a,+ );+ setDocument({ ...document, annotations: next });+ void saveDocument({ ...document, annotations: next });+ }, [annot, textDraft, document, selection.id, setDocument, saveDocument]);++ return (+ <div style={{ display: "grid", gridTemplateRows: "auto 1fr", minHeight: 0 }}>+ <header className={styles.paneHead}>+ <h2>{kindLabel(selection.kind)}</h2>+ <span style={{ marginLeft: "auto", display: "inline-flex", gap: 4 }}>+ <button+ type="button"+ className={styles.iconBtn}+ title="Deselect"+ aria-label="Deselect"+ onClick={onClear}+ >+ ×+ </button>+ </span>+ </header>+ <div className={styles.paneBody}>+ {selection.kind === "zoom" ? (+ <>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(3, 1fr)",+ gap: 6,+ marginBottom: 12,+ }}+ >+ {depthNames.map((label, i) => (+ <button+ type="button"+ key={label}+ onClick={() => {+ if (!region) return;+ const next = document.zoomRanges.map((z) =>+ z.id === selection.id+ ? { ...z, depth: (i + 1) as 1 | 2 | 3 | 4 | 5 | 6, customScale: undefined }+ : z,+ ) as AxcutDocument["zoomRanges"];+ // ponytail: single discrete click — go through editor+ // mutation/undo path. Persist immediately to disk.+ setDocument({ ...document, zoomRanges: next });+ void saveDocument({ ...document, zoomRanges: next });+ }}+ style={{+ padding: "6px 8px",+ border: `1px solid ${currentDepth === i ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 8,+ background: currentDepth === i ? "var(--accent-wash)" : "var(--bg)",+ color: "var(--fg-2)",+ font: "500 12px/1 var(--font-mono)",+ cursor: "pointer",+ }}+ >+ {label}+ </button>+ ))}+ </div>+ {region ? (+ <div+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ padding: "0 4px",+ }}+ >+ {Math.round((region as { startMs: number }).startMs)}ms —{" "}+ {Math.round((region as { endMs: number }).endMs)}ms+ </div>+ ) : null}+ </>+ ) : selection.kind === "annotation" ? (+ annot ? (+ <>+ <textarea+ value={textDraft}+ onChange={(e) => setTextDraft(e.target.value)}+ onBlur={flushText}+ style={{+ width: "100%",+ minHeight: 80,+ padding: "8px 10px",+ border: "1px solid var(--border)",+ borderRadius: 8,+ background: "var(--bg)",+ color: "var(--fg-2)",+ font: "400 13px/1.5 var(--font-body)",+ outline: "none",+ resize: "vertical",+ }}+ />+ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ marginTop: 4,+ marginBottom: 12,+ }}+ >+ <span>{annot.type}</span>+ <span style={{ font: "500 10px/1 var(--font-mono)", color: "var(--muted)" }}>+ {Math.round(annot.startMs)}ms — {Math.round(annot.endMs)}ms+ </span>+ </div>+ <Field label="Text color">+ <input+ type="color"+ value={annot.style?.color ?? "#ffffff"}+ onChange={(e) => {+ const next = document.annotations.map((a) =>+ a.id === selection.id+ ? { ...a, style: { ...a.style, color: e.target.value } }+ : a,+ );+ setDocument({ ...document, annotations: next });+ void saveDocument({ ...document, annotations: next });+ }}+ style={{+ width: "100%",+ height: 32,+ border: "1px solid var(--border)",+ borderRadius: 6,+ background: "var(--bg)",+ }}+ />+ </Field>+ <Field label="Font size">+ <select+ value={String(annot.style?.fontSize ?? 32)}+ onChange={(e) => {+ const next = document.annotations.map((a) =>+ a.id === selection.id+ ? { ...a, style: { ...a.style, fontSize: Number(e.target.value) } }+ : a,+ );+ setDocument({ ...document, annotations: next });+ void saveDocument({ ...document, annotations: next });+ }}+ style={selectStyle()}+ >+ {[12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 96, 128].map(+ (n) => (+ <option key={n} value={n}>+ {n} px+ </option>+ ),+ )}+ </select>+ </Field>+ <Field label="Animation">+ <select+ value={annot.style?.textAnimation ?? "none"}+ onChange={(e) => {+ const next = document.annotations.map((a) =>+ a.id === selection.id+ ? {+ ...a,+ style: { ...a.style, textAnimation: e.target.value as never },+ }+ : a,+ );+ setDocument({ ...document, annotations: next });+ void saveDocument({ ...document, annotations: next });+ }}+ style={selectStyle()}+ >+ {["none", "fade", "rise", "pop", "slide-left", "typewriter", "pulse"].map((a) => (+ <option key={a} value={a}>+ {a}+ </option>+ ))}+ </select>+ </Field>+ </>+ ) : null+ ) : selection.kind === "skip" ? (+ <div+ style={{ font: "500 12px var(--font-body)", color: "var(--muted)", padding: "0 4px" }}+ >+ Trim region — drag the handles in the timeline to resize. Press Del to remove the cut.+ </div>+ ) : region ? (+ <div+ style={{ font: "500 12px var(--font-body)", color: "var(--muted)", padding: "0 4px" }}+ >+ Speed: {(region as { speed: number }).speed}× ·{" "}+ {Math.round((region as { startMs: number }).startMs)}ms—+ {(region as { endMs: number }).endMs}ms+ </div>+ ) : null}+ <button+ type="button"+ onClick={() => onRemove(selection.kind, selection.id)}+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ gap: 6,+ width: "100%",+ marginTop: 16,+ padding: "10px 12px",+ border: "1px solid var(--danger)",+ borderRadius: 8,+ background: "var(--danger-soft)",+ color: "var(--danger)",+ font: "600 13px/1 var(--font-body)",+ cursor: "pointer",+ }}+ >+ <Trash2 size={14} />+ Delete {kindLabel(selection.kind).toLowerCase()}+ </button>+ </div>+ </div>+ );+}++function kindLabel(kind: RegionKind): string {+ switch (kind) {+ case "zoom":+ return "Zoom region";+ case "skip":+ return "Trim region";+ case "annotation":+ return "Annotation";+ case "speed":+ return "Speed region";+ }+}++function Field({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div style={{ marginBottom: 8 }}>+ <div+ style={{+ font: "500 10px/1 var(--font-mono)",+ color: "var(--muted)",+ textTransform: "uppercase",+ letterSpacing: "0.06em",+ marginBottom: 4,+ }}+ >+ {label}+ </div>+ {children}+ </div>+ );+}++function selectStyle(): React.CSSProperties {+ return {+ width: "100%",+ padding: "6px 8px",+ border: "1px solid var(--border)",+ borderRadius: 6,+ background: "var(--bg)",+ color: "var(--fg-2)",+ font: "500 12px var(--font-body)",+ };+}diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxnew file mode 100644index 000000000..62d8a3c41--- /dev/null+++ b/src/components/ai-edition/RightPanes.tsx@@ -0,0 +1,810 @@+// Six right-rail panes matching design/openscreen-editor.html. Each control+// reads from + writes to the project document via `useEditorSettings`, so the+// design's UI is the canonical surface (no more "more options" link to a+// legacy panel — the legacy SettingsPanel is still available to the legacy+// VideoEditor and to per-region inspectors, but the panes here are+// self-sufficient).++import {+ Crop as CropIcon,+ FileText,+ HelpCircle,+ Layout as LayoutIcon,+ MousePointerClick,+ Palette,+ Sliders,+} from "lucide-react";+import { type ChangeEvent, type ReactNode, useEffect, useRef, useState } from "react";+import type { AxcutClip, AxcutTranscript } from "@/lib/ai-edition/schema";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { CURSOR_THEMES } from "@/lib/cursor/cursorThemes";+import { resolveImageWallpaperUrl, WALLPAPER_PATHS } from "@/lib/wallpaper";+import styles from "./NewEditorShell.module.css";+import { TranscriptEditor } from "./TranscriptEditor";++export type RightPaneId =+ | "background"+ | "transcript"+ | "effects"+ | "layout"+ | "cursor"+ | "timeline";++interface PaneProps {+ title: string;+ icon: ReactNode;+ helpLabel?: string;+ children: ReactNode;+}++function Pane({ title, icon, helpLabel, children }: PaneProps) {+ return (+ <div className={`${styles.pane} ${styles.isActive}`}>+ <header className={styles.paneHead}>+ <h2>{title}</h2>+ <span style={{ marginLeft: "auto", display: "inline-flex", gap: 4 }}>+ <button+ type="button"+ className={styles.iconBtn}+ title={helpLabel ?? "Help"}+ aria-label={helpLabel ?? "Help"}+ >+ <HelpCircle size={14} />+ </button>+ </span>+ <span style={{ display: "none" }}>{icon}</span>+ </header>+ <div className={styles.paneBody}>{children}</div>+ </div>+ );+}++// ─── Background ────────────────────────────────────────────────────++// ponytail: keep the gradient palette small and curated — every block renders+// in the picker and gets serialized to legacyEditor on save.+const GRAD_PRESETS: readonly string[] = [+ "linear-gradient(135deg, #eaebed, #bcc0c6)",+ "linear-gradient(135deg, #10b981, #eaebed)",+ "linear-gradient(135deg, #6b7280, #bcc0c6)",+ "linear-gradient(135deg, #eaebed, #10b981)",+ "linear-gradient(135deg, #16171d, #6b7280)",+ "linear-gradient(135deg, #bcc0c6, #16171d)",+ "linear-gradient(135deg, #10b981, #6b7280)",+ "linear-gradient(135deg, #eaebed, #10b981)",+ "linear-gradient(135deg, #6b7280, #16171d)",+ "linear-gradient(135deg, #bcc0c6, #10b981)",+ "linear-gradient(135deg, #16171d, #6b7280)",+ "linear-gradient(135deg, #eaebed, #bcc0c6)",+ "linear-gradient(135deg, #10b981, #bcc0c6)",+ "linear-gradient(135deg, #eaebed, #16171d)",+ "linear-gradient(135deg, #6b7280, #10b981)",+ "linear-gradient(135deg, #bcc0c6, #eaebed)",+];++const COLOR_PALETTE: readonly string[] = [+ "#16171d",+ "#6b7280",+ "#bcc0c6",+ "#eaebed",+ "#ffffff",+ "#10b981",+ "#0ea371",+ "#34d399",+ "#f59e0b",+ "#ef4444",+ "#3b82f6",+ "#8b5cf6",+ "#ec4899",+ "#f97316",+ "#22c55e",+ "#1e293b",+];++const IMAGE_ACCEPT = ".jpg,.jpeg,.png,image/jpeg,image/png";++// Wallpaper picker — image / solid color / gradient tabs.+//+// Wallpapers round-trip through the legacyEditor envelope exactly as they did+// in the v2 editor: gradient strings stay as-is, colors as `#hex`, and image+// paths are restricted to `/wallpapers/...` or the user's own data: URLs from+// the upload custom flow.+export function BackgroundPane() {+ const { settings, set, hasDocument } = useEditorSettings();+ const [tab, setTab] = useState<"image" | "color" | "gradient">("image");+ const fileInputRef = useRef<HTMLInputElement | null>(null);+ const customUrls = useMemoCustomWallpapers(settings.wallpaper);++ const isSelected = (value: string) => settings.wallpaper === value;++ const handleTabChange = (next: "image" | "color" | "gradient") => {+ setTab(next);+ };++ const handlePickFile = () => {+ if (!hasDocument) return;+ fileInputRef.current?.click();+ };++ const handleFileSelected = (e: ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ e.target.value = "";+ if (!file) return;+ if (!file.type.startsWith("image/")) return;+ const reader = new FileReader();+ reader.onload = () => {+ const dataUrl = typeof reader.result === "string" ? reader.result : "";+ if (!dataUrl) return;+ void set({ wallpaper: dataUrl });+ };+ reader.readAsDataURL(file);+ };++ return (+ <Pane title="Background" icon={<Palette size={14} />}>+ <div className={styles.paneTabs} role="tablist">+ <button+ type="button"+ className={tab === "image" ? styles.isActive : ""}+ onClick={() => handleTabChange("image")}+ >+ Image+ </button>+ <button+ type="button"+ className={tab === "color" ? styles.isActive : ""}+ onClick={() => handleTabChange("color")}+ >+ Color+ </button>+ <button+ type="button"+ className={tab === "gradient" ? styles.isActive : ""}+ onClick={() => handleTabChange("gradient")}+ >+ Gradient+ </button>+ </div>+ {tab === "image" ? (+ <>+ <button+ type="button"+ className={styles.uploadBtn}+ disabled={!hasDocument}+ onClick={handlePickFile}+ >+ Upload custom+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept={IMAGE_ACCEPT}+ style={{ display: "none" }}+ onChange={handleFileSelected}+ />+ <div className={styles.bgGrid}>+ {customUrls.map((url) => (+ <button+ type="button"+ key={`custom-${url.slice(-32)}`}+ className={`${styles.bgThumb} ${isSelected(url) ? styles.isActive : ""}`}+ style={{ background: `center/cover no-repeat url(${url})` }}+ aria-label="Custom wallpaper"+ disabled={!hasDocument}+ onClick={() => void set({ wallpaper: url })}+ />+ ))}+ {WALLPAPER_PATHS.map((path, i) => {+ const previewUrl = resolveImageWallpaperUrl(path);+ return (+ <button+ type="button"+ key={path}+ className={`${styles.bgThumb} ${isSelected(path) ? styles.isActive : ""}`}+ style={{ background: `center/cover no-repeat url(${previewUrl})` }}+ aria-label={`Background ${i + 1}`}+ disabled={!hasDocument}+ onClick={() => void set({ wallpaper: path })}+ />+ );+ })}+ </div>+ </>+ ) : tab === "color" ? (+ <BackgroundColorTab+ value={settings.wallpaper}+ hasDocument={hasDocument}+ isSelected={isSelected}+ onPick={(color) => void set({ wallpaper: color })}+ />+ ) : (+ <div className={styles.bgGrid}>+ {GRAD_PRESETS.map((bg, i) => (+ <button+ type="button"+ key={bg}+ className={`${styles.bgThumb} ${isSelected(bg) ? styles.isActive : ""}`}+ style={{ background: bg }}+ aria-label={`Gradient ${i + 1}`}+ disabled={!hasDocument}+ onClick={() => void set({ wallpaper: bg })}+ />+ ))}+ </div>+ )}+ </Pane>+ );+}++// ponytail: keep the user's last data: URL after they switch tabs so the Image+// tab can keep showing it without immediately pushing it back through `set`.+function useMemoCustomWallpapers(current: string): string[] {+ const [cached, setCached] = useState<string[]>([]);+ const lastValue = useRef(current);+ useEffect(() => {+ if (current.startsWith("data:")) {+ setCached((prev) => {+ if (prev[0] === current) return prev;+ return [current, ...prev.filter((u) => u !== current)].slice(0, 6);+ });+ }+ lastValue.current = current;+ }, [current]);+ return cached;+}++function BackgroundColorTab({+ value,+ hasDocument,+ isSelected,+ onPick,+}: {+ value: string;+ hasDocument: boolean;+ isSelected: (v: string) => boolean;+ onPick: (next: string) => void;+}) {+ const [hexDraft, setHexDraft] = useState(value.startsWith("#") ? value : "#000000");+ useEffect(() => {+ if (value.startsWith("#")) setHexDraft(value);+ }, [value]);+ const commitHex = () => {+ const next = normaliseHex(hexDraft);+ if (next) onPick(next);+ };+ return (+ <>+ <div className={styles.bgGrid} style={{ margin: "0 var(--sp-4) 12px" }}>+ {COLOR_PALETTE.map((c) => (+ <button+ type="button"+ key={c}+ className={`${styles.bgThumb} ${isSelected(c) ? styles.isActive : ""}`}+ style={{ background: c }}+ aria-label={`Color ${c}`}+ disabled={!hasDocument}+ onClick={() => onPick(c)}+ />+ ))}+ </div>+ <div+ style={{+ margin: "0 var(--sp-4) 12px",+ display: "flex",+ alignItems: "center",+ gap: 8,+ }}+ >+ <input+ type="color"+ value={hexDraft}+ disabled={!hasDocument}+ onChange={(e) => setHexDraft(e.target.value)}+ onBlur={commitHex}+ style={{+ width: 48,+ height: 36,+ border: "1px solid var(--border)",+ borderRadius: 8,+ background: "var(--surface)",+ padding: 0,+ }}+ />+ <input+ type="text"+ value={hexDraft}+ disabled={!hasDocument}+ onChange={(e) => setHexDraft(e.target.value)}+ onBlur={commitHex}+ onKeyDown={(e) => {+ if (e.key === "Enter") commitHex();+ }}+ style={{+ flex: 1,+ height: 36,+ border: "1px solid var(--border)",+ borderRadius: 8,+ background: "var(--surface)",+ padding: "0 12px",+ color: "var(--fg-2)",+ font: "500 13px var(--font-mono)",+ }}+ />+ </div>+ </>+ );+}++function normaliseHex(raw: string): string | null {+ const trimmed = raw.trim();+ if (!trimmed) return null;+ const withHash = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;+ if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(withHash)) return null;+ return withHash.toLowerCase();+}++// ─── Transcript ────────────────────────────────────────────────────++export function TranscriptPane({+ transcript,+ clips,+ currentTimeSec,+ onSeek,+ onDropWordRange,+ onTranscribe,+ canTranscribe,+ isTranscribing,+}: {+ transcript: AxcutTranscript | null;+ clips: AxcutClip[];+ currentTimeSec: number;+ onSeek: (sec: number) => void;+ onDropWordRange: (start: number, end: number) => void;+ onTranscribe: () => void;+ canTranscribe: boolean;+ isTranscribing: boolean;+}) {+ if (!transcript) {+ return (+ <Pane title="Current transcription" icon={<FileText size={14} />}>+ <div+ style={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ padding: 32,+ gap: 12,+ color: "var(--muted)",+ textAlign: "center",+ }}+ >+ <FileText size={28} style={{ color: "var(--dim)" }} />+ <p style={{ font: "500 13px var(--font-body)", color: "var(--fg-2)" }}>+ No transcript yet+ </p>+ <p style={{ font: "400 12px var(--font-body)", color: "var(--muted)", maxWidth: 260 }}>+ Transcribe uses local Whisper — runs in your browser, no data leaves the device.+ </p>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={onTranscribe}+ disabled={!canTranscribe || isTranscribing}+ >+ {isTranscribing ? "Transcribing…" : "Transcribe now"}+ </button>+ </div>+ </Pane>+ );+ }+ return (+ <div className={`${styles.pane} ${styles.isActive}`}>+ <header className={styles.paneHead}>+ <h2>Current transcription</h2>+ </header>+ <div className={styles.paneBody}>+ <TranscriptEditor+ transcript={transcript}+ clips={clips}+ currentTimeSec={currentTimeSec}+ onSeek={onSeek}+ onDropWordRange={onDropWordRange}+ />+ </div>+ </div>+ );+}++// ─── Video Effects ─────────────────────────────────────────────────++export function VideoEffectsPane() {+ const { settings, set, setLive, commit, hasDocument } = useEditorSettings();+ return (+ <Pane title="Video effects" icon={<Sliders size={14} />}>+ <div className={styles.paneRow}>+ <span className="label">Blur BG</span>+ <Toggle+ checked={settings.showBlur}+ disabled={!hasDocument}+ onChange={(v) => void set({ showBlur: v })}+ />+ </div>+ <div className={styles.sliderGrid}>+ <SliderCell+ label="Motion blur"+ value={settings.motionBlurAmount * 100}+ min={0}+ max={100}+ suffix="%"+ disabled={!hasDocument}+ onChange={(v) => setLive({ motionBlurAmount: v / 100 })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Shadow"+ value={settings.shadowIntensity * 100}+ min={0}+ max={100}+ suffix="%"+ disabled={!hasDocument}+ onChange={(v) => setLive({ shadowIntensity: v / 100 })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Roundness"+ value={settings.borderRadius}+ min={0}+ max={64}+ step={0.5}+ suffix="px"+ disabled={!hasDocument}+ onChange={(v) => setLive({ borderRadius: v })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Padding"+ value={settings.padding}+ min={0}+ max={100}+ suffix="%"+ disabled={!hasDocument}+ onChange={(v) => setLive({ padding: v })}+ onCommit={() => void commit()}+ />+ </div>+ </Pane>+ );+}++// ─── Layout (webcam) ──────────────────────────────────────────────++const WEBCAM_PRESETS = [+ { value: "picture-in-picture", label: "Picture in picture" },+ { value: "dual-frame", label: "Side by side" },+ { value: "vertical-stack", label: "Top / bottom" },+ { value: "no-webcam", label: "Screen only" },+] as const;++const CAMERA_SHAPES: Array<{+ value: "rectangle" | "circle" | "square" | "rounded";+ label: string;+ icon: ReactNode;+}> = [+ { value: "rectangle", label: "Rect", icon: <rect x="3" y="6" width="18" height="12" rx="1" /> },+ { value: "circle", label: "Circle", icon: <circle cx="12" cy="12" r="9" /> },+ { value: "square", label: "Square", icon: <rect x="4" y="4" width="16" height="16" rx="1" /> },+ { value: "rounded", label: "Rounded", icon: <rect x="3" y="6" width="18" height="12" rx="6" /> },+];++export function LayoutPane() {+ const { settings, set, setLive, commit, hasDocument } = useEditorSettings();+ // ponytail: the mask shape picker only makes sense for Picture-in-Picture.+ // Dual-frame (side-by-side) and vertical-stack (top/bottom) hardcode a+ // rectangle in the legacy layout math, so we hide those controls when the+ // preset isn't PiP.+ const isPip = settings.webcamLayoutPreset === "picture-in-picture";+ return (+ <Pane title="Layout" icon={<LayoutIcon size={14} />}>+ <div className={styles.sectionLabel}>Preset</div>+ <div className={styles.field}>+ <label>Layout</label>+ <select+ value={settings.webcamLayoutPreset}+ disabled={!hasDocument}+ onChange={(e) =>+ void set({ webcamLayoutPreset: e.target.value as typeof settings.webcamLayoutPreset })+ }+ >+ {WEBCAM_PRESETS.map((p) => (+ <option key={p.value} value={p.value}>+ {p.label}+ </option>+ ))}+ </select>+ </div>+ <div className={styles.paneRow}>+ <span className="label">Mirror webcam</span>+ <Toggle+ checked={settings.webcamMirrored}+ disabled={!hasDocument}+ onChange={(v) => void set({ webcamMirrored: v })}+ />+ </div>+ <div className={styles.paneRow}>+ <span className="label">Shrink on zoom</span>+ <Toggle+ checked={settings.webcamReactiveZoom}+ disabled={!hasDocument}+ onChange={(v) => void set({ webcamReactiveZoom: v })}+ />+ </div>+ {isPip ? (+ <>+ <div className={styles.sectionLabel}>Camera shape</div>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(4, 1fr)",+ gap: 8,+ padding: "0 var(--sp-4) 12px",+ }}+ >+ {CAMERA_SHAPES.map((shape) => {+ const isActive = settings.webcamMaskShape === shape.value;+ return (+ <button+ type="button"+ key={shape.value}+ className={`${styles.cursorCell} ${isActive ? styles.isActive : ""}`}+ style={{+ flexDirection: "column",+ gap: 4,+ padding: 8,+ display: "flex",+ alignItems: "center",+ }}+ disabled={!hasDocument}+ onClick={() => void set({ webcamMaskShape: shape.value })}+ >+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ width={22}+ height={22}+ >+ {shape.icon}+ </svg>+ <span style={{ font: "500 11px/1 var(--font-body)" }}>{shape.label}</span>+ </button>+ );+ })}+ </div>+ </>+ ) : null}+ {isPip ? (+ <div className={styles.sliderGrid}>+ <div className={`${styles.sliderCell} ${styles.full}`}>+ <div className="head">+ <span className="label">Webcam size</span>+ <span className="val">{Math.round(settings.webcamSizePreset)}%</span>+ </div>+ <input+ type="range"+ min={10}+ max={50}+ step={1}+ defaultValue={settings.webcamSizePreset}+ disabled={!hasDocument}+ onChange={(e) => setLive({ webcamSizePreset: Number(e.target.value) })}+ onMouseUp={() => void commit()}+ onTouchEnd={() => void commit()}+ onKeyUp={() => void commit()}+ />+ </div>+ </div>+ ) : null}+ </Pane>+ );+}++// ─── Cursor ───────────────────────────────────────────────────────++const CURSOR_STYLE_LABELS: Array<{ title: string; d: string }> = [+ {+ title: "Arrow",+ d: "M5.5 3.21V20.8c0 .45.54.67.85.35l4.86-4.86 2.94 6.4c.5.1.8-.13.95-.55l1.86-6.4 6.4-1.86c.42-.15.65-.5.55-.95l-6.4-2.94 4.86-4.86c.32-.31.1-.85-.35-.85H5.5z",+ },+ {+ title: "Pointer",+ d: "M14 4.1 12 6 M5.1 8l-2.9-.8 M6 12l-1.9 2 M7.2 2.2 8 5.1 M9 11V6a3 3 0 1 1 6 0v5",+ },+ {+ title: "Hand",+ d: "M18 11V6a2 2 0 0 0-4 0v5 M14 10V4a2 2 0 0 0-4 0v6 M10 10.5V6a2 2 0 0 0-4 0v8",+ },+ { title: "Text", d: "M14 4.1 12 6 M5.1 8l-2.9-.8 M6 12l-1.9 2 M7.2 2.2 8 5.1" },+ { title: "Cross", d: "M12 2v20M2 12h20" },+];++export function CursorPane() {+ const { settings, set, setLive, commit, hasDocument } = useEditorSettings();+ return (+ <Pane title="Cursor" icon={<MousePointerClick size={14} />}>+ <div className={styles.paneRow}>+ <span className="label">Show cursor</span>+ <Toggle+ checked={settings.cursorShow}+ disabled={!hasDocument}+ onChange={(v) => void set({ cursor: { show: v } })}+ />+ </div>+ <div className={styles.paneRow}>+ <span className="label">Clip to canvas</span>+ <Toggle+ checked={settings.cursor.clipToBounds}+ disabled={!hasDocument}+ onChange={(v) => void set({ cursor: { clipToBounds: v } })}+ />+ </div>+ <div className={styles.sectionLabel}>Cursor style</div>+ <div className={styles.cursorGrid}>+ {CURSOR_THEMES.slice(0, 5).map((theme) => {+ const isActive = settings.cursorTheme === theme.id;+ return (+ <button+ type="button"+ key={theme.id}+ className={`${styles.cursorCell} ${isActive ? styles.isActive : ""}`}+ title={theme.name}+ disabled={!hasDocument}+ onClick={() => void set({ cursor: { theme: theme.id } })}+ >+ <svg viewBox="0 0 24 24" fill="currentColor" width={18} height={18}>+ <path d={CURSOR_STYLE_LABELS[0]?.d ?? ""} />+ </svg>+ </button>+ );+ })}+ </div>+ <div className={styles.sliderGrid}>+ <SliderCell+ label="Size"+ value={settings.cursor.size * 10}+ min={5}+ max={100}+ step={0.1}+ decimals={1}+ disabled={!hasDocument}+ onChange={(v) => setLive({ cursor: { size: v / 10 } })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Smoothing"+ value={settings.cursor.smoothing * 100}+ min={0}+ max={100}+ suffix="%"+ disabled={!hasDocument}+ onChange={(v) => setLive({ cursor: { smoothing: v / 100 } })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Motion blur"+ value={settings.cursor.motionBlur * 100}+ min={0}+ max={100}+ suffix="%"+ disabled={!hasDocument}+ onChange={(v) => setLive({ cursor: { motionBlur: v / 100 } })}+ onCommit={() => void commit()}+ />+ <SliderCell+ label="Click bounce"+ value={settings.cursor.clickBounce * 10}+ min={0}+ max={50}+ step={0.1}+ decimals={1}+ disabled={!hasDocument}+ onChange={(v) => setLive({ cursor: { clickBounce: v / 10 } })}+ onCommit={() => void commit()}+ />+ </div>+ </Pane>+ );+}++// ─── Timeline (trim waveform) ──────────────────────────────────────++export function TimelinePaneBody() {+ const { settings, set, hasDocument } = useEditorSettings();+ return (+ <Pane title="Timeline" icon={<CropIcon size={14} />}>+ <div className={styles.paneRow}>+ <span className="label">Show audio waveform on trim track</span>+ <Toggle+ checked={settings.showTrimWaveform}+ disabled={!hasDocument}+ onChange={(v) => void set({ showTrimWaveform: v })}+ />+ </div>+ </Pane>+ );+}++// ─── primitives ───────────────────────────────────────────────────++function Toggle({+ checked,+ disabled,+ onChange,+}: {+ checked: boolean;+ disabled?: boolean;+ onChange: (next: boolean) => void;+}) {+ return (+ <button+ type="button"+ className={`${styles.toggle} ${checked ? styles.isOn : ""}`}+ aria-pressed={checked}+ disabled={disabled}+ onClick={() => onChange(!checked)}+ />+ );+}++function SliderCell({+ label,+ value,+ min,+ max,+ step = 1,+ decimals = 0,+ suffix = "",+ disabled,+ onChange,+ onCommit,+}: {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ decimals?: number;+ suffix?: string;+ disabled?: boolean;+ onChange: (next: number) => void;+ onCommit: () => void;+}) {+ return (+ <div className={styles.sliderCell}>+ <div className="head">+ <span className="label">{label}</span>+ <span className="val">+ {value.toFixed(decimals)}+ {suffix}+ </span>+ </div>+ <input+ type="range"+ min={min}+ max={max}+ step={step}+ defaultValue={value}+ disabled={disabled}+ onChange={(e) => onChange(Number(e.target.value))}+ onMouseUp={onCommit}+ onTouchEnd={onCommit}+ onKeyUp={onCommit}+ />+ </div>+ );+}++// ponytail: legacy color wheel / hue track styling was a cosmetic placeholder —+// the active BackgroundColorTab uses real pickers (color input + hex text) so+// the static style helpers are no longer needed.diff --git a/src/components/ai-edition/TimelinePane.module.css b/src/components/ai-edition/TimelinePane.module.cssnew file mode 100644index 000000000..6c3db76c2--- /dev/null+++ b/src/components/ai-edition/TimelinePane.module.css@@ -0,0 +1,304 @@+.pane {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding: 0.75rem;+ background: var(--card);+ border-top: 1px solid var(--border);+ min-height: 180px;+}++.header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}++.heading {+ font-size: 0.875rem;+ font-weight: 600;+ margin: 0;+ color: var(--card-foreground);+ text-transform: uppercase;+ letter-spacing: 0.025em;+}++.meta {+ font-size: 0.75rem;+ color: var(--muted-foreground);+ margin: 0;+}++.readout {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ font-size: 0.8125rem;+}++.muted {+ color: var(--muted-foreground);+}++.tool {+ display: flex;+ align-items: center;+ gap: 0.25rem;+ padding: 0.25rem 0.625rem;+ border-radius: 0.375rem;+ border: 1px solid var(--border);+ background: var(--background);+ color: var(--card-foreground);+ font-size: 0.75rem;+ cursor: pointer;+}++.tool:hover:not(:disabled) {+ background: var(--accent);+}++.tool:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.navigatorRow {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.fitButton {+ padding: 0.125rem 0.5rem;+ border-radius: 0.25rem;+ border: 1px solid var(--border);+ background: var(--background);+ color: var(--muted-foreground);+ font-size: 0.6875rem;+ cursor: pointer;+}++.fitButton:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.navigator {+ position: relative;+ flex: 1;+ height: 24px;+ border-radius: 0.25rem;+ background: var(--background);+ border: 1px solid var(--border);+ overflow: hidden;+ cursor: pointer;+}++.navigatorContent {+ position: absolute;+ inset: 0;+}++.navigatorCut {+ position: absolute;+ top: 4px;+ bottom: 4px;+ background: var(--destructive);+ opacity: 0.3;+ border-radius: 2px;+}++.navigatorWindow {+ position: absolute;+ top: 0;+ bottom: 0;+ background: var(--primary);+ opacity: 0.15;+ border: 1px solid var(--primary);+ border-radius: 2px;+ cursor: grab;+}++.navigatorHandle {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 4px;+ background: var(--primary);+ border-radius: 1px;+ cursor: ew-resize;+}++.navigatorHandle.start {+ left: -2px;+}++.navigatorHandle.end {+ right: -2px;+}++.viewport {+ position: relative;+ overflow-x: auto;+ overflow-y: hidden;+ flex: 1;+ min-height: 80px;+ cursor: crosshair;+ user-select: none;+}++.viewport.panning {+ cursor: grabbing;+}++.viewport.scrubbing {+ cursor: grabbing;+}++.canvas {+ position: relative;+ min-height: 100%;+}++.ruler {+ position: relative;+ border-bottom: 1px solid var(--border);+ overflow: hidden;+}++.tick {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 1px;+ background: var(--border);+}++.tickMajor {+ background: var(--muted-foreground);+}++.tickMajor span {+ position: absolute;+ top: 4px;+ left: 4px;+ font-size: 0.625rem;+ color: var(--muted-foreground);+ white-space: nowrap;+}++.trackLane {+ position: relative;+ height: 60px;+ margin-top: 4px;+}++.segment {+ position: absolute;+ top: 0;+ bottom: 0;+ border-radius: 0.25rem;+ display: flex;+ align-items: center;+ overflow: hidden;+}++.kept {+ background: var(--primary);+ opacity: 0.25;+}++.kept.active {+ opacity: 0.45;+}++.cut {+ background: var(--destructive);+ opacity: 0.2;+ border: 1px dashed var(--destructive);+}++.cut.active {+ opacity: 0.35;+}++.segmentLabel {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ padding: 0 0.5rem;+ font-size: 0.625rem;+ color: var(--card-foreground);+ white-space: nowrap;+ overflow: hidden;+}++.segmentLabel small {+ color: var(--muted-foreground);+}++.cutHandle {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 8px;+ background: var(--destructive);+ opacity: 0.6;+ border: none;+ cursor: ew-resize;+}++.cutHandle:hover {+ opacity: 1;+}++.handleStart {+ left: 0;+ border-radius: 0.25rem 0 0 0.25rem;+}++.handleEnd {+ right: 0;+ border-radius: 0 0.25rem 0.25rem 0;+}++.cutDelete {+ position: absolute;+ top: 2px;+ right: 12px;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 18px;+ height: 18px;+ border-radius: 0.25rem;+ border: none;+ background: var(--destructive);+ color: white;+ cursor: pointer;+ opacity: 0.7;+}++.cutDelete:hover {+ opacity: 1;+}++.playhead {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 2px;+ background: var(--primary);+ z-index: 10;+ pointer-events: none;+}++.empty {+ display: flex;+ align-items: center;+ justify-content: center;+ height: 100%;+ color: var(--muted-foreground);+ font-size: 0.8125rem;+}diff --git a/src/components/ai-edition/TimelinePane.tsx b/src/components/ai-edition/TimelinePane.tsxnew file mode 100644index 000000000..e3e22e98d--- /dev/null+++ b/src/components/ai-edition/TimelinePane.tsx@@ -0,0 +1,813 @@+import { Plus, Trash2 } from "lucide-react";+import {+ type CSSProperties,+ type PointerEvent as ReactPointerEvent,+ type WheelEvent as ReactWheelEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import type { Interval } from "@/lib/ai-edition/document/timeline";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import {+ formatSeconds,+ locateVirtualPosition,+ totalVirtualDuration,+} from "@/lib/ai-edition/timeline/virtual-preview";+import styles from "./TimelinePane.module.css";++// ponytail: ported from axcut/apps/web/src/components/TimelinePane.tsx, adapted+// to CSS modules + OpenScreen imports. Single-source trim view: clips are kept+// intervals, cuts are removed ranges. Multi-asset drag-drop lands in a follow-up.++interface TimelinePaneProps {+ clips: AxcutClip[];+ currentTimeSec: number;+ sourceDurationSec: number;+ busy?: boolean;+ onPreviewSource: (sourceTimeSec: number) => void;+ onReplaceTimeline: (intervals: Interval[], reason: string) => void;+}++interface SourceRange {+ id: string;+ startSec: number;+ endSec: number;+}++type TimelineItem = SourceRange & { kind: "kept" | "cut" };++interface ResizeState {+ id: number;+ cutId: string;+ edge: "start" | "end";+ startClientX: number;+ startSec: number;+ endSec: number;+ currentStartSec: number;+ currentEndSec: number;+ baseCuts: SourceRange[];+ pxPerSec: number;+}++interface PanState {+ startClientX: number;+ startScrollLeft: number;+}++interface NavigatorDragState {+ mode: "move" | "start" | "end";+ startClientX: number;+ overviewWidthPx: number;+ startVisibleStartSec: number;+ startVisibleEndSec: number;+}++const MIN_CUT_DURATION_SEC = 0.1;+const MIN_SOURCE_DURATION_SEC = 0.001;+const MAX_PX_PER_SEC = 280;+const MIN_SEGMENT_WIDTH_PX = 1;+const RULER_HEIGHT_PX = 28;++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++function normalizeRanges(+ durationSec: number,+ ranges: Array<{ id?: string; startSec: number; endSec: number }>,+ idPrefix: string,+): SourceRange[] {+ const normalized = ranges+ .map((range, index) => ({+ id: range.id ?? `${idPrefix}_${index + 1}`,+ startSec: clamp(range.startSec, 0, durationSec),+ endSec: clamp(range.endSec, 0, durationSec),+ }))+ .filter((range) => range.endSec > range.startSec)+ .sort((a, b) => a.startSec - b.startSec);+ const merged: SourceRange[] = [];+ for (const range of normalized) {+ const previous = merged.at(-1);+ if (!previous || range.startSec > previous.endSec) {+ merged.push({ ...range, id: `${idPrefix}_${merged.length + 1}` });+ continue;+ }+ previous.endSec = Math.max(previous.endSec, range.endSec);+ }+ return merged;+}++function deriveCutRanges(keptIntervals: SourceRange[], durationSec: number): SourceRange[] {+ if (durationSec <= MIN_SOURCE_DURATION_SEC || keptIntervals.length === 0) return [];+ const cuts: SourceRange[] = [];+ let cursor = 0;+ for (const interval of keptIntervals) {+ if (interval.startSec > cursor) {+ cuts.push({ id: `cut_${cuts.length + 1}`, startSec: cursor, endSec: interval.startSec });+ }+ cursor = Math.max(cursor, interval.endSec);+ }+ if (cursor < durationSec) {+ cuts.push({ id: `cut_${cuts.length + 1}`, startSec: cursor, endSec: durationSec });+ }+ return cuts;+}++function invertCutRanges(cuts: SourceRange[], durationSec: number): SourceRange[] {+ const intervals: SourceRange[] = [];+ let cursor = 0;+ for (const cut of normalizeRanges(durationSec, cuts, "cut")) {+ if (cut.startSec > cursor) {+ intervals.push({+ id: `clip_${intervals.length + 1}`,+ startSec: cursor,+ endSec: cut.startSec,+ });+ }+ cursor = Math.max(cursor, cut.endSec);+ }+ if (cursor < durationSec) {+ intervals.push({ id: `clip_${intervals.length + 1}`, startSec: cursor, endSec: durationSec });+ }+ return intervals;+}++function buildTimelineItems(kept: SourceRange[], cuts: SourceRange[]): TimelineItem[] {+ return [+ ...kept.map((r) => ({ ...r, kind: "kept" as const })),+ ...cuts.map((r) => ({ ...r, kind: "cut" as const })),+ ].sort((a, b) => a.startSec - b.startSec || (a.kind === "kept" ? -1 : 1));+}++function timelineItemStyle(item: TimelineItem, pxPerSec: number): CSSProperties {+ return {+ left: `${item.startSec * pxPerSec}px`,+ width: `${Math.max(MIN_SEGMENT_WIDTH_PX, (item.endSec - item.startSec) * pxPerSec)}px`,+ minWidth: `${MIN_SEGMENT_WIDTH_PX}px`,+ };+}++function buildRulerTicks(+ durationSec: number,+ pxPerSec: number,+): Array<{ timeSec: number; major: boolean }> {+ const majorStepSec = chooseTickStep(90 / Math.max(pxPerSec, 0.001));+ const minorStepSec = majorStepSec / 5;+ const ticks: Array<{ timeSec: number; major: boolean }> = [];+ for (let timeSec = 0; timeSec <= durationSec + minorStepSec / 2; timeSec += minorStepSec) {+ const rounded = Number(timeSec.toFixed(4));+ const major = Math.abs(rounded / majorStepSec - Math.round(rounded / majorStepSec)) < 0.001;+ ticks.push({ timeSec: Math.min(durationSec, rounded), major });+ }+ return ticks;+}++function chooseTickStep(minStepSec: number): number {+ const steps = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];+ return steps.find((step) => step >= minStepSec) ?? steps.at(-1) ?? 600;+}++export function TimelinePane({+ clips,+ currentTimeSec,+ sourceDurationSec,+ busy = false,+ onPreviewSource,+ onReplaceTimeline,+}: TimelinePaneProps) {+ const scrollRef = useRef<HTMLDivElement | null>(null);+ const overviewRef = useRef<HTMLDivElement | null>(null);+ const resizeRef = useRef<ResizeState | null>(null);+ const panRef = useRef<PanState | null>(null);+ const navigatorDragRef = useRef<NavigatorDragState | null>(null);+ const resizeSequenceRef = useRef(0);+ const [viewportWidthPx, setViewportWidthPx] = useState(0);+ const [scrollLeftPx, setScrollLeftPx] = useState(0);+ const [zoom, setZoom] = useState(1);+ const [resizeState, setResizeState] = useState<ResizeState | null>(null);+ const [panning, setPanning] = useState(false);+ const [scrubbing, setScrubbing] = useState(false);+ const [navigatorDragging, setNavigatorDragging] = useState(false);++ const virtualDurationSec = totalVirtualDuration(clips);+ const activePosition = locateVirtualPosition(clips, currentTimeSec);+ const sourceDuration = useMemo(+ () =>+ Math.max(+ sourceDurationSec,+ ...clips.map((clip) => clip.sourceEndSec ?? 0),+ MIN_SOURCE_DURATION_SEC,+ ),+ [clips, sourceDurationSec],+ );+ const fitPxPerSec = useMemo(+ () => Math.max(0.001, viewportWidthPx / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)),+ [sourceDuration, viewportWidthPx],+ );+ const pxPerSec = clamp(fitPxPerSec * zoom, fitPxPerSec, MAX_PX_PER_SEC);+ const contentWidthPx = Math.max(viewportWidthPx, Math.ceil(sourceDuration * pxPerSec));+ const visibleStartSec = clamp(scrollLeftPx / Math.max(pxPerSec, 0.001), 0, sourceDuration);+ const visibleDurationSec = clamp(viewportWidthPx / Math.max(pxPerSec, 0.001), 0, sourceDuration);+ const visibleEndSec = clamp(visibleStartSec + visibleDurationSec, 0, sourceDuration);+ const navigatorWindowStyle = useMemo(+ () =>+ ({+ left: `${(visibleStartSec / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)) * 100}%`,+ width: `${Math.max(0, ((visibleEndSec - visibleStartSec) / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)) * 100)}%`,+ }) as CSSProperties,+ [sourceDuration, visibleEndSec, visibleStartSec],+ );++ const keptIntervals = useMemo(+ () =>+ normalizeRanges(+ sourceDuration,+ clips.map((clip) => ({ startSec: clip.sourceStartSec, endSec: clip.sourceEndSec ?? 0 })),+ "clip",+ ),+ [clips, sourceDuration],+ );+ const committedCutRanges = useMemo(+ () => deriveCutRanges(keptIntervals, sourceDuration),+ [keptIntervals, sourceDuration],+ );+ const visibleCutRanges = useMemo(() => {+ if (!resizeState) return committedCutRanges;+ return normalizeRanges(+ sourceDuration,+ committedCutRanges.map((cut) =>+ cut.id === resizeState.cutId+ ? { id: cut.id, startSec: resizeState.currentStartSec, endSec: resizeState.currentEndSec }+ : cut,+ ),+ "cut",+ );+ }, [committedCutRanges, resizeState, sourceDuration]);+ const visibleKeptIntervals = useMemo(+ () => invertCutRanges(visibleCutRanges, sourceDuration),+ [sourceDuration, visibleCutRanges],+ );+ const timelineItems = useMemo(+ () => buildTimelineItems(visibleKeptIntervals, visibleCutRanges),+ [visibleKeptIntervals, visibleCutRanges],+ );+ const rulerTicks = useMemo(+ () => buildRulerTicks(sourceDuration, pxPerSec),+ [pxPerSec, sourceDuration],+ );+ const playheadSourceSec = activePosition?.sourceTimeSec ?? null;++ useEffect(() => {+ const scrollElement = scrollRef.current;+ if (!scrollElement) return;+ const updateWidth = () => setViewportWidthPx(scrollElement.clientWidth);+ updateWidth();+ const observer = new ResizeObserver(updateWidth);+ observer.observe(scrollElement);+ return () => observer.disconnect();+ }, []);++ useEffect(() => {+ resizeRef.current = resizeState;+ }, [resizeState]);++ const replaceTimelineFromCuts = useCallback(+ (cuts: SourceRange[], reason: string) => {+ onReplaceTimeline(+ invertCutRanges(normalizeRanges(sourceDuration, cuts, "cut"), sourceDuration),+ reason,+ );+ },+ [onReplaceTimeline, sourceDuration],+ );++ const seekSource = useCallback(+ (sourceSec: number) => {+ const bounded = clamp(sourceSec, 0, sourceDuration);+ onPreviewSource(bounded);+ },+ [onPreviewSource, sourceDuration],+ );++ const seekClientX = useCallback(+ (clientX: number) => {+ const scrollElement = scrollRef.current;+ if (!scrollElement) return;+ const rect = scrollElement.getBoundingClientRect();+ const sourceSec =+ (scrollElement.scrollLeft + clientX - rect.left) / Math.max(pxPerSec, 0.001);+ seekSource(sourceSec);+ },+ [pxPerSec, seekSource],+ );++ const zoomAt = useCallback(+ (nextZoom: number, anchorClientX?: number) => {+ const scrollElement = scrollRef.current;+ const boundedZoom = clamp(nextZoom, 1, MAX_PX_PER_SEC / Math.max(fitPxPerSec, 0.001));+ if (!scrollElement) {+ setZoom(boundedZoom);+ return;+ }+ const rect = scrollElement.getBoundingClientRect();+ const anchorX = anchorClientX === undefined ? rect.left + rect.width / 2 : anchorClientX;+ const sourceAtAnchor = (scrollElement.scrollLeft + anchorX - rect.left) / pxPerSec;+ const nextPxPerSec = clamp(fitPxPerSec * boundedZoom, fitPxPerSec, MAX_PX_PER_SEC);+ setZoom(boundedZoom);+ requestAnimationFrame(() => {+ const nextScrollLeft = Math.max(0, sourceAtAnchor * nextPxPerSec - (anchorX - rect.left));+ scrollElement.scrollLeft = nextScrollLeft;+ setScrollLeftPx(scrollElement.scrollLeft);+ });+ },+ [fitPxPerSec, pxPerSec],+ );++ const setVisibleWindow = useCallback(+ (startSec: number, endSec: number) => {+ const scrollElement = scrollRef.current;+ if (!scrollElement || viewportWidthPx <= 0) return;+ const minVisibleDurationSec = Math.max(+ MIN_CUT_DURATION_SEC,+ viewportWidthPx / MAX_PX_PER_SEC,+ );+ const visibleDuration = clamp(endSec - startSec, minVisibleDurationSec, sourceDuration);+ const visibleStart = clamp(startSec, 0, Math.max(0, sourceDuration - visibleDuration));+ const nextPxPerSec = viewportWidthPx / Math.max(visibleDuration, MIN_SOURCE_DURATION_SEC);+ const nextZoom = clamp(+ nextPxPerSec / Math.max(fitPxPerSec, 0.001),+ 1,+ MAX_PX_PER_SEC / Math.max(fitPxPerSec, 0.001),+ );+ setZoom(nextZoom);+ requestAnimationFrame(() => {+ const currentPxPerSec = clamp(fitPxPerSec * nextZoom, fitPxPerSec, MAX_PX_PER_SEC);+ scrollElement.scrollLeft = visibleStart * currentPxPerSec;+ setScrollLeftPx(scrollElement.scrollLeft);+ });+ },+ [fitPxPerSec, sourceDuration, viewportWidthPx],+ );++ const fitTimeline = useCallback(() => {+ setZoom(1);+ requestAnimationFrame(() => {+ if (scrollRef.current) {+ scrollRef.current.scrollLeft = 0;+ setScrollLeftPx(0);+ }+ });+ }, []);++ const addCut = useCallback(() => {+ if (busy || sourceDuration <= MIN_SOURCE_DURATION_SEC) return;+ const centerSec = activePosition?.sourceTimeSec ?? clips[0]?.sourceStartSec ?? 0;+ const startSec = clamp(centerSec - 0.5, 0, Math.max(0, sourceDuration - MIN_CUT_DURATION_SEC));+ const endSec = clamp(centerSec + 0.5, startSec + MIN_CUT_DURATION_SEC, sourceDuration);+ replaceTimelineFromCuts(+ [...committedCutRanges, { id: `cut_${committedCutRanges.length + 1}`, startSec, endSec }],+ `Added cut ${formatSeconds(startSec)}-${formatSeconds(endSec)}`,+ );+ }, [+ activePosition?.sourceTimeSec,+ busy,+ clips,+ committedCutRanges,+ replaceTimelineFromCuts,+ sourceDuration,+ ]);++ const deleteCut = useCallback(+ (cut: SourceRange) => {+ if (busy) return;+ replaceTimelineFromCuts(+ committedCutRanges.filter((item) => item.id !== cut.id),+ `Deleted cut ${formatSeconds(cut.startSec)}-${formatSeconds(cut.endSec)}`,+ );+ },+ [busy, committedCutRanges, replaceTimelineFromCuts],+ );++ const startResize = useCallback(+ (cut: SourceRange, edge: ResizeState["edge"], event: ReactPointerEvent<HTMLElement>) => {+ if (busy) return;+ event.preventDefault();+ event.stopPropagation();+ const nextState: ResizeState = {+ id: resizeSequenceRef.current + 1,+ cutId: cut.id,+ edge,+ startClientX: event.clientX,+ startSec: cut.startSec,+ endSec: cut.endSec,+ currentStartSec: cut.startSec,+ currentEndSec: cut.endSec,+ baseCuts: committedCutRanges,+ pxPerSec,+ };+ resizeSequenceRef.current = nextState.id;+ resizeRef.current = nextState;+ setResizeState(nextState);+ seekSource(edge === "start" ? cut.startSec : cut.endSec);++ const move = (moveEvent: PointerEvent) => {+ const current = resizeRef.current;+ if (!current) return;+ const deltaSec =+ (moveEvent.clientX - current.startClientX) / Math.max(current.pxPerSec, 0.001);+ const currentIndex = current.baseCuts.findIndex((item) => item.id === current.cutId);+ const previousCut = currentIndex > 0 ? current.baseCuts[currentIndex - 1] : null;+ const nextCut =+ currentIndex >= 0 && currentIndex < current.baseCuts.length - 1+ ? current.baseCuts[currentIndex + 1]+ : null;+ const nextStartSec =+ current.edge === "start"+ ? clamp(+ current.startSec + deltaSec,+ previousCut?.endSec ?? 0,+ current.currentEndSec - MIN_CUT_DURATION_SEC,+ )+ : current.currentStartSec;+ const nextEndSec =+ current.edge === "end"+ ? clamp(+ current.endSec + deltaSec,+ current.currentStartSec + MIN_CUT_DURATION_SEC,+ nextCut?.startSec ?? sourceDuration,+ )+ : current.currentEndSec;+ const updated = { ...current, currentStartSec: nextStartSec, currentEndSec: nextEndSec };+ resizeRef.current = updated;+ setResizeState(updated);+ seekSource(current.edge === "start" ? nextStartSec : nextEndSec);+ };++ const end = () => {+ const current = resizeRef.current;+ resizeRef.current = null;+ setResizeState(null);+ globalThis.document.body.classList.remove("timeline-resizing-cut");+ globalThis.window.removeEventListener("pointermove", move);+ globalThis.window.removeEventListener("pointerup", end);+ globalThis.window.removeEventListener("pointercancel", end);+ if (!current) return;+ if (+ Math.abs(current.currentStartSec - current.startSec) < 0.01 &&+ Math.abs(current.currentEndSec - current.endSec) < 0.01+ )+ return;+ replaceTimelineFromCuts(+ current.baseCuts.map((item) =>+ item.id === current.cutId+ ? { ...item, startSec: current.currentStartSec, endSec: current.currentEndSec }+ : item,+ ),+ `Resized cut ${formatSeconds(current.startSec)}-${formatSeconds(current.endSec)} → ${formatSeconds(current.currentStartSec)}-${formatSeconds(current.currentEndSec)}`,+ );+ };++ globalThis.document.body.classList.add("timeline-resizing-cut");+ globalThis.window.addEventListener("pointermove", move);+ globalThis.window.addEventListener("pointerup", end, { once: true });+ globalThis.window.addEventListener("pointercancel", end, { once: true });+ },+ [busy, committedCutRanges, replaceTimelineFromCuts, pxPerSec, seekSource, sourceDuration],+ );++ const startScrub = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest(`.${styles.cutHandle}, .${styles.cutDelete}`)) return;+ if (event.button !== 0 || clips.length === 0) return;+ event.preventDefault();+ seekClientX(event.clientX);+ setScrubbing(true);+ globalThis.document.body.classList.add("timeline-scrubbing");+ const move = (moveEvent: PointerEvent) => seekClientX(moveEvent.clientX);+ const end = () => {+ setScrubbing(false);+ globalThis.document.body.classList.remove("timeline-scrubbing");+ globalThis.window.removeEventListener("pointermove", move);+ globalThis.window.removeEventListener("pointerup", end);+ globalThis.window.removeEventListener("pointercancel", end);+ };+ globalThis.window.addEventListener("pointermove", move);+ globalThis.window.addEventListener("pointerup", end, { once: true });+ globalThis.window.addEventListener("pointercancel", end, { once: true });+ },+ [clips.length, seekClientX],+ );++ const startPan = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ const target = event.target instanceof Element ? event.target : null;+ if (busy || target?.closest(`button, .${styles.cutHandle}, .${styles.cutDelete}`)) return;+ const scrollElement = scrollRef.current;+ if (!scrollElement || scrollElement.scrollWidth <= scrollElement.clientWidth) return;+ event.preventDefault();+ panRef.current = { startClientX: event.clientX, startScrollLeft: scrollElement.scrollLeft };+ setPanning(true);+ globalThis.document.body.classList.add("timeline-panning");+ const move = (moveEvent: PointerEvent) => {+ const pan = panRef.current;+ if (!pan || !scrollRef.current) return;+ scrollRef.current.scrollLeft = pan.startScrollLeft - (moveEvent.clientX - pan.startClientX);+ };+ const end = () => {+ panRef.current = null;+ setPanning(false);+ globalThis.document.body.classList.remove("timeline-panning");+ globalThis.window.removeEventListener("pointermove", move);+ globalThis.window.removeEventListener("pointerup", end);+ globalThis.window.removeEventListener("pointercancel", end);+ };+ globalThis.window.addEventListener("pointermove", move);+ globalThis.window.addEventListener("pointerup", end, { once: true });+ globalThis.window.addEventListener("pointercancel", end, { once: true });+ },+ [busy],+ );++ const handleTimelinePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ if (event.altKey || event.button === 1) {+ startPan(event);+ return;+ }+ startScrub(event);+ },+ [startPan, startScrub],+ );++ const handleWheel = useCallback(+ (event: ReactWheelEvent<HTMLDivElement>) => {+ if (!(event.ctrlKey || event.metaKey)) return;+ event.preventDefault();+ const direction = event.deltaY > 0 ? -1 : 1;+ zoomAt(zoom * (direction > 0 ? 1.18 : 1 / 1.18), event.clientX);+ },+ [zoom, zoomAt],+ );++ const handleTimelineScroll = useCallback(() => {+ setScrollLeftPx(scrollRef.current?.scrollLeft ?? 0);+ }, []);++ const startNavigatorDrag = useCallback(+ (mode: NavigatorDragState["mode"], event: ReactPointerEvent<HTMLElement>) => {+ if (busy || clips.length === 0) return;+ const overview = overviewRef.current;+ if (!overview) return;+ event.preventDefault();+ event.stopPropagation();+ const nextState: NavigatorDragState = {+ mode,+ startClientX: event.clientX,+ overviewWidthPx: Math.max(1, overview.clientWidth),+ startVisibleStartSec: visibleStartSec,+ startVisibleEndSec: visibleEndSec,+ };+ navigatorDragRef.current = nextState;+ setNavigatorDragging(true);+ globalThis.document.body.classList.add("timeline-navigating");+ const move = (moveEvent: PointerEvent) => {+ const current = navigatorDragRef.current;+ if (!current) return;+ const deltaSec =+ ((moveEvent.clientX - current.startClientX) / current.overviewWidthPx) * sourceDuration;+ const currentDuration = current.startVisibleEndSec - current.startVisibleStartSec;+ if (current.mode === "move") {+ const nextStartSec = clamp(+ current.startVisibleStartSec + deltaSec,+ 0,+ Math.max(0, sourceDuration - currentDuration),+ );+ setVisibleWindow(nextStartSec, nextStartSec + currentDuration);+ return;+ }+ if (current.mode === "start") {+ const nextStartSec = clamp(+ current.startVisibleStartSec + deltaSec,+ 0,+ current.startVisibleEndSec - MIN_CUT_DURATION_SEC,+ );+ setVisibleWindow(nextStartSec, current.startVisibleEndSec);+ return;+ }+ const nextEndSec = clamp(+ current.startVisibleEndSec + deltaSec,+ current.startVisibleStartSec + MIN_CUT_DURATION_SEC,+ sourceDuration,+ );+ setVisibleWindow(current.startVisibleStartSec, nextEndSec);+ };+ const end = () => {+ navigatorDragRef.current = null;+ setNavigatorDragging(false);+ globalThis.document.body.classList.remove("timeline-navigating");+ globalThis.window.removeEventListener("pointermove", move);+ globalThis.window.removeEventListener("pointerup", end);+ globalThis.window.removeEventListener("pointercancel", end);+ };+ globalThis.window.addEventListener("pointermove", move);+ globalThis.window.addEventListener("pointerup", end, { once: true });+ globalThis.window.addEventListener("pointercancel", end, { once: true });+ },+ [busy, clips.length, setVisibleWindow, sourceDuration, visibleEndSec, visibleStartSec],+ );++ return (+ <section className={styles.pane}>+ <div className={styles.header}>+ <div>+ <h2 className={styles.heading}>Timeline</h2>+ <p className={styles.meta}>+ {clips.length} clip{clips.length === 1 ? "" : "s"} · {committedCutRanges.length} cut+ {committedCutRanges.length === 1 ? "" : "s"} · {formatSeconds(virtualDurationSec)} total+ </p>+ </div>+ <div className={styles.readout}>+ <button+ type="button"+ className={styles.tool}+ onClick={addCut}+ disabled={busy || clips.length === 0}+ title="Add cut at playhead"+ >+ <Plus size={14} />+ <span>Add cut</span>+ </button>+ <strong>{formatSeconds(currentTimeSec)}</strong>+ <span className={styles.muted}>+ {activePosition+ ? `Clip ${activePosition.clipIndex + 1}/${clips.length}`+ : "No active clip"}+ </span>+ </div>+ </div>++ <div className={styles.navigatorRow}>+ <button+ type="button"+ className={styles.fitButton}+ onClick={fitTimeline}+ disabled={zoom <= 1.01}+ title="Fit full timeline"+ >+ Fit+ </button>+ <div+ ref={overviewRef}+ className={+ navigatorDragging ? `${styles.navigator} ${styles.navigating}` : styles.navigator+ }+ aria-label="Timeline zoom and pan navigator"+ >+ <div className={styles.navigatorContent}>+ {committedCutRanges.map((cut) => (+ <span+ key={cut.id}+ className={styles.navigatorCut}+ style={{+ left: `${(cut.startSec / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)) * 100}%`,+ width: `${((cut.endSec - cut.startSec) / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)) * 100}%`,+ }}+ />+ ))}+ </div>+ <div+ className={styles.navigatorWindow}+ style={navigatorWindowStyle}+ onPointerDown={(e) => startNavigatorDrag("move", e)}+ >+ <span+ className={`${styles.navigatorHandle} ${styles.start}`}+ onPointerDown={(e) => startNavigatorDrag("start", e)}+ />+ <span+ className={`${styles.navigatorHandle} ${styles.end}`}+ onPointerDown={(e) => startNavigatorDrag("end", e)}+ />+ </div>+ </div>+ </div>++ <div+ ref={scrollRef}+ className={[+ styles.viewport,+ panning ? styles.panning : "",+ scrubbing ? styles.scrubbing : "",+ ]+ .filter(Boolean)+ .join(" ")}+ onPointerDown={handleTimelinePointerDown}+ onWheel={handleWheel}+ onScroll={handleTimelineScroll}+ aria-label="Source timeline. Click or drag to scrub, Alt+drag to pan, Ctrl+wheel to zoom."+ >+ {clips.length > 0 ? (+ <div className={styles.canvas} style={{ width: `${contentWidthPx}px` }}>+ <div className={styles.ruler} style={{ height: `${RULER_HEIGHT_PX}px` }}>+ {rulerTicks.map((tick) => (+ <div+ key={`${tick.timeSec}-${tick.major ? "major" : "minor"}`}+ className={tick.major ? `${styles.tick} ${styles.tickMajor}` : styles.tick}+ style={{ left: `${tick.timeSec * pxPerSec}px` }}+ >+ {tick.major ? <span>{formatSeconds(tick.timeSec)}</span> : null}+ </div>+ ))}+ </div>+ <div className={styles.trackLane}>+ {timelineItems.map((item) => {+ const itemStyle = timelineItemStyle(item, pxPerSec);+ if (item.kind === "cut") {+ const active = resizeState?.cutId === item.id;+ return (+ <div+ key={item.id}+ className={+ active+ ? `${styles.segment} ${styles.cut} ${styles.active}`+ : `${styles.segment} ${styles.cut}`+ }+ style={itemStyle}+ title={`Cut ${formatSeconds(item.startSec)}-${formatSeconds(item.endSec)}`}+ >+ <button+ type="button"+ className={`${styles.cutHandle} ${styles.handleStart}`}+ onPointerDown={(e) => startResize(item, "start", e)}+ disabled={busy}+ aria-label={`Adjust cut start at ${formatSeconds(item.startSec)}`}+ />+ <div className={styles.segmentLabel}>+ <span>Cut</span>+ <small>+ {formatSeconds(item.startSec)}–{formatSeconds(item.endSec)}+ </small>+ </div>+ <button+ type="button"+ className={styles.cutDelete}+ onClick={(e) => {+ e.stopPropagation();+ deleteCut(item);+ }}+ disabled={busy}+ aria-label={`Delete cut ${formatSeconds(item.startSec)}-${formatSeconds(item.endSec)}`}+ >+ <Trash2 size={12} />+ </button>+ <button+ type="button"+ className={`${styles.cutHandle} ${styles.handleEnd}`}+ onPointerDown={(e) => startResize(item, "end", e)}+ disabled={busy}+ aria-label={`Adjust cut end at ${formatSeconds(item.endSec)}`}+ />+ </div>+ );+ }+ const active =+ playheadSourceSec !== null &&+ playheadSourceSec >= item.startSec &&+ playheadSourceSec <= item.endSec;+ return (+ <div+ key={item.id}+ className={+ active+ ? `${styles.segment} ${styles.kept} ${styles.active}`+ : `${styles.segment} ${styles.kept}`+ }+ style={itemStyle}+ title={`Kept ${formatSeconds(item.startSec)}-${formatSeconds(item.endSec)}`}+ >+ <div className={styles.segmentLabel}>+ <span>{formatSeconds(item.startSec)}</span>+ </div>+ </div>+ );+ })}+ {playheadSourceSec !== null && (+ <div+ className={styles.playhead}+ style={{ left: `${playheadSourceSec * pxPerSec}px` }}+ aria-hidden="true"+ />+ )}+ </div>+ </div>+ ) : (+ <div className={styles.empty}>No clips yet. Add a video asset to start.</div>+ )}+ </div>+ </section>+ );+}diff --git a/src/components/ai-edition/Titlebar.tsx b/src/components/ai-edition/Titlebar.tsxnew file mode 100644index 000000000..8675947b4--- /dev/null+++ b/src/components/ai-edition/Titlebar.tsx@@ -0,0 +1,522 @@+import {+ ChevronDown,+ Download,+ FileVideo,+ FolderOpen,+ FolderPlus,+ Languages,+ Moon,+ PanelLeft,+ PanelRight,+ Rows3,+ Save,+ Settings,+ Sun,+ Video,+} from "lucide-react";+import { type ReactNode, useEffect, useRef, useState } from "react";+import { useI18n } from "@/contexts/I18nContext";+import { useTheme } from "@/hooks/useTheme";+import type { Locale } from "@/i18n/config";+import styles from "./NewEditorShell.module.css";++interface ProjectSummary {+ id: string;+ title: string;+ updatedAt: string;+}++export interface TitlebarActions {+ openProject: () => void;+ newProject: () => void;+ save: () => void;+ saveAs: () => void;+ newRecording: () => void;+ recorder: () => void;+ export: () => void;+ toggleLeft: () => void;+ toggleRight: () => void;+ toggleBottom: () => void;+ openSettings: () => void;+ renameProject: (title: string) => void;+}++interface TitlebarProps {+ project: ProjectSummary | null;+ dirty: boolean;+ lastSavedAt: Date | null;+ canExport: boolean;+ leftCollapsed: boolean;+ rightCollapsed: boolean;+ bottomCollapsed: boolean;+ actions: TitlebarActions;+}++function timeAgo(d: Date | null): string {+ if (!d) return "Not saved yet";+ const delta = Date.now() - d.getTime();+ if (delta < 5_000) return "just now";+ if (delta < 60_000) return `${Math.floor(delta / 1000)}s ago`;+ if (delta < 3_600_000) return `${Math.floor(delta / 60_000)}m ago`;+ if (delta < 86_400_000) return `${Math.floor(delta / 3_600_000)}h ago`;+ return d.toLocaleDateString();+}++export function Titlebar({+ project,+ dirty,+ lastSavedAt,+ canExport,+ leftCollapsed,+ rightCollapsed,+ bottomCollapsed,+ actions,+}: TitlebarProps) {+ const { theme, toggle: toggleTheme } = useTheme();+ const [, setTick] = useState(0);++ useEffect(() => {+ if (dirty || !lastSavedAt) return;+ const timer = setInterval(() => {+ setTick((t) => t + 1);+ }, 10_000);+ return () => clearInterval(timer);+ }, [dirty, lastSavedAt]);++ const openShortcuts = () => window.dispatchEvent(new CustomEvent("openscreen:open-shortcuts"));+ return (+ <header className={styles.titlebar}>+ <span className={styles.lights} aria-hidden>+ <span className={styles.r} />+ <span className={styles.y} />+ <span className={styles.g} />+ </span>+ <span className={styles.brand}>+ <span className={styles.brandMark} aria-hidden>+ O+ </span>+ OpenScreen+ </span>+ <span className={styles.sep} aria-hidden />+ <ProjectNameField project={project} onRename={actions.renameProject} />+ <span className={styles.saved}>+ {dirty ? (+ <>+ <span className={styles.dot} aria-hidden style={{ background: "var(--warn)" }} />+ Unsaved changes+ </>+ ) : (+ <>+ <span className={styles.dot} aria-hidden />+ Saved · {timeAgo(lastSavedAt)}+ </>+ )}+ </span>+ <span className={styles.projActions}>+ <IconButton title="Open project" ariaLabel="Open project" onClick={actions.openProject}>+ <FolderOpen size={16} />+ </IconButton>+ <IconButton title="New project" ariaLabel="New project" onClick={actions.newProject}>+ <FolderPlus size={16} />+ </IconButton>+ <SaveDropdown+ disabled={!project}+ dirty={dirty}+ onSave={actions.save}+ onSaveAs={actions.saveAs}+ />+ </span>+ <LangButton />+ <button+ type="button"+ className={styles.recorderBtn}+ title="New recording"+ aria-label="New recording"+ onClick={actions.newRecording}+ >+ <Video size={16} />+ <span>New recording</span>+ </button>+ <button+ type="button"+ className={styles.recorderBtn}+ style={{ background: "transparent", borderColor: "var(--border)", color: "var(--fg-2)" }}+ title="Return to recorder"+ aria-label="Return to recorder"+ onClick={actions.recorder}+ >+ Return to recorder+ </button>+ <span className={styles.right}>+ <IconButton+ title="Export"+ ariaLabel="Export"+ onClick={actions.export}+ disabled={!canExport}+ >+ <Download size={16} />+ </IconButton>+ <IconButton+ title="Toggle left panel"+ ariaLabel="Toggle left panel"+ ariaPressed={!leftCollapsed}+ onClick={actions.toggleLeft}+ >+ <PanelLeft size={16} />+ </IconButton>+ <IconButton+ title="Toggle timeline"+ ariaLabel="Toggle timeline"+ ariaPressed={!bottomCollapsed}+ onClick={actions.toggleBottom}+ >+ <Rows3 size={16} />+ </IconButton>+ <IconButton+ title="Toggle right panel"+ ariaLabel="Toggle right panel"+ ariaPressed={!rightCollapsed}+ onClick={actions.toggleRight}+ >+ <PanelRight size={16} />+ </IconButton>+ <IconButton+ title={theme === "dark" ? "Switch to light theme" : "Switch to dark theme"}+ ariaLabel={theme === "dark" ? "Switch to light theme" : "Switch to dark theme"}+ ariaPressed={theme === "dark"}+ onClick={toggleTheme}+ >+ {theme === "dark" ? <Sun size={16} /> : <Moon size={16} />}+ </IconButton>+ <IconButton title="Shortcuts (?)" ariaLabel="Shortcuts" onClick={openShortcuts}>+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <circle cx="12" cy="12" r="10" />+ <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />+ <line x1="12" y1="17" x2="12.01" y2="17" />+ </svg>+ </IconButton>+ <IconButton title="Settings" ariaLabel="Settings" onClick={actions.openSettings}>+ <Settings size={16} />+ </IconButton>+ </span>+ </header>+ );+}++function SaveDropdown({+ disabled,+ dirty,+ onSave,+ onSaveAs,+}: {+ disabled: boolean;+ dirty: boolean;+ onSave: () => void;+ onSaveAs: () => void;+}) {+ const [open, setOpen] = useState(false);+ const ref = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ if (!open) return;+ const onDocClick = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener("mousedown", onDocClick);+ return () => document.removeEventListener("mousedown", onDocClick);+ }, [open]);+ return (+ <div ref={ref} style={{ position: "relative" }}>+ <button+ type="button"+ className={styles.iconBtn}+ title="Save project"+ aria-label="Save project"+ aria-pressed={open}+ disabled={disabled}+ onClick={() => setOpen((v) => !v)}+ >+ <Save size={16} />+ {dirty ? (+ <span+ aria-hidden+ style={{+ position: "absolute",+ top: 4,+ right: 4,+ width: 6,+ height: 6,+ borderRadius: "50%",+ background: "var(--warn)",+ }}+ />+ ) : null}+ </button>+ {open ? (+ <div+ role="menu"+ style={{+ position: "absolute",+ top: "calc(100% + 4px)",+ left: 0,+ minWidth: 180,+ background: "var(--surface)",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ boxShadow: "var(--elev-pop)",+ padding: 4,+ zIndex: 60,+ }}+ >+ <MenuItem+ icon={<Save size={14} />}+ label="Save"+ hint="⌘S"+ onClick={() => {+ setOpen(false);+ onSave();+ }}+ />+ <MenuItem+ icon={<FileVideo size={14} />}+ label="Save as…"+ hint="⌘⇧S"+ onClick={() => {+ setOpen(false);+ onSaveAs();+ }}+ />+ </div>+ ) : null}+ </div>+ );+}++function MenuItem({+ icon,+ label,+ hint,+ onClick,+}: {+ icon: ReactNode;+ label: string;+ hint?: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ role="menuitem"+ style={{+ display: "flex",+ alignItems: "center",+ gap: 8,+ width: "100%",+ padding: "6px 10px",+ border: 0,+ background: "transparent",+ color: "var(--fg-2)",+ borderRadius: "var(--r-sm)",+ cursor: "pointer",+ font: "500 12px var(--font-body)",+ }}+ onClick={onClick}+ >+ {icon}+ <span style={{ flex: 1, textAlign: "left" }}>{label}</span>+ {hint ? (+ <span+ style={{+ font: "500 10px/1 var(--font-mono)",+ color: "var(--meta)",+ letterSpacing: "0.04em",+ }}+ >+ {hint}+ </span>+ ) : null}+ </button>+ );+}++function IconButton({+ children,+ title,+ ariaLabel,+ ariaPressed,+ onClick,+ disabled,+}: {+ children: ReactNode;+ title: string;+ ariaLabel?: string;+ ariaPressed?: boolean;+ onClick?: () => void;+ disabled?: boolean;+}) {+ return (+ <button+ type="button"+ className={styles.iconBtn}+ title={title}+ aria-label={ariaLabel ?? title}+ aria-pressed={ariaPressed}+ onClick={onClick}+ disabled={disabled}+ >+ {children}+ </button>+ );+}++function LangButton() {+ const { locale, setLocale } = useI18n();+ const [open, setOpen] = useState(false);+ const ref = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ if (!open) return;+ const onDocClick = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener("mousedown", onDocClick);+ return () => document.removeEventListener("mousedown", onDocClick);+ }, [open]);+ return (+ <div ref={ref} style={{ position: "relative" }}>+ <button+ type="button"+ className={styles.langSel}+ onClick={() => setOpen((v) => !v)}+ aria-label="Change language"+ aria-pressed={open}+ >+ <Languages size={16} style={{ color: "var(--fg)" }} />+ <span style={{ fontSize: 13, fontWeight: 500 }}>{locale.toUpperCase()}</span>+ <ChevronDown size={10} style={{ color: "var(--muted)" }} />+ </button>+ {open ? (+ <div+ style={{+ position: "absolute",+ top: "calc(100% + 4px)",+ right: 0,+ minWidth: 160,+ background: "var(--surface)",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ boxShadow: "var(--elev-pop)",+ padding: 4,+ zIndex: 60,+ }}+ >+ {LANGS.map((l) => (+ <button+ key={l.code}+ type="button"+ style={{+ display: "block",+ width: "100%",+ textAlign: "left",+ padding: "6px 10px",+ border: 0,+ background: l.code === locale ? "var(--accent-wash)" : "transparent",+ color: l.code === locale ? "var(--accent)" : "var(--fg-2)",+ borderRadius: "var(--r-sm)",+ cursor: "pointer",+ font: "500 12px var(--font-body)",+ }}+ onClick={() => {+ setLocale(l.code as Locale);+ setOpen(false);+ }}+ >+ {l.label}+ </button>+ ))}+ </div>+ ) : null}+ </div>+ );+}++function ProjectNameField({+ project,+ onRename,+}: {+ project: ProjectSummary | null;+ onRename: (title: string) => void;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(project?.title ?? "");+ const inputRef = useRef<HTMLInputElement | null>(null);++ useEffect(() => {+ if (editing) {+ setDraft(project?.title ?? "");+ inputRef.current?.select();+ }+ }, [editing, project?.title]);++ const commit = () => {+ setEditing(false);+ const next = draft.trim();+ if (next && next !== project?.title) onRename(next);+ };++ return (+ <span className={styles.project}>+ {editing ? (+ <input+ ref={inputRef}+ className={styles.projectInput}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commit();+ } else if (e.key === "Escape") {+ setEditing(false);+ }+ }}+ />+ ) : (+ <button+ type="button"+ className={styles.projectName}+ title="Rename project"+ aria-label="Rename project"+ disabled={!project}+ onClick={() => setEditing(true)}+ >+ {project?.title ?? "No project"}+ </button>+ )}+ </span>+ );+}++const LANGS = [+ { code: "en", label: "English" },+ { code: "fr", label: "Français" },+ { code: "es", label: "Español" },+ { code: "de", label: "Deutsch" },+ { code: "it", label: "Italiano" },+ { code: "ja-JP", label: "日本語" },+ { code: "ko-KR", label: "한국어" },+ { code: "pt-BR", label: "Português (BR)" },+ { code: "ru", label: "Русский" },+ { code: "tr", label: "Türkçe" },+ { code: "vi", label: "Tiếng Việt" },+ { code: "zh-CN", label: "简体中文" },+ { code: "zh-TW", label: "繁體中文" },+];diff --git a/src/components/ai-edition/TranscriptEditor.module.css b/src/components/ai-edition/TranscriptEditor.module.cssnew file mode 100644index 000000000..74e4ace7a--- /dev/null+++ b/src/components/ai-edition/TranscriptEditor.module.css@@ -0,0 +1,75 @@+.container {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ padding: 0.5rem 0.75rem;+ border-top: 1px solid var(--border);+ background: var(--card);+ max-height: 180px;+ overflow: hidden;+}++.header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+}++.heading {+ font-size: 0.75rem;+ font-weight: 600;+ margin: 0;+ color: var(--muted-foreground);+ text-transform: uppercase;+ letter-spacing: 0.025em;+}++.cutButton {+ padding: 0.25rem 0.625rem;+ border-radius: 0.375rem;+ border: 1px solid var(--destructive);+ background: var(--destructive);+ color: white;+ font-size: 0.75rem;+ cursor: pointer;+}++.cutButton:hover {+ opacity: 0.85;+}++.textArea {+ flex: 1;+ overflow-y: auto;+ line-height: 1.6;+ font-size: 0.8125rem;+ padding: 0.25rem;+}++.word {+ display: inline-block;+ padding: 0.0625rem 0.1875rem;+ border-radius: 0.125rem;+ cursor: pointer;+ transition: background-color 100ms ease;+}++.word:hover {+ background: var(--accent);+}++.word.skipped {+ color: var(--destructive);+ text-decoration: line-through;+ opacity: 0.6;+}++.word.selected {+ background: var(--primary);+ color: var(--primary-foreground);+}++.word.current {+ border-bottom: 2px solid var(--primary);+}diff --git a/src/components/ai-edition/TranscriptEditor.tsx b/src/components/ai-edition/TranscriptEditor.tsxnew file mode 100644index 000000000..bbccc45e2--- /dev/null+++ b/src/components/ai-edition/TranscriptEditor.tsx@@ -0,0 +1,117 @@+import { useCallback, useMemo, useState } from "react";+import type { AxcutClip, AxcutTranscript } from "@/lib/ai-edition/schema";+import { formatSeconds, keptWordIdSet } from "@/lib/ai-edition/timeline/virtual-preview";+import styles from "./TranscriptEditor.module.css";++// ponytail: simplified port of axcut's TranscriptEditor. Click a word to+// select, shift-click another word to select a range, press "Cut" to drop+// that range from the timeline. Kept words = default, skipped = red.++interface TranscriptEditorProps {+ transcript: AxcutTranscript;+ clips: AxcutClip[];+ currentTimeSec: number;+ onSeek: (timeSec: number) => void;+ onDropWordRange: (startSec: number, endSec: number) => void;+}++export function TranscriptEditor({+ transcript,+ clips,+ currentTimeSec,+ onSeek,+ onDropWordRange,+}: TranscriptEditorProps) {+ const [anchorWordId, setAnchorWordId] = useState<string | null>(null);+ const [focusWordId, setFocusWordId] = useState<string | null>(null);+ const keptIds = useMemo(() => keptWordIdSet(clips), [clips]);++ const handleWordClick = useCallback(+ (event: React.MouseEvent, wordId: string, startSec: number) => {+ if (event.shiftKey && anchorWordId) {+ setFocusWordId(wordId);+ } else {+ setAnchorWordId(wordId);+ setFocusWordId(wordId);+ onSeek(startSec);+ }+ },+ [anchorWordId, onSeek],+ );++ const selectedRange = useMemo(() => {+ if (!anchorWordId || !focusWordId) return null;+ const startIndex = transcript.words.findIndex((w) => w.id === anchorWordId);+ const endIndex = transcript.words.findIndex((w) => w.id === focusWordId);+ if (startIndex < 0 || endIndex < 0) return null;+ const [from, to] = startIndex <= endIndex ? [startIndex, endIndex] : [endIndex, startIndex];+ const selected = transcript.words.slice(from, to + 1);+ if (selected.length === 0) return null;+ return {+ startSec: Math.min(...selected.map((w) => w.startSec)),+ endSec: Math.max(...selected.map((w) => w.endSec)),+ text: selected.map((w) => w.text).join(" "),+ };+ }, [anchorWordId, focusWordId, transcript.words]);++ const handleCut = useCallback(() => {+ if (selectedRange) {+ onDropWordRange(selectedRange.startSec, selectedRange.endSec);+ setAnchorWordId(null);+ setFocusWordId(null);+ }+ }, [onDropWordRange, selectedRange]);++ return (+ <div className={styles.container}>+ <div className={styles.header}>+ <h3 className={styles.heading}>Transcript</h3>+ {selectedRange && (+ <button type="button" className={styles.cutButton} onClick={handleCut}>+ Cut {formatSeconds(selectedRange.startSec)}–{formatSeconds(selectedRange.endSec)}+ </button>+ )}+ </div>+ <div className={styles.textArea}>+ {transcript.words.map((word) => {+ const isKept = keptIds.has(word.id);+ const isSelected =+ anchorWordId && focusWordId+ ? isInRange(word.id, anchorWordId, focusWordId, transcript.words)+ : false;+ const isCurrent = currentTimeSec >= word.startSec && currentTimeSec <= word.endSec;+ return (+ <span+ key={word.id}+ className={[+ styles.word,+ !isKept ? styles.skipped : "",+ isSelected ? styles.selected : "",+ isCurrent ? styles.current : "",+ ]+ .filter(Boolean)+ .join(" ")}+ onClick={(e) => handleWordClick(e, word.id, word.startSec)}+ >+ {word.text}+ </span>+ );+ })}+ </div>+ </div>+ );+}++function isInRange(+ wordId: string,+ anchorId: string,+ focusId: string,+ words: { id: string }[],+): boolean {+ const start = words.findIndex((w) => w.id === anchorId);+ const end = words.findIndex((w) => w.id === focusId);+ if (start < 0 || end < 0) return false;+ const [from, to] = start <= end ? [start, end] : [end, start];+ const index = words.findIndex((w) => w.id === wordId);+ return index >= from && index <= to;+}diff --git a/src/components/ai-edition/VirtualPreview.module.css b/src/components/ai-edition/VirtualPreview.module.cssnew file mode 100644index 000000000..9829585cf--- /dev/null+++ b/src/components/ai-edition/VirtualPreview.module.css@@ -0,0 +1,93 @@+.container {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ width: 100%;+ height: 100%;+ align-items: center;+ justify-content: center;+}++.videoFrame {+ position: relative;+ width: 100%;+ height: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+}++.video {+ max-width: 100%;+ max-height: 100%;+ border-radius: 0.5rem;+}++.overlay {+ position: absolute;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--muted-foreground);+ font-size: 0.875rem;+ background: var(--card);+ padding: 0.75rem 1.25rem;+ border-radius: 0.5rem;+}++.controls {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ width: 100%;+ max-width: 600px;+ padding: 0 0.5rem;+}++.iconButton {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ border-radius: 0.375rem;+ border: 1px solid var(--border);+ background: var(--card);+ color: var(--card-foreground);+ cursor: pointer;+ transition: background-color 120ms ease;+}++.iconButton:hover:not(:disabled) {+ background: var(--accent);+}++.iconButton:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.readout {+ display: flex;+ align-items: baseline;+ gap: 0.25rem;+ font-size: 0.8125rem;+ white-space: nowrap;+}++.muted {+ color: var(--muted-foreground);+}++.slider {+ flex: 1;+ height: 0.25rem;+ accent-color: var(--primary);+}++.placeholder {+ color: var(--muted-foreground);+ font-size: 0.875rem;+ text-align: center;+ padding: 2rem;+}diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxnew file mode 100644index 000000000..92f01147b--- /dev/null+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -0,0 +1,272 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { fromFileUrl } from "@/components/video-editor/projectPersistence";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import {+ clampVirtualTime,+ locateSourcePosition,+ locateVirtualPosition,+ totalVirtualDuration,+} from "@/lib/ai-edition/timeline/virtual-preview";+import { CursorPreviewLayer } from "./CursorPreviewLayer";+import styles from "./VirtualPreview.module.css";++export interface VideoSource {+ id: string;+ src: string;+ label: string;+}++interface VirtualPreviewProps {+ videoSources: VideoSource[];+ clips: AxcutClip[];+ seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;+ onTimeChange?: (timeSec: number) => void;+ onLoadedMetadata?: (durationSec: number) => void;+ onVideoElement?: (element: HTMLVideoElement | null) => void;+ videoStyle?: React.CSSProperties;+ onVideoError?: () => void;+}++export function VirtualPreview({+ videoSources,+ clips,+ seekTarget,+ onTimeChange,+ onLoadedMetadata,+ onVideoElement,+ videoStyle,+ onVideoError,+}: VirtualPreviewProps) {+ const videoRef = useRef<HTMLVideoElement | null>(null);++ const isProgrammaticSeekRef = useRef(false);+ const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);+ const [virtualTimeSec, setVirtualTimeSec] = useState(0);+ const [isPlaying, setIsPlaying] = useState(false);+ const [loadState, setLoadState] = useState<"idle" | "loading" | "ready" | "error">("idle");+ const [sourceIndex, setSourceIndex] = useState(0);++ const virtualDurationSec = useMemo(() => totalVirtualDuration(clips), [clips]);+ const activeSource = videoSources[sourceIndex] ?? null;++ // ponytail: the cursor overlay wants source-media time (the recorded+ // cursor samples live on the original mp4 timeline, not the edited+ // virtual timeline). Read `video.currentTime` every animation frame so+ // the cursor follows the playhead even when the user scrubs.+ const [sourceTimeSec, setSourceTimeSec] = useState(0);+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run when the active source swaps so the rAF reads from the new <video>.+ useEffect(() => {+ let raf = 0;+ const tick = () => {+ const v = videoRef.current;+ if (v && Number.isFinite(v.currentTime)) {+ setSourceTimeSec(v.currentTime);+ }+ raf = window.requestAnimationFrame(tick);+ };+ raf = window.requestAnimationFrame(tick);+ return () => window.cancelAnimationFrame(raf);+ }, [activeSource?.src]);++ // report the video element up; re-notify (and clear) whenever the active+ // source changes so the parent doesn't keep a stale node after the keyed+ // <video> is swapped for a new asset.+ const activeSourceKey = activeSource?.src ?? null;+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run on source swap+ useEffect(() => {+ onVideoElement?.(videoRef.current);+ return () => onVideoElement?.(null);+ }, [onVideoElement, activeSourceKey]);++ const updateVirtualTime = useCallback(+ (nextTimeSec: number) => {+ setVirtualTimeSec(nextTimeSec);+ onTimeChange?.(nextTimeSec);+ },+ [onTimeChange],+ );++ const seekToVirtualTime = useCallback(+ (nextVirtualTimeSec: number, preservePlayback = false) => {+ const position = locateVirtualPosition(clips, nextVirtualTimeSec);+ if (!position) {+ updateVirtualTime(0);+ setIsPlaying(false);+ return;+ }++ const targetIndex = videoSources.findIndex((vs) => vs.id === position.clip.assetId);+ const isAssetSwitch = targetIndex >= 0 && targetIndex !== sourceIndex;+ const shouldContinuePlayback = preservePlayback && isPlaying;++ if (isAssetSwitch) {+ setSourceIndex(targetIndex);+ setLoadState("loading");+ updateVirtualTime(position.virtualTimeSec);+ pendingSeekRef.current = {+ sourceTimeSec: position.sourceTimeSec,+ play: shouldContinuePlayback,+ };+ return;+ }++ const video = videoRef.current;+ if (!video) return;++ isProgrammaticSeekRef.current = true;+ updateVirtualTime(position.virtualTimeSec);+ if (Math.abs(video.currentTime - position.sourceTimeSec) > 0.01) {+ video.currentTime = position.sourceTimeSec;+ }+ if (shouldContinuePlayback) {+ void video.play().catch(() => setIsPlaying(false));+ }+ },+ [clips, videoSources, sourceIndex, isPlaying, updateVirtualTime],+ );++ const seekToSourceTime = useCallback((sourceTimeSec: number) => {+ const video = videoRef.current;+ if (!video) return;+ isProgrammaticSeekRef.current = true;+ if (Math.abs(video.currentTime - sourceTimeSec) > 0.01) {+ video.currentTime = sourceTimeSec;+ }+ }, []);++ const handleTimeUpdate = useCallback(() => {+ const video = videoRef.current;+ if (!video || clips.length === 0) return;+ const activeSourceId = videoSources[sourceIndex]?.id;+ if (isProgrammaticSeekRef.current) {+ isProgrammaticSeekRef.current = false;+ const position = locateSourcePosition(clips, video.currentTime, activeSourceId);+ if (position) {+ updateVirtualTime(clampVirtualTime(clips, position.virtualTimeSec));+ }+ return;+ }+ const position = locateSourcePosition(clips, video.currentTime, activeSourceId);+ if (!position) {+ // ponytail: fall back to timeline order, not same-asset order, so+ // cross-asset / reordered clips don't keep playing unmapped media.+ const nextClip = clips.find((clip) => clip.timelineStartSec > virtualTimeSec + 0.001);+ if (nextClip) {+ seekToVirtualTime(nextClip.timelineStartSec, true);+ } else {+ video.pause();+ updateVirtualTime(virtualDurationSec);+ setIsPlaying(false);+ }+ return;+ }+ const currentClip = position.clip;+ const reachedClipEnd = video.currentTime >= (currentClip.sourceEndSec ?? Infinity) - 0.04;+ if (reachedClipEnd) {+ const nextClip = clips[position.clipIndex + 1];+ if (!nextClip) {+ video.pause();+ updateVirtualTime(virtualDurationSec);+ setIsPlaying(false);+ return;+ }+ seekToVirtualTime(nextClip.timelineStartSec, true);+ return;+ }+ updateVirtualTime(clampVirtualTime(clips, position.virtualTimeSec));+ }, [+ clips,+ seekToVirtualTime,+ updateVirtualTime,+ virtualDurationSec,+ videoSources,+ sourceIndex,+ virtualTimeSec,+ ]);++ useEffect(() => {+ const video = videoRef.current;+ setIsPlaying(false);+ updateVirtualTime(0);+ setSourceIndex(0);+ setLoadState(videoSources.length > 0 ? "loading" : "idle");+ if (!video) return;+ video.pause();+ if (clips.length > 0) {+ const start = locateVirtualPosition(clips, 0);+ if (start) video.currentTime = start.sourceTimeSec;+ }+ }, [updateVirtualTime, videoSources, clips.length, clips]);++ useEffect(() => {+ if (!seekTarget) return;+ if (seekTarget.isSource) {+ seekToSourceTime(seekTarget.timeSec);+ } else {+ seekToVirtualTime(seekTarget.timeSec);+ }+ }, [seekTarget, seekToVirtualTime, seekToSourceTime]);++ return (+ <div className={styles.container}>+ {activeSource ? (+ <div className={styles.videoFrame}>+ <video+ key={activeSource.src}+ ref={videoRef}+ src={activeSource.src}+ className={styles.video}+ style={videoStyle}+ preload="metadata"+ playsInline+ onLoadedMetadata={(e) => {+ setLoadState("ready");+ const duration = e.currentTarget.duration;+ if (Number.isFinite(duration) && duration > 0) {+ onLoadedMetadata?.(duration);+ }+ if (pendingSeekRef.current) {+ const { sourceTimeSec, play } = pendingSeekRef.current;+ pendingSeekRef.current = null;+ e.currentTarget.currentTime = sourceTimeSec;+ if (play) {+ void e.currentTarget.play().catch(() => setIsPlaying(false));+ }+ } else if (clips.length > 0) {+ seekToVirtualTime(virtualTimeSec);+ }+ }}+ onWaiting={() => setLoadState("loading")}+ onCanPlay={() => setLoadState("ready")}+ onError={() => {+ // ponytail: don't blindly advance to the next source — if+ // the failed source owns the current virtual clip, the+ // next sourceIndex will seekToVirtualTime right back into+ // the same failed asset, looping. Fail the preview.+ pendingSeekRef.current = null;+ setLoadState("error");+ setIsPlaying(false);+ onVideoError?.();+ }}+ onPause={() => setIsPlaying(false)}+ onPlay={() => setIsPlaying(true)}+ onEnded={() => setIsPlaying(false)}+ onTimeUpdate={handleTimeUpdate}+ />+ {loadState !== "ready" && (+ <div className={styles.overlay}>+ {loadState === "error" ? "Video preview could not be loaded." : "Loading preview…"}+ </div>+ )}+ <CursorPreviewLayer+ videoPath={activeSource ? fromFileUrl(activeSource.src) : null}+ currentTimeSec={sourceTimeSec}+ isPlaying={isPlaying}+ />+ </div>+ ) : (+ <div className={styles.placeholder}>Attach a video to start previewing.</div>+ )}+ </div>+ );+}diff --git a/src/components/ai-edition/WebcamOverlay.tsx b/src/components/ai-edition/WebcamOverlay.tsxnew file mode 100644index 000000000..4b4c98273--- /dev/null+++ b/src/components/ai-edition/WebcamOverlay.tsx@@ -0,0 +1,122 @@+// Live webcam preview overlay. Reads `document.cameraTrack.sourcePath` and+// the current virtual time and drives a real <video> element at the right+// source-time. The webcam is a derived stream — cuts/zoom/speed come from the+// main timeline. This component only reads; it does not write.+//+// ponytail: the camera plays in parallel with the screen. Source-time mapping+// cameraTime = clip.sourceStartSec + (currentTimeSec − clip.timelineStartSec)+// adjustment = (cameraTrack.startMs + cameraTrack.offsetMs) / 1000+// final = max(0, cameraTime − adjustment)+// (startMs is when the camera comes online; offsetMs is the early/late delay).++import { useEffect, useMemo, useState } from "react";+import { toFileUrl } from "@/components/video-editor/projectPersistence";+import type { WebcamLayoutPreset, WebcamMaskShape } from "@/components/video-editor/types";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";+import { getCssClipPath } from "@/lib/webcamMaskShapes";+import styles from "./NewEditorShell.module.css";++interface WebcamOverlayProps {+ clips: AxcutClip[];+ currentTimeSec: number;+ onTimeChange: (sec: number) => void;+ isPlaying: boolean;+ // ponytail: container renders without a frame; the <video> is the only+ // thing the user actually sees. Border radius + clip-path therefore+ // belong on the video so they actually round the camera content.+ borderRadius: number;+ webcamMaskShape: WebcamMaskShape;+ layoutPreset: WebcamLayoutPreset;+}++export function WebcamOverlay(props: WebcamOverlayProps) {+ const { settings } = useEditorSettings();+ const cameraTrack = useProjectStore((s) => s.document?.cameraTrack ?? null);++ const [videoEl, setVideoEl] = useState<HTMLVideoElement | null>(null);+ const [hasError, setHasError] = useState(false);++ const cameraTime = useMemo(() => {+ if (!cameraTrack?.visible) return null;+ const position = locateVirtualPosition(props.clips, props.currentTimeSec);+ if (!position) return null;+ const offsetSec = (cameraTrack.startMs + cameraTrack.offsetMs) / 1000;+ return Math.max(0, position.sourceTimeSec - offsetSec);+ }, [+ cameraTrack?.visible,+ cameraTrack?.startMs,+ cameraTrack?.offsetMs,+ props.clips,+ props.currentTimeSec,+ ]);++ // Drive the camera <video> time so its playback matches the main timeline.+ useEffect(() => {+ if (!videoEl) return;+ if (cameraTime === null) return;+ if (Math.abs(videoEl.currentTime - cameraTime) > 0.18) {+ try {+ videoEl.currentTime = cameraTime;+ } catch {+ // ponytail: silent — video not ready yet+ }+ }+ }, [videoEl, cameraTime]);++ // Mirror play/pause with the main preview so the camera stays in sync.+ useEffect(() => {+ if (!videoEl) return;+ if (props.isPlaying) {+ void videoEl.play().catch(() => {+ setHasError(true);+ });+ } else {+ videoEl.pause();+ }+ }, [videoEl, props.isPlaying]);++ if (!cameraTrack?.sourcePath || !cameraTrack.visible) {+ return null;+ }++ const showError = hasError;+ // ponytail: the layout computes the final borderRadius (preset fraction+ // for dual-frame/overlay, 0 for stack, half-circle for circle PiP, etc.).+ // Push it onto the <video> itself so it actually clips the camera+ // content; the container stays a transparent, overflow:hidden wrapper.+ const style: React.CSSProperties = {+ display: showError ? "none" : "block",+ transform: settings.webcamMirrored ? "scaleX(-1)" : undefined,+ clipPath: getCssClipPath(props.webcamMaskShape) ?? undefined,+ borderRadius: `${props.borderRadius}px`,+ };++ return (+ <video+ key={cameraTrack.sourcePath}+ ref={(el) => {+ setVideoEl(el);+ setHasError(false);+ }}+ src={toFileUrl(cameraTrack.sourcePath)}+ className={styles.webcamVideo}+ muted+ playsInline+ preload="metadata"+ onError={() => setHasError(true)}+ onLoadedMetadata={() => {+ if (cameraTime !== null && videoEl && Math.abs(videoEl.currentTime - cameraTime) > 0.18) {+ try {+ videoEl.currentTime = cameraTime;+ } catch {+ // silent+ }+ }+ }}+ style={style}+ />+ );+}diff --git a/src/components/video-editor/AddCustomFontDialog.tsx b/src/components/video-editor/AddCustomFontDialog.tsxdeleted file mode 100644index 872559d28..000000000--- a/src/components/video-editor/AddCustomFontDialog.tsx+++ /dev/null@@ -1,174 +0,0 @@-import { Plus } from "lucide-react";-import { useState } from "react";-import { toast } from "sonner";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { useScopedT } from "@/contexts/I18nContext";-import {- addCustomFont,- type CustomFont,- generateFontId,- isValidGoogleFontsUrl,- parseFontFamilyFromImport,-} from "@/lib/customFonts";--interface AddCustomFontDialogProps {- onFontAdded?: (font: CustomFont) => void;-}--export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {- const t = useScopedT("settings");- const tc = useScopedT("common");- const [open, setOpen] = useState(false);- const [importUrl, setImportUrl] = useState("");- const [fontName, setFontName] = useState("");- const [loading, setLoading] = useState(false);-- const handleImportUrlChange = (url: string) => {- setImportUrl(url);-- if (isValidGoogleFontsUrl(url)) {- const extracted = parseFontFamilyFromImport(url);- if (extracted && !fontName) {- setFontName(extracted);- }- }- };-- const handleAdd = async () => {- if (!importUrl.trim()) {- toast.error(t("customFont.errorEmptyUrl"));- return;- }-- if (!isValidGoogleFontsUrl(importUrl)) {- toast.error(t("customFont.errorInvalidUrl"));- return;- }-- if (!fontName.trim()) {- toast.error(t("customFont.errorEmptyName"));- return;- }-- setLoading(true);-- try {- const fontFamily = parseFontFamilyFromImport(importUrl);- if (!fontFamily) {- toast.error(t("customFont.errorExtractFailed"));- setLoading(false);- return;- }-- const newFont: CustomFont = {- id: generateFontId(fontName),- name: fontName.trim(),- fontFamily: fontFamily,- importUrl: importUrl.trim(),- };-- // Loads and verifies the font; throws on failure- await addCustomFont(newFont);-- if (onFontAdded) {- onFontAdded(newFont);- }-- toast.success(t("customFont.successMessage", { fontName }));-- setImportUrl("");- setFontName("");- setOpen(false);- } catch (error) {- console.error("Failed to add custom font:", error);- const errorMessage = error instanceof Error ? error.message : "Failed to load font";- toast.error(t("customFont.failedToAdd"), {- description: errorMessage.includes("timeout")- ? t("customFont.errorTimeout")- : t("customFont.errorLoadFailed"),- });- } finally {- setLoading(false);- }- };-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <Button- variant="outline"- size="sm"- className="w-full bg-white/5 border-white/10 text-slate-200 hover:bg-white/10 h-9 text-xs"- >- <Plus className="w-3 h-3 mr-1" />- {t("customFont.dialogTitle")}- </Button>- </DialogTrigger>- <DialogContent className="bg-[#1a1a1c] border-white/10 text-slate-200">- <DialogHeader>- <DialogTitle>{t("customFont.dialogTitle")}</DialogTitle>- <DialogDescription className="text-slate-400">- Add a custom font from Google Fonts to use in your annotations.- </DialogDescription>- </DialogHeader>-- <div className="space-y-4 mt-4">- <div className="space-y-2">- <Label htmlFor="import-url" className="text-slate-200">- {t("customFont.urlLabel")}- </Label>- <Input- id="import-url"- placeholder={t("customFont.urlPlaceholder")}- value={importUrl}- onChange={(e) => handleImportUrlChange(e.target.value)}- className="bg-white/5 border-white/10 text-slate-200"- />- <p className="text-xs text-slate-400">{t("customFont.urlHelp")}</p>- </div>-- <div className="space-y-2">- <Label htmlFor="font-name" className="text-slate-200">- {t("customFont.nameLabel")}- </Label>- <Input- id="font-name"- placeholder={t("customFont.namePlaceholder")}- value={fontName}- onChange={(e) => setFontName(e.target.value)}- className="bg-white/5 border-white/10 text-slate-200"- />- <p className="text-xs text-slate-400">{t("customFont.nameHelp")}</p>- </div>-- <div className="flex justify-end gap-2 mt-6">- <Button- variant="outline"- onClick={() => setOpen(false)}- className="bg-white/5 border-white/10 text-slate-200 hover:bg-white/10"- >- {tc("actions.cancel")}- </Button>- <Button- onClick={handleAdd}- disabled={loading}- className="bg-blue-600 hover:bg-blue-700 text-white"- >- {loading ? t("customFont.addingButton") : t("customFont.addButton")}- </Button>- </div>- </div>- </DialogContent>- </Dialog>- );-}diff --git a/src/components/video-editor/AnnotationOverlay.tsx b/src/components/video-editor/AnnotationOverlay.tsxdeleted file mode 100644index 09669d4e7..000000000--- a/src/components/video-editor/AnnotationOverlay.tsx+++ /dev/null@@ -1,648 +0,0 @@-import { type CSSProperties, type PointerEvent, useEffect, useRef, useState } from "react";-import { Rnd } from "react-rnd";-import { getTextAnimationState } from "@/lib/annotationTextAnimation";-import {- getBlurOverlayColor,- getMosaicGridOverlayColor,- getNormalizedMosaicBlockSize,-} from "@/lib/blurEffects";-import { cn } from "@/lib/utils";-import { getArrowComponent } from "./ArrowSvgs";-import {- type AnnotationRegion,- type BlurData,- DEFAULT_BLUR_BLOCK_SIZE,- DEFAULT_BLUR_DATA,- DEFAULT_BLUR_INTENSITY,-} from "./types";--const FREEHAND_POINT_THRESHOLD = 1;-type PreviewCanvasSource = {- width: number;- height: number;- clientWidth?: number;- clientHeight?: number;-};--function buildBlurPolygonClipPath(points: Array<{ x: number; y: number }>) {- if (points.length < 3) return undefined;- const polygon = points.map((point) => `${point.x}% ${point.y}%`).join(", ");- return `polygon(${polygon})`;-}--function buildBlurFreehandPath(points: Array<{ x: number; y: number }>, closed = true) {- if (closed ? points.length < 3 : points.length < 2) return null;- const [firstPoint, ...rest] = points;- const path = `M ${firstPoint.x} ${firstPoint.y} ${rest.map((point) => `L ${point.x} ${point.y}`).join(" ")}`;- return closed ? `${path} Z` : path;-}--interface AnnotationOverlayProps {- annotation: AnnotationRegion;- isSelected: boolean;- containerWidth: number;- containerHeight: number;- onPositionChange: (id: string, position: { x: number; y: number }) => void;- onSizeChange: (id: string, size: { width: number; height: number }) => void;- onBlurDataChange?: (id: string, blurData: BlurData) => void;- onBlurDataCommit?: () => void;- onClick: (id: string) => void;- zIndex: number;- isSelectedBoost: boolean; // raise z-index when selected, for easier editing- previewSourceCanvas?: PreviewCanvasSource | null;- previewFrameVersion?: number;- currentTimeMs: number;-}--export function AnnotationOverlay({- annotation,- isSelected,- containerWidth,- containerHeight,- onPositionChange,- onSizeChange,- onBlurDataChange,- onBlurDataCommit,- onClick,- zIndex,- isSelectedBoost,- previewSourceCanvas,- previewFrameVersion,- currentTimeMs,-}: AnnotationOverlayProps) {- const committedX = (annotation.position.x / 100) * containerWidth;- const committedY = (annotation.position.y / 100) * containerHeight;- const committedWidth = (annotation.size.width / 100) * containerWidth;- const committedHeight = (annotation.size.height / 100) * containerHeight;- const blurShape = annotation.type === "blur" ? (annotation.blurData?.shape ?? "rectangle") : null;- const isSelectedFreehandBlur = isSelected && blurShape === "freehand";- const isDraggingRef = useRef(false);- const isDrawingFreehandRef = useRef(false);- const freehandPointsRef = useRef<Array<{ x: number; y: number }>>([]);- const [isFreehandDrawing, setIsFreehandDrawing] = useState(false);- const [draftFreehandPoints, setDraftFreehandPoints] = useState<Array<{ x: number; y: number }>>(- [],- );- const [livePointerPoint, setLivePointerPoint] = useState<{ x: number; y: number } | null>(null);- const mosaicCanvasRef = useRef<HTMLCanvasElement | null>(null);- const blurType = "mosaic";- const blurOverlayColor =- annotation.type === "blur" ? getBlurOverlayColor(annotation.blurData) : "";- const mosaicGridOverlayColor =- annotation.type === "blur" ? getMosaicGridOverlayColor(annotation.blurData) : "";- const [liveRect, setLiveRect] = useState({- x: committedX,- y: committedY,- width: committedWidth,- height: committedHeight,- });-- useEffect(() => {- setLiveRect({- x: committedX,- y: committedY,- width: committedWidth,- height: committedHeight,- });- }, [committedHeight, committedWidth, committedX, committedY]);-- const { x, y, width, height } = liveRect;-- useEffect(() => {- if (annotation.type !== "blur") {- return;- }- void previewFrameVersion;-- const canvas = mosaicCanvasRef.current;- const sourceCanvas = previewSourceCanvas;- if (!canvas || !sourceCanvas) {- return;- }-- const sourceWidth = sourceCanvas.width;- const sourceHeight = sourceCanvas.height;- const sourceClientWidth = sourceCanvas.clientWidth || containerWidth || sourceWidth;- const sourceClientHeight = sourceCanvas.clientHeight || containerHeight || sourceHeight;- if (- sourceWidth <= 0 ||- sourceHeight <= 0 ||- sourceClientWidth <= 0 ||- sourceClientHeight <= 0- ) {- return;- }-- const drawWidth = Math.max(1, Math.round(width));- const drawHeight = Math.max(1, Math.round(height));- if (drawWidth <= 0 || drawHeight <= 0) {- return;- }-- canvas.width = drawWidth;- canvas.height = drawHeight;-- const context = canvas.getContext("2d", { willReadFrequently: true });- if (!context) {- return;- }-- const scaleX = sourceWidth / sourceClientWidth;- const scaleY = sourceHeight / sourceClientHeight;- const sourceX = Math.max(0, Math.floor(x * scaleX));- const sourceY = Math.max(0, Math.floor(y * scaleY));- const sourceSampleWidth = Math.max(1, Math.ceil(drawWidth * scaleX));- const sourceSampleHeight = Math.max(1, Math.ceil(drawHeight * scaleY));- const clampedSampleWidth = Math.max(1, Math.min(sourceSampleWidth, sourceWidth - sourceX));- const clampedSampleHeight = Math.max(1, Math.min(sourceSampleHeight, sourceHeight - sourceY));- const blockSize = getNormalizedMosaicBlockSize(annotation.blurData);- const downscaledWidth = Math.max(1, Math.round(drawWidth / blockSize));- const downscaledHeight = Math.max(1, Math.round(drawHeight / blockSize));- canvas.width = downscaledWidth;- canvas.height = downscaledHeight;-- context.clearRect(0, 0, downscaledWidth, downscaledHeight);- context.imageSmoothingEnabled = true;- context.drawImage(- sourceCanvas as CanvasImageSource,- sourceX,- sourceY,- clampedSampleWidth,- clampedSampleHeight,- 0,- 0,- downscaledWidth,- downscaledHeight,- );- }, [- annotation,- containerHeight,- containerWidth,- height,- previewFrameVersion,- previewSourceCanvas,- width,- x,- y,- ]);-- const renderArrow = () => {- const direction = annotation.figureData?.arrowDirection || "right";- const color = annotation.figureData?.color || "#34B27B";- const strokeWidth = annotation.figureData?.strokeWidth || 4;-- const ArrowComponent = getArrowComponent(direction);- return <ArrowComponent color={color} strokeWidth={strokeWidth} />;- };-- const normalizePoint = (event: PointerEvent<HTMLDivElement>) => {- const rect = event.currentTarget.getBoundingClientRect();- const x = ((event.clientX - rect.left) / rect.width) * 100;- const y = ((event.clientY - rect.top) / rect.height) * 100;- return {- x: Math.max(0, Math.min(100, x)),- y: Math.max(0, Math.min(100, y)),- };- };-- const appendFreehandPoint = (point: { x: number; y: number }) => {- const points = freehandPointsRef.current;- const lastPoint = points[points.length - 1];- if (!lastPoint) {- points.push(point);- return;- }- const dx = point.x - lastPoint.x;- const dy = point.y - lastPoint.y;- // Sample freehand points in annotation-space percent units to avoid overly dense paths.- if (Math.hypot(dx, dy) >= FREEHAND_POINT_THRESHOLD) {- points.push(point);- }- };-- const handleFreehandPointerDown = (event: PointerEvent<HTMLDivElement>) => {- if (- !isSelected ||- annotation.type !== "blur" ||- annotation.blurData?.shape !== "freehand" ||- !onBlurDataChange- ) {- return;- }- event.preventDefault();- event.stopPropagation();- event.currentTarget.setPointerCapture(event.pointerId);- isDrawingFreehandRef.current = true;- setIsFreehandDrawing(true);- const point = normalizePoint(event);- freehandPointsRef.current = [point];- setDraftFreehandPoints([point]);- setLivePointerPoint(point);- };-- const handleFreehandPointerMove = (event: PointerEvent<HTMLDivElement>) => {- if (!isDrawingFreehandRef.current) return;- event.preventDefault();- event.stopPropagation();- const point = normalizePoint(event);- setLivePointerPoint(point);- appendFreehandPoint(point);- setDraftFreehandPoints([...freehandPointsRef.current]);- };-- const finishFreehandPointer = (event: PointerEvent<HTMLDivElement>) => {- if (!isDrawingFreehandRef.current || !onBlurDataChange) return;- isDrawingFreehandRef.current = false;- setIsFreehandDrawing(false);- try {- event.currentTarget.releasePointerCapture(event.pointerId);- } catch {- // no-op if already released- }- const points = [...freehandPointsRef.current];- if (livePointerPoint) {- const last = points[points.length - 1];- if (!last || Math.hypot(last.x - livePointerPoint.x, last.y - livePointerPoint.y) > 0.001) {- points.push(livePointerPoint);- }- }- if (points.length >= 3) {- const closedPoints = [...points];- const first = closedPoints[0];- const last = closedPoints[closedPoints.length - 1];- if (Math.hypot(last.x - first.x, last.y - first.y) > 0.001) {- closedPoints.push({ ...first });- }- onBlurDataChange(annotation.id, {- ...(annotation.blurData || { ...DEFAULT_BLUR_DATA, shape: "freehand" }),- shape: "freehand",- freehandPoints: closedPoints,- });- setDraftFreehandPoints(closedPoints);- onBlurDataCommit?.();- }- setLivePointerPoint(null);- };-- const renderContent = () => {- switch (annotation.type) {- case "text": {- const animationState = getTextAnimationState(annotation, currentTimeMs);- const typewriterClip =- animationState.revealProgress < 1- ? `inset(0 ${100 - animationState.revealProgress * 100}% 0 0)`- : undefined;- return (- <div- className="w-full h-full flex items-center p-2 overflow-hidden"- style={{- justifyContent:- annotation.style.textAlign === "left"- ? "flex-start"- : annotation.style.textAlign === "right"- ? "flex-end"- : "center",- alignItems: "center",- }}- >- <span- style={{- color: annotation.style.color,- backgroundColor: annotation.style.backgroundColor,- fontSize: `${annotation.style.fontSize}px`,- fontFamily: annotation.style.fontFamily,- fontWeight: annotation.style.fontWeight,- fontStyle: annotation.style.fontStyle,- textDecoration: annotation.style.textDecoration,- textAlign: annotation.style.textAlign,- opacity: animationState.opacity,- transform: `translate(${animationState.translateX}px, ${animationState.translateY}px) scale(${animationState.scale})`,- transformOrigin: "center",- clipPath: typewriterClip,- WebkitClipPath: typewriterClip,- wordBreak: "break-word",- whiteSpace: "pre-wrap",- boxDecorationBreak: "clone",- WebkitBoxDecorationBreak: "clone",- padding: "0.1em 0.2em",- borderRadius: "4px",- lineHeight: "1.4",- }}- >- {annotation.content}- </span>- </div>- );- }-- case "image":- if (annotation.content && annotation.content.startsWith("data:image")) {- return (- <img- src={annotation.content}- alt="Annotation"- className="w-full h-full object-contain"- draggable={false}- />- );- }- return (- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">- No image- </div>- );-- case "figure":- if (!annotation.figureData) {- return (- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">- No arrow data- </div>- );- }-- return (- <div className="w-full h-full flex items-center justify-center p-2">{renderArrow()}</div>- );-- case "blur": {- const shape = annotation.blurData?.shape ?? "rectangle";- const blurIntensity = Math.max(- 1,- Math.round(annotation.blurData?.intensity ?? DEFAULT_BLUR_INTENSITY),- );- const blockSize = Math.max(- 1,- Math.round(annotation.blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE),- );- const activeFreehandPoints =- shape === "freehand"- ? isFreehandDrawing- ? draftFreehandPoints- : (annotation.blurData?.freehandPoints ?? [])- : [];- const drawingPoints =- isFreehandDrawing && livePointerPoint- ? (() => {- const last = activeFreehandPoints[activeFreehandPoints.length - 1];- if (!last) return [livePointerPoint];- const dx = livePointerPoint.x - last.x;- const dy = livePointerPoint.y - last.y;- return Math.hypot(dx, dy) > 0.01- ? [...activeFreehandPoints, livePointerPoint]- : activeFreehandPoints;- })()- : activeFreehandPoints;- const clipPath =- shape === "freehand" ? buildBlurPolygonClipPath(activeFreehandPoints) : undefined;- const freehandPath =- shape === "freehand"- ? buildBlurFreehandPath(- isFreehandDrawing ? drawingPoints : activeFreehandPoints,- !isFreehandDrawing,- )- : null;- const currentPointerPoint = isFreehandDrawing- ? livePointerPoint || drawingPoints[drawingPoints.length - 1] || null- : null;- const shapeBorderRadius = shape === "oval" ? "50%" : shape === "rectangle" ? "8px" : "0";- const shouldShowFreehandBlurFill =- shape !== "freehand" || (!!clipPath && !isFreehandDrawing);- const shapeMaskStyle: CSSProperties = {- borderRadius: shapeBorderRadius,- clipPath: isFreehandDrawing ? undefined : clipPath,- WebkitClipPath: isFreehandDrawing ? undefined : clipPath,- };- const isFreehandSelected = isSelectedFreehandBlur;- return (- <div className="w-full h-full relative">- <div- className="absolute inset-0 overflow-hidden"- style={{- ...shapeMaskStyle,- isolation: "isolate",- }}- >- <div- className="absolute inset-0"- style={{- ...shapeMaskStyle,- backdropFilter: blurType === "mosaic" ? "none" : `blur(${blurIntensity}px)`,- WebkitBackdropFilter: blurType === "mosaic" ? "none" : `blur(${blurIntensity}px)`,- backgroundColor: blurOverlayColor,- opacity: shouldShowFreehandBlurFill ? 1 : 0,- }}- />- {blurType === "mosaic" && shouldShowFreehandBlurFill && (- <canvas- ref={mosaicCanvasRef}- className="absolute inset-0 w-full h-full"- style={{- ...shapeMaskStyle,- imageRendering: "pixelated",- }}- />- )}- {blurType === "mosaic" && shouldShowFreehandBlurFill && (- <div- className="absolute inset-0 pointer-events-none"- style={{- ...shapeMaskStyle,- backgroundColor: blurOverlayColor,- }}- />- )}- {blurType === "mosaic" && (- <div- className="absolute inset-0 pointer-events-none"- style={{- ...shapeMaskStyle,- backgroundImage: `linear-gradient(${mosaicGridOverlayColor} 1px, transparent 1px), linear-gradient(90deg, ${mosaicGridOverlayColor} 1px, transparent 1px)`,- backgroundSize: `${blockSize}px ${blockSize}px`,- mixBlendMode: "screen",- opacity: 0.35,- }}- />- )}- {isSelected && shape !== "freehand" && (- <div- className="absolute inset-0 pointer-events-none border-2 border-[#34B27B]/80"- style={{ borderRadius: shapeBorderRadius }}- />- )}- </div>- {isSelected && shape === "freehand" && freehandPath && (- <svg- viewBox="0 0 100 100"- preserveAspectRatio="none"- className="absolute inset-0 pointer-events-none"- >- <path- d={freehandPath}- fill="none"- stroke="#34B27B"- strokeWidth="0.55"- strokeLinecap="round"- strokeLinejoin="round"- />- {currentPointerPoint && (- <circle- cx={currentPointerPoint.x}- cy={currentPointerPoint.y}- r="0.6"- fill="#34B27B"- />- )}- </svg>- )}- {isFreehandSelected && (- <div- className="absolute inset-0 cursor-crosshair"- onPointerDown={handleFreehandPointerDown}- onPointerMove={handleFreehandPointerMove}- onPointerUp={finishFreehandPointer}- onPointerCancel={finishFreehandPointer}- />- )}- </div>- );- }-- default:- return null;- }- };-- return (- <Rnd- position={{ x, y }}- size={{ width, height }}- onDragStart={() => {- isDraggingRef.current = true;- }}- onDrag={(_e, d) => {- setLiveRect((prev) => ({- ...prev,- x: d.x,- y: d.y,- }));- }}- onDragStop={(_e, d) => {- setLiveRect((prev) => ({- ...prev,- x: d.x,- y: d.y,- }));- const xPercent = (d.x / containerWidth) * 100;- const yPercent = (d.y / containerHeight) * 100;- onPositionChange(annotation.id, { x: xPercent, y: yPercent });-- // Delay clearing so the trailing click doesn't fire onClick- setTimeout(() => {- isDraggingRef.current = false;- }, 100);- }}- onResize={(_e, _direction, ref, _delta, position) => {- setLiveRect({- x: position.x,- y: position.y,- width: ref.offsetWidth,- height: ref.offsetHeight,- });- }}- onResizeStop={(_e, _direction, ref, _delta, position) => {- setLiveRect({- x: position.x,- y: position.y,- width: ref.offsetWidth,- height: ref.offsetHeight,- });- const xPercent = (position.x / containerWidth) * 100;- const yPercent = (position.y / containerHeight) * 100;- const widthPercent = (ref.offsetWidth / containerWidth) * 100;- const heightPercent = (ref.offsetHeight / containerHeight) * 100;- onPositionChange(annotation.id, { x: xPercent, y: yPercent });- onSizeChange(annotation.id, { width: widthPercent, height: heightPercent });- }}- onClick={() => {- if (isDraggingRef.current) return;- onClick(annotation.id);- }}- bounds="parent"- className={cn(- "cursor-move",- isSelected &&- annotation.type !== "blur" &&- "ring-2 ring-[#34B27B] ring-offset-2 ring-offset-transparent",- )}- style={{- zIndex: isSelectedBoost ? zIndex + 1000 : zIndex, // keep the selected annotation on top- pointerEvents: isSelected ? "auto" : "none",- border:- isSelected && annotation.type !== "blur" ? "2px solid rgba(52, 178, 123, 0.8)" : "none",- backgroundColor:- isSelected && annotation.type !== "blur" ? "rgba(52, 178, 123, 0.1)" : "transparent",- boxShadow:- isSelected && annotation.type !== "blur" ? "0 0 0 1px rgba(52, 178, 123, 0.35)" : "none",- }}- enableResizing={isSelected && !isSelectedFreehandBlur}- disableDragging={!isSelected || isSelectedFreehandBlur}- resizeHandleStyles={{- topLeft: {- width: "12px",- height: "12px",- backgroundColor: isSelected ? "white" : "transparent",- border: isSelected ? "2px solid #34B27B" : "none",- borderRadius: "50%",- left: "-6px",- top: "-6px",- cursor: "nwse-resize",- },- topRight: {- width: "12px",- height: "12px",- backgroundColor: isSelected ? "white" : "transparent",- border: isSelected ? "2px solid #34B27B" : "none",- borderRadius: "50%",- right: "-6px",- top: "-6px",- cursor: "nesw-resize",- },- bottomLeft: {- width: "12px",- height: "12px",- backgroundColor: isSelected ? "white" : "transparent",- border: isSelected ? "2px solid #34B27B" : "none",- borderRadius: "50%",- left: "-6px",- bottom: "-6px",- cursor: "nesw-resize",- },- bottomRight: {- width: "12px",- height: "12px",- backgroundColor: isSelected ? "white" : "transparent",- border: isSelected ? "2px solid #34B27B" : "none",- borderRadius: "50%",- right: "-6px",- bottom: "-6px",- cursor: "nwse-resize",- },- }}- >- <div- className={cn(- "w-full h-full",- annotation.type !== "blur" && "rounded-lg",- annotation.type === "text" && "bg-transparent",- annotation.type === "image" && "bg-transparent",- annotation.type === "figure" && "bg-transparent",- annotation.type === "blur" && "bg-transparent",- isSelected && annotation.type !== "blur" && "shadow-lg",- )}- >- {renderContent()}- </div>- </Rnd>- );-}diff --git a/src/components/video-editor/AnnotationSettingsPanel.tsx b/src/components/video-editor/AnnotationSettingsPanel.tsxdeleted file mode 100644index 91fee8ec8..000000000--- a/src/components/video-editor/AnnotationSettingsPanel.tsx+++ /dev/null@@ -1,671 +0,0 @@-import Block from "@uiw/react-color-block";-import {- AlignCenter,- AlignLeft,- AlignRight,- Bold,- ChevronDown,- Copy,- Image as ImageIcon,- Italic,- Trash2,- Type,- Underline,- Upload,-} from "lucide-react";-import { useEffect, useRef, useState } from "react";-import { toast } from "sonner";-import { Button } from "@/components/ui/button";-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { Slider } from "@/components/ui/slider";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";-import { useScopedT } from "@/contexts/I18nContext";-import { normalizeTextAnimation, TEXT_ANIMATION_OPTIONS } from "@/lib/annotationTextAnimation";-import { type CustomFont, getCustomFonts } from "@/lib/customFonts";-import { cn } from "@/lib/utils";-import ColorPicker from "../ui/color-picker";-import { AddCustomFontDialog } from "./AddCustomFontDialog";-import { getArrowComponent } from "./ArrowSvgs";-import {- type AnnotationRegion,- type AnnotationType,- type ArrowDirection,- type FigureData,-} from "./types";--interface AnnotationSettingsPanelProps {- annotation: AnnotationRegion;- onContentChange: (content: string) => void;- onTypeChange: (type: AnnotationType) => void;- onStyleChange: (style: Partial<AnnotationRegion["style"]>) => void;- onFigureDataChange?: (figureData: FigureData) => void;- onDuplicate?: () => void;- onDelete: () => void;-}--const FONT_FAMILIES: Array<- | { value: string; labelKey: string; name?: never }- | { value: string; labelKey?: never; name: string }-> = [- { value: "Inter", name: "Inter" },- { value: "system-ui, -apple-system, sans-serif", labelKey: "classic" },- { value: "Georgia, serif", labelKey: "editor" },- { value: "Impact, Arial Black, sans-serif", labelKey: "strong" },- { value: "Courier New, monospace", labelKey: "typewriter" },- { value: "Brush Script MT, cursive", labelKey: "deco" },- { value: "Arial, sans-serif", labelKey: "simple" },- { value: "Verdana, sans-serif", labelKey: "modern" },- { value: "Trebuchet MS, sans-serif", labelKey: "clean" },- { value: '"Plus Jakarta Sans", sans-serif', name: "Plus Jakarta Sans" },- { value: '"Space Grotesk", sans-serif', name: "Space Grotesk" },- { value: '"DM Sans", sans-serif', name: "DM Sans" },- { value: "Sora, sans-serif", name: "Sora" },- { value: "Manrope, sans-serif", name: "Manrope" },- { value: '"IBM Plex Sans", sans-serif', name: "IBM Plex Sans" },- { value: '"Playfair Display", Georgia, serif', name: "Playfair Display" },- { value: "Merriweather, Georgia, serif", name: "Merriweather" },- { value: "Lora, Georgia, serif", name: "Lora" },- { value: '"IBM Plex Mono", monospace', name: "IBM Plex Mono" },- { value: '"Fira Code", monospace', name: "Fira Code" },- { value: '"Bebas Neue", sans-serif', name: "Bebas Neue" },- { value: "Oswald, sans-serif", name: "Oswald" },- { value: "Caveat, cursive", name: "Caveat" },- { value: '"Permanent Marker", cursive', name: "Permanent Marker" },-];--const FONT_SIZES = [12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 96, 128];--export function AnnotationSettingsPanel({- annotation,- onContentChange,- onTypeChange,- onStyleChange,- onFigureDataChange,- onDuplicate,- onDelete,-}: AnnotationSettingsPanelProps) {- const t = useScopedT("settings");- const fileInputRef = useRef<HTMLInputElement>(null);- const [customFonts, setCustomFonts] = useState<CustomFont[]>([]);- const fontStyleLabels: Record<string, string> = {- classic: t("fontStyles.classic"),- editor: t("fontStyles.editor"),- strong: t("fontStyles.strong"),- typewriter: t("fontStyles.typewriter"),- deco: t("fontStyles.deco"),- simple: t("fontStyles.simple"),- modern: t("fontStyles.modern"),- clean: t("fontStyles.clean"),- };- const getFontLabel = (font: (typeof FONT_FAMILIES)[number]) =>- font.labelKey ? fontStyleLabels[font.labelKey] : font.name;-- useEffect(() => {- setCustomFonts(getCustomFonts());- }, []);-- const colorPalette = [- "#FF0000", // Red- "#FFD700", // Yellow/Gold- "#00FF00", // Green- "#FFFFFF", // White- "#0000FF", // Blue- "#FF6B00", // Orange- "#9B59B6", // Purple- "#E91E63", // Pink- "#00BCD4", // Cyan- "#FF5722", // Deep Orange- "#8BC34A", // Light Green- "#FFC107", // Amber- "#34B27B", // Brand Green- "#000000", // Black- "#607D8B", // Blue Grey- "#795548", // Brown- ];-- const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {- const files = event.target.files;- if (!files || files.length === 0) return;-- const file = files[0];-- const validTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"];- if (!validTypes.includes(file.type)) {- toast.error(t("annotation.invalidImageType"), {- description: t("annotation.imageFormatsOnly"),- });- event.target.value = "";- return;- }-- const reader = new FileReader();-- reader.onload = (e) => {- const dataUrl = e.target?.result as string;- if (dataUrl) {- onContentChange(dataUrl);- toast.success(t("annotation.imageUploadSuccess"));- }- };-- reader.onerror = () => {- toast.error(t("imageUpload.failedToUpload"), {- description: t("imageUpload.errorReading"),- });- };-- reader.readAsDataURL(file);- event.target.value = "";- };-- return (- <div className="min-w-0 p-4 flex flex-col h-full overflow-y-auto custom-scrollbar">- <div className="mb-3">- <div className="mb-4">- <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500">- {t("annotation.active")}- </span>- <div className="mt-1 text-xl font-semibold text-slate-100">{t("annotation.title")}</div>- </div>-- {/* Type Selector */}- <Tabs- value={annotation.type}- onValueChange={(value) => onTypeChange(value as AnnotationType)}- className="mb-4"- >- <TabsList className="mb-4 bg-white/[0.035] border border-white/[0.06] p-0.5 w-full grid grid-cols-3 h-9 rounded-xl">- <TabsTrigger- value="text"- className="data-[state=active]:bg-[#34B27B] data-[state=active]:text-white text-slate-400 rounded-lg transition-all gap-1.5 text-[11px]"- >- <Type className="w-4 h-4" />- {t("annotation.typeText")}- </TabsTrigger>- <TabsTrigger- value="image"- className="data-[state=active]:bg-[#34B27B] data-[state=active]:text-white text-slate-400 rounded-lg transition-all gap-1.5 text-[11px]"- >- <ImageIcon className="w-4 h-4" />- {t("annotation.typeImage")}- </TabsTrigger>- <TabsTrigger- value="figure"- className="data-[state=active]:bg-[#34B27B] data-[state=active]:text-white text-slate-400 rounded-lg transition-all gap-1.5 text-[11px]"- >- <svg- className="w-4 h-4"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M4 12h16m0 0l-6-6m6 6l-6 6" strokeLinecap="round" strokeLinejoin="round" />- </svg>- {t("annotation.typeArrow")}- </TabsTrigger>- </TabsList>-- {/* Text Content */}- <TabsContent value="text" className="mt-0 space-y-4">- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.textContent")}- </label>- <textarea- value={annotation.textContent || annotation.content}- onChange={(e) => onContentChange(e.target.value)}- placeholder={t("annotation.textPlaceholder")}- rows={5}- className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-slate-200 text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-[#34B27B] focus:border-transparent resize-none"- />- </div>-- {/* Styling Controls */}- <div className="space-y-4">- {/* Font Family & Size */}- <div className="grid grid-cols-2 gap-2">- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.fontStyle")}- </label>- <Select- value={annotation.style.fontFamily}- onValueChange={(value) => onStyleChange({ fontFamily: value })}- >- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">- <SelectValue placeholder={t("annotation.selectStyle")} />- </SelectTrigger>- <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[300px]">- {FONT_FAMILIES.map((font) => (- <SelectItem- key={font.value}- value={font.value}- style={{ fontFamily: font.value }}- >- {getFontLabel(font)}- </SelectItem>- ))}- {customFonts.length > 0 && (- <>- <div className="px-2 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-wider">- {t("annotation.customFonts")}- </div>- {customFonts.map((font) => (- <SelectItem- key={font.id}- value={font.fontFamily}- style={{ fontFamily: font.fontFamily }}- >- {font.name}- </SelectItem>- ))}- </>- )}- </SelectContent>- </Select>- </div>- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.size")}- </label>- <Select- value={annotation.style.fontSize.toString()}- onValueChange={(value) => onStyleChange({ fontSize: parseInt(value) })}- >- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">- <SelectValue placeholder={t("annotation.size")} />- </SelectTrigger>- <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[200px]">- {FONT_SIZES.map((size) => (- <SelectItem key={size} value={size.toString()}>- {size}px- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>-- {/* Add Custom Font Button */}- <div>- <AddCustomFontDialog- onFontAdded={(font) => {- setCustomFonts(getCustomFonts());- onStyleChange({ fontFamily: font.fontFamily });- }}- />- </div>-- <div>- <label className="mb-2 block text-xs font-medium text-slate-200">- {t("annotation.textAnimation")}- </label>- <Select- value={normalizeTextAnimation(annotation.style.textAnimation)}- onValueChange={(value) =>- onStyleChange({ textAnimation: normalizeTextAnimation(value) })- }- >- <SelectTrigger className="h-9 w-full border-white/10 bg-white/5 text-xs text-slate-200">- <SelectValue placeholder={t("annotation.selectAnimation")} />- </SelectTrigger>- <SelectContent className="max-h-[240px] border-white/10 bg-[#1a1a1c] text-slate-200">- {TEXT_ANIMATION_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- {t(option.translationKey)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* Formatting Toggles */}- <div className="flex items-center justify-between gap-2">- <ToggleGroup- type="multiple"- className="justify-start bg-white/5 p-1 rounded-lg border border-white/5"- >- <ToggleGroupItem- value="bold"- aria-label="Toggle bold"- data-state={annotation.style.fontWeight === "bold" ? "on" : "off"}- onClick={() =>- onStyleChange({- fontWeight: annotation.style.fontWeight === "bold" ? "normal" : "bold",- })- }- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <Bold className="h-4 w-4" />- </ToggleGroupItem>- <ToggleGroupItem- value="italic"- aria-label="Toggle italic"- data-state={annotation.style.fontStyle === "italic" ? "on" : "off"}- onClick={() =>- onStyleChange({- fontStyle: annotation.style.fontStyle === "italic" ? "normal" : "italic",- })- }- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <Italic className="h-4 w-4" />- </ToggleGroupItem>- <ToggleGroupItem- value="underline"- aria-label="Toggle underline"- data-state={annotation.style.textDecoration === "underline" ? "on" : "off"}- onClick={() =>- onStyleChange({- textDecoration:- annotation.style.textDecoration === "underline" ? "none" : "underline",- })- }- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <Underline className="h-4 w-4" />- </ToggleGroupItem>- </ToggleGroup>-- <ToggleGroup- type="single"- value={annotation.style.textAlign}- className="justify-start bg-white/5 p-1 rounded-lg border border-white/5"- >- <ToggleGroupItem- value="left"- aria-label="Align left"- onClick={() => onStyleChange({ textAlign: "left" })}- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <AlignLeft className="h-4 w-4" />- </ToggleGroupItem>- <ToggleGroupItem- value="center"- aria-label="Align center"- onClick={() => onStyleChange({ textAlign: "center" })}- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <AlignCenter className="h-4 w-4" />- </ToggleGroupItem>- <ToggleGroupItem- value="right"- aria-label="Align right"- onClick={() => onStyleChange({ textAlign: "right" })}- className="h-8 w-8 data-[state=on]:bg-[#34B27B] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"- >- <AlignRight className="h-4 w-4" />- </ToggleGroupItem>- </ToggleGroup>- </div>-- {/* Colors */}- <div className="grid grid-cols-2 gap-4">- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.textColor")}- </label>- <Popover>- <PopoverTrigger asChild>- <Button- variant="outline"- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"- >- <div- className="w-4 h-4 rounded-full border border-white/20"- style={{ backgroundColor: annotation.style.color }}- />- <span className="text-xs text-slate-300 truncate flex-1 text-left">- {annotation.style.color}- </span>- <ChevronDown className="h-3 w-3 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent- side="top"- className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl"- >- <ColorPicker- selectedColor={annotation.style.color}- colorPalette={colorPalette}- translations={{- colorWheel: t("annotation.colorWheel"),- colorPalette: t("annotation.colorPalette"),- }}- onUpdateColor={(color) => {- onStyleChange({ color: color });- }}- />- </PopoverContent>- </Popover>- </div>- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.background")}- </label>- <Popover>- <PopoverTrigger asChild>- <Button- variant="outline"- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"- >- <div className="w-4 h-4 rounded-full border border-white/20 relative overflow-hidden">- <div className="absolute inset-0 checkerboard-bg opacity-50" />- <div- className="absolute inset-0"- style={{ backgroundColor: annotation.style.backgroundColor }}- />- </div>- <span className="text-xs text-slate-300 truncate flex-1 text-left">- {annotation.style.backgroundColor === "transparent"- ? t("annotation.none")- : t("annotation.color")}- </span>- <ChevronDown className="h-3 w-3 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent- side="top"- className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl"- >- <ColorPicker- selectedColor={annotation.style.backgroundColor}- colorPalette={colorPalette}- translations={{- colorWheel: t("annotation.colorWheel"),- colorPalette: t("annotation.colorPalette"),- clearBackground: t("annotation.clearBackground"),- }}- clearBackgroundOption={true}- onUpdateColor={(color) => {- onStyleChange({ backgroundColor: color });- }}- />- </PopoverContent>- </Popover>- </div>- </div>- </div>- </TabsContent>-- {/* Image Upload */}- <TabsContent value="image" className="mt-0 space-y-4">- <input- type="file"- ref={fileInputRef}- onChange={handleImageUpload}- accept=".jpg,.jpeg,.png,.gif,.webp,image/*"- className="hidden"- />- <Button- onClick={() => fileInputRef.current?.click()}- variant="outline"- className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#34B27B] hover:text-white hover:border-[#34B27B] transition-all py-8"- >- <Upload className="w-5 h-5" />- {t("annotation.uploadImage")}- </Button>-- {annotation.content && annotation.content.startsWith("data:image") && (- <div className="rounded-lg border border-white/10 overflow-hidden bg-white/5 p-2">- <img- src={annotation.content}- alt="Uploaded annotation"- className="w-full h-auto rounded-md"- />- </div>- )}-- <p className="text-xs text-slate-500 text-center leading-relaxed">- {t("annotation.supportedFormats")}- </p>- </TabsContent>-- <TabsContent value="figure" className="mt-0 space-y-4">- <div>- <label className="text-xs font-medium text-slate-200 mb-3 block">- {t("annotation.arrowDirection")}- </label>- <div className="grid grid-cols-4 gap-2">- {(- [- "up",- "down",- "left",- "right",- "up-right",- "up-left",- "down-right",- "down-left",- ] as ArrowDirection[]- ).map((direction) => {- const ArrowComponent = getArrowComponent(direction);- return (- <button- key={direction}- onClick={() => {- const newFigureData: FigureData = {- ...annotation.figureData!,- arrowDirection: direction,- };- onFigureDataChange?.(newFigureData);- }}- className={cn(- "h-16 rounded-lg border flex items-center justify-center transition-all p-2",- annotation.figureData?.arrowDirection === direction- ? "bg-[#34B27B] border-[#34B27B]"- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20",- )}- >- <ArrowComponent- color={- annotation.figureData?.arrowDirection === direction- ? "#ffffff"- : "#94a3b8"- }- strokeWidth={3}- />- </button>- );- })}- </div>- </div>-- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.strokeWidth", {- width: String(annotation.figureData?.strokeWidth || 4),- })}- </label>- <Slider- value={[annotation.figureData?.strokeWidth || 4]}- onValueChange={([value]) => {- const newFigureData: FigureData = {- ...annotation.figureData!,- strokeWidth: value,- };- onFigureDataChange?.(newFigureData);- }}- min={1}- max={6}- step={1}- className="w-full"- />- </div>-- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- {t("annotation.arrowColor")}- </label>- <Popover>- <PopoverTrigger asChild>- <Button- variant="outline"- className="w-full h-10 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10"- >- <div- className="w-5 h-5 rounded-full border border-white/20"- style={{ backgroundColor: annotation.figureData?.color || "#34B27B" }}- />- <span className="text-xs text-slate-300 truncate flex-1 text-left">- {annotation.figureData?.color || "#34B27B"}- </span>- <ChevronDown className="h-3 w-3 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">- <Block- color={annotation.figureData?.color || "#34B27B"}- colors={colorPalette}- onChange={(color) => {- const newFigureData: FigureData = {- ...annotation.figureData!,- color: color.hex,- };- onFigureDataChange?.(newFigureData);- }}- style={{- borderRadius: "8px",- }}- />- </PopoverContent>- </Popover>- </div>- </TabsContent>- </Tabs>-- <div className="mt-4 grid grid-cols-2 gap-2">- <Button- onClick={() => onDuplicate?.()}- variant="outline"- size="sm"- disabled={!onDuplicate}- className="w-full gap-2 bg-white/5 text-slate-200 border border-white/10 hover:bg-white/10 hover:border-white/20 transition-all"- >- <Copy className="w-4 h-4" />- Duplicate- </Button>-- <Button- onClick={onDelete}- variant="destructive"- size="sm"- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all"- >- <Trash2 className="w-4 h-4" />- {t("annotation.deleteAnnotation")}- </Button>- </div>- </div>- </div>- );-}diff --git a/src/components/video-editor/ArrowSvgs.tsx b/src/components/video-editor/ArrowSvgs.tsxdeleted file mode 100644index 5078b844e..000000000--- a/src/components/video-editor/ArrowSvgs.tsx+++ /dev/null@@ -1,200 +0,0 @@-import type { ArrowDirection } from "./types";--interface ArrowSvgProps {- color: string;- strokeWidth: number;- className?: string;-}--/**- * Inline SVG arrows for 8 directions. Pure paths (not icon fonts) so export can replicate them.- */--export function ArrowUp({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 50 20 L 50 80 M 50 20 L 35 35 M 50 20 L 65 35"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDown({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 50 20 L 50 80 M 50 80 L 35 65 M 50 80 L 65 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 80 50 L 20 50 M 20 50 L 35 35 M 20 50 L 35 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 20 50 L 80 50 M 80 50 L 65 35 M 80 50 L 65 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowUpRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 25 75 L 75 25 M 75 25 L 60 30 M 75 25 L 70 40"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowUpLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 75 75 L 25 25 M 25 25 L 40 30 M 25 25 L 30 40"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDownRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 25 25 L 75 75 M 75 75 L 70 60 M 75 75 L 60 70"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDownLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 75 25 L 25 75 M 25 75 L 30 60 M 25 75 L 40 70"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function getArrowComponent(direction: ArrowDirection) {- switch (direction) {- case "up":- return ArrowUp;- case "down":- return ArrowDown;- case "left":- return ArrowLeft;- case "right":- return ArrowRight;- case "up-right":- return ArrowUpRight;- case "up-left":- return ArrowUpLeft;- case "down-right":- return ArrowDownRight;- case "down-left":- return ArrowDownLeft;- }-}diff --git a/src/components/video-editor/BlurSettingsPanel.tsx b/src/components/video-editor/BlurSettingsPanel.tsxdeleted file mode 100644index 7ead89460..000000000--- a/src/components/video-editor/BlurSettingsPanel.tsx+++ /dev/null@@ -1,193 +0,0 @@-import { Trash2 } from "lucide-react";-import { Button } from "@/components/ui/button";-import { Slider } from "@/components/ui/slider";-import { useScopedT } from "@/contexts/I18nContext";-import { getBlurOverlayColor } from "@/lib/blurEffects";-import { cn } from "@/lib/utils";-import {- type AnnotationRegion,- type BlurColor,- type BlurData,- type BlurShape,- DEFAULT_BLUR_BLOCK_SIZE,- DEFAULT_BLUR_DATA,- MAX_BLUR_BLOCK_SIZE,- MIN_BLUR_BLOCK_SIZE,-} from "./types";--interface BlurSettingsPanelProps {- blurRegion: AnnotationRegion;- onBlurDataChange: (blurData: BlurData) => void;- onBlurDataCommit?: () => void;- onDelete: () => void;-}--export function BlurSettingsPanel({- blurRegion,- onBlurDataChange,- onBlurDataCommit,- onDelete,-}: BlurSettingsPanelProps) {- const t = useScopedT("settings");-- const blurShapeOptions: Array<{ value: BlurShape; labelKey: string }> = [- { value: "rectangle", labelKey: "blurShapeRectangle" },- { value: "oval", labelKey: "blurShapeOval" },- ];- const blurColorOptions: Array<{ value: BlurColor; labelKey: string }> = [- { value: "white", labelKey: "blurColorWhite" },- { value: "black", labelKey: "blurColorBlack" },- ];-- return (- <div className="min-w-0 p-4 flex flex-col h-full overflow-y-auto custom-scrollbar">- <div className="mb-3">- <div className="mb-4">- <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500">- {t("annotation.blurTypeMosaic")}- </span>- <div className="mt-1 text-xl font-semibold text-slate-100">- {t("annotation.typeBlur")}- </div>- </div>-- <div className="grid grid-cols-2 gap-2">- {blurShapeOptions.map((shape) => {- const activeShape = blurRegion.blurData?.shape || DEFAULT_BLUR_DATA.shape;- const isActive = activeShape === shape.value;- return (- <button- key={shape.value}- onClick={() => {- const nextBlurData: BlurData = {- ...DEFAULT_BLUR_DATA,- ...blurRegion.blurData,- type: "mosaic",- shape: shape.value,- };- onBlurDataChange(nextBlurData);- requestAnimationFrame(() => {- onBlurDataCommit?.();- });- }}- className={cn(- "h-12 rounded-lg border flex items-center justify-center transition-all p-2 gap-2",- isActive- ? "bg-[#34B27B] border-[#34B27B]"- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20",- )}- >- {shape.value === "rectangle" && (- <div- className={cn(- "w-8 h-5 border-2 rounded-sm",- isActive ? "border-white" : "border-slate-400",- )}- />- )}- {shape.value === "oval" && (- <div- className={cn(- "w-8 h-5 border-2 rounded-full",- isActive ? "border-white" : "border-slate-400",- )}- />- )}- <span className="text-[10px] leading-none font-medium">- {t(`annotation.${shape.labelKey}`)}- </span>- </button>- );- })}- </div>-- <div className="mt-4">- <label className="text-xs font-medium text-slate-300 mb-2 block">- {t("annotation.blurColor")}- </label>- <div className="grid grid-cols-2 gap-2">- {blurColorOptions.map((option) => {- const activeColor = blurRegion.blurData?.color ?? DEFAULT_BLUR_DATA.color;- const isActive = activeColor === option.value;- return (- <button- key={option.value}- onClick={() => {- const nextBlurData: BlurData = {- ...DEFAULT_BLUR_DATA,- ...blurRegion.blurData,- type: "mosaic",- color: option.value,- };- onBlurDataChange(nextBlurData);- requestAnimationFrame(() => {- onBlurDataCommit?.();- });- }}- className={cn(- "h-10 rounded-lg border flex items-center gap-2 px-3 transition-all",- isActive- ? "bg-[#34B27B] border-[#34B27B]"- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20",- )}- >- <div- className="w-4 h-4 rounded-full border border-white/20"- style={{- backgroundColor: getBlurOverlayColor({- ...DEFAULT_BLUR_DATA,- ...blurRegion.blurData,- color: option.value,- }),- }}- />- <span className="text-xs text-slate-200">- {t(`annotation.${option.labelKey}`)}- </span>- </button>- );- })}- </div>- </div>-- <div className="mt-4 p-3 rounded-lg editor-control-surface">- <div className="flex items-center justify-between mb-2">- <span className="text-xs font-medium text-slate-300">- {t("annotation.mosaicBlockSize")}- </span>- <span className="text-[10px] text-slate-400 font-mono">- {Math.round(blurRegion.blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE)}- px- </span>- </div>- <Slider- value={[blurRegion.blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE]}- onValueChange={(values) => {- onBlurDataChange({- ...DEFAULT_BLUR_DATA,- ...blurRegion.blurData,- type: "mosaic",- blockSize: values[0],- });- }}- onValueCommit={() => onBlurDataCommit?.()}- min={MIN_BLUR_BLOCK_SIZE}- max={MAX_BLUR_BLOCK_SIZE}- step={1}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>-- <Button- onClick={onDelete}- variant="destructive"- size="sm"- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all mt-4"- >- <Trash2 className="w-4 h-4" />- {t("annotation.deleteAnnotation")}- </Button>- </div>- </div>- );-}diff --git a/src/components/video-editor/CropControl.tsx b/src/components/video-editor/CropControl.tsxdeleted file mode 100644index faedf1cfb..000000000--- a/src/components/video-editor/CropControl.tsx+++ /dev/null@@ -1,253 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { cn } from "@/lib/utils";-import { type AspectRatio } from "@/utils/aspectRatioUtils";-import { DEFAULT_SOURCE_DIMENSIONS } from "./editorDefaults";--interface CropRegion {- x: number; // 0-1 normalized- y: number; // 0-1 normalized- width: number; // 0-1 normalized- height: number; // 0-1 normalized-}--interface CropControlProps {- videoElement: HTMLVideoElement | null;- cropRegion: CropRegion;- onCropChange: (region: CropRegion) => void;- aspectRatio: AspectRatio;-}--type DragHandle = "top" | "right" | "bottom" | "left" | "move" | null;--export function CropControl({ videoElement, cropRegion, onCropChange }: CropControlProps) {- const canvasRef = useRef<HTMLCanvasElement>(null);- const containerRef = useRef<HTMLDivElement>(null);- const [isDragging, setIsDragging] = useState<DragHandle>(null);- const [dragStart, setDragStart] = useState({ x: 0, y: 0 });- const [initialCrop, setInitialCrop] = useState<CropRegion>(cropRegion);-- useEffect(() => {- if (!videoElement || !canvasRef.current) return;-- const canvas = canvasRef.current;- const ctx = canvas.getContext("2d", { alpha: false });- if (!ctx) return;-- canvas.width = videoElement.videoWidth || DEFAULT_SOURCE_DIMENSIONS.width;- canvas.height = videoElement.videoHeight || DEFAULT_SOURCE_DIMENSIONS.height;-- const draw = () => {- if (videoElement.readyState >= 2) {- ctx.clearRect(0, 0, canvas.width, canvas.height);- ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);- }- requestAnimationFrame(draw);- };-- const rafId = requestAnimationFrame(draw);- return () => cancelAnimationFrame(rafId);- }, [videoElement]);-- const getContainerRect = () => {- return (- containerRef.current?.getBoundingClientRect() || { width: 0, height: 0, left: 0, top: 0 }- );- };-- const handlePointerDown = (e: React.PointerEvent, handle: DragHandle) => {- e.stopPropagation();- e.preventDefault();- setIsDragging(handle);- const rect = getContainerRect();- setDragStart({- x: (e.clientX - rect.left) / rect.width,- y: (e.clientY - rect.top) / rect.height,- });- setInitialCrop(cropRegion);-- e.currentTarget.setPointerCapture(e.pointerId);- };-- const handlePointerMove = (e: React.PointerEvent) => {- if (!isDragging) return;-- const rect = getContainerRect();- const currentX = (e.clientX - rect.left) / rect.width;- const currentY = (e.clientY - rect.top) / rect.height;- const deltaX = currentX - dragStart.x;- const deltaY = currentY - dragStart.y;-- let newCrop = { ...initialCrop };-- switch (isDragging) {- case "top": {- const newY = Math.max(0, initialCrop.y + deltaY);- const bottom = initialCrop.y + initialCrop.height;- newCrop.y = Math.min(newY, bottom - 0.1);- newCrop.height = bottom - newCrop.y;- break;- }- case "bottom":- newCrop.height = Math.max(0.1, Math.min(initialCrop.height + deltaY, 1 - initialCrop.y));- break;- case "left": {- const newX = Math.max(0, initialCrop.x + deltaX);- const right = initialCrop.x + initialCrop.width;- newCrop.x = Math.min(newX, right - 0.1);- newCrop.width = right - newCrop.x;- break;- }- case "right":- newCrop.width = Math.max(0.1, Math.min(initialCrop.width + deltaX, 1 - initialCrop.x));- break;- case "move": {- newCrop.x = Math.max(0, Math.min(initialCrop.x + deltaX, 1 - initialCrop.width));- newCrop.y = Math.max(0, Math.min(initialCrop.y + deltaY, 1 - initialCrop.height));- break;- }- }-- onCropChange(newCrop);- };-- const handlePointerUp = (e: React.PointerEvent) => {- if (isDragging) {- try {- e.currentTarget.releasePointerCapture(e.pointerId);- } catch {- // Pointer may already be released; ignore.- }- }- setIsDragging(null);- };-- const cropPixelX = cropRegion.x * 100;- const cropPixelY = cropRegion.y * 100;- const cropPixelWidth = cropRegion.width * 100;- const cropPixelHeight = cropRegion.height * 100;- const videoAspectRatio = videoElement- ? videoElement.videoWidth / videoElement.videoHeight- : 16 / 9;- const isVideoPortrait = videoAspectRatio < 1;- const maxContainerWidth = isVideoPortrait ? "40vw" : "75vw";- const maxContainerHeight = "75vh";-- return (- <div className="w-full p-8">- <div- ref={containerRef}- className="relative w-full bg-black rounded-lg overflow-visible cursor-default select-none shadow-2xl"- style={{- aspectRatio: videoAspectRatio,- maxWidth: maxContainerWidth,- maxHeight: maxContainerHeight,- margin: "0 auto",- }}- onPointerMove={handlePointerMove}- onPointerUp={handlePointerUp}- onPointerLeave={handlePointerUp}- >- <canvas- ref={canvasRef}- className="w-full h-full rounded-lg"- style={{ imageRendering: "auto" }}- />-- <div className="absolute inset-0 pointer-events-none" style={{ transition: "none" }}>- <svg- width="100%"- height="100%"- className="absolute inset-0"- style={{ transition: "none" }}- >- <defs>- <mask id="cropMask">- <rect width="100%" height="100%" fill="white" />- <rect- x={`${cropPixelX}%`}- y={`${cropPixelY}%`}- width={`${cropPixelWidth}%`}- height={`${cropPixelHeight}%`}- fill="black"- style={{ transition: "none" }}- />- </mask>- </defs>- <rect- width="100%"- height="100%"- fill="black"- fillOpacity="0.6"- mask="url(#cropMask)"- style={{ transition: "none" }}- />- </svg>- </div>-- <div- className="absolute z-10 pointer-events-auto cursor-move"- style={{- left: `${cropPixelX}%`,- top: `${cropPixelY}%`,- width: `${cropPixelWidth}%`,- height: `${cropPixelHeight}%`,- transition: "none",- }}- onPointerDown={(e) => handlePointerDown(e, "move")}- />-- <div- className={cn("absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#34B27B]")}- style={{- left: `${cropPixelX}%`,- top: `${cropPixelY}%`,- width: `${cropPixelWidth}%`,- transform: "translateY(-50%)",- willChange: "transform",- transition: "none",- }}- onPointerDown={(e) => handlePointerDown(e, "top")}- />-- <div- className={cn("absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#34B27B]")}- style={{- left: `${cropPixelX}%`,- top: `${cropPixelY + cropPixelHeight}%`,- width: `${cropPixelWidth}%`,- transform: "translateY(-50%)",- willChange: "transform",- transition: "none",- }}- onPointerDown={(e) => handlePointerDown(e, "bottom")}- />-- <div- className={cn("absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#34B27B]")}- style={{- left: `${cropPixelX}%`,- top: `${cropPixelY}%`,- height: `${cropPixelHeight}%`,- transform: "translateX(-50%)",- willChange: "transform",- transition: "none",- }}- onPointerDown={(e) => handlePointerDown(e, "left")}- />-- <div- className={cn("absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#34B27B]")}- style={{- left: `${cropPixelX + cropPixelWidth}%`,- top: `${cropPixelY}%`,- height: `${cropPixelHeight}%`,- transform: "translateX(-50%)",- willChange: "transform",- transition: "none",- }}- onPointerDown={(e) => handlePointerDown(e, "right")}- />- </div>- </div>- );-}diff --git a/src/components/video-editor/EditorEmptyState.tsx b/src/components/video-editor/EditorEmptyState.tsxdeleted file mode 100644index 2a5c49547..000000000--- a/src/components/video-editor/EditorEmptyState.tsx+++ /dev/null@@ -1,209 +0,0 @@-import { AlertCircle, Film, FolderOpen, Upload, X } from "lucide-react";-import { useCallback, useRef, useState } from "react";-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { useScopedT } from "@/contexts/I18nContext";-import { getProjectFolder, parentDirectoryOf, saveUserPreferences } from "@/lib/userPreferences";-import { nativeBridgeClient } from "@/native";--interface EditorEmptyStateProps {- onVideoImported: (videoPath: string) => void;- /** Called with the loaded project data; handles both button click and drag-drop */- onProjectOpened: (project: unknown, path: string | null) => void;-}--type DropError = "unsupported-format" | "load-failed" | null;--export function EditorEmptyState({ onVideoImported, onProjectOpened }: EditorEmptyStateProps) {- const te = useScopedT("editor");- const tc = useScopedT("common");- const [isDraggingOver, setIsDraggingOver] = useState(false);- const [dropError, setDropError] = useState<DropError>(null);- // Freeze the last non-null error type so dialog content doesn't snap to the else-branch- // during the closing animation (same pattern as UnsavedChangesDialog).- const lastDropErrorRef = useRef<Exclude<DropError, null>>("unsupported-format");- if (dropError !== null) {- lastDropErrorRef.current = dropError;- }-- const handleImportVideo = useCallback(async () => {- const result = await window.electronAPI.openVideoFilePicker();- if (result.canceled || !result.success || !result.path) return;-- const setResult = await nativeBridgeClient.project.setCurrentVideoPath(result.path);- if (!setResult.success) return;-- onVideoImported(result.path);- }, [onVideoImported]);-- const handleLoadProject = useCallback(async () => {- const result = await nativeBridgeClient.project.loadProjectFile(getProjectFolder());- if (result.canceled || !result.success || !result.project) return;- if (result.path) {- const folder = parentDirectoryOf(result.path);- if (folder) {- saveUserPreferences({ projectFolder: folder });- }- }- onProjectOpened(result.project, result.path ?? null);- }, [onProjectOpened]);-- const handleDragOver = useCallback((e: React.DragEvent) => {- e.preventDefault();- if (e.dataTransfer.items.length > 0) {- setIsDraggingOver(true);- }- }, []);-- const handleDragLeave = useCallback((e: React.DragEvent) => {- if (!e.currentTarget.contains(e.relatedTarget as Node)) {- setIsDraggingOver(false);- }- }, []);-- const handleDrop = useCallback(- async (e: React.DragEvent) => {- e.preventDefault();- setIsDraggingOver(false);-- const files = Array.from(e.dataTransfer.files);- if (files.length === 0) return;-- const projectFile = files.find((f) => f.name.endsWith(".openscreen"));- if (!projectFile) {- setDropError("unsupported-format");- return;- }-- // Use Electron's webUtils.getPathForFile; File.path was removed in Electron 32+- let filePath: string;- try {- filePath = window.electronAPI.getPathForFile(projectFile);- } catch {- setDropError("load-failed");- return;- }- if (!filePath) {- setDropError("load-failed");- return;- }-- let result: Awaited<ReturnType<typeof window.electronAPI.loadProjectFileFromPath>>;- try {- result = await window.electronAPI.loadProjectFileFromPath(filePath);- } catch {- setDropError("load-failed");- return;- }- if (!result.success || !result.project) {- setDropError("load-failed");- return;- }-- onProjectOpened(result.project, result.path ?? null);- },- [onProjectOpened],- );-- return (- <div- className="flex h-full w-full flex-col items-center justify-center bg-[#09090b]"- onDragOver={handleDragOver}- onDragLeave={handleDragLeave}- onDrop={handleDrop}- >- {/* Drop overlay */}- {isDraggingOver && (- <div className="pointer-events-none absolute inset-0 z-50 flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-[#34B27B] bg-[#34B27B]/10">- <Upload className="mb-3 h-10 w-10 text-[#34B27B]" />- <p className="text-base font-semibold text-[#34B27B]">{te("emptyState.dropOverlay")}</p>- </div>- )}-- {/* Drop error dialog */}- <Dialog open={dropError !== null} onOpenChange={(open) => !open && setDropError(null)}>- <DialogContent className="bg-[#09090b] border-white/10 rounded-2xl max-w-sm p-6 gap-0">- <DialogHeader className="mb-4">- <div className="flex items-center gap-3">- <img- src="./openscreen.png"- alt=""- aria-hidden="true"- className="w-9 h-9 rounded-xl flex-shrink-0"- />- <DialogTitle className="text-base font-semibold text-slate-200 leading-tight">- {lastDropErrorRef.current === "unsupported-format"- ? te("emptyState.dropErrors.unsupportedFormatTitle")- : te("emptyState.dropErrors.couldNotOpenTitle")}- </DialogTitle>- </div>- </DialogHeader>-- <div className="flex flex-col items-center gap-3 mb-6 text-center">- <div className="flex items-center justify-center w-10 h-10 rounded-full bg-white/5 ring-1 ring-white/10">- <AlertCircle className="w-5 h-5 text-slate-400 flex-shrink-0" />- </div>- <p className="text-sm text-slate-400 leading-relaxed">- {lastDropErrorRef.current === "unsupported-format"- ? te("emptyState.dropErrors.unsupportedFormatMessage")- : te("emptyState.dropErrors.couldNotOpenMessage")}- </p>- </div>-- <button- type="button"- onClick={() => setDropError(null)}- className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-slate-300 font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-white/30 focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- <X className="w-4 h-4" />- {tc("actions.close")}- </button>- </DialogContent>- </Dialog>-- <div className="relative flex flex-col items-center gap-8 px-6 text-center">- {/* Logo */}- <img- src="./openscreen.png"- alt=""- aria-hidden="true"- className="h-16 w-16 rounded-2xl opacity-90"- />-- <div className="flex flex-col gap-2">- <h2 className="text-xl font-semibold text-slate-200">{te("emptyState.title")}</h2>- <p className="max-w-sm text-sm leading-relaxed text-slate-500">- {te("emptyState.description")}- </p>- </div>-- {/* Actions */}- <div className="flex flex-col gap-3 w-full max-w-xs">- <button- type="button"- onClick={handleImportVideo}- className="flex items-center justify-center gap-2.5 w-full px-4 py-3 rounded-xl bg-[#34B27B] hover:bg-[#2d9e6c] active:bg-[#27885c] text-white font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[#34B27B] focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- <Film className="h-4 w-4" />- {te("emptyState.importVideoButton")}- </button>- <button- type="button"- onClick={handleLoadProject}- className="flex items-center justify-center gap-2.5 w-full px-4 py-3 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-slate-300 font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-white/30 focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- <FolderOpen className="h-4 w-4" />- {te("emptyState.loadProjectButton")}- </button>- </div>-- <div className="flex flex-col items-center gap-2">- <p className="text-xs text-slate-600">{te("emptyState.supportedFormats")}</p>- <div className="flex items-center gap-1.5 text-xs text-slate-700 mt-4">- <Upload className="h-3 w-3" />- <span>{te("emptyState.dragDropHint")}</span>- </div>- </div>- </div>- </div>- );-}diff --git a/src/components/video-editor/ExportDialog.tsx b/src/components/video-editor/ExportDialog.tsxdeleted file mode 100644index b012617c1..000000000--- a/src/components/video-editor/ExportDialog.tsx+++ /dev/null@@ -1,283 +0,0 @@-import { Download, Loader2, X } from "lucide-react";-import { useEffect, useState } from "react";-import { Button } from "@/components/ui/button";-import { useScopedT } from "@/contexts/I18nContext";-import type { ExportProgress } from "@/lib/exporter";--interface ExportDialogProps {- isOpen: boolean;- onClose: () => void;- progress: ExportProgress | null;- isExporting: boolean;- error: string | null;- onCancel?: () => void;- exportFormat?: "mp4" | "gif";- exportedFilePath?: string;- onShowInFolder?: () => void;-}--export function ExportDialog({- isOpen,- onClose,- progress,- isExporting,- error,- onCancel,- exportFormat = "mp4",- exportedFilePath,- onShowInFolder,-}: ExportDialogProps) {- const t = useScopedT("dialogs");- const [showSuccess, setShowSuccess] = useState(false);-- useEffect(() => {- if (isExporting) {- setShowSuccess(false);- }- }, [isExporting]);-- // Reset when the dialog opens fresh (not mid-export).- useEffect(() => {- if (isOpen && !isExporting && !progress) {- setShowSuccess(false);- }- }, [isOpen, isExporting, progress]);-- useEffect(() => {- if (!isExporting && progress && progress.percentage >= 100 && !error) {- setShowSuccess(true);- const timer = setTimeout(() => {- setShowSuccess(false);- onClose();- }, 2000);- return () => clearTimeout(timer);- }- }, [isExporting, progress, error, onClose]);-- if (!isOpen) return null;-- const formatLabel = exportFormat === "gif" ? "GIF" : "Video";-- // Compiling phase: frames are done but the export is still finishing.- const isCompiling =- isExporting && progress && progress.percentage >= 100 && exportFormat === "gif";- const isFinalizing = progress?.phase === "finalizing";- // Streaming a large recording into OPFS before frames start rendering.- const isPreparing = progress?.phase === "preparing";- const renderProgress = progress?.renderProgress;-- const getStatusMessage = () => {- if (error) return t("export.tryAgain");- if (isCompiling || isFinalizing) {- if (exportFormat === "mp4") {- return t("export.finalizingVideo");- }- if (renderProgress !== undefined && renderProgress > 0) {- return t("export.compilingGifProgress", { progress: String(renderProgress) });- }- return t("export.compilingGifWait");- }- return t("export.takeMoment");- };-- const getTitle = () => {- if (error) return t("export.failed");- if (isFinalizing && exportFormat === "mp4") return t("export.finalizingVideoTitle");- if (isCompiling || isFinalizing) return t("export.compilingGif");- return t("export.exportingFormat", { format: formatLabel });- };-- return (- <>- <div- className="fixed inset-0 bg-black/80 backdrop-blur-md z-50 animate-in fade-in duration-200"- onClick={isExporting ? undefined : onClose}- />- <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-[60] bg-[#09090b] rounded-2xl shadow-2xl border border-white/10 p-8 w-[90vw] max-w-md animate-in zoom-in-95 duration-200">- <div className="flex items-center justify-between mb-6">- <div className="flex items-center gap-4">- {showSuccess ? (- <>- <div className="w-12 h-12 rounded-full bg-[#34B27B]/20 flex items-center justify-center ring-1 ring-[#34B27B]/50">- <Download className="w-6 h-6 text-[#34B27B]" />- </div>- <div className="flex flex-col gap-2">- <span className="text-xl font-bold text-slate-200 block">- {t("export.complete")}- </span>- <span className="text-sm text-slate-400">- {t("export.yourFormatReady", { format: formatLabel.toLowerCase() })}- </span>- {exportedFilePath && (- <Button- variant="secondary"- onClick={onShowInFolder}- className="mt-2 w-fit px-3 py-1 text-sm rounded-md bg-white/10 hover:bg-white/20 text-slate-200"- >- {t("export.showInFolder")}- </Button>- )}- {exportedFilePath && (- <span className="text-xs text-slate-500 break-all max-w-xs mt-1">- {exportedFilePath.split("/").pop()}- </span>- )}- </div>- </>- ) : (- <>- {isExporting ? (- <div className="w-12 h-12 rounded-full bg-[#34B27B]/10 flex items-center justify-center">- <Loader2 className="w-6 h-6 text-[#34B27B] animate-spin" />- </div>- ) : (- <div className="w-12 h-12 rounded-full bg-white/5 flex items-center justify-center border border-white/10">- <Download className="w-6 h-6 text-slate-200" />- </div>- )}- <div>- <span className="text-xl font-bold text-slate-200 block">{getTitle()}</span>- <span className="text-sm text-slate-400">{getStatusMessage()}</span>- </div>- </>- )}- </div>- {!isExporting && (- <Button- variant="ghost"- size="icon"- onClick={onClose}- className="hover:bg-white/10 text-slate-400 hover:text-white rounded-full"- >- <X className="w-5 h-5" />- </Button>- )}- </div>-- {error && (- <div className="mb-6 animate-in slide-in-from-top-2">- <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-4 flex items-start gap-3">- <div className="p-1 bg-red-500/20 rounded-full">- <X className="w-3 h-3 text-red-400" />- </div>- <p className="whitespace-pre-wrap break-words text-sm text-red-400 leading-relaxed">- {error}- </p>- </div>- </div>- )}-- {isExporting && progress && (- <div className="space-y-6">- <div className="space-y-2">- <div className="flex justify-between text-xs font-medium text-slate-400 uppercase tracking-wider">- <span>- {isCompiling || isFinalizing- ? t("export.compiling")- : isPreparing- ? t("export.processing")- : t("export.renderingFrames")}- </span>- <span className="font-mono text-slate-200">- {isCompiling || isFinalizing ? (- renderProgress !== undefined && renderProgress > 0 ? (- `${renderProgress}%`- ) : (- <span className="flex items-center gap-2">- <Loader2 className="w-3 h-3 animate-spin" />- {t("export.processing")}- </span>- )- ) : (- `${progress.percentage.toFixed(0)}%`- )}- </span>- </div>- <div className="h-2 bg-white/5 rounded-full overflow-hidden border border-white/5">- {isCompiling || isFinalizing ? (- // Real progress if we have it, otherwise an indeterminate bar.- renderProgress !== undefined && renderProgress > 0 ? (- <div- className="h-full bg-[#34B27B] shadow-[0_0_10px_rgba(52,178,123,0.3)] transition-all duration-300 ease-out"- style={{ width: `${renderProgress}%` }}- />- ) : (- <div className="h-full w-full relative overflow-hidden">- <div- className="absolute h-full w-1/3 bg-[#34B27B] shadow-[0_0_10px_rgba(52,178,123,0.3)]"- style={{- animation: "indeterminate 1.5s ease-in-out infinite",- }}- />- <style>{`- @keyframes indeterminate {- 0% { transform: translateX(-100%); }- 100% { transform: translateX(400%); }- }- `}</style>- </div>- )- ) : (- <div- className="h-full bg-[#34B27B] shadow-[0_0_10px_rgba(52,178,123,0.3)] transition-all duration-300 ease-out"- style={{ width: `${Math.min(progress.percentage, 100)}%` }}- />- )}- </div>- </div>-- <div className="grid grid-cols-2 gap-4">- <div className="bg-white/5 rounded-xl p-3 border border-white/5">- <div className="text-[10px] text-slate-500 uppercase tracking-wider mb-1">- {isCompiling || isFinalizing ? t("export.status") : t("export.format")}- </div>- <div className="text-slate-200 font-medium text-sm">- {isFinalizing && exportFormat === "mp4"- ? t("export.finalizing")- : isCompiling || isFinalizing- ? t("export.compilingStatus")- : formatLabel}- </div>- </div>- <div className="bg-white/5 rounded-xl p-3 border border-white/5">- <div className="text-[10px] text-slate-500 uppercase tracking-wider mb-1">- {t("export.frames")}- </div>- <div className="text-slate-200 font-medium text-sm">- {isPreparing ? (- <span className="flex items-center gap-2">- <Loader2 className="w-3 h-3 animate-spin" />- {t("export.processing")}- </span>- ) : (- `${progress.currentFrame} / ${progress.totalFrames}`- )}- </div>- </div>- </div>-- {onCancel && (- <div className="pt-2">- <Button- onClick={onCancel}- variant="destructive"- className="w-full py-6 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all rounded-xl"- >- {t("export.cancelExport")}- </Button>- </div>- )}- </div>- )}-- {showSuccess && (- <div className="text-center py-4 animate-in zoom-in-95">- <p className="text-lg text-slate-200 font-medium">- {t("export.savedSuccessfully", { format: formatLabel })}- </p>- </div>- )}- </div>- </>- );-}diff --git a/src/components/video-editor/FormatSelector.tsx b/src/components/video-editor/FormatSelector.tsxdeleted file mode 100644index 9bd54b66f..000000000--- a/src/components/video-editor/FormatSelector.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { Film, Image } from "lucide-react";-import { useScopedT } from "@/contexts/I18nContext";-import type { ExportFormat } from "@/lib/exporter/types";-import { cn } from "@/lib/utils";--interface FormatSelectorProps {- selectedFormat: ExportFormat;- onFormatChange: (format: ExportFormat) => void;- disabled?: boolean;-}--const formatOptions: Array<{ value: ExportFormat; icon: React.ReactNode }> = [- { value: "mp4", icon: <Film className="w-5 h-5" /> },- { value: "gif", icon: <Image className="w-5 h-5" /> },-];--export function FormatSelector({- selectedFormat,- onFormatChange,- disabled = false,-}: FormatSelectorProps) {- const t = useScopedT("settings");-- const formatLabels: Record<ExportFormat, { label: string; description: string }> = {- mp4: { label: t("exportFormat.mp4Video"), description: t("exportFormat.mp4Description") },- gif: { label: t("exportFormat.gifAnimation"), description: t("exportFormat.gifDescription") },- };-- return (- <div className="grid grid-cols-2 gap-3">- {formatOptions.map((option) => {- const isSelected = selectedFormat === option.value;- const labels = formatLabels[option.value];- return (- <button- key={option.value}- type="button"- disabled={disabled}- onClick={() => onFormatChange(option.value)}- className={cn(- "relative flex flex-col items-center gap-2 p-4 rounded-xl border transition-all duration-200",- "focus:outline-none focus:ring-2 focus:ring-[#34B27B]/50 focus:ring-offset-2 focus:ring-offset-[#09090b]",- isSelected- ? "bg-[#34B27B]/10 border-[#34B27B]/50 text-white"- : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:border-white/20 hover:text-slate-200",- disabled && "opacity-50 cursor-not-allowed",- )}- >- <div- className={cn(- "w-10 h-10 rounded-full flex items-center justify-center transition-colors",- isSelected ? "bg-[#34B27B]/20 text-[#34B27B]" : "bg-white/5",- )}- >- {option.icon}- </div>- <div className="text-center">- <div className="font-medium text-sm">{labels.label}</div>- <div className="text-xs text-slate-500 mt-0.5">{labels.description}</div>- </div>- {isSelected && (- <div className="absolute top-2 right-2 w-2 h-2 rounded-full bg-[#34B27B]" />- )}- </button>- );- })}- </div>- );-}diff --git a/src/components/video-editor/GifOptionsPanel.tsx b/src/components/video-editor/GifOptionsPanel.tsxdeleted file mode 100644index f350d46c8..000000000--- a/src/components/video-editor/GifOptionsPanel.tsx+++ /dev/null@@ -1,111 +0,0 @@-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { Switch } from "@/components/ui/switch";-import {- GIF_FRAME_RATES,- GIF_SIZE_PRESETS,- type GifFrameRate,- type GifSizePreset,-} from "@/lib/exporter/types";--interface GifOptionsPanelProps {- frameRate: GifFrameRate;- onFrameRateChange: (rate: GifFrameRate) => void;- loop: boolean;- onLoopChange: (loop: boolean) => void;- sizePreset: GifSizePreset;- onSizePresetChange: (preset: GifSizePreset) => void;- outputDimensions: { width: number; height: number };- disabled?: boolean;-}--export function GifOptionsPanel({- frameRate,- onFrameRateChange,- loop,- onLoopChange,- sizePreset,- onSizePresetChange,- outputDimensions,- disabled = false,-}: GifOptionsPanelProps) {- const sizePresetOptions = Object.entries(GIF_SIZE_PRESETS).map(([key, value]) => ({- value: key as GifSizePreset,- label: value.label,- }));-- return (- <div className="space-y-4 animate-in slide-in-from-bottom-2 duration-200">- {/* Frame Rate */}- <div className="space-y-2">- <label className="text-xs font-medium text-slate-400 uppercase tracking-wider">- Frame Rate- </label>- <Select- value={String(frameRate)}- onValueChange={(value) => onFrameRateChange(Number(value) as GifFrameRate)}- disabled={disabled}- >- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 hover:bg-white/10">- <SelectValue />- </SelectTrigger>- <SelectContent className="bg-[#1a1a1f] border-white/10 z-[100]">- {GIF_FRAME_RATES.map((rate) => (- <SelectItem- key={rate.value}- value={String(rate.value)}- className="text-slate-200 focus:bg-white/10 focus:text-white"- >- {rate.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* Size Preset */}- <div className="space-y-2">- <label className="text-xs font-medium text-slate-400 uppercase tracking-wider">- Output Size- </label>- <Select- value={sizePreset}- onValueChange={(value) => onSizePresetChange(value as GifSizePreset)}- disabled={disabled}- >- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 hover:bg-white/10">- <SelectValue />- </SelectTrigger>- <SelectContent className="bg-[#1a1a1f] border-white/10 z-[100]">- {sizePresetOptions.map((option) => (- <SelectItem- key={option.value}- value={option.value}- className="text-slate-200 focus:bg-white/10 focus:text-white"- >- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- <div className="text-xs text-slate-500">- Output: {outputDimensions.width} × {outputDimensions.height}px- </div>- </div>-- {/* Loop Toggle */}- <div className="flex items-center justify-between py-2">- <div>- <label className="text-sm font-medium text-slate-200">Loop Animation</label>- <p className="text-xs text-slate-500">GIF will play continuously</p>- </div>- <Switch checked={loop} onCheckedChange={onLoopChange} disabled={disabled} />- </div>- </div>- );-}diff --git a/src/components/video-editor/KeyboardShortcutsHelp.tsx b/src/components/video-editor/KeyboardShortcutsHelp.tsxdeleted file mode 100644index 23311225c..000000000--- a/src/components/video-editor/KeyboardShortcutsHelp.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { HelpCircle, Settings2 } from "lucide-react";-import { useScopedT } from "@/contexts/I18nContext";-import { useShortcuts } from "@/contexts/ShortcutsContext";-import { FIXED_SHORTCUTS, formatBinding, SHORTCUT_ACTIONS } from "@/lib/shortcuts";-import { BLUR_REGIONS_ENABLED } from "./featureFlags";--export function KeyboardShortcutsHelp() {- const { shortcuts, isMac, openConfig } = useShortcuts();- const t = useScopedT("shortcuts");-- return (- <div className="relative group">- <HelpCircle className="w-4 h-4 text-slate-500 hover:text-[#34B27B] transition-colors cursor-help" />-- <div className="absolute right-0 top-full mt-2 w-64 bg-[#09090b] border border-white/10 rounded-lg p-3 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 shadow-xl z-50">- <div className="flex items-center justify-between mb-2">- <span className="text-xs font-semibold text-slate-200">{t("title")}</span>- <button- type="button"- onClick={openConfig}- title="Customize shortcuts"- className="flex items-center gap-1 text-[10px] text-slate-500 hover:text-[#34B27B] transition-colors"- >- <Settings2 className="w-3 h-3" />- {t("customize")}- </button>- </div>-- <div className="space-y-1.5 text-[10px]">- {SHORTCUT_ACTIONS.filter((action) => BLUR_REGIONS_ENABLED || action !== "addBlur").map(- (action) => (- <div key={action} className="flex items-center justify-between">- <span className="text-slate-400">{t(`actions.${action}`)}</span>- <kbd className="px-1 py-0.5 bg-white/5 border border-white/10 rounded text-[#34B27B] font-mono">- {formatBinding(shortcuts[action], isMac)}- </kbd>- </div>- ),- )}-- <div className="pt-1 border-t border-white/5 mt-1 space-y-1.5">- {FIXED_SHORTCUTS.map((fixed) => (- <div key={fixed.i18nKey} className="flex items-center justify-between">- <span className="text-slate-400">- {t(`fixedActions.${fixed.i18nKey}`, { defaultValue: fixed.label })}- </span>- <kbd className="px-1 py-0.5 bg-white/5 border border-white/10 rounded text-[#34B27B] font-mono">- {isMac- ? fixed.display- .replace(/Ctrl/g, "⌘")- .replace(/Shift/g, "⇧")- .replace(/Alt/g, "⌥")- : fixed.display}- </kbd>- </div>- ))}- </div>- </div>- </div>- </div>- );-}diff --git a/src/components/video-editor/PlaybackControls.tsx b/src/components/video-editor/PlaybackControls.tsxdeleted file mode 100644index bdec37cc7..000000000--- a/src/components/video-editor/PlaybackControls.tsx+++ /dev/null@@ -1,112 +0,0 @@-import { Maximize, Minimize, Pause, Play } from "lucide-react";-import { useScopedT } from "@/contexts/I18nContext";-import { cn } from "@/lib/utils";-import { Button } from "../ui/button";--interface PlaybackControlsProps {- isPlaying: boolean;- currentTime: number;- duration: number;- isFullscreen?: boolean;- onToggleFullscreen?: () => void;- onTogglePlayPause: () => void;- onSeek: (time: number) => void;-}--export default function PlaybackControls({- isPlaying,- currentTime,- duration,- isFullscreen = false,- onToggleFullscreen,- onTogglePlayPause,- onSeek,-}: PlaybackControlsProps) {- const t = useScopedT("common");-- function formatTime(seconds: number) {- if (!isFinite(seconds) || isNaN(seconds) || seconds < 0) return "0:00";- const mins = Math.floor(seconds / 60);- const secs = Math.floor(seconds % 60);- return `${mins}:${secs.toString().padStart(2, "0")}`;- }-- function handleSeekChange(e: React.ChangeEvent<HTMLInputElement>) {- onSeek(parseFloat(e.target.value));- }-- const progress = duration > 0 ? (currentTime / duration) * 100 : 0;-- return (- <div className="flex items-center gap-2 px-1 py-0.5 rounded-full bg-black/60 backdrop-blur-md border border-white/10 shadow-xl transition-all duration-300 hover:bg-black/70 hover:border-white/20">- <Button- onClick={onTogglePlayPause}- size="icon"- className={cn(- "w-8 h-8 rounded-full transition-all duration-200 border border-white/10",- isPlaying- ? "bg-white/10 text-white hover:bg-white/20"- : "bg-white text-black hover:bg-white/90 hover:scale-105 shadow-[0_0_15px_rgba(255,255,255,0.3)]",- )}- aria-label={isPlaying ? t("playback.pause") : t("playback.play")}- >- {isPlaying ? (- <Pause className="w-3.5 h-3.5 fill-current" />- ) : (- <Play className="w-3.5 h-3.5 fill-current ml-0.5" />- )}- </Button>-- <span className="text-[9px] font-medium text-slate-300 tabular-nums w-[30px] text-right">- {formatTime(currentTime)}- </span>-- <div className="flex-1 relative h-6 flex items-center group">- {/* Custom Track Background */}- <div className="absolute left-0 right-0 h-0.5 bg-white/10 rounded-full overflow-hidden">- <div className="h-full bg-[#34B27B] rounded-full" style={{ width: `${progress}%` }} />- </div>-- {/* Interactive Input */}- <input- type="range"- min="0"- max={duration || 100}- value={currentTime}- onChange={handleSeekChange}- step="0.01"- className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"- />-- {/* Custom Thumb (visual only, follows progress) */}- <div- className="absolute w-2.5 h-2.5 bg-white rounded-full shadow-lg pointer-events-none group-hover:scale-125 transition-transform duration-100"- style={{- left: `${progress}%`,- transform: "translateX(-50%)",- }}- />- </div>-- <span className="text-[9px] font-medium text-slate-500 tabular-nums w-[30px]">- {formatTime(duration)}- </span>-- {onToggleFullscreen && (- <Button- onClick={onToggleFullscreen}- size="icon"- variant="ghost"- className="w-7 h-7 rounded-full transition-all duration-200 border border-transparent bg-transparent hover:bg-white/10 text-white hover:text-white hover:border-white/10 shrink-0 shadow-none ml-0.5"- aria-label={isFullscreen ? t("playback.exitFullscreen") : t("playback.fullscreen")}- >- {isFullscreen ? (- <Minimize className="w-3.5 h-3.5" />- ) : (- <Maximize className="w-3.5 h-3.5" />- )}- </Button>- )}- </div>- );-}diff --git a/src/components/video-editor/SettingsPanel.tsx b/src/components/video-editor/SettingsPanel.tsxdeleted file mode 100644index b80ac021d..000000000--- a/src/components/video-editor/SettingsPanel.tsx+++ /dev/null@@ -1,2221 +0,0 @@-import * as SliderPrimitive from "@radix-ui/react-slider";-import {- Brackets,- Bug,- Crop,- Download,- FileDown,- Film,- Image,- Info,- LayoutPanelTop,- Lock,- MousePointerClick,- Palette,- SlidersHorizontal,- Sparkles,- Star,- Trash2,- Unlock,- Upload,- X,-} from "lucide-react";-import { type ComponentType, useCallback, useMemo, useRef, useState } from "react";-import { toast } from "sonner";-import defaultCursorPreviewUrl from "@/assets/cursors/Cursor=Default.svg";-import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,-} from "@/components/ui/accordion";-import { Button } from "@/components/ui/button";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { Slider } from "@/components/ui/slider";-import { Switch } from "@/components/ui/switch";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import { Tooltip } from "@/components/ui/tooltip";-import { useScopedT } from "@/contexts/I18nContext";-import { getAssetPath } from "@/lib/assetPath";-import { WEBCAM_LAYOUT_PRESETS } from "@/lib/compositeLayout";-import { CURSOR_THEMES, DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";-import type { ExportFormat, ExportQuality, GifFrameRate, GifSizePreset } from "@/lib/exporter";-import {- calculateEffectiveSourceDimensions,- GIF_FRAME_RATES,- GIF_SIZE_PRESETS,-} from "@/lib/exporter";-import { buildGradientFromEditor } from "@/lib/gradientBuilder";-import { cn } from "@/lib/utils";-import { resolveImageWallpaperUrl, WALLPAPER_PATHS } from "@/lib/wallpaper";-import { type AspectRatio, isPortraitAspectRatio } from "@/utils/aspectRatioUtils";-import { getTestId } from "@/utils/getTestId";-import ColorPicker from "../ui/color-picker";-import GradientEditor from "../ui/gradient-editor";-import { AnnotationSettingsPanel } from "./AnnotationSettingsPanel";-import { BlurSettingsPanel } from "./BlurSettingsPanel";-import { BACKGROUND_IMAGE_ACCEPT, isSupportedBackgroundImageType } from "./backgroundImageUpload";-import { CropControl } from "./CropControl";-import { parseCustomPlaybackSpeedInput } from "./customPlaybackSpeed";-import {- DEFAULT_CURSOR_SETTINGS,- DEFAULT_EDITOR_LAYOUT_SETTINGS,- DEFAULT_EXPORT_SETTINGS,- DEFAULT_GIF_SETTINGS,- DEFAULT_SOURCE_DIMENSIONS,- DEFAULT_WEBCAM_SETTINGS,-} from "./editorDefaults";-import { BLUR_REGIONS_ENABLED } from "./featureFlags";-import { KeyboardShortcutsHelp } from "./KeyboardShortcutsHelp";-import type {- AnnotationRegion,- AnnotationType,- BlurData,- CropRegion,- FigureData,- PlaybackSpeed,- Rotation3DPreset,- WebcamLayoutPreset,- WebcamMaskShape,- WebcamSizePreset,- ZoomDepth,- ZoomFocus,- ZoomFocusMode,-} from "./types";-import {- DEFAULT_WEBCAM_MIRRORED,- DEFAULT_WEBCAM_REACTIVE_ZOOM,- MAX_NATIVE_PLAYBACK_RATE,- MAX_PLAYBACK_SPEED,- MAX_ZOOM_SCALE,- MIN_ZOOM_SCALE,- ROTATION_3D_PRESET_ORDER,- SPEED_OPTIONS,- ZOOM_DEPTH_SCALES,-} from "./types";-import { getFocusBoundsForScale } from "./videoPlayback/focusUtils";--function CustomSpeedInput({- value,- onChange,- onError,-}: {- value: number;- onChange: (val: number) => void;- onError: () => void;-}) {- const isPreset = SPEED_OPTIONS.some((o) => o.speed === value);- const [draft, setDraft] = useState(isPreset ? "" : String(value));- const [isFocused, setIsFocused] = useState(false);-- const prevValue = useRef(value);- if (!isFocused && prevValue.current !== value) {- prevValue.current = value;- setDraft(isPreset ? "" : String(value));- }-- const handleChange = useCallback(- (e: React.ChangeEvent<HTMLInputElement>) => {- const result = parseCustomPlaybackSpeedInput(e.target.value);- if (result.status === "too-fast") {- onError();- return;- }-- setDraft(result.draft);- if (result.status === "valid") {- onChange(result.speed);- }- },- [onChange, onError],- );-- const handleBlur = useCallback(() => {- setIsFocused(false);- const result = parseCustomPlaybackSpeedInput(draft);- if (result.status === "valid") {- setDraft(String(result.speed));- } else {- setDraft(isPreset ? "" : String(value));- }- }, [draft, isPreset, value]);-- return (- <div className="flex items-center gap-1">- <input- type="text"- inputMode="decimal"- pattern="[0-9]*[.]?[0-9]*"- placeholder="--"- value={draft}- onFocus={() => setIsFocused(true)}- onChange={handleChange}- onBlur={handleBlur}- onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}- className="w-12 bg-white/5 border border-white/10 rounded-md px-1 py-0.5 text-[11px] font-semibold text-[#d97706] text-center focus:outline-none focus:border-[#d97706]/40"- />- <span className="text-[11px] font-semibold text-slate-500">×</span>- </div>- );-}--function ZoomFocusCoordInput({- percent,- onChange,- onCommit,- disabled,- ariaLabel,-}: {- percent: number;- onChange: (nextPercent: number) => void;- onCommit?: () => void;- disabled?: boolean;- ariaLabel: string;-}) {- // While focused, show the draft so partial entries like "5" or "" survive re-renders.- // While not focused, mirror the live prop so overlay drags update the number live.- const [draft, setDraft] = useState<string | null>(null);- const display = percent.toFixed(1);-- return (- <input- type="number"- inputMode="decimal"- min={0}- max={100}- step={0.1}- value={draft ?? display}- disabled={disabled}- aria-label={ariaLabel}- onFocus={() => setDraft(display)}- onChange={(e) => {- const next = e.target.value;- setDraft(next);- const parsed = Number(next);- if (next !== "" && Number.isFinite(parsed)) {- const clamped = Math.min(100, Math.max(0, parsed));- onChange(clamped);- }- }}- onBlur={() => {- setDraft(null);- onCommit?.();- }}- onKeyDown={(e) => {- if (e.key === "Enter") (e.target as HTMLInputElement).blur();- }}- className="h-7 w-full rounded-md border border-white/10 bg-white/5 px-2 text-[11px] text-slate-200 outline-none focus:border-[#34B27B]/50 focus:ring-1 focus:ring-[#34B27B]/30 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none disabled:opacity-50 disabled:cursor-not-allowed"- />- );-}--const GRADIENTS = [- "linear-gradient( 111.6deg, rgba(114,167,232,1) 9.4%, rgba(253,129,82,1) 43.9%, rgba(253,129,82,1) 54.8%, rgba(249,202,86,1) 86.3% )",- "linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%)",- "radial-gradient( circle farthest-corner at 3.2% 49.6%, rgba(80,12,139,0.87) 0%, rgba(161,10,144,0.72) 83.6% )",- "linear-gradient( 111.6deg, rgba(0,56,68,1) 0%, rgba(163,217,185,1) 51.5%, rgba(231, 148, 6, 1) 88.6% )",- "linear-gradient( 107.7deg, rgba(235,230,44,0.55) 8.4%, rgba(252,152,15,1) 90.3% )",- "linear-gradient( 91deg, rgba(72,154,78,1) 5.2%, rgba(251,206,70,1) 95.9% )",- "radial-gradient( circle farthest-corner at 10% 20%, rgba(2,37,78,1) 0%, rgba(4,56,126,1) 19.7%, rgba(85,245,221,1) 100.2% )",- "linear-gradient( 109.6deg, rgba(15,2,2,1) 11.2%, rgba(36,163,190,1) 91.1% )",- "linear-gradient(135deg, #FBC8B4, #2447B1)",- "linear-gradient(109.6deg, #F635A6, #36D860)",- "linear-gradient(90deg, #FF0101, #4DFF01)",- "linear-gradient(315deg, #EC0101, #5044A9)",- "linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)",- "linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%)",- "linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%)",- "linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)",- "linear-gradient(to right, #4facfe 0%, #00f2fe 100%)",- "linear-gradient(to top, #fcc5e4 0%, #fda34b 15%, #ff7882 35%, #c8699e 52%, #7046aa 71%, #0c1db8 87%, #020f75 100%)",- "linear-gradient(to right, #fa709a 0%, #fee140 100%)",- "linear-gradient(to top, #30cfd0 0%, #330867 100%)",- "linear-gradient(to top, #c471f5 0%, #fa71cd 100%)",- "linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%)",- "linear-gradient(to top, #48c6ef 0%, #6f86d6 100%)",- "linear-gradient(to right, #0acffe 0%, #495aff 100%)",-];--interface SettingsPanelProps {- selected: string;- onWallpaperChange: (path: string) => void;- selectedZoomDepth?: ZoomDepth | null;- onZoomDepthChange?: (depth: ZoomDepth) => void;- selectedZoomCustomScale?: number | null;- onZoomCustomScaleChange?: (scale: number) => void;- onZoomCustomScaleCommit?: () => void;- onZoomPreviewStart?: () => void;- onZoomPreviewEnd?: () => void;- selectedZoomFocusMode?: ZoomFocusMode | null;- onZoomFocusModeChange?: (mode: ZoomFocusMode) => void;- /** When the global Auto-Focus toggle is on, the per-zoom selector is locked. */- focusModeLocked?: boolean;- selectedZoomFocus?: ZoomFocus | null;- onZoomFocusCoordinateChange?: (focus: ZoomFocus) => void;- onZoomFocusCoordinateCommit?: () => void;- hasCursorTelemetry?: boolean;- selectedZoomId?: string | null;- onZoomDelete?: (id: string) => void;- selectedZoomRotationPreset?: Rotation3DPreset | null;- onZoomRotationPresetChange?: (preset: Rotation3DPreset | null) => void;- selectedTrimId?: string | null;- onTrimDelete?: (id: string) => void;- shadowIntensity?: number;- onShadowChange?: (intensity: number) => void;- onShadowCommit?: () => void;- showBlur?: boolean;- onBlurChange?: (showBlur: boolean) => void;- showTrimWaveform?: boolean;- onTrimWaveformChange?: (show: boolean) => void;- motionBlurAmount?: number;- onMotionBlurChange?: (amount: number) => void;- onMotionBlurCommit?: () => void;- borderRadius?: number;- onBorderRadiusChange?: (radius: number) => void;- onBorderRadiusCommit?: () => void;- padding?: number;- onPaddingChange?: (padding: number) => void;- onPaddingCommit?: () => void;- cropRegion?: CropRegion;- onCropChange?: (region: CropRegion) => void;- aspectRatio: AspectRatio;- videoElement?: HTMLVideoElement | null;- exportQuality?: ExportQuality;- onExportQualityChange?: (quality: ExportQuality) => void;- // Export format settings- exportFormat?: ExportFormat;- onExportFormatChange?: (format: ExportFormat) => void;- gifFrameRate?: GifFrameRate;- onGifFrameRateChange?: (rate: GifFrameRate) => void;- gifLoop?: boolean;- onGifLoopChange?: (loop: boolean) => void;- gifSizePreset?: GifSizePreset;- onGifSizePresetChange?: (preset: GifSizePreset) => void;- gifOutputDimensions?: { width: number; height: number };- onExport?: () => void;- onExportPanelOpen?: () => void;- unsavedExport?: {- arrayBuffer: ArrayBuffer;- fileName: string;- format: string;- } | null;- onSaveUnsavedExport?: () => void;- selectedAnnotationId?: string | null;- annotationRegions?: AnnotationRegion[];- onAnnotationContentChange?: (id: string, content: string) => void;- onAnnotationTypeChange?: (id: string, type: AnnotationType) => void;- onAnnotationStyleChange?: (id: string, style: Partial<AnnotationRegion["style"]>) => void;- onAnnotationFigureDataChange?: (id: string, figureData: FigureData) => void;- onAnnotationDuplicate?: (id: string) => void;- onAnnotationDelete?: (id: string) => void;- selectedBlurId?: string | null;- blurRegions?: AnnotationRegion[];- onBlurDataChange?: (id: string, blurData: BlurData) => void;- onBlurDataCommit?: () => void;- onBlurDelete?: (id: string) => void;- selectedSpeedId?: string | null;- selectedSpeedValue?: PlaybackSpeed | null;- onSpeedChange?: (speed: PlaybackSpeed) => void;- onSpeedDelete?: (id: string) => void;- hasWebcam?: boolean;- webcamLayoutPreset?: WebcamLayoutPreset;- onWebcamLayoutPresetChange?: (preset: WebcamLayoutPreset) => void;- webcamMaskShape?: import("./types").WebcamMaskShape;- onWebcamMaskShapeChange?: (shape: import("./types").WebcamMaskShape) => void;- webcamMirrored?: boolean;- onWebcamMirroredChange?: (mirrored: boolean) => void;- webcamReactiveZoom?: boolean;- onWebcamReactiveZoomChange?: (reactive: boolean) => void;- webcamSizePreset?: WebcamSizePreset;- onWebcamSizePresetChange?: (size: WebcamSizePreset) => void;- onWebcamSizePresetCommit?: () => void;- onSaveDiagnostic?: () => Promise<void>;- showCursor?: boolean;- onShowCursorChange?: (show: boolean) => void;- cursorSize?: number;- onCursorSizeChange?: (size: number) => void;- cursorSmoothing?: number;- onCursorSmoothingChange?: (smoothing: number) => void;- cursorMotionBlur?: number;- onCursorMotionBlurChange?: (blur: number) => void;- cursorClickBounce?: number;- onCursorClickBounceChange?: (bounce: number) => void;- cursorClipToBounds?: boolean;- onCursorClipToBoundsChange?: (clip: boolean) => void;- cursorTheme?: string;- onCursorThemeChange?: (theme: string) => void;- hasCursorData?: boolean;- showCursorSettings?: boolean;-}--export default SettingsPanel;--const ZOOM_DEPTH_OPTIONS: Array<{ depth: ZoomDepth; label: string }> = [- { depth: 1, label: "1.25×" },- { depth: 2, label: "1.5×" },- { depth: 3, label: "1.8×" },- { depth: 4, label: "2.2×" },- { depth: 5, label: "3.5×" },- { depth: 6, label: "5×" },-];--type SettingsPanelMode = "background" | "effects" | "layout" | "cursor" | "export" | "timeline";--const MP4_EXPORT_SHORT_SIDES = {- medium: 720,- good: 1080,-} as const;--function formatSourceDimensions(videoElement?: HTMLVideoElement | null, cropRegion?: CropRegion) {- const width = videoElement?.videoWidth ?? 0;- const height = videoElement?.videoHeight ?? 0;-- if (width <= 0 || height <= 0) {- return null;- }-- const dimensions = calculateEffectiveSourceDimensions(width, height, cropRegion);- return { ...dimensions, shortSide: Math.min(dimensions.width, dimensions.height) };-}--export function SettingsPanel({- selected,- onWallpaperChange,- selectedZoomDepth,- onZoomDepthChange,- selectedZoomCustomScale,- onZoomCustomScaleChange,- onZoomCustomScaleCommit,- onZoomPreviewStart,- onZoomPreviewEnd,- selectedZoomFocusMode,- onZoomFocusModeChange,- focusModeLocked = false,- selectedZoomFocus,- onZoomFocusCoordinateChange,- onZoomFocusCoordinateCommit,- hasCursorTelemetry = false,- selectedZoomId,- onZoomDelete,- selectedZoomRotationPreset,- onZoomRotationPresetChange,- selectedTrimId,- onTrimDelete,- shadowIntensity = 0,- onShadowChange,- onShadowCommit,- showBlur,- onBlurChange,- showTrimWaveform = false,- onTrimWaveformChange,- motionBlurAmount = 0,- onMotionBlurChange,- onMotionBlurCommit,- borderRadius = 0,- onBorderRadiusChange,- onBorderRadiusCommit,- padding = DEFAULT_EDITOR_LAYOUT_SETTINGS.padding,- onPaddingChange,- onPaddingCommit,- cropRegion,- onCropChange,- aspectRatio,- videoElement,- exportQuality = DEFAULT_EXPORT_SETTINGS.quality,- onExportQualityChange,- exportFormat = DEFAULT_EXPORT_SETTINGS.format,- onExportFormatChange,- gifFrameRate = DEFAULT_GIF_SETTINGS.frameRate,- onGifFrameRateChange,- gifLoop = DEFAULT_GIF_SETTINGS.loop,- onGifLoopChange,- gifSizePreset = DEFAULT_GIF_SETTINGS.sizePreset,- onGifSizePresetChange,- gifOutputDimensions = DEFAULT_GIF_SETTINGS.outputDimensions,- onExport,- onExportPanelOpen,- unsavedExport,- onSaveUnsavedExport,- selectedAnnotationId,- annotationRegions = [],- onAnnotationContentChange,- onAnnotationTypeChange,- onAnnotationStyleChange,- onAnnotationFigureDataChange,- onAnnotationDuplicate,- onAnnotationDelete,- selectedBlurId,- blurRegions = [],- onBlurDataChange,- onBlurDataCommit,- onBlurDelete,- selectedSpeedId,- selectedSpeedValue,- onSpeedChange,- onSpeedDelete,- hasWebcam = false,- webcamLayoutPreset = DEFAULT_WEBCAM_SETTINGS.layoutPreset,- onWebcamLayoutPresetChange,- webcamMaskShape = DEFAULT_WEBCAM_SETTINGS.maskShape,- onWebcamMaskShapeChange,- webcamMirrored = DEFAULT_WEBCAM_MIRRORED,- onWebcamMirroredChange,- webcamReactiveZoom = DEFAULT_WEBCAM_REACTIVE_ZOOM,- onWebcamReactiveZoomChange,- webcamSizePreset = DEFAULT_WEBCAM_SETTINGS.sizePreset,- onWebcamSizePresetChange,- onWebcamSizePresetCommit,- onSaveDiagnostic,- showCursor = DEFAULT_CURSOR_SETTINGS.show,- onShowCursorChange,- cursorSize = DEFAULT_CURSOR_SETTINGS.size,- onCursorSizeChange,- cursorSmoothing = DEFAULT_CURSOR_SETTINGS.smoothing,- onCursorSmoothingChange,- cursorMotionBlur = DEFAULT_CURSOR_SETTINGS.motionBlur,- onCursorMotionBlurChange,- cursorClickBounce = DEFAULT_CURSOR_SETTINGS.clickBounce,- onCursorClickBounceChange,- cursorClipToBounds = DEFAULT_CURSOR_SETTINGS.clipToBounds,- onCursorClipToBoundsChange,- cursorTheme = DEFAULT_CURSOR_SETTINGS.theme,- onCursorThemeChange,- hasCursorData = false,- showCursorSettings = true,-}: SettingsPanelProps) {- const t = useScopedT("settings");- const [activePanelMode, setActivePanelMode] = useState<SettingsPanelMode>("background");- const sourceDimensions = formatSourceDimensions(videoElement, cropRegion);- // Resolved URLs are for DOM rendering only. We persist the canonical- // `/wallpapers/wallpaperN.jpg` form from WALLPAPER_PATHS, never the file:// URL.- const wallpaperPreviewUrls = useMemo(() => WALLPAPER_PATHS.map(resolveImageWallpaperUrl), []);- // Built-in "Default" plus each bundled theme. Thumbnails use the theme's arrow asset;- // the persisted value is the theme id.- const cursorThemeOptions = useMemo(- () => [- {- id: DEFAULT_CURSOR_THEME_ID,- name: t("cursor.themeDefault"),- previewUrl: defaultCursorPreviewUrl,- },- ...CURSOR_THEMES.map((theme) => {- const previewPath = (theme.assets.arrow ?? theme.assets.pointer)?.assetPath;- return {- id: theme.id,- name: theme.name,- previewUrl: previewPath ? getAssetPath(previewPath) : defaultCursorPreviewUrl,- };- }),- ],- [t],- );- const [customImages, setCustomImages] = useState<string[]>([]);- const fileInputRef = useRef<HTMLInputElement>(null);- const colorPalette = [- "#FF0000",- "#FFD700",- "#00FF00",- "#FFFFFF",- "#0000FF",- "#FF6B00",- "#9B59B6",- "#E91E63",- "#00BCD4",- "#FF5722",- "#8BC34A",- "#FFC107",- "#34B27B",- "#000000",- "#607D8B",- "#795548",- ];-- const [selectedColor, setSelectedColor] = useState("#ADADAD");- const [gradient, setGradient] = useState<string>(GRADIENTS[0]);- const [cropAspectLocked, setCropAspectLocked] = useState(false);- const [cropAspectRatio, setCropAspectRatio] = useState("");- const isPortraitCanvas = isPortraitAspectRatio(aspectRatio);-- const videoWidth = videoElement?.videoWidth || DEFAULT_SOURCE_DIMENSIONS.width;- const videoHeight = videoElement?.videoHeight || DEFAULT_SOURCE_DIMENSIONS.height;-- const handleCropNumericChange = useCallback(- (field: "x" | "y" | "width" | "height", pixelValue: number) => {- if (!cropRegion || !onCropChange) return;-- const next = { ...cropRegion };- switch (field) {- case "x":- next.x = Math.max(0, Math.min(pixelValue / videoWidth, 1 - next.width));- break;- case "y":- next.y = Math.max(0, Math.min(pixelValue / videoHeight, 1 - next.height));- break;- case "width": {- const newWidth = Math.max(0.05, Math.min(pixelValue / videoWidth, 1 - next.x));- if (cropAspectLocked && next.width > 0 && next.height > 0) {- const ratio = next.width / next.height;- const newHeight = newWidth / ratio;- if (next.y + newHeight <= 1) {- next.width = newWidth;- next.height = newHeight;- }- } else {- next.width = newWidth;- }- break;- }- case "height": {- const newHeight = Math.max(0.05, Math.min(pixelValue / videoHeight, 1 - next.y));- if (cropAspectLocked && next.width > 0 && next.height > 0) {- const ratio = next.width / next.height;- const newWidth = newHeight * ratio;- if (next.x + newWidth <= 1) {- next.height = newHeight;- next.width = newWidth;- }- } else {- next.height = newHeight;- }- break;- }- }-- onCropChange(next);- },- [cropRegion, onCropChange, videoWidth, videoHeight, cropAspectLocked],- );-- const applyCropAspectPreset = useCallback(- (preset: string) => {- if (!cropRegion || !onCropChange) return;-- setCropAspectRatio(preset);- if (preset === "") {- setCropAspectLocked(false);- return;- }-- const [wStr, hStr] = preset.split(":");- const targetRatio = Number(wStr) / Number(hStr);- const next = { ...cropRegion };-- const nextHeight = (next.width * videoWidth) / (targetRatio * videoHeight);- if (next.y + nextHeight <= 1 && nextHeight >= 0.05) {- next.height = nextHeight;- } else {- const nextWidth = (next.height * videoHeight * targetRatio) / videoWidth;- if (next.x + nextWidth <= 1 && nextWidth >= 0.05) {- next.width = nextWidth;- }- }-- onCropChange(next);- setCropAspectLocked(true);- },- [cropRegion, onCropChange, videoWidth, videoHeight],- );-- const getCropPixelValue = useCallback(- (field: "x" | "y" | "width" | "height"): number => {- if (!cropRegion) return 0;- switch (field) {- case "x":- return Math.round(cropRegion.x * videoWidth);- case "y":- return Math.round(cropRegion.y * videoHeight);- case "width":- return Math.round(cropRegion.width * videoWidth);- case "height":- return Math.round(cropRegion.height * videoHeight);- }- },- [cropRegion, videoWidth, videoHeight],- );- const [showCropDropdown, setShowCropDropdown] = useState(false);- const handleCropToggle = () => setShowCropDropdown((open) => !open);-- const zoomEnabled = Boolean(selectedZoomDepth);- const trimEnabled = Boolean(selectedTrimId);- const hasTimelineSelection = Boolean(selectedZoomId || selectedTrimId || selectedSpeedId);- const hasCursorPanel = showCursorSettings && hasCursorData;- const panelModes: Array<{- id: SettingsPanelMode;- label: string;- icon: ComponentType<{ className?: string }>;- disabled?: boolean;- }> = [- { id: "background", label: t("background.title"), icon: Palette },- { id: "effects", label: t("effects.title"), icon: SlidersHorizontal },- { id: "layout", label: t("layout.title"), icon: LayoutPanelTop, disabled: !hasWebcam },- { id: "timeline", label: t("timeline.title"), icon: Brackets },- ...(hasCursorPanel- ? [- {- id: "cursor" as const,- label: t("effects.title"),- icon: MousePointerClick,- },- ]- : []),- ];- const exportPanelMode = {- id: "export" as const,- label: exportFormat === "gif" ? t("export.gifButton") : t("export.videoButton"),- icon: Download,- };- const activeModeLabel = hasTimelineSelection- ? selectedZoomId- ? t("zoom.level")- : selectedSpeedId- ? t("speed.playbackSpeed")- : t("trim.deleteRegion")- : activePanelMode === "timeline"- ? t("timeline.title")- : ([...panelModes, exportPanelMode].find((mode) => mode.id === activePanelMode)?.label ??- t("background.title"));-- const handleDeleteClick = () => {- if (selectedZoomId && onZoomDelete) {- onZoomDelete(selectedZoomId);- }- };-- const handleTrimDeleteClick = () => {- if (selectedTrimId && onTrimDelete) {- onTrimDelete(selectedTrimId);- }- };-- const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {- const files = event.target.files;- if (!files || files.length === 0) return;-- const file = files[0];-- if (!isSupportedBackgroundImageType(file.type, file.name)) {- toast.error(t("imageUpload.invalidFileType"), {- description: t("imageUpload.jpgOnly"),- });- event.target.value = "";- return;- }-- const reader = new FileReader();-- reader.onload = (e) => {- const dataUrl = e.target?.result as string;- if (dataUrl) {- setCustomImages((prev) => [...prev, dataUrl]);- onWallpaperChange(dataUrl);- toast.success(t("imageUpload.uploadSuccess"));- }- };-- reader.onerror = () => {- toast.error(t("imageUpload.failedToUpload"), {- description: t("imageUpload.errorReading"),- });- };-- reader.readAsDataURL(file);- // Reset input so the same file can be selected again- event.target.value = "";- };-- const handleRemoveCustomImage = (imageUrl: string, event: React.MouseEvent) => {- event.stopPropagation();- setCustomImages((prev) => prev.filter((img) => img !== imageUrl));- // If the removed image was selected, reset to the first wallpaper.- if (selected === imageUrl) {- onWallpaperChange(WALLPAPER_PATHS[0]);- }- };-- const selectedAnnotation = selectedAnnotationId- ? annotationRegions.find((a) => a.id === selectedAnnotationId)- : null;- const selectedBlur = selectedBlurId- ? blurRegions.find((region) => region.id === selectedBlurId)- : null;- const commonFooterLinks = (- <div className="flex gap-2 mt-3">- <button- type="button"- onClick={() => {- window.electronAPI?.openExternalUrl(- "https://github.com/EtienneLescot/openscreen/issues/new/choose",- );- }}- className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"- >- <Bug className="w-3 h-3 text-[#34B27B]" />- {t("support.reportBug")}- </button>- {onSaveDiagnostic && (- <button- type="button"- onClick={onSaveDiagnostic}- className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"- >- <FileDown className="w-3 h-3 text-slate-400" />- {t("support.saveDiagnostics")}- </button>- )}- <button- type="button"- onClick={() => {- window.electronAPI?.openExternalUrl("https://github.com/EtienneLescot/openscreen");- }}- className="flex-1 flex items-center justify-center gap-1.5 text-[10px] text-slate-500 hover:text-slate-300 py-1.5 transition-colors"- >- <Star className="w-3 h-3 text-yellow-400" />- {t("support.starOnGithub")}- </button>- </div>- );-- // Annotation selected: show its settings panel instead.- if (- selectedAnnotation &&- onAnnotationContentChange &&- onAnnotationTypeChange &&- onAnnotationStyleChange &&- onAnnotationDelete- ) {- return (- <div className="editor-inspector-shell flex min-w-0 flex-col h-full overflow-hidden">- <div className="min-h-0 flex-1 overflow-hidden">- <AnnotationSettingsPanel- annotation={selectedAnnotation}- onContentChange={(content) => onAnnotationContentChange(selectedAnnotation.id, content)}- onTypeChange={(type) => onAnnotationTypeChange(selectedAnnotation.id, type)}- onStyleChange={(style) => onAnnotationStyleChange(selectedAnnotation.id, style)}- onFigureDataChange={- onAnnotationFigureDataChange- ? (figureData) => onAnnotationFigureDataChange(selectedAnnotation.id, figureData)- : undefined- }- onDuplicate={- onAnnotationDuplicate ? () => onAnnotationDuplicate(selectedAnnotation.id) : undefined- }- onDelete={() => onAnnotationDelete(selectedAnnotation.id)}- />- </div>- <div className="flex-shrink-0 p-3 border-t border-white/[0.07] bg-black/25">- {commonFooterLinks}- </div>- </div>- );- }-- if (BLUR_REGIONS_ENABLED && selectedBlur && onBlurDataChange && onBlurDelete) {- return (- <div className="editor-inspector-shell flex min-w-0 flex-col h-full overflow-hidden">- <div className="min-h-0 flex-1 overflow-hidden">- <BlurSettingsPanel- blurRegion={selectedBlur}- onBlurDataChange={(blurData) => onBlurDataChange(selectedBlur.id, blurData)}- onBlurDataCommit={onBlurDataCommit}- onDelete={() => onBlurDelete(selectedBlur.id)}- />- </div>- <div className="flex-shrink-0 p-3 border-t border-white/[0.07] bg-black/25">- {commonFooterLinks}- </div>- </div>- );- }-- return (- <div className="editor-inspector-shell flex min-w-0 flex-col h-full overflow-hidden">- <div className="flex min-h-0 flex-1">- <div className="settings-mode-rail flex w-11 shrink-0 flex-col items-center gap-1 border-r border-white/[0.07] bg-black/20 px-1 py-2.5">- {panelModes.map((mode) => {- const Icon = mode.icon;- const isActive = activePanelMode === mode.id && !hasTimelineSelection;- return (- <button- key={mode.id}- type="button"- title={mode.label}- disabled={mode.disabled}- onClick={() => {- if (mode.id === "layout" && mode.disabled) return;- setActivePanelMode(mode.id);- }}- className={cn(- "flex h-8 w-8 items-center justify-center rounded-lg border transition-all",- mode.disabled- ? "cursor-not-allowed border-transparent text-slate-700"- : isActive- ? "border-[#34B27B]/50 bg-[#34B27B]/15 text-[#34B27B] shadow-[0_0_0_1px_rgba(52,178,123,0.12)]"- : "border-transparent text-slate-500 hover:border-white/10 hover:bg-white/[0.06] hover:text-slate-200",- )}- >- <Icon className="h-4 w-4" />- </button>- );- })}- <button- type="button"- title={t("crop.cropVideo")}- onClick={handleCropToggle}- className="mt-1 flex h-8 w-8 items-center justify-center rounded-lg border border-transparent text-slate-500 transition-all hover:border-white/10 hover:bg-white/[0.06] hover:text-slate-200"- >- <Crop className="h-4 w-4" />- </button>- <button- data-testid={getTestId("export-panel-button")}- type="button"- title={exportPanelMode.label}- onClick={() => {- setActivePanelMode(exportPanelMode.id);- onExportPanelOpen?.();- }}- className={cn(- "mt-auto flex h-8 w-8 items-center justify-center rounded-lg border transition-all",- activePanelMode === "export" && !hasTimelineSelection- ? "border-[#34B27B]/50 bg-[#34B27B]/15 text-[#34B27B] shadow-[0_0_0_1px_rgba(52,178,123,0.12)]"- : "border-transparent text-slate-500 hover:border-white/10 hover:bg-white/[0.06] hover:text-slate-200",- )}- >- <Download className="h-4 w-4" />- </button>- </div>- <div className="flex-1 overflow-y-auto custom-scrollbar p-3 pb-0">- <div className="mb-3 flex items-center justify-between px-1">- <span className="text-sm font-semibold text-slate-100">{activeModeLabel}</span>- <KeyboardShortcutsHelp />- </div>- {zoomEnabled && (- <div className="editor-panel-section mb-3 space-y-3 px-1">- <div className="flex items-center justify-between">- <span className="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">- {t("zoom.level")}- </span>- <span className="rounded-full border border-[#34B27B]/25 bg-[#34B27B]/10 px-2 py-0.5 text-[11px] font-semibold tabular-nums text-[#34B27B]">- {(- selectedZoomCustomScale ??- (selectedZoomDepth != null- ? ZOOM_DEPTH_SCALES[selectedZoomDepth]- : MIN_ZOOM_SCALE)- ).toFixed(2)}- ×- </span>- </div>- <div className="grid grid-cols-6 gap-1">- {ZOOM_DEPTH_OPTIONS.map((option) => {- const effectiveScale =- selectedZoomCustomScale ??- (selectedZoomDepth != null ? ZOOM_DEPTH_SCALES[selectedZoomDepth] : null);- const isActive = effectiveScale === ZOOM_DEPTH_SCALES[option.depth];- return (- <Button- key={option.depth}- type="button"- disabled={!zoomEnabled}- onClick={() => onZoomDepthChange?.(option.depth)}- className={cn(- "h-8 w-full rounded-lg border px-1 text-center transition-all duration-150 ease-out",- zoomEnabled- ? "opacity-100 cursor-pointer"- : "opacity-40 cursor-not-allowed",- isActive- ? "border-[#34B27B]/70 bg-[#34B27B] text-white shadow-[0_8px_20px_rgba(52,178,123,0.18)]"- : "border-white/[0.06] bg-white/[0.035] text-slate-400 hover:bg-white/[0.075] hover:border-white/15 hover:text-slate-200",- )}- >- <span className="text-[11px] font-semibold">{option.label}</span>- </Button>- );- })}- </div>- {zoomEnabled && (- <div>- <SliderPrimitive.Root- min={MIN_ZOOM_SCALE}- max={MAX_ZOOM_SCALE}- step={0.01}- value={[- selectedZoomCustomScale ??- (selectedZoomDepth != null- ? ZOOM_DEPTH_SCALES[selectedZoomDepth]- : MIN_ZOOM_SCALE),- ]}- onValueChange={(values) => onZoomCustomScaleChange?.(values[0])}- onValueCommit={() => onZoomCustomScaleCommit?.()}- disabled={!zoomEnabled}- className="relative flex w-full touch-none select-none items-center py-1"- >- <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full border border-white/10 bg-white/5">- <SliderPrimitive.Range- className={cn(- "absolute h-full transition-colors duration-150",- selectedZoomCustomScale != null ? "bg-[#34B27B]" : "bg-white/20",- )}- />- </SliderPrimitive.Track>- <SliderPrimitive.Thumb- className={cn(- "block h-3.5 w-3.5 rounded-full border-2 shadow transition-all duration-150",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#34B27B]/50",- "disabled:pointer-events-none disabled:opacity-50 cursor-grab active:cursor-grabbing",- selectedZoomCustomScale != null- ? "border-[#34B27B] bg-[#34B27B] shadow-[0_0_6px_rgba(52,178,123,0.4)]"- : "border-white/20 bg-[#2a2a30] hover:border-white/40",- )}- />- </SliderPrimitive.Root>- <div className="flex justify-between text-[10px] text-slate-600 mt-1">- <span>{MIN_ZOOM_SCALE.toFixed(1)}×</span>- <span>{MAX_ZOOM_SCALE.toFixed(1)}×</span>- </div>- </div>- )}- {zoomEnabled && hasCursorTelemetry && (- <div className="space-y-1.5">- <div className="flex items-center justify-between gap-3">- <span className="text-[11px] font-medium text-slate-400">- {t("zoom.focusMode.title")}- </span>- <div className="grid w-32 grid-cols-2 gap-0.5 rounded-lg border border-white/[0.06] bg-white/[0.035] p-0.5">- {(["manual", "auto"] as const).map((mode) => {- const isActive = selectedZoomFocusMode === mode;- return (- <Button- key={mode}- type="button"- disabled={focusModeLocked}- onClick={() => !focusModeLocked && onZoomFocusModeChange?.(mode)}- className={cn(- "h-6 w-full rounded-md border px-1 text-center transition-all duration-150 ease-out",- isActive- ? "border-[#34B27B]/50 bg-[#34B27B] text-white"- : "border-transparent bg-transparent text-slate-400 hover:bg-white/[0.06] hover:text-slate-200",- focusModeLocked ? "cursor-not-allowed opacity-50" : "cursor-pointer",- )}- >- <span className="text-[10px] font-semibold capitalize">- {t(`zoom.focusMode.${mode}`)}- </span>- </Button>- );- })}- </div>- </div>- {focusModeLocked && (- <div className="flex items-start gap-1 text-[10px] leading-snug text-slate-500">- <Info size={11} className="mt-px shrink-0" />- <span>{t("zoom.focusMode.lockedDisclaimer")}</span>- </div>- )}- </div>- )}- {zoomEnabled && onZoomPreviewStart && onZoomPreviewEnd && (- <Button- type="button"- onPointerDown={() => onZoomPreviewStart()}- onPointerUp={() => onZoomPreviewEnd()}- onPointerLeave={() => onZoomPreviewEnd()}- onPointerCancel={() => onZoomPreviewEnd()}- onKeyDown={(e) => {- if ((e.key === " " || e.key === "Enter") && !e.repeat) {- e.preventDefault();- onZoomPreviewStart();- }- }}- onKeyUp={(e) => {- if (e.key === " " || e.key === "Enter") {- e.preventDefault();- onZoomPreviewEnd();- }- }}- onBlur={() => onZoomPreviewEnd()}- className="h-7 w-full select-none rounded-md border border-white/[0.08] bg-white/[0.04] text-[10px] font-semibold text-slate-300 transition-all duration-150 ease-out hover:bg-white/[0.08] hover:text-slate-100 active:border-[#34B27B]/50 active:bg-[#34B27B] active:text-white cursor-pointer"- >- {t("zoom.previewHold")}- </Button>- )}- {zoomEnabled &&- selectedZoomFocusMode !== "auto" &&- selectedZoomFocus &&- onZoomFocusCoordinateChange &&- (() => {- const effectiveZoomScale =- selectedZoomCustomScale ??- (selectedZoomDepth != null- ? ZOOM_DEPTH_SCALES[selectedZoomDepth]- : MIN_ZOOM_SCALE);- const bounds = getFocusBoundsForScale(effectiveZoomScale);- const xRange = bounds.maxX - bounds.minX;- const yRange = bounds.maxY - bounds.minY;- const focusToPercentX = (cx: number) =>- xRange <= 0- ? 50- : Math.max(0, Math.min(100, ((cx - bounds.minX) / xRange) * 100));- const focusToPercentY = (cy: number) =>- yRange <= 0- ? 50- : Math.max(0, Math.min(100, ((cy - bounds.minY) / yRange) * 100));- const percentToFocusX = (p: number) =>- xRange <= 0 ? bounds.minX : bounds.minX + (p / 100) * xRange;- const percentToFocusY = (p: number) =>- yRange <= 0 ? bounds.minY : bounds.minY + (p / 100) * yRange;- return (- <div>- <span className="text-[11px] font-medium text-slate-400 mb-1.5 block">- {t("zoom.position.title")}- </span>- <div className="grid grid-cols-2 gap-2">- <div className="flex flex-col gap-1">- <label className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">- {t("zoom.position.x")}- </label>- <ZoomFocusCoordInput- ariaLabel={t("zoom.position.x")}- percent={focusToPercentX(selectedZoomFocus.cx)}- onChange={(p) =>- onZoomFocusCoordinateChange({- cx: percentToFocusX(p),- cy: selectedZoomFocus.cy,- })- }- onCommit={onZoomFocusCoordinateCommit}- />- </div>- <div className="flex flex-col gap-1">- <label className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">- {t("zoom.position.y")}- </label>- <ZoomFocusCoordInput- ariaLabel={t("zoom.position.y")}- percent={focusToPercentY(selectedZoomFocus.cy)}- onChange={(p) =>- onZoomFocusCoordinateChange({- cx: selectedZoomFocus.cx,- cy: percentToFocusY(p),- })- }- onCommit={onZoomFocusCoordinateCommit}- />- </div>- </div>- </div>- );- })()}- {zoomEnabled && (- <div>- <span className="text-[11px] font-medium text-slate-400 mb-1.5 block">- {t("zoom.threeD.title")}- </span>- <div className="grid grid-cols-3 gap-1.5">- {ROTATION_3D_PRESET_ORDER.map((preset) => {- const isActive = selectedZoomRotationPreset === preset;- return (- <Button- key={preset}- type="button"- onClick={() => onZoomRotationPresetChange?.(isActive ? null : preset)}- className={cn(- "h-8 w-full rounded-lg border px-1 text-center transition-all duration-150 ease-out cursor-pointer",- isActive- ? "border-[#34B27B]/60 bg-[#34B27B] text-white"- : "border-white/[0.06] bg-white/[0.035] text-slate-400 hover:bg-white/[0.075] hover:border-white/15 hover:text-slate-200",- )}- >- <span className="text-xs font-semibold capitalize">- {t(`zoom.threeD.preset.${preset}`)}- </span>- </Button>- );- })}- </div>- </div>- )}-- {zoomEnabled && (- <Button- onClick={handleDeleteClick}- variant="destructive"- size="sm"- className="mt-1 w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"- >- <Trash2 className="w-3 h-3" />- {t("zoom.deleteZoom")}- </Button>- )}- </div>- )}-- {trimEnabled && (- <div className="mb-4">- <Button- onClick={handleTrimDeleteClick}- variant="destructive"- size="sm"- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"- >- <Trash2 className="w-3 h-3" />- {t("trim.deleteRegion")}- </Button>- </div>- )}-- {selectedSpeedId && (- <div className="editor-panel-section mb-3 space-y-3 px-1">- <div className="flex items-center justify-between">- <span className="text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">- {t("speed.playbackSpeed")}- </span>- {selectedSpeedId && selectedSpeedValue && (- <span className="rounded-full border border-[#d97706]/25 bg-[#d97706]/10 px-2 py-0.5 text-[11px] font-semibold tabular-nums text-[#d97706]">- {SPEED_OPTIONS.find((o) => o.speed === selectedSpeedValue)?.label ??- `${selectedSpeedValue}×`}- </span>- )}- </div>- <div className="grid grid-cols-5 gap-1">- {SPEED_OPTIONS.map((option) => {- const isActive = selectedSpeedValue === option.speed;- return (- <Button- key={option.speed}- type="button"- disabled={!selectedSpeedId}- onClick={() => onSpeedChange?.(option.speed)}- className={cn(- "h-8 w-full rounded-lg border px-1 text-center transition-all duration-150 ease-out",- selectedSpeedId- ? "opacity-100 cursor-pointer"- : "opacity-40 cursor-not-allowed",- isActive- ? "border-[#d97706]/70 bg-[#d97706] text-white shadow-[0_8px_20px_rgba(217,119,6,0.16)]"- : "border-white/[0.06] bg-white/[0.035] text-slate-400 hover:bg-white/[0.075] hover:border-white/15 hover:text-slate-200",- )}- >- <span className="text-[11px] font-semibold">{option.label}</span>- </Button>- );- })}- </div>- <div className="flex items-center justify-between rounded-lg border border-white/[0.06] bg-white/[0.03] px-2 py-1.5">- <span- className={cn(- "text-[11px]",- selectedSpeedId ? "text-slate-500" : "text-slate-600",- )}- >- {t("speed.customPlaybackSpeed")}- </span>- {selectedSpeedId ? (- <CustomSpeedInput- value={selectedSpeedValue ?? 1}- onChange={(val) => onSpeedChange?.(val)}- onError={() =>- toast.error(t("speed.maxSpeedError", { max: MAX_PLAYBACK_SPEED }))- }- />- ) : (- <div className="flex items-center gap-1 opacity-40">- <div className="w-12 bg-white/5 border border-white/10 rounded-md px-1 py-0.5 text-[11px] font-semibold text-slate-600 text-center">- --- </div>- <span className="text-[11px] font-semibold text-slate-600">×</span>- </div>- )}- </div>- {selectedSpeedId &&- selectedSpeedValue != null &&- selectedSpeedValue > MAX_NATIVE_PLAYBACK_RATE && (- <p className="px-1 text-[10px] leading-snug text-slate-500">- {t("speed.previewFrameSteppingHint", { native: MAX_NATIVE_PLAYBACK_RATE })}- </p>- )}- {selectedSpeedId && (- <Button- onClick={() => selectedSpeedId && onSpeedDelete?.(selectedSpeedId)}- variant="destructive"- size="sm"- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all h-8 text-xs"- >- <Trash2 className="w-3 h-3" />- {t("speed.deleteRegion")}- </Button>- )}- </div>- )}-- {!hasTimelineSelection && (- <Accordion type="multiple" value={[activePanelMode]} className="space-y-2">- {hasWebcam && activePanelMode === "layout" && (- <AccordionItem value="layout" className="editor-panel-section px-3">- <AccordionTrigger className="py-2.5 hover:no-underline">- <div className="flex items-center gap-2">- <Sparkles className="w-4 h-4 text-[#34B27B]" />- <span className="text-xs font-medium">{t("layout.title")}</span>- </div>- </AccordionTrigger>- <AccordionContent className="pb-3">- <div className="p-2 rounded-lg editor-control-surface">- <div className="text-[10px] font-medium text-slate-300 mb-1.5">- {t("layout.preset")}- </div>- <Select- value={webcamLayoutPreset}- onValueChange={(value: WebcamLayoutPreset) =>- onWebcamLayoutPresetChange?.(value)- }- >- <SelectTrigger className="h-8 bg-black/20 border-white/10 text-xs">- <SelectValue placeholder={t("layout.selectPreset")} />- </SelectTrigger>- <SelectContent>- {WEBCAM_LAYOUT_PRESETS.filter((preset) => {- if (preset.value === "picture-in-picture") return true;- if (preset.value === "no-webcam") return true;- if (preset.value === "vertical-stack") return isPortraitCanvas;- return !isPortraitCanvas;- }).map((preset) => (- <SelectItem key={preset.value} value={preset.value} className="text-xs">- {preset.value === "picture-in-picture"- ? t("layout.pictureInPicture")- : preset.value === "vertical-stack"- ? t("layout.verticalStack")- : preset.value === "no-webcam"- ? t("layout.noWebcam")- : t("layout.dualFrame")}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- {webcamLayoutPreset !== "no-webcam" && (- <div className="mt-2 flex items-center justify-between p-2 rounded-lg editor-control-surface">- <div className="text-[10px] font-medium text-slate-300">- {t("layout.mirrorWebcam")}- </div>- <Switch- checked={webcamMirrored}- onCheckedChange={onWebcamMirroredChange}- className="data-[state=checked]:bg-[#34B27B] scale-90"- aria-label={t("layout.mirrorWebcam")}- />- </div>- )}- {webcamLayoutPreset === "picture-in-picture" && (- <div className="mt-2 flex items-center justify-between p-2 rounded-lg editor-control-surface">- <div className="flex items-center gap-1 text-[10px] font-medium text-slate-300">- <span>{t("layout.reactiveWebcam")}</span>- <Tooltip- content={t("layout.reactiveWebcamDescription")}- className="max-w-[220px] leading-snug whitespace-normal"- >- <button- type="button"- className="text-slate-400 transition-colors hover:text-slate-200"- aria-label={t("layout.reactiveWebcamDescription")}- >- <Info size={11} />- </button>- </Tooltip>- </div>- <Switch- checked={webcamReactiveZoom}- onCheckedChange={onWebcamReactiveZoomChange}- className="data-[state=checked]:bg-[#34B27B] scale-90"- aria-label={t("layout.reactiveWebcam")}- />- </div>- )}- {webcamLayoutPreset === "picture-in-picture" && (- <div className="mt-2 p-2 rounded-lg editor-control-surface">- <div className="text-[10px] font-medium text-slate-300 mb-1.5">- {t("layout.webcamShape")}- </div>- <div className="grid grid-cols-4 gap-1.5">- {(- [- { value: "rectangle", label: "Rect" },- { value: "circle", label: "Circle" },- { value: "square", label: "Square" },- { value: "rounded", label: "Rounded" },- ] as Array<{ value: WebcamMaskShape; label: string }>- ).map((shape) => (- <button- key={shape.value}- type="button"- onClick={() => onWebcamMaskShapeChange?.(shape.value)}- className={cn(- "h-10 rounded-lg border flex flex-col items-center justify-center gap-0.5 transition-all",- webcamMaskShape === shape.value- ? "bg-[#34B27B] border-[#34B27B] text-white"- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20 text-slate-400",- )}- >- <svg- width="16"- height="16"- viewBox="0 0 16 16"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- {shape.value === "rectangle" && (- <rect- x="1"- y="3"- width="14"- height="10"- rx="2"- stroke="currentColor"- strokeWidth="1.5"- />- )}- {shape.value === "circle" && (- <circle- cx="8"- cy="8"- r="6.5"- stroke="currentColor"- strokeWidth="1.5"- />- )}- {shape.value === "square" && (- <rect- x="2"- y="2"- width="12"- height="12"- rx="1"- stroke="currentColor"- strokeWidth="1.5"- />- )}- {shape.value === "rounded" && (- <rect- x="1"- y="3"- width="14"- height="10"- rx="5"- stroke="currentColor"- strokeWidth="1.5"- />- )}- </svg>- <span className="text-[8px] leading-none">{shape.label}</span>- </button>- ))}- </div>- </div>- )}- {webcamLayoutPreset === "picture-in-picture" && (- <div className="p-2 rounded-lg editor-control-surface mt-2">- <div className="flex items-center justify-between mb-1.5">- <div className="text-[10px] font-medium text-slate-300">- {t("layout.webcamSize")}- </div>- <div className="text-[10px] font-medium text-slate-400">- {webcamSizePreset}%- </div>- </div>- <Slider- value={[webcamSizePreset]}- onValueChange={(values) => onWebcamSizePresetChange?.(values[0])}- onValueCommit={() => onWebcamSizePresetCommit?.()}- min={10}- max={50}- step={1}- className="w-full"- />- </div>- )}- </AccordionContent>- </AccordionItem>- )}-- {(activePanelMode === "effects" || activePanelMode === "cursor") && (- <AccordionItem value={activePanelMode} className="editor-panel-section px-3">- <AccordionTrigger className="py-2.5 hover:no-underline">- <div className="flex items-center gap-2">- {activePanelMode === "cursor" ? (- <MousePointerClick className="w-4 h-4 text-[#34B27B]" />- ) : (- <SlidersHorizontal className="w-4 h-4 text-[#34B27B]" />- )}- <span className="text-xs font-medium">{t("effects.title")}</span>- </div>- </AccordionTrigger>- <AccordionContent className="pb-3">- {activePanelMode === "effects" && (- <>- <div className="grid grid-cols-2 gap-2 mb-3">- <div className="flex items-center justify-between p-2 rounded-lg editor-control-surface">- <div className="text-[10px] font-medium text-slate-300">- {t("effects.blurBg")}- </div>- <Switch- checked={showBlur}- onCheckedChange={onBlurChange}- className="data-[state=checked]:bg-[#34B27B] scale-90"- />- </div>- </div>-- <div className="grid grid-cols-2 gap-2">- <div className="p-2 rounded-lg editor-control-surface">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("effects.motionBlur")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {motionBlurAmount === 0- ? t("effects.off")- : motionBlurAmount.toFixed(2)}- </span>- </div>- <Slider- value={[motionBlurAmount]}- onValueChange={(values) => onMotionBlurChange?.(values[0])}- onValueCommit={() => onMotionBlurCommit?.()}- min={0}- max={1}- step={0.01}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div className="p-2 rounded-lg editor-control-surface">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("effects.shadow")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {Math.round(shadowIntensity * 100)}%- </span>- </div>- <Slider- value={[shadowIntensity]}- onValueChange={(values) => onShadowChange?.(values[0])}- onValueCommit={() => onShadowCommit?.()}- min={0}- max={1}- step={0.01}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div className="p-2 rounded-lg editor-control-surface">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("effects.roundness")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {borderRadius}px- </span>- </div>- <Slider- value={[borderRadius]}- onValueChange={(values) => onBorderRadiusChange?.(values[0])}- onValueCommit={() => onBorderRadiusCommit?.()}- min={0}- max={64}- step={0.5}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div- className={`p-2 rounded-lg editor-control-surface ${webcamLayoutPreset === "vertical-stack" ? "opacity-40 pointer-events-none" : ""}`}- >- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("effects.padding")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {webcamLayoutPreset === "vertical-stack" ? "—" : `${padding}%`}- </span>- </div>- <Slider- value={[webcamLayoutPreset === "vertical-stack" ? 0 : padding]}- onValueChange={(values) => onPaddingChange?.(values[0])}- onValueCommit={() => onPaddingCommit?.()}- min={0}- max={100}- step={1}- disabled={webcamLayoutPreset === "vertical-stack"}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- </div>- </>- )}-- {activePanelMode === "cursor" && showCursorSettings && hasCursorData && (- <div className="p-2 rounded-lg editor-control-surface mt-2 space-y-3">- <div className="flex items-center justify-between">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.show")}- </div>- <Switch- checked={showCursor}- onCheckedChange={onShowCursorChange}- className="data-[state=checked]:bg-[#34B27B] scale-90"- />- </div>- {showCursor && (- <>- <div className="flex items-center justify-between">- <div className="flex items-center gap-1 text-[10px] font-medium text-slate-300">- <span>{t("cursor.clipToBounds")}</span>- <Tooltip- content={t("cursor.clipToBoundsDescription")}- className="max-w-[220px] leading-snug whitespace-normal"- >- <button- type="button"- className="text-slate-400 transition-colors hover:text-slate-200"- aria-label={t("cursor.clipToBoundsDescription")}- >- <Info size={11} />- </button>- </Tooltip>- </div>- <Switch- checked={cursorClipToBounds}- onCheckedChange={onCursorClipToBoundsChange}- className="data-[state=checked]:bg-[#34B27B] scale-90"- aria-label={t("cursor.clipToBounds")}- />- </div>- {cursorThemeOptions.length > 1 && (- <div className="space-y-1.5">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.theme")}- </div>- <div className="flex flex-wrap gap-1.5">- {cursorThemeOptions.map((option) => {- const isSelected = cursorTheme === option.id;- return (- <button- type="button"- key={option.id}- title={option.name}- aria-label={option.name}- aria-pressed={isSelected}- onClick={() => onCursorThemeChange?.(option.id)}- className={cn(- "flex items-center justify-center w-8 h-8 rounded-lg border overflow-hidden transition-all duration-150 shadow-sm bg-white/5",- isSelected- ? "border-[#34B27B] ring-1 ring-[#34B27B]/30"- : "border-white/10 hover:border-[#34B27B]/40 opacity-80 hover:opacity-100",- )}- >- <img- src={option.previewUrl}- alt=""- className="w-5 h-5 object-contain"- draggable={false}- />- </button>- );- })}- </div>- </div>- )}- <div className="grid grid-cols-2 gap-2">- <div className="p-2 rounded-lg bg-white/5 border border-white/5">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.size")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {cursorSize.toFixed(1)}- </span>- </div>- <Slider- value={[cursorSize]}- onValueChange={(values) => onCursorSizeChange?.(values[0])}- min={0.5}- max={10}- step={0.1}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div className="p-2 rounded-lg bg-white/5 border border-white/5">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.smoothing")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {Math.round(cursorSmoothing * 100)}%- </span>- </div>- <Slider- value={[cursorSmoothing]}- onValueChange={(values) => onCursorSmoothingChange?.(values[0])}- min={0}- max={1}- step={0.01}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div className="p-2 rounded-lg bg-white/5 border border-white/5">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.motionBlur")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {Math.round(cursorMotionBlur * 100)}%- </span>- </div>- <Slider- value={[cursorMotionBlur]}- onValueChange={(values) => onCursorMotionBlurChange?.(values[0])}- min={0}- max={1}- step={0.01}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- <div className="p-2 rounded-lg bg-white/5 border border-white/5">- <div className="flex items-center justify-between mb-1">- <div className="text-[10px] font-medium text-slate-300">- {t("cursor.clickBounce")}- </div>- <span className="text-[10px] text-slate-500 font-mono">- {cursorClickBounce.toFixed(1)}- </span>- </div>- <Slider- value={[cursorClickBounce]}- onValueChange={(values) => onCursorClickBounceChange?.(values[0])}- min={0}- max={5}- step={0.1}- className="w-full [&_[role=slider]]:bg-[#34B27B] [&_[role=slider]]:border-[#34B27B] [&_[role=slider]]:h-3 [&_[role=slider]]:w-3"- />- </div>- </div>- </>- )}- </div>- )}- </AccordionContent>- </AccordionItem>- )}-- {activePanelMode === "background" && (- <AccordionItem value="background" className="editor-panel-section px-3">- <AccordionTrigger className="py-2.5 hover:no-underline">- <div className="flex items-center gap-2">- <Palette className="w-4 h-4 text-[#34B27B]" />- <span className="text-xs font-medium">{t("background.title")}</span>- </div>- </AccordionTrigger>- <AccordionContent className="pb-3">- <Tabs defaultValue="image" className="w-full">- <TabsList className="mb-2 grid h-7 w-full grid-cols-3 rounded-lg border border-white/5 bg-white/5 p-0.5">- <TabsTrigger- value="image"- className="h-full min-w-0 rounded-md px-1 py-0 text-[10px] leading-none text-slate-400 transition-colors data-[state=active]:bg-[#34B27B] data-[state=active]:text-white data-[state=active]:shadow-none"- >- {t("background.image")}- </TabsTrigger>- <TabsTrigger- value="color"- className="h-full min-w-0 rounded-md px-1 py-0 text-[10px] leading-none text-slate-400 transition-colors data-[state=active]:bg-[#34B27B] data-[state=active]:text-white data-[state=active]:shadow-none"- >- {t("background.color")}- </TabsTrigger>- <TabsTrigger- value="gradient"- className="h-full min-w-0 rounded-md px-1 py-0 text-[10px] leading-none text-slate-400 transition-colors data-[state=active]:bg-[#34B27B] data-[state=active]:text-white data-[state=active]:shadow-none"- >- {t("background.gradient")}- </TabsTrigger>- </TabsList>-- <div className="overflow-y-auto custom-scrollbar">- <TabsContent value="image" className="mt-0 space-y-2">- <input- type="file"- ref={fileInputRef}- onChange={handleImageUpload}- accept={BACKGROUND_IMAGE_ACCEPT}- className="hidden"- />- <Button- onClick={() => fileInputRef.current?.click()}- variant="outline"- className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#34B27B] hover:text-white hover:border-[#34B27B] transition-all h-7 text-[10px]"- >- <Upload className="w-3 h-3" />- {t("background.uploadCustom")}- </Button>-- <div className="grid grid-cols-6 gap-2">- {customImages.map((imageUrl, idx) => {- const isSelected = selected === imageUrl;- return (- <div- key={`custom-${idx}`}- className={cn(- "aspect-square w-8 h-8 rounded-lg border overflow-hidden cursor-pointer transition-all duration-150 relative group shadow-sm",- isSelected- ? "border-[#34B27B] ring-1 ring-[#34B27B]/30"- : "border-white/10 hover:border-[#34B27B]/40 opacity-80 hover:opacity-100 bg-white/5",- )}- style={{- backgroundImage: `url(${imageUrl})`,- backgroundSize: "cover",- backgroundPosition: "center",- }}- onClick={() => onWallpaperChange(imageUrl)}- role="button"- >- <button- onClick={(e) => handleRemoveCustomImage(imageUrl, e)}- className="absolute top-0.5 right-0.5 w-3 h-3 bg-red-500/90 hover:bg-red-500 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"- >- <X className="w-2 h-2 text-white" />- </button>- </div>- );- })}-- {WALLPAPER_PATHS.map((canonicalPath, i) => {- const previewUrl = wallpaperPreviewUrls[i] ?? canonicalPath;- const isSelected = selected === canonicalPath;- return (- <div- key={canonicalPath}- className={cn(- "aspect-square w-8 h-8 rounded-lg border overflow-hidden cursor-pointer transition-all duration-150 shadow-sm",- isSelected- ? "border-[#34B27B] ring-1 ring-[#34B27B]/30"- : "border-white/10 hover:border-[#34B27B]/40 opacity-80 hover:opacity-100 bg-white/5",- )}- style={{- backgroundImage: `url(${previewUrl})`,- backgroundSize: "cover",- backgroundPosition: "center",- }}- onClick={() => onWallpaperChange(canonicalPath)}- role="button"- />- );- })}- </div>- </TabsContent>-- <TabsContent value="color" className="mt-0">- <ColorPicker- selectedColor={selectedColor}- colorPalette={colorPalette}- translations={{- colorWheel: t("background.colorWheel"),- colorPalette: t("background.colorPalette"),- }}- onUpdateColor={(color) => {- setSelectedColor(color);- onWallpaperChange(color);- }}- />- </TabsContent>-- <TabsContent value="gradient" className="mt-0 space-y-3">- <div className="space-y-1">- <div className="text-[10px] font-medium uppercase tracking-wider text-slate-400 px-1">- {t("background.presets")}- </div>- <div className="grid grid-cols-6 gap-2">- {GRADIENTS.map((g, idx) => (- <div- key={g}- className={cn(- "aspect-square w-8 h-8 rounded-lg border overflow-hidden cursor-pointer transition-all duration-150 shadow-sm",- gradient === g- ? "border-[#34B27B] ring-1 ring-[#34B27B]/30"- : "border-white/10 hover:border-[#34B27B]/40 opacity-80 hover:opacity-100 bg-white/5",- )}- style={{ background: g }}- aria-label={t("background.gradientLabel", {- index: idx + 1,- })}- onClick={() => {- setGradient(g);- onWallpaperChange(g);- }}- role="button"- />- ))}- </div>- </div>- <div className="space-y-1">- <div className="text-[10px] font-medium uppercase tracking-wider text-slate-400 px-1">- {t("background.custom")}- </div>- <GradientEditor- onChange={(state) => {- const css = buildGradientFromEditor(state);- setGradient(css);- onWallpaperChange(css);- }}- />- </div>- </TabsContent>- </div>- </Tabs>- </AccordionContent>- </AccordionItem>- )}- {activePanelMode === "timeline" && (- <AccordionItem value="timeline" className="editor-panel-section px-3">- <AccordionTrigger className="py-2.5 hover:no-underline">- <div className="flex items-center gap-2">- <Brackets className="w-4 h-4 text-[#34B27B]" />- <span className="text-xs font-medium">{t("timeline.title")}</span>- </div>- </AccordionTrigger>- <AccordionContent className="pb-3">- <div className="flex items-center justify-between p-2 rounded-lg editor-control-surface">- <div className="text-[10px] font-medium text-slate-300">- {t("timeline.waveform")}- </div>- <Switch- checked={showTrimWaveform}- onCheckedChange={onTrimWaveformChange}- className="data-[state=checked]:bg-[#34B27B] scale-90 ml-2 shrink-0"- />- </div>- </AccordionContent>- </AccordionItem>- )}- </Accordion>- )}- </div>- </div>-- {showCropDropdown && cropRegion && onCropChange && (- <>- <div- className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 animate-in fade-in duration-200"- onClick={() => setShowCropDropdown(false)}- />- <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-[60] bg-[#09090b] rounded-2xl shadow-2xl border border-white/10 p-8 w-[90vw] max-w-5xl max-h-[90vh] overflow-auto animate-in zoom-in-95 duration-200">- <div className="flex items-center justify-between mb-6">- <div>- <span className="text-xl font-bold text-slate-200">{t("crop.cropVideo")}</span>- <p className="text-sm text-slate-400 mt-2">{t("crop.dragInstruction")}</p>- </div>- <Button- variant="ghost"- size="icon"- onClick={() => setShowCropDropdown(false)}- className="hover:bg-white/10 text-slate-400 hover:text-white"- >- <X className="w-5 h-5" />- </Button>- </div>- <CropControl- videoElement={videoElement || null}- cropRegion={cropRegion}- onCropChange={onCropChange}- aspectRatio={aspectRatio}- />- <div className="mt-6 space-y-4">- <div className="flex flex-wrap items-end gap-3">- {[- { label: "X", field: "x" as const, max: videoWidth },- { label: "Y", field: "y" as const, max: videoHeight },- { label: "W", field: "width" as const, max: videoWidth },- { label: "H", field: "height" as const, max: videoHeight },- ].map(({ label, field, max }) => (- <div key={field} className="flex flex-col gap-1">- <label className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">- {label}- </label>- <input- type="number"- min={0}- max={max}- value={getCropPixelValue(field)}- onChange={(e) => handleCropNumericChange(field, Number(e.target.value))}- className="w-[90px] h-8 rounded-md border border-white/10 bg-white/5 px-2 text-xs text-slate-200 outline-none focus:border-[#34B27B]/50 focus:ring-1 focus:ring-[#34B27B]/30 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"- />- </div>- ))}-- <div className="flex flex-col gap-1">- <label className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">- {t("crop.ratio")}- </label>- <div className="flex items-center gap-1.5">- <select- value={cropAspectRatio}- onChange={(e) => applyCropAspectPreset(e.target.value)}- className="h-8 rounded-md border border-white/10 bg-[#1a1a1f] px-2 text-xs text-slate-200 outline-none focus:border-[#34B27B]/50 cursor-pointer"- >- <option value="" className="bg-[#1a1a1f] text-slate-200">- {t("crop.free")}- </option>- <option value="16:9" className="bg-[#1a1a1f] text-slate-200">- 16:9- </option>- <option value="9:16" className="bg-[#1a1a1f] text-slate-200">- 9:16- </option>- <option value="4:3" className="bg-[#1a1a1f] text-slate-200">- 4:3- </option>- <option value="3:4" className="bg-[#1a1a1f] text-slate-200">- 3:4- </option>- <option value="1:1" className="bg-[#1a1a1f] text-slate-200">- 1:1- </option>- <option value="21:9" className="bg-[#1a1a1f] text-slate-200">- 21:9- </option>- </select>- <button- type="button"- onClick={() => setCropAspectLocked((prev) => !prev)}- className={cn(- "h-8 w-8 flex items-center justify-center rounded-md border transition-all",- cropAspectLocked- ? "border-[#34B27B]/50 bg-[#34B27B]/10 text-[#34B27B]"- : "border-white/10 bg-white/5 text-slate-400 hover:text-slate-200",- )}- title={- cropAspectLocked ? t("crop.unlockAspectRatio") : t("crop.lockAspectRatio")- }- >- {cropAspectLocked ? (- <Lock className="w-3.5 h-3.5" />- ) : (- <Unlock className="w-3.5 h-3.5" />- )}- </button>- </div>- </div>-- <p className="text-[10px] text-slate-500 self-center ml-2">- {videoWidth} × {videoHeight}px- </p>- </div>-- <div className="flex justify-end">- <Button- onClick={() => setShowCropDropdown(false)}- size="lg"- className="bg-[#34B27B] hover:bg-[#34B27B]/90 text-white"- >- {t("crop.done")}- </Button>- </div>- </div>- </div>- </>- )}-- <div className="flex-shrink-0 p-3 border-t border-white/[0.07] bg-black/25">- {activePanelMode === "export" && !hasTimelineSelection && (- <>- <div className="flex items-center gap-2 mb-3">- <button- data-testid={getTestId("mp4-format-button")}- onClick={() => onExportFormatChange?.("mp4")}- className={cn(- "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",- exportFormat === "mp4"- ? "bg-[#34B27B]/10 border-[#34B27B]/50 text-white"- : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200",- )}- >- <Film className="w-3.5 h-3.5" />- {t("exportFormat.mp4")}- </button>- <button- data-testid={getTestId("gif-format-button")}- onClick={() => onExportFormatChange?.("gif")}- className={cn(- "flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg border transition-all text-xs font-medium",- exportFormat === "gif"- ? "bg-[#34B27B]/10 border-[#34B27B]/50 text-white"- : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:text-slate-200",- )}- >- <Image className="w-3.5 h-3.5" />- {t("exportFormat.gif")}- </button>- </div>-- {exportFormat === "mp4" && (- <div className="mb-3 space-y-1.5">- {sourceDimensions && (- <div className="flex items-center justify-between px-0.5 text-[10px] leading-none text-slate-500">- <span>{t("exportQuality.title")}</span>- <span>- Source {sourceDimensions.width}x{sourceDimensions.height}- </span>- </div>- )}- <div className="bg-white/5 border border-white/5 p-0.5 w-full grid grid-cols-3 h-9 rounded-lg">- <button- onClick={() => onExportQualityChange?.("medium")}- className={cn(- "rounded-md transition-all text-[10px] font-medium flex flex-col items-center justify-center leading-none gap-0.5",- exportQuality === "medium"- ? "bg-white text-black"- : "text-slate-400 hover:text-slate-200",- )}- >- <span>{t("exportQuality.low")}</span>- {sourceDimensions &&- sourceDimensions.shortSide < MP4_EXPORT_SHORT_SIDES.medium && (- <span- className={cn(- "text-[8px] font-medium",- exportQuality === "medium" ? "text-black/55" : "text-amber-300/80",- )}- >- Upscale- </span>- )}- </button>- <button- onClick={() => onExportQualityChange?.("good")}- className={cn(- "rounded-md transition-all text-[10px] font-medium flex flex-col items-center justify-center leading-none gap-0.5",- exportQuality === "good"- ? "bg-white text-black"- : "text-slate-400 hover:text-slate-200",- )}- >- <span>{t("exportQuality.medium")}</span>- {sourceDimensions &&- sourceDimensions.shortSide < MP4_EXPORT_SHORT_SIDES.good && (- <span- className={cn(- "text-[8px] font-medium",- exportQuality === "good" ? "text-black/55" : "text-amber-300/80",- )}- >- Upscale- </span>- )}- </button>- <button- onClick={() => onExportQualityChange?.("source")}- className={cn(- "rounded-md transition-all text-[10px] font-medium flex flex-col items-center justify-center leading-none gap-0.5",- exportQuality === "source"- ? "bg-white text-black"- : "text-slate-400 hover:text-slate-200",- )}- >- <span>{t("exportQuality.high")}</span>- {sourceDimensions && (- <span- className={cn(- "text-[8px] font-medium",- exportQuality === "source" ? "text-black/55" : "text-slate-500",- )}- >- {sourceDimensions.shortSide}p- </span>- )}- </button>- </div>- </div>- )}-- {exportFormat === "gif" && (- <div className="mb-3 space-y-2">- <div className="flex items-center gap-2">- <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-4 h-7 rounded-lg">- {GIF_FRAME_RATES.map((rate) => (- <button- key={rate.value}- onClick={() => onGifFrameRateChange?.(rate.value)}- className={cn(- "rounded-md transition-all text-[10px] font-medium",- gifFrameRate === rate.value- ? "bg-white text-black"- : "text-slate-400 hover:text-slate-200",- )}- >- {rate.value}- </button>- ))}- </div>- <div className="flex-1 bg-white/5 border border-white/5 p-0.5 grid grid-cols-3 h-7 rounded-lg">- {Object.entries(GIF_SIZE_PRESETS).map(([key, _preset]) => (- <button- key={key}- data-testid={getTestId(`gif-size-button-${key}`)}- onClick={() => onGifSizePresetChange?.(key as GifSizePreset)}- className={cn(- "rounded-md transition-all text-[10px] font-medium",- gifSizePreset === key- ? "bg-white text-black"- : "text-slate-400 hover:text-slate-200",- )}- >- {key === "original"- ? "Orig"- : key.charAt(0).toUpperCase() + key.slice(1, 3)}- </button>- ))}- </div>- </div>- <div className="flex items-center justify-between">- <span className="text-[10px] text-slate-500">- {gifOutputDimensions.width} × {gifOutputDimensions.height}px- </span>- <div className="flex items-center gap-2">- <span className="text-[10px] text-slate-400">{t("gifSettings.loop")}</span>- <Switch- checked={gifLoop}- onCheckedChange={onGifLoopChange}- className="data-[state=checked]:bg-[#34B27B] scale-75"- />- </div>- </div>- </div>- )}-- {unsavedExport && (- <Button- type="button"- size="lg"- onClick={onSaveUnsavedExport}- className="w-full mb-2 py-5 text-sm font-semibold flex items-center justify-center gap-2 bg-indigo-500 text-white rounded-xl shadow-lg shadow-indigo-500/20 hover:bg-indigo-500/90 hover:scale-[1.02] active:scale-[0.98] transition-all duration-200"- >- <Download className="w-4 h-4" />- {t("export.chooseSaveLocation")}- </Button>- )}- <Button- data-testid={getTestId("export-button")}- type="button"- size="lg"- onClick={onExport}- className="w-full py-5 text-sm font-semibold flex items-center justify-center gap-2 bg-[#34B27B] text-white rounded-xl shadow-lg shadow-[#34B27B]/20 hover:bg-[#3fc98d] hover:scale-[1.01] active:scale-[0.99] transition-all duration-200"- >- <Download className="w-4 h-4" />- {exportFormat === "gif" ? t("export.gifButton") : t("export.videoButton")}- </Button>- </>- )}-- {commonFooterLinks}- </div>- </div>- );-}diff --git a/src/components/video-editor/ShortcutsConfigDialog.tsx b/src/components/video-editor/ShortcutsConfigDialog.tsxindex dcd073513..a4b4e2141 100644--- a/src/components/video-editor/ShortcutsConfigDialog.tsx+++ b/src/components/video-editor/ShortcutsConfigDialog.tsx@@ -27,8 +27,16 @@ import { BLUR_REGIONS_ENABLED } from "./featureFlags";const MODIFIER_KEYS = new Set(["Control", "Shift", "Alt", "Meta"]);export function ShortcutsConfigDialog() {- const { shortcuts, isMac, isConfigOpen, closeConfig, setShortcuts, persistShortcuts } =- useShortcuts();+ const {+ shortcuts,+ isMac,+ isConfigOpen,+ openConfig,+ closeConfig,+ setShortcuts,+ persistShortcuts,+ } = useShortcuts();+ void openConfig;const t = useScopedT("shortcuts");const tc = useScopedT("common");diff --git a/src/components/video-editor/TutorialHelp.tsx b/src/components/video-editor/TutorialHelp.tsxdeleted file mode 100644index 4e9c2b57b..000000000--- a/src/components/video-editor/TutorialHelp.tsx+++ /dev/null@@ -1,133 +0,0 @@-import { ArrowRight, HelpCircle, Scissors } from "lucide-react";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { useScopedT } from "@/contexts/I18nContext";--export function TutorialHelp() {- const t = useScopedT("dialogs");- return (- <Dialog>- <DialogTrigger asChild>- <Button- variant="ghost"- size="sm"- className="h-7 px-2 text-xs text-slate-400 hover:text-slate-200 hover:bg-white/10 transition-all gap-1.5"- >- <HelpCircle className="w-3.5 h-3.5" />- <span className="font-medium">{t("tutorial.triggerLabel")}</span>- </Button>- </DialogTrigger>- <DialogContent className="max-w-2xl bg-[#09090b] border-white/10 [&>button]:text-slate-400 [&>button:hover]:text-white">- <DialogHeader>- <DialogTitle className="text-xl font-semibold text-slate-200 flex items-center gap-2">- <Scissors className="w-5 h-5 text-[#ef4444]" /> {t("tutorial.title")}- </DialogTitle>- <DialogDescription className="text-slate-400">- {t("tutorial.description")}- </DialogDescription>- </DialogHeader>- <div className="mt-4 space-y-8">- {/* Explanation */}- <div className="bg-white/5 rounded-lg p-4 border border-white/5">- <p className="text-slate-300 leading-relaxed">- {t("tutorial.explanationBefore")}- <span className="text-[#ef4444] font-bold"> {t("tutorial.remove")}</span>- {t("tutorial.explanationMiddle")}- <span className="text-[#ef4444] font-bold"> {t("tutorial.covered")}</span>- {t("tutorial.explanationAfter")}- </p>- </div>- {/* Visual Illustration */}- <div className="space-y-2">- <h3 className="text-sm font-medium text-slate-400 uppercase tracking-wider">- {t("tutorial.visualExample")}- </h3>- <div className="relative h-24 bg-[#000] rounded-lg border border-white/10 flex items-center px-4 overflow-hidden select-none">- {/* Background track (Kept parts) */}- <div className="absolute inset-x-4 h-2 bg-slate-600 rounded-full overflow-hidden">- {/* Solid line representing video */}- </div>- {/* Removed Segment 1 */}- <div- className="absolute left-[20%] h-8 bg-[#ef4444]/20 border border-[#ef4444] rounded flex flex-col items-center justify-center z-10"- style={{ width: "20%" }}- >- <span className="text-[10px] font-bold text-[#ef4444] bg-black/50 px-1 rounded">- {t("tutorial.removed")}- </span>- </div>- {/* Removed Segment 2 */}- <div- className="absolute left-[65%] h-8 bg-[#ef4444]/20 border border-[#ef4444] rounded flex flex-col items-center justify-center z-10"- style={{ width: "15%" }}- >- <span className="text-[10px] font-bold text-[#ef4444] bg-black/50 px-1 rounded">- {t("tutorial.removed")}- </span>- </div>- {/* Labels for kept parts */}- <div className="absolute left-[5%] text-[10px] text-slate-400 font-medium">- {t("tutorial.kept")}- </div>- <div className="absolute left-[50%] text-[10px] text-slate-400 font-medium">- {t("tutorial.kept")}- </div>- <div className="absolute left-[90%] text-[10px] text-slate-400 font-medium">- {t("tutorial.kept")}- </div>- </div>- <div className="flex justify-center mt-2">- <ArrowRight className="w-4 h-4 text-slate-600 rotate-90" />- </div>- {/* Result */}- <div className="relative h-12 bg-[#000] rounded-lg border border-white/10 flex items-center justify-center gap-1 px-4 select-none">- <div- className="h-8 bg-slate-700 rounded flex items-center justify-center opacity-80"- style={{ width: "30%" }}- >- <span className="text-[10px] text-white font-medium">{t("tutorial.part1")}</span>- </div>- <div- className="h-8 bg-slate-700 rounded flex items-center justify-center opacity-80"- style={{ width: "30%" }}- >- <span className="text-[10px] text-white font-medium">{t("tutorial.part2")}</span>- </div>- <div- className="h-8 bg-slate-700 rounded flex items-center justify-center opacity-80"- style={{ width: "30%" }}- >- <span className="text-[10px] text-white font-medium">{t("tutorial.part3")}</span>- </div>- <span className="absolute right-4 text-xs text-slate-400">- {t("tutorial.finalVideo")}- </span>- </div>- </div>- {/* Steps */}- <div className="grid grid-cols-2 gap-4">- <div className="p-3 rounded bg-white/5 border border-white/5">- <div className="text-[#ef4444] font-bold mb-1">{t("tutorial.step1Title")}</div>- <p className="text-xs text-slate-400">- {t("tutorial.step1DescriptionBefore")}- <kbd className="bg-white/10 px-1 rounded text-slate-300">T</kbd>- {t("tutorial.step1DescriptionAfter")}- </p>- </div>- <div className="p-3 rounded bg-white/5 border border-white/5">- <div className="text-[#ef4444] font-bold mb-1">{t("tutorial.step2Title")}</div>- <p className="text-xs text-slate-400">{t("tutorial.step2Description")}</p>- </div>- </div>- </div>- </DialogContent>- </Dialog>- );-}diff --git a/src/components/video-editor/UnsavedChangesDialog.tsx b/src/components/video-editor/UnsavedChangesDialog.tsxdeleted file mode 100644index f7423b620..000000000--- a/src/components/video-editor/UnsavedChangesDialog.tsx+++ /dev/null@@ -1,96 +0,0 @@-import { Save, Trash2 } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { useScopedT } from "@/contexts/I18nContext";--interface UnsavedChangesDialogProps {- isOpen: boolean;- variant?: "close" | "newProject" | "loadProject";- onSaveAndClose: () => void;- onDiscardAndClose: () => void;- onCancel: () => void;-}--export function UnsavedChangesDialog({- isOpen,- variant = "close",- onSaveAndClose,- onDiscardAndClose,- onCancel,-}: UnsavedChangesDialogProps) {- const td = useScopedT("dialogs");- const tc = useScopedT("common");-- const detail =- variant === "newProject"- ? td("unsavedChanges.detailNewProject")- : variant === "loadProject"- ? td("unsavedChanges.detailLoadProject")- : td("unsavedChanges.detail");- const saveLabel =- variant === "newProject"- ? td("unsavedChanges.saveAndNewProject")- : variant === "loadProject"- ? td("unsavedChanges.saveAndLoadProject")- : td("unsavedChanges.saveAndClose");- const discardLabel =- variant === "newProject"- ? td("unsavedChanges.discardAndNewProject")- : variant === "loadProject"- ? td("unsavedChanges.discardAndLoadProject")- : td("unsavedChanges.discardAndClose");-- return (- <Dialog open={isOpen} onOpenChange={(open) => !open && onCancel()}>- <DialogContent className="bg-[#09090b] border-white/10 rounded-2xl max-w-sm p-6 gap-0">- <DialogHeader className="mb-5">- <div className="flex items-center gap-3">- <img- src="./openscreen.png"- alt=""- aria-hidden="true"- className="w-9 h-9 rounded-xl flex-shrink-0"- />- <DialogTitle className="text-base font-semibold text-slate-200 leading-tight">- {td("unsavedChanges.title")}- </DialogTitle>- </div>- </DialogHeader>-- <p className="text-sm text-slate-300 mb-1">{td("unsavedChanges.message")}</p>- <DialogDescription className="text-sm text-slate-500 mb-6">{detail}</DialogDescription>-- <div className="flex flex-col gap-2">- <button- type="button"- onClick={onSaveAndClose}- className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg bg-[#34B27B] hover:bg-[#2d9e6c] active:bg-[#27885c] text-white font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[#34B27B] focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- <Save className="w-4 h-4" />- {saveLabel}- </button>- <button- type="button"- onClick={onDiscardAndClose}- className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg bg-white/5 hover:bg-red-500/15 border border-white/10 hover:border-red-500/30 text-slate-300 hover:text-red-400 font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-white/30 focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- <Trash2 className="w-4 h-4" />- {discardLabel}- </button>- <button- type="button"- onClick={onCancel}- className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg hover:bg-white/5 text-slate-500 hover:text-slate-300 font-medium text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-white/20 focus-visible:ring-offset-2 focus-visible:ring-offset-[#09090b]"- >- {tc("actions.cancel")}- </button>- </div>- </DialogContent>- </Dialog>- );-}diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsxdeleted file mode 100644index e0cb2f154..000000000--- a/src/components/video-editor/VideoEditor.tsx+++ /dev/null@@ -1,3350 +0,0 @@-import type { Span } from "dnd-timeline";-import { ChevronDown, FolderOpen, Languages, Save, Video } from "lucide-react";-import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";-import { toast } from "sonner";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Label } from "@/components/ui/label";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { useI18n, useScopedT } from "@/contexts/I18nContext";-import { useShortcuts } from "@/contexts/ShortcutsContext";-import { INITIAL_EDITOR_STATE, useEditorHistory } from "@/hooks/useEditorHistory";-import { type Locale } from "@/i18n/config";-import { getAvailableLocales, getLocaleName } from "@/i18n/loader";-import {- captionSegmentsToAnnotationRegions,- extractMono16kFromVideoUrl,- MAX_CAPTION_AUDIO_SEC,- reconcileAutoCaptionTimelineGaps,- shiftTrimRegionsMsForCaptionBuffer,- transcribeMono16kToSegments,- trimLeadingSilenceMono16k,-} from "@/lib/captioning";-import { hasNativeCursorRecordingData } from "@/lib/cursor/nativeCursor";-import {- calculateEffectiveSourceDimensions,- calculateMp4ExportSettings,- calculateOutputDimensions,- type ExportFormat,- type ExportProgress,- type ExportQuality,- type ExportSettings,- GIF_SIZE_PRESETS,- GifExporter,- type GifFrameRate,- type GifSizePreset,- VideoExporter,-} from "@/lib/exporter";-import { computeFrameStepTime } from "@/lib/frameStep";-import type { CursorCaptureMode, ProjectMedia } from "@/lib/recordingSession";-import { isTextEditingTarget, matchesShortcut } from "@/lib/shortcuts";-import {- getExportFolder,- getProjectFolder,- loadUserPreferences,- parentDirectoryOf,- saveUserPreferences,-} from "@/lib/userPreferences";-import { BackgroundLoadError } from "@/lib/wallpaper";-import { nativeBridgeClient, useCursorRecordingData, useCursorTelemetry } from "@/native";-import type { NativePlatform } from "@/native/contracts";-import {- getAspectRatioValue,- getNativeAspectRatioValue,- isPortraitAspectRatio,-} from "@/utils/aspectRatioUtils";-import { EditorEmptyState } from "./EditorEmptyState";-import { EditorMenuBar } from "./EditorMenuBar";-import { ExportDialog } from "./ExportDialog";-import {- DEFAULT_CURSOR_SETTINGS,- DEFAULT_EXPORT_SETTINGS,- DEFAULT_GIF_SETTINGS,- DEFAULT_SOURCE_DIMENSIONS,-} from "./editorDefaults";-import PlaybackControls from "./PlaybackControls";-import {- createProjectData,- createProjectSnapshot,- deriveNextId,- fromFileUrl,- hasProjectUnsavedChanges,- normalizeProjectEditor,- resolveProjectMedia,- toFileUrl,- validateProjectData,-} from "./projectPersistence";-import {- buildPastedAnnotation,- buildSpeedRegion,- buildZoomRegion,- type CopiedRegion,- extractAnnotationAttributes,- extractSpeedAttributes,- extractZoomAttributes,- getCopiedRegion,- replaceAnnotationAttributes,- setCopiedRegion,-} from "./regionClipboard";-import { findFreeGapAt } from "./regionPlacement";-import { SettingsPanel } from "./SettingsPanel";-import TimelineEditor from "./timeline/TimelineEditor";-import { buildAutoZoomSuggestions } from "./timeline/zoomSuggestionUtils";-import {- type AnnotationRegion,- type BlurData,- type CameraFullscreenRegion,- clampFocusToDepth,- createTextAnnotationRegion,- DEFAULT_ANNOTATION_POSITION,- DEFAULT_ANNOTATION_SIZE,- DEFAULT_ANNOTATION_STYLE,- DEFAULT_BLUR_DATA,- DEFAULT_FIGURE_DATA,- DEFAULT_PLAYBACK_SPEED,- DEFAULT_ZOOM_DEPTH,- type FigureData,- type PlaybackSpeed,- type Rotation3DPreset,- resolveTextAnnotationContent,- type SpeedRegion,- type TrimRegion,- ZOOM_DEPTH_SCALES,- type ZoomDepth,- type ZoomFocus,- type ZoomFocusMode,- type ZoomRegion,-} from "./types";-import { UnsavedChangesDialog } from "./UnsavedChangesDialog";-import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";--/** Single Sonner slot so auto-caption phases update in place instead of stacking. */-const AUTO_CAPTION_PROGRESS_TOAST_ID = "auto-caption-progress";--function isClickInteractionType(interactionType: string | null | undefined) {- return (- interactionType === "click" ||- interactionType === "double-click" ||- interactionType === "right-click" ||- interactionType === "middle-click"- );-}--interface ExportDiagnostics {- formatLabel: "GIF" | "Video";- reason?: string;- sourcePath?: string | null;- width?: number;- height?: number;- frameRate?: number;- codec?: string;- bitrate?: number;-}--function getFileNameForDiagnostics(filePath?: string | null) {- if (!filePath) return "unknown";-- try {- const url = new URL(filePath);- if (url.protocol === "file:") {- return decodeURIComponent(url.pathname).split(/[\\/]/).pop() || filePath;- }- } catch {- // Treat non-URL values as filesystem paths.- }-- return filePath.split(/[\\/]/).pop() || filePath;-}--function buildExportDiagnosticMessage(diagnostics: ExportDiagnostics) {- const details = [- diagnostics.reason ? `Reason: ${diagnostics.reason}` : null,- `Source: ${getFileNameForDiagnostics(diagnostics.sourcePath)}`,- diagnostics.width && diagnostics.height- ? `Output: ${diagnostics.width}x${diagnostics.height}${- diagnostics.frameRate ? ` @ ${diagnostics.frameRate} fps` : ""- }`- : null,- diagnostics.codec ? `Codec: ${diagnostics.codec}` : null,- diagnostics.bitrate ? `Bitrate: ${Math.round(diagnostics.bitrate / 1_000_000)} Mbps` : null,- `VideoEncoder: ${"VideoEncoder" in window ? "available" : "unavailable"}`,- ].filter(Boolean);-- return `${diagnostics.formatLabel} export failed\n${details.join("\n")}`;-}--function buildSaveDiagnosticMessage(formatLabel: "GIF" | "Video", reason?: string) {- return `${formatLabel} export save failed${reason ? `\nReason: ${reason}` : ""}`;-}--const CAPTION_WORD_CHOICES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;--export default function VideoEditor() {- const {- state: editorState,- pushState,- updateState,- commitState,- undo,- redo,- resetState,- canUndo,- canRedo,- } = useEditorHistory(INITIAL_EDITOR_STATE);-- const {- zoomRegions,- cameraFullscreenRegions,- autoZoomEnabled,- autoFocusAll,- trimRegions,- speedRegions,- annotationRegions,- cropRegion,- wallpaper,- shadowIntensity,- showBlur,- showTrimWaveform,- motionBlurAmount,- borderRadius,- padding,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- } = editorState;-- // Non-undoable state- const [videoPath, setVideoPath] = useState<string | null>(null);- const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);- const [webcamVideoPath, setWebcamVideoPath] = useState<string | null>(null);- const [webcamVideoSourcePath, setWebcamVideoSourcePath] = useState<string | null>(null);- const [currentProjectPath, setCurrentProjectPath] = useState<string | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [isPlaying, setIsPlaying] = useState(false);- const [currentTime, setCurrentTime] = useState(0);- const [duration, setDuration] = useState(0);- const currentTimeRef = useRef(currentTime);- currentTimeRef.current = currentTime;- const durationRef = useRef(duration);- durationRef.current = duration;- const [selectedZoomId, setSelectedZoomId] = useState<string | null>(null);- const [selectedCameraFullscreenId, setSelectedCameraFullscreenId] = useState<string | null>(null);- const [isPreviewingZoom, setIsPreviewingZoom] = useState(false);- const [selectedTrimId, setSelectedTrimId] = useState<string | null>(null);- const [selectedSpeedId, setSelectedSpeedId] = useState<string | null>(null);- const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);- const [selectedBlurId, setSelectedBlurId] = useState<string | null>(null);- const [isExporting, setIsExporting] = useState(false);- const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);- const [exportError, setExportError] = useState<string | null>(null);- const [showExportDialog, setShowExportDialog] = useState(false);- const [showNewRecordingDialog, setShowNewRecordingDialog] = useState(false);- const [exportQuality, setExportQuality] = useState<ExportQuality>(- DEFAULT_EXPORT_SETTINGS.quality,- );- const [exportFormat, setExportFormat] = useState<ExportFormat>(DEFAULT_EXPORT_SETTINGS.format);- const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(DEFAULT_GIF_SETTINGS.frameRate);- const [gifLoop, setGifLoop] = useState(DEFAULT_GIF_SETTINGS.loop);- const [gifSizePreset, setGifSizePreset] = useState<GifSizePreset>(- DEFAULT_GIF_SETTINGS.sizePreset,- );- const [exportedFilePath, setExportedFilePath] = useState<string | null>(null);- const [lastSavedSnapshot, setLastSavedSnapshot] = useState<string | null>(null);- const [unsavedExport, setUnsavedExport] = useState<{- arrayBuffer: ArrayBuffer;- fileName: string;- format: string;- } | null>(null);- const [isFullscreen, setIsFullscreen] = useState(false);- const [showCloseConfirmDialog, setShowCloseConfirmDialog] = useState(false);- // Unsaved-changes confirmation for New Project / Load Project.- // The window-close flow uses showCloseConfirmDialog above.- const [confirmDialogVariant, setConfirmDialogVariant] = useState<- "newProject" | "loadProject" | null- >(null);- const playerContainerRef = useRef<HTMLDivElement | null>(null);- const cursorTelemetrySourcePath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);- const { samples: cursorTelemetry, error: cursorTelemetryError } =- useCursorTelemetry(cursorTelemetrySourcePath);- const { data: cursorRecordingData, error: cursorRecordingDataError } =- useCursorRecordingData(cursorTelemetrySourcePath);- const cursorClickTimestamps = useMemo<number[]>(() => {- const recordingClicks =- cursorRecordingData?.samples- .filter((sample) => isClickInteractionType(sample.interactionType))- .map((sample) => sample.timeMs) ?? [];- if (recordingClicks.length > 0) {- return recordingClicks;- }-- return cursorTelemetry- .filter((sample) => isClickInteractionType(sample.interactionType))- .map((sample) => sample.timeMs);- }, [cursorRecordingData, cursorTelemetry]);-- // Cursor & motion blur visual settings (non-undoable preferences)- const [showCursor, setShowCursor] = useState(DEFAULT_CURSOR_SETTINGS.show);- const [cursorSize, setCursorSize] = useState(DEFAULT_CURSOR_SETTINGS.size);- const [cursorSmoothing, setCursorSmoothing] = useState(DEFAULT_CURSOR_SETTINGS.smoothing);- const [cursorMotionBlur, setCursorMotionBlur] = useState(DEFAULT_CURSOR_SETTINGS.motionBlur);- const [cursorClickBounce, setCursorClickBounce] = useState(DEFAULT_CURSOR_SETTINGS.clickBounce);- const [cursorClipToBounds, setCursorClipToBounds] = useState(- DEFAULT_CURSOR_SETTINGS.clipToBounds,- );- const [cursorTheme, setCursorTheme] = useState(DEFAULT_CURSOR_SETTINGS.theme);- const [nativePlatform, setNativePlatform] = useState<NativePlatform | null>(null);- const [recordingCursorCaptureMode, setRecordingCursorCaptureMode] =- useState<CursorCaptureMode | null>(null);-- const videoPlaybackRef = useRef<VideoPlaybackRef>(null);-- const nextZoomIdRef = useRef(1);- const nextCameraFullscreenIdRef = useRef(1);- const nextTrimIdRef = useRef(1);- const nextSpeedIdRef = useRef(1);-- const { shortcuts, isMac } = useShortcuts();- // Windows recordings include captured cursor assets. macOS hides the system- // cursor in ScreenCaptureKit and renders telemetry samples with OpenScreen's- // default arrow asset for the editable overlay.- const hasEditableCursorRecording =- recordingCursorCaptureMode === "editable-overlay" &&- (nativePlatform === "win32" || nativePlatform === "darwin") &&- hasNativeCursorRecordingData(cursorRecordingData);- const effectiveShowCursor = showCursor && hasEditableCursorRecording;- const showCursorSettings = hasEditableCursorRecording;- const { locale, setLocale, t: rawT } = useI18n();- const t = useScopedT("editor");- const ts = useScopedT("settings");- const tt = useScopedT("timeline");- const availableLocales = getAvailableLocales();-- const nextAnnotationIdRef = useRef(1);- const nextAnnotationZIndexRef = useRef(1);- const isAutoCaptioningRef = useRef(false);- const [isAutoCaptioning, setIsAutoCaptioning] = useState(false);- const [showAutoCaptionsDialog, setShowAutoCaptionsDialog] = useState(false);- const [captionWordsMin, setCaptionWordsMin] = useState(2);- const [captionWordsMax, setCaptionWordsMax] = useState(7);- const exporterRef = useRef<VideoExporter | null>(null);-- const annotationOnlyRegions = useMemo(- () => annotationRegions.filter((region) => region.type !== "blur"),- [annotationRegions],- );- const blurRegions = useMemo(- () => annotationRegions.filter((region) => region.type === "blur"),- [annotationRegions],- );-- const currentProjectMedia = useMemo<ProjectMedia | null>(() => {- const screenVideoPath = videoSourcePath ?? (videoPath ? fromFileUrl(videoPath) : null);- if (!screenVideoPath) {- return null;- }-- const webcamSourcePath =- webcamVideoSourcePath ?? (webcamVideoPath ? fromFileUrl(webcamVideoPath) : null);- return {- screenVideoPath,- ...(webcamSourcePath ? { webcamVideoPath: webcamSourcePath } : {}),- ...(recordingCursorCaptureMode ? { cursorCaptureMode: recordingCursorCaptureMode } : {}),- };- }, [- videoPath,- videoSourcePath,- webcamVideoPath,- webcamVideoSourcePath,- recordingCursorCaptureMode,- ]);-- const applyLoadedProject = useCallback(- async (candidate: unknown, path?: string | null) => {- if (!validateProjectData(candidate)) {- return false;- }-- const project = candidate;- const projectMedia = resolveProjectMedia(project);- if (!projectMedia) {- return false;- }- const sourcePath = projectMedia.screenVideoPath;- const webcamSourcePath = projectMedia.webcamVideoPath ?? null;- const projectCursorCaptureMode = projectMedia.cursorCaptureMode ?? null;- const normalizedEditor = normalizeProjectEditor(project.editor);- const inferredDurationMs = Math.max(- 0,- ...normalizedEditor.zoomRegions.map((region) => region.endMs),- ...normalizedEditor.cameraFullscreenRegions.map((region) => region.endMs),- ...normalizedEditor.trimRegions.map((region) => region.endMs),- ...normalizedEditor.speedRegions.map((region) => region.endMs),- ...normalizedEditor.annotationRegions.map((region) => region.endMs),- );-- try {- videoPlaybackRef.current?.pause();- } catch {- // no-op- }- setIsPlaying(false);- setCurrentTime(0);- // This inferred duration is only a placeholder until the video element's real- // metadata resolves (see VideoPlayback's syncResolvedDuration).- setDuration(inferredDurationMs > 0 ? inferredDurationMs / 1000 : 0);-- setError(null);- setVideoSourcePath(sourcePath);- setVideoPath(toFileUrl(sourcePath));- setWebcamVideoSourcePath(webcamSourcePath);- setWebcamVideoPath(webcamSourcePath ? toFileUrl(webcamSourcePath) : null);- setRecordingCursorCaptureMode(projectCursorCaptureMode);- setCurrentProjectPath(path ?? null);- // Reset the memoized last-resolved-duration guard so resolution isn't skipped- // just because the real duration happens to match a value already seen from- // before this load (e.g. reloading a project referencing the same video file,- // whose src may not change and so never re-fires `loadedmetadata`). Must run- // after the setDuration placeholder above, or its correction gets clobbered by- // the same-tick placeholder assignment winning the state-batch race.- videoPlaybackRef.current?.resetDurationResolution();-- // A loaded project keeps its zooms exactly as saved, so never auto-suggest- // over it (even if it has zero zooms because the user deleted them all).- autoProcessedSourceRef.current = sourcePath;-- pushState({- wallpaper: normalizedEditor.wallpaper,- shadowIntensity: normalizedEditor.shadowIntensity,- showBlur: normalizedEditor.showBlur,- showTrimWaveform: normalizedEditor.showTrimWaveform,- motionBlurAmount: normalizedEditor.motionBlurAmount,- borderRadius: normalizedEditor.borderRadius,- padding: normalizedEditor.padding,- cropRegion: normalizedEditor.cropRegion,- zoomRegions: normalizedEditor.zoomRegions,- cameraFullscreenRegions: normalizedEditor.cameraFullscreenRegions,- autoZoomEnabled: normalizedEditor.autoZoomEnabled,- autoFocusAll: normalizedEditor.autoFocusAll,- trimRegions: normalizedEditor.trimRegions,- speedRegions: normalizedEditor.speedRegions,- annotationRegions: normalizedEditor.annotationRegions,- aspectRatio: normalizedEditor.aspectRatio,- webcamLayoutPreset: normalizedEditor.webcamLayoutPreset,- webcamMaskShape: normalizedEditor.webcamMaskShape,- webcamMirrored: normalizedEditor.webcamMirrored,- webcamReactiveZoom: normalizedEditor.webcamReactiveZoom,- webcamSizePreset: normalizedEditor.webcamSizePreset,- webcamPosition: normalizedEditor.webcamPosition,- });- setExportQuality(normalizedEditor.exportQuality);- setExportFormat(normalizedEditor.exportFormat);- setGifFrameRate(normalizedEditor.gifFrameRate);- setGifLoop(normalizedEditor.gifLoop);- setGifSizePreset(normalizedEditor.gifSizePreset);- setCursorTheme(normalizedEditor.cursorTheme);-- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);-- nextZoomIdRef.current = deriveNextId(- "zoom",- normalizedEditor.zoomRegions.map((region) => region.id),- );- nextCameraFullscreenIdRef.current = deriveNextId(- "camera-fullscreen",- normalizedEditor.cameraFullscreenRegions.map((region) => region.id),- );- nextTrimIdRef.current = deriveNextId(- "trim",- normalizedEditor.trimRegions.map((region) => region.id),- );- nextSpeedIdRef.current = deriveNextId(- "speed",- normalizedEditor.speedRegions.map((region) => region.id),- );- nextAnnotationIdRef.current = deriveNextId(- "annotation",- normalizedEditor.annotationRegions.map((region) => region.id),- );- nextAnnotationZIndexRef.current =- normalizedEditor.annotationRegions.reduce(- (max, region) => Math.max(max, region.zIndex),- 0,- ) + 1;-- setLastSavedSnapshot(- createProjectSnapshot(- {- screenVideoPath: sourcePath,- ...(webcamSourcePath ? { webcamVideoPath: webcamSourcePath } : {}),- ...(projectCursorCaptureMode ? { cursorCaptureMode: projectCursorCaptureMode } : {}),- },- normalizedEditor,- ),- );- return true;- },- [pushState],- );-- const currentProjectSnapshot = useMemo(() => {- if (!currentProjectMedia) {- return null;- }- return createProjectSnapshot(currentProjectMedia, {- wallpaper,- shadowIntensity,- showBlur,- showTrimWaveform,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- zoomRegions,- cameraFullscreenRegions,- autoZoomEnabled,- autoFocusAll,- trimRegions,- speedRegions,- annotationRegions,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- exportQuality,- exportFormat,- gifFrameRate,- gifLoop,- gifSizePreset,- cursorTheme,- });- }, [- currentProjectMedia,- cursorTheme,- wallpaper,- shadowIntensity,- showBlur,- showTrimWaveform,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- zoomRegions,- cameraFullscreenRegions,- autoZoomEnabled,- autoFocusAll,- trimRegions,- speedRegions,- annotationRegions,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- exportQuality,- exportFormat,- gifFrameRate,- gifLoop,- gifSizePreset,- ]);-- const hasUnsavedChanges = hasProjectUnsavedChanges(currentProjectSnapshot, lastSavedSnapshot);-- useEffect(() => {- async function loadInitialData() {- try {- const currentProjectResult = await nativeBridgeClient.project.loadCurrentProjectFile();- if (currentProjectResult.success && currentProjectResult.project) {- const restored = await applyLoadedProject(- currentProjectResult.project,- currentProjectResult.path ?? null,- );- if (restored) {- return;- }- }-- const currentSessionResult = await window.electronAPI.getCurrentRecordingSession();- if (currentSessionResult.success && currentSessionResult.session) {- const session = currentSessionResult.session;- const sourcePath = fromFileUrl(session.screenVideoPath);- const webcamSourcePath = session.webcamVideoPath- ? fromFileUrl(session.webcamVideoPath)- : null;- setVideoSourcePath(sourcePath);- setVideoPath(toFileUrl(sourcePath));- setWebcamVideoSourcePath(webcamSourcePath);- setWebcamVideoPath(webcamSourcePath ? toFileUrl(webcamSourcePath) : null);- setRecordingCursorCaptureMode(session.cursorCaptureMode ?? null);- setCurrentProjectPath(null);- setLastSavedSnapshot(- createProjectSnapshot(- {- screenVideoPath: sourcePath,- ...(webcamSourcePath ? { webcamVideoPath: webcamSourcePath } : {}),- ...(session.cursorCaptureMode- ? { cursorCaptureMode: session.cursorCaptureMode }- : {}),- },- INITIAL_EDITOR_STATE,- ),- );- return;- }-- const result = await nativeBridgeClient.project.getCurrentVideoPath();- if (result.success && result.path) {- setVideoSourcePath(result.path);- setVideoPath(toFileUrl(result.path));- setRecordingCursorCaptureMode(null);- setCurrentProjectPath(null);- setLastSavedSnapshot(- createProjectSnapshot({ screenVideoPath: result.path }, INITIAL_EDITOR_STATE),- );- }- // No video/project/session, so leave videoPath null and let the- // EditorEmptyState dashboard render instead of an error screen.- } catch (err) {- setError("Error loading video: " + String(err));- } finally {- setLoading(false);- }- }-- loadInitialData();- }, [applyLoadedProject]);-- // Avoid overwriting saved prefs with defaults before they've loaded.- const [prefsHydrated, setPrefsHydrated] = useState(false);-- // Load persisted user preferences on mount (intentionally runs once)- useEffect(() => {- const prefs = loadUserPreferences();- updateState({- padding: prefs.padding,- aspectRatio: prefs.aspectRatio,- });- setExportQuality(prefs.exportQuality);- setExportFormat(prefs.exportFormat);- setPrefsHydrated(true);- }, [updateState]);-- // Auto-save user preferences when settings change- useEffect(() => {- if (!prefsHydrated) return;- saveUserPreferences({ padding, aspectRatio, exportQuality, exportFormat });- }, [prefsHydrated, padding, aspectRatio, exportQuality, exportFormat]);-- const saveProject = useCallback(- async (forceSaveAs: boolean) => {- if (!videoPath) {- toast.error(t("errors.noVideoLoaded"));- return false;- }-- if (!currentProjectMedia) {- toast.error(t("errors.unableToDetermineSourcePath"));- return false;- }-- const editorState = {- wallpaper,- shadowIntensity,- showBlur,- showTrimWaveform,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- zoomRegions,- cameraFullscreenRegions,- autoZoomEnabled,- autoFocusAll,- trimRegions,- speedRegions,- annotationRegions,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- exportQuality,- exportFormat,- gifFrameRate,- gifLoop,- gifSizePreset,- cursorTheme,- };- const projectData = createProjectData(currentProjectMedia, editorState);-- const fileNameBase =- currentProjectMedia.screenVideoPath- .split(/[\\/]/)- .pop()- ?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;- // Normalize the same way as currentProjectSnapshot so the post-save- // baseline compares equal and hasUnsavedChanges clears.- const projectSnapshot = createProjectSnapshot(currentProjectMedia, editorState);- const result = await nativeBridgeClient.project.saveProjectFile(- projectData,- fileNameBase,- forceSaveAs ? undefined : (currentProjectPath ?? undefined),- );-- if (result.canceled) {- toast.info(t("project.saveCanceled"));- return false;- }-- if (!result.success) {- toast.error(result.message || t("project.failedToSave"));- return false;- }-- if (result.path) {- setCurrentProjectPath(result.path);- }- setLastSavedSnapshot(projectSnapshot);-- toast.success(t("project.savedTo", { path: result.path ?? "" }));- return true;- },- [- currentProjectMedia,- currentProjectPath,- wallpaper,- shadowIntensity,- showBlur,- showTrimWaveform,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- zoomRegions,- cameraFullscreenRegions,- autoZoomEnabled,- autoFocusAll,- trimRegions,- speedRegions,- annotationRegions,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- exportQuality,- exportFormat,- gifFrameRate,- gifLoop,- gifSizePreset,- cursorTheme,- videoPath,- t,- ],- );-- useEffect(() => {- window.electronAPI.setHasUnsavedChanges(hasUnsavedChanges);- }, [hasUnsavedChanges]);-- useEffect(() => {- const cleanup = window.electronAPI.onRequestSaveBeforeClose(async () => {- return saveProject(false);- });- return () => cleanup();- }, [saveProject]);-- useEffect(() => {- const cleanup = window.electronAPI.onRequestCloseConfirm(() => {- setShowCloseConfirmDialog(true);- });- return () => cleanup();- }, []);-- const handleCloseConfirmSave = useCallback(() => {- setShowCloseConfirmDialog(false);- window.electronAPI.sendCloseConfirmResponse("save");- }, []);-- const handleCloseConfirmDiscard = useCallback(() => {- setShowCloseConfirmDialog(false);- window.electronAPI.sendCloseConfirmResponse("discard");- }, []);-- const handleCloseConfirmCancel = useCallback(() => {- setShowCloseConfirmDialog(false);- window.electronAPI.sendCloseConfirmResponse("cancel");- }, []);-- const handleSaveProject = useCallback(async () => {- await saveProject(false);- }, [saveProject]);-- const handleSaveProjectAs = useCallback(async () => {- await saveProject(true);- }, [saveProject]);-- const handleNewRecordingConfirm = useCallback(async () => {- const result = await window.electronAPI.startNewRecording();- if (result.success) {- setShowNewRecordingDialog(false);- } else {- console.error("Failed to start new recording:", result.error);- setError("Failed to start new recording: " + (result.error || "Unknown error"));- }- }, []);-- const doLoadProject = useCallback(async () => {- const result = await nativeBridgeClient.project.loadProjectFile(getProjectFolder());-- if (result.canceled) {- return;- }-- if (!result.success) {- toast.error(result.message || t("project.failedToLoad"));- return;- }-- const restored = await applyLoadedProject(result.project, result.path ?? null);- if (!restored) {- toast.error(t("project.invalidFormat"));- return;- }-- if (result.path) {- const folder = parentDirectoryOf(result.path);- if (folder) {- saveUserPreferences({ projectFolder: folder });- }- }-- toast.success(t("project.loadedFrom", { path: result.path ?? "" }));- }, [applyLoadedProject, t]);-- const handleLoadProject = useCallback(async () => {- if (hasUnsavedChanges) {- setConfirmDialogVariant("loadProject");- return;- }- await doLoadProject();- }, [hasUnsavedChanges, doLoadProject]);-- const handleLoadProjectConfirmSave = useCallback(async () => {- setConfirmDialogVariant(null);- const saved = await saveProject(false);- if (saved) {- await doLoadProject();- }- }, [saveProject, doLoadProject]);-- const handleLoadProjectConfirmDiscard = useCallback(async () => {- setConfirmDialogVariant(null);- await doLoadProject();- }, [doLoadProject]);-- // New Project: clear all media/project/editor state back to the empty- // Studio dashboard. Prompts to save first when there are unsaved changes.- const doNewProject = useCallback(async () => {- await nativeBridgeClient.project.clearCurrentVideoPath();- setVideoPath(null);- setVideoSourcePath(null);- setWebcamVideoPath(null);- setWebcamVideoSourcePath(null);- setCurrentProjectPath(null);- setLastSavedSnapshot(null);- // Reset undoable editor state + undo/redo history to a clean slate.- resetState();- // Reset non-undoable selection state.- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- // Reset playback.- setCurrentTime(0);- setIsPlaying(false);- // Reset cursor preferences to defaults.- setShowCursor(DEFAULT_CURSOR_SETTINGS.show);- setCursorSize(DEFAULT_CURSOR_SETTINGS.size);- setCursorSmoothing(DEFAULT_CURSOR_SETTINGS.smoothing);- setCursorMotionBlur(DEFAULT_CURSOR_SETTINGS.motionBlur);- setCursorClickBounce(DEFAULT_CURSOR_SETTINGS.clickBounce);- setCursorClipToBounds(DEFAULT_CURSOR_SETTINGS.clipToBounds);- setCursorTheme(DEFAULT_CURSOR_SETTINGS.theme);- // Reset region ID counters.- nextZoomIdRef.current = 1;- nextCameraFullscreenIdRef.current = 1;- nextTrimIdRef.current = 1;- nextSpeedIdRef.current = 1;- nextAnnotationIdRef.current = 1;- nextAnnotationZIndexRef.current = 1;- }, [resetState]);-- const handleNewProject = useCallback(async () => {- if (hasUnsavedChanges) {- setConfirmDialogVariant("newProject");- return;- }- await doNewProject();- }, [hasUnsavedChanges, doNewProject]);-- const handleNewProjectConfirmSave = useCallback(async () => {- setConfirmDialogVariant(null);- const saved = await saveProject(false);- if (saved) {- await doNewProject();- }- }, [saveProject, doNewProject]);-- const handleNewProjectConfirmDiscard = useCallback(async () => {- setConfirmDialogVariant(null);- await doNewProject();- }, [doNewProject]);-- useEffect(() => {- const removeNewProjectListener = window.electronAPI.onMenuNewProject(handleNewProject);- const removeLoadListener = window.electronAPI.onMenuLoadProject(handleLoadProject);- const removeSaveListener = window.electronAPI.onMenuSaveProject(handleSaveProject);- const removeSaveAsListener = window.electronAPI.onMenuSaveProjectAs(handleSaveProjectAs);-- return () => {- removeNewProjectListener?.();- removeLoadListener?.();- removeSaveListener?.();- removeSaveAsListener?.();- };- }, [handleNewProject, handleLoadProject, handleSaveProject, handleSaveProjectAs]);-- useEffect(() => {- let canceled = false;- nativeBridgeClient.system- .getPlatform()- .then((platform) => {- if (!canceled) {- setNativePlatform(platform);- }- })- .catch((error) => {- console.warn("Unable to resolve native platform for cursor settings:", error);- if (!canceled) {- setNativePlatform(null);- }- });-- return () => {- canceled = true;- };- }, []);-- useEffect(() => {- if (cursorTelemetryError) {- console.warn("Unable to load cursor telemetry:", cursorTelemetryError);- }- }, [cursorTelemetryError]);-- useEffect(() => {- if (cursorRecordingDataError) {- console.warn("Unable to load cursor recording data:", cursorRecordingDataError);- }- }, [cursorRecordingDataError]);-- function togglePlayPause() {- const playback = videoPlaybackRef.current;- const video = playback?.video;- if (!playback || !video) return;-- if (isPlaying) {- playback.pause();- } else {- playback.play().catch((err) => console.error("Video play failed:", err));- }- }-- const toggleFullscreen = useCallback(() => {- setIsFullscreen((prev) => !prev);- }, []);-- useEffect(() => {- if (!isFullscreen) return;- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === "Escape") {- setIsFullscreen(false);- }- };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [isFullscreen]);-- function handleSeek(time: number) {- const video = videoPlaybackRef.current?.video;- if (!video) return;- video.currentTime = time;- }-- // Reads the live playhead position directly off the <video> element, bypassing- // `currentTime` React state entirely. The timeline's playhead subscribes to this- // via its own rAF loop so it stays in lockstep with actual playback regardless of- // how long this (large) component's own re-render takes — see issue #111.- const getPlaybackTimeMs = useCallback(() => {- const video = videoPlaybackRef.current?.video;- if (video) return video.currentTime * 1000;- return currentTimeRef.current * 1000;- }, []);-- const handleSelectZoom = useCallback((id: string | null) => {- setSelectedZoomId(id);- if (id) {- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- }- }, []);-- const handleSelectCameraFullscreen = useCallback((id: string | null) => {- setSelectedCameraFullscreenId(id);- if (id) {- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- }- }, []);-- const handleSelectTrim = useCallback((id: string | null) => {- setSelectedTrimId(id);- if (id) {- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- }- }, []);-- const handleSelectAnnotation = useCallback((id: string | null) => {- setSelectedAnnotationId(id);- if (id) {- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedBlurId(null);- }- }, []);-- const handleSelectBlur = useCallback((id: string | null) => {- setSelectedBlurId(id);- if (id) {- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedAnnotationId(null);- setSelectedSpeedId(null);- }- }, []);-- const handleZoomAdded = useCallback(- (span: Span) => {- const id = `zoom-${nextZoomIdRef.current++}`;- const newRegion: ZoomRegion = {- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- depth: DEFAULT_ZOOM_DEPTH,- customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],- focus: { cx: 0.5, cy: 0.5 },- // Auto-Focus on means new zooms follow the cursor too.- focusMode: autoFocusAll ? "auto" : undefined,- source: "manual",- };- pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, newRegion] }));- setSelectedZoomId(id);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- },- [pushState, autoFocusAll],- );-- const handleCameraFullscreenAdded = useCallback(- (span: Span) => {- const id = `camera-fullscreen-${nextCameraFullscreenIdRef.current++}`;- const newRegion: CameraFullscreenRegion = {- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- };- pushState((prev) => ({- cameraFullscreenRegions: [...prev.cameraFullscreenRegions, newRegion],- }));- setSelectedCameraFullscreenId(id);- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- },- [pushState],- );-- const handleCameraFullscreenSpanChange = useCallback(- (id: string, span: Span) => {- pushState((prev) => ({- cameraFullscreenRegions: prev.cameraFullscreenRegions.map((region) =>- region.id === id- ? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }- : region,- ),- }));- },- [pushState],- );-- const handleCameraFullscreenDelete = useCallback(- (id: string) => {- pushState((prev) => ({- cameraFullscreenRegions: prev.cameraFullscreenRegions.filter((r) => r.id !== id),- }));- if (selectedCameraFullscreenId === id) {- setSelectedCameraFullscreenId(null);- }- },- [selectedCameraFullscreenId, pushState],- );-- // Builds fresh "auto" zoom regions from cursor telemetry without overlapping- // existing ones. Used by both the on-load auto-suggest pass and the wand toggle.- // These regions always follow the cursor for their whole span (focusMode "auto") —- // that's the entire point of an auto-placed zoom: it should pan to track the cursor- // as it moves, not freeze at the dwell point that triggered the suggestion. This is- // independent of the global "Auto Focus All" toggle, which only affects the default- // for manually-drawn zoom regions.- const buildAutoZoomRegions = useCallback(- (existingRegions: ZoomRegion[]): ZoomRegion[] => {- const totalMs = Math.round(duration * 1000);- const suggestions = buildAutoZoomSuggestions({- cursorTelemetry,- totalMs,- existingRegions,- defaultDurationMs: Math.max(1000, Math.round(totalMs * 0.05)),- });- return suggestions.map((suggestion) => ({- id: `zoom-${nextZoomIdRef.current++}`,- startMs: Math.round(suggestion.span.start),- endMs: Math.round(suggestion.span.end),- depth: DEFAULT_ZOOM_DEPTH,- customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],- focus: clampFocusToDepth(suggestion.focus, DEFAULT_ZOOM_DEPTH),- focusMode: "auto" as const,- source: "auto" as const,- }));- },- [cursorTelemetry, duration],- );-- // Auto-suggest zooms once per fresh recording (no existing zooms, telemetry- // available, wand enabled). Loaded projects are marked processed elsewhere so- // they're never touched. The ref guard runs this once per source and survives undo.- const autoProcessedSourceRef = useRef<string | null>(null);- useEffect(() => {- if (!autoZoomEnabled || !cursorTelemetrySourcePath) return;- if (autoProcessedSourceRef.current === cursorTelemetrySourcePath) return;- if (cursorTelemetry.length < 2 || duration <= 0) return;- // Only auto-suggest for a fresh recording; don't disturb existing zooms.- if (zoomRegions.length > 0) {- autoProcessedSourceRef.current = cursorTelemetrySourcePath;- return;- }- const newRegions = buildAutoZoomRegions([]);- autoProcessedSourceRef.current = cursorTelemetrySourcePath;- if (newRegions.length === 0) return;- pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, ...newRegions] }));- }, [- autoZoomEnabled,- cursorTelemetrySourcePath,- cursorTelemetry,- duration,- zoomRegions,- buildAutoZoomRegions,- pushState,- ]);-- // Wand toggle: ON regenerates suggestions around existing zooms; OFF removes- // only untouched auto zooms (manual and edited-to-manual survive).- const handleToggleAutoZoom = useCallback(- (enabled: boolean) => {- if (enabled) {- autoProcessedSourceRef.current = cursorTelemetrySourcePath;- pushState((prev) => ({- autoZoomEnabled: true,- zoomRegions: [...prev.zoomRegions, ...buildAutoZoomRegions(prev.zoomRegions)],- }));- } else {- pushState((prev) => ({- autoZoomEnabled: false,- zoomRegions: prev.zoomRegions.filter((region) => region.source !== "auto"),- }));- }- },- [pushState, buildAutoZoomRegions, cursorTelemetrySourcePath],- );-- // Flip every zoom between auto (cursor-follow) and manual at once.- const handleToggleAutoFocusAll = useCallback(- (on: boolean) => {- pushState((prev) => ({- autoFocusAll: on,- zoomRegions: prev.zoomRegions.map((region) => ({- ...region,- focusMode: on ? "auto" : "manual",- })),- }));- },- [pushState],- );-- const handleTrimAdded = useCallback(- (span: Span) => {- const id = `trim-${nextTrimIdRef.current++}`;- const newRegion: TrimRegion = {- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- };- pushState((prev) => ({ trimRegions: [...prev.trimRegions, newRegion] }));- setSelectedTrimId(id);- setSelectedZoomId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- },- [pushState],- );-- const handleZoomSpanChange = useCallback(- (id: string, span: Span) => {- pushState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) =>- region.id === id- ? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- source: "manual",- }- : region,- ),- }));- },- [pushState],- );-- const handleTrimSpanChange = useCallback(- (id: string, span: Span) => {- pushState((prev) => ({- trimRegions: prev.trimRegions.map((region) =>- region.id === id- ? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }- : region,- ),- }));- },- [pushState],- );-- // Focus drag: updateState for live preview, commitState on pointer-up.- const handleZoomFocusChange = useCallback(- (id: string, focus: ZoomFocus) => {- updateState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) =>- region.id === id- ? { ...region, focus: clampFocusToDepth(focus, region.depth), source: "manual" }- : region,- ),- }));- },- [updateState],- );-- const handleZoomDepthChange = useCallback(- (depth: ZoomDepth) => {- if (!selectedZoomId) return;- pushState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) =>- region.id === selectedZoomId- ? {- ...region,- depth,- customScale: ZOOM_DEPTH_SCALES[depth],- focus: clampFocusToDepth(region.focus, depth),- source: "manual",- }- : region,- ),- }));- },- [selectedZoomId, pushState],- );-- const handleZoomCustomScaleChange = useCallback(- (scale: number) => {- if (!selectedZoomId) return;- const rounded = Math.round(scale * 100) / 100;- if (!Number.isFinite(rounded)) return;- updateState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) =>- region.id === selectedZoomId- ? { ...region, customScale: rounded, source: "manual" }- : region,- ),- }));- },- [selectedZoomId, updateState],- );-- const handleZoomCustomScaleCommit = useCallback(() => {- commitState();- }, [commitState]);-- const handleZoomFocusModeChange = useCallback(- (focusMode: ZoomFocusMode) => {- if (!selectedZoomId) return;- pushState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) =>- region.id === selectedZoomId ? { ...region, focusMode, source: "manual" } : region,- ),- }));- },- [selectedZoomId, pushState],- );-- const handleZoomDelete = useCallback(- (id: string) => {- pushState((prev) => ({- zoomRegions: prev.zoomRegions.filter((r) => r.id !== id),- }));- if (selectedZoomId === id) {- setSelectedZoomId(null);- }- },- [selectedZoomId, pushState],- );-- const handleZoomRotationPresetChange = useCallback(- (preset: Rotation3DPreset | null) => {- if (!selectedZoomId) return;- pushState((prev) => ({- zoomRegions: prev.zoomRegions.map((region) => {- if (region.id !== selectedZoomId) return region;- if (preset === null) {- const { rotationPreset: _p, ...rest } = region;- return { ...rest, source: "manual" };- }- return { ...region, rotationPreset: preset, source: "manual" };- }),- }));- },- [selectedZoomId, pushState],- );-- const handleTrimDelete = useCallback(- (id: string) => {- pushState((prev) => ({- trimRegions: prev.trimRegions.filter((r) => r.id !== id),- }));- if (selectedTrimId === id) {- setSelectedTrimId(null);- }- },- [selectedTrimId, pushState],- );-- const handleSelectSpeed = useCallback((id: string | null) => {- setSelectedSpeedId(id);- if (id) {- setSelectedZoomId(null);- setSelectedCameraFullscreenId(null);- setSelectedTrimId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- }- }, []);-- const handleSpeedAdded = useCallback(- (span: Span) => {- const id = `speed-${nextSpeedIdRef.current++}`;- const newRegion: SpeedRegion = {- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- speed: DEFAULT_PLAYBACK_SPEED,- };- pushState((prev) => ({- speedRegions: [...prev.speedRegions, newRegion],- }));- setSelectedSpeedId(id);- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedAnnotationId(null);- setSelectedBlurId(null);- },- [pushState],- );-- const handleSpeedSpanChange = useCallback(- (id: string, span: Span) => {- pushState((prev) => ({- speedRegions: prev.speedRegions.map((region) =>- region.id === id- ? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }- : region,- ),- }));- },- [pushState],- );-- const handleSpeedDelete = useCallback(- (id: string) => {- pushState((prev) => ({- speedRegions: prev.speedRegions.filter((region) => region.id !== id),- }));- if (selectedSpeedId === id) {- setSelectedSpeedId(null);- }- },- [selectedSpeedId, pushState],- );-- const handleSpeedChange = useCallback(- (speed: PlaybackSpeed) => {- if (!selectedSpeedId) return;- pushState((prev) => ({- speedRegions: prev.speedRegions.map((region) =>- region.id === selectedSpeedId ? { ...region, speed } : region,- ),- }));- },- [selectedSpeedId, pushState],- );-- const handleAnnotationAdded = useCallback(- (span: Span) => {- const id = `annotation-${nextAnnotationIdRef.current++}`;- const zIndex = nextAnnotationZIndexRef.current++;- const newRegion = createTextAnnotationRegion({- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- zIndex,- });- pushState((prev) => ({- annotationRegions: [...prev.annotationRegions, newRegion],- }));- setSelectedAnnotationId(id);- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedBlurId(null);- },- [pushState],- );-- const handleBlurAdded = useCallback(- (span: Span) => {- const id = `annotation-${nextAnnotationIdRef.current++}`;- const zIndex = nextAnnotationZIndexRef.current++;- const newRegion: AnnotationRegion = {- id,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- type: "blur",- content: "",- position: { ...DEFAULT_ANNOTATION_POSITION },- size: { ...DEFAULT_ANNOTATION_SIZE },- style: { ...DEFAULT_ANNOTATION_STYLE },- zIndex,- blurData: { ...DEFAULT_BLUR_DATA },- };- pushState((prev) => ({- annotationRegions: [...prev.annotationRegions, newRegion],- }));- setSelectedBlurId(id);- setSelectedAnnotationId(null);- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- },- [pushState],- );-- const handleAnnotationSpanChange = useCallback(- (id: string, span: Span) => {- pushState((prev) => {- const editedAutoCaption =- prev.annotationRegions.find((region) => region.id === id)?.annotationSource ===- "auto-caption";- const next = prev.annotationRegions.map((region) =>- region.id === id- ? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }- : region,- );- return {- annotationRegions: editedAutoCaption ? reconcileAutoCaptionTimelineGaps(next) : next,- };- });- },- [pushState],- );-- const handleAnnotationDuplicate = useCallback(- (id: string) => {- const duplicateId = `annotation-${nextAnnotationIdRef.current++}`;- const duplicateZIndex = nextAnnotationZIndexRef.current++;- pushState((prev) => {- const source = prev.annotationRegions.find((region) => region.id === id);- if (!source) return {};-- const { annotationSource: _stripCaptionLink, ...sourceWithoutCaptionLink } = source;-- const duplicate: AnnotationRegion = {- ...sourceWithoutCaptionLink,- id: duplicateId,- zIndex: duplicateZIndex,- position: { x: source.position.x + 4, y: source.position.y + 4 },- size: { ...source.size },- style: { ...source.style },- figureData: source.figureData ? { ...source.figureData } : undefined,- };-- return { annotationRegions: [...prev.annotationRegions, duplicate] };- });- setSelectedAnnotationId(duplicateId);- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedBlurId(null);- },- [pushState],- );-- const handleAnnotationDelete = useCallback(- (id: string) => {- pushState((prev) => ({- annotationRegions: prev.annotationRegions.filter((r) => r.id !== id),- }));- if (selectedAnnotationId === id) {- setSelectedAnnotationId(null);- }- if (selectedBlurId === id) {- setSelectedBlurId(null);- }- },- [selectedAnnotationId, selectedBlurId, pushState],- );-- const handleAnnotationContentChange = useCallback(- (id: string, content: string) => {- pushState((prev) => ({- annotationRegions: prev.annotationRegions.map((region) => {- if (region.id !== id) return region;- if (region.type === "text") {- return { ...region, content, textContent: content };- } else if (region.type === "image") {- return { ...region, content, imageContent: content };- }- return { ...region, content };- }),- }));- },- [pushState],- );-- const handleAnnotationTypeChange = useCallback(- (id: string, type: AnnotationRegion["type"]) => {- pushState((prev) => ({- annotationRegions: prev.annotationRegions.map((region) => {- if (region.id !== id) return region;- const updatedRegion = { ...region, type };- if (type === "text") {- updatedRegion.content = resolveTextAnnotationContent(region.textContent);- } else if (type === "image") {- updatedRegion.content = region.imageContent || "";- } else if (type === "figure") {- updatedRegion.content = "";- if (!region.figureData) {- updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };- }- } else if (type === "blur") {- updatedRegion.content = "";- if (!region.blurData) {- updatedRegion.blurData = { ...DEFAULT_BLUR_DATA };- }- }- return updatedRegion;- }),- }));-- if (type === "blur" && selectedAnnotationId === id) {- setSelectedAnnotationId(null);- setSelectedBlurId(id);- setSelectedSpeedId(null);- } else if (type !== "blur" && selectedBlurId === id) {- setSelectedBlurId(null);- setSelectedAnnotationId(id);- }- },- [pushState, selectedAnnotationId, selectedBlurId],- );-- const handleAnnotationStyleChange = useCallback(- (id: string, style: Partial<AnnotationRegion["style"]>) => {- pushState((prev) => {- const touched = prev.annotationRegions.find((r) => r.id === id);- const syncAutoCaptions = touched?.annotationSource === "auto-caption";- return {- annotationRegions: prev.annotationRegions.map((region) => {- if (syncAutoCaptions && region.annotationSource === "auto-caption") {- return { ...region, style: { ...region.style, ...style } };- }- return region.id === id ? { ...region, style: { ...region.style, ...style } } : region;- }),- };- });- },- [pushState],- );-- const handleAnnotationFigureDataChange = useCallback(- (id: string, figureData: FigureData) => {- pushState((prev) => ({- annotationRegions: prev.annotationRegions.map((region) =>- region.id === id ? { ...region, figureData } : region,- ),- }));- },- [pushState],- );-- const handleBlurDataPreviewChange = useCallback(- (id: string, blurData: BlurData) => {- updateState((prev) => ({- annotationRegions: prev.annotationRegions.map((region) =>- region.id === id- ? {- ...region,- blurData,- // Freehand drawing area is the full video surface.- ...(blurData.shape === "freehand"- ? {- position: { x: 0, y: 0 },- size: { width: 100, height: 100 },- }- : {}),- }- : region,- ),- }));- },- [updateState],- );-- const handleBlurDataPanelChange = useCallback(- (id: string, blurData: BlurData) => {- pushState((prev) => ({- annotationRegions: prev.annotationRegions.map((region) =>- region.id === id- ? {- ...region,- blurData,- ...(blurData.shape === "freehand"- ? {- position: { x: 0, y: 0 },- size: { width: 100, height: 100 },- }- : {}),- }- : region,- ),- }));- },- [pushState],- );-- const handleAnnotationPositionChange = useCallback(- (id: string, position: { x: number; y: number }) => {- pushState((prev) => {- const moved = prev.annotationRegions.find((r) => r.id === id);- const syncAutoCaptions = moved?.annotationSource === "auto-caption";- return {- annotationRegions: prev.annotationRegions.map((region) => {- if (syncAutoCaptions && region.annotationSource === "auto-caption") {- return { ...region, position };- }- return region.id === id ? { ...region, position } : region;- }),- };- });- },- [pushState],- );-- const handleAnnotationSizeChange = useCallback(- (id: string, size: { width: number; height: number }) => {- pushState((prev) => {- const resized = prev.annotationRegions.find((r) => r.id === id);- const syncAutoCaptions = resized?.annotationSource === "auto-caption";- return {- annotationRegions: prev.annotationRegions.map((region) => {- if (syncAutoCaptions && region.annotationSource === "auto-caption") {- return { ...region, size };- }- return region.id === id ? { ...region, size } : region;- }),- };- });- },- [pushState],- );-- const handleCopySelected = useCallback(() => {- // Copy the selected region of any kind into the clipboard. A selected blur is an- // annotation (type "blur" lives in annotationRegions), so it copies via that row.- const copyTargets = [- [selectedZoomId, zoomRegions, extractZoomAttributes, "zoom"],- [selectedSpeedId, speedRegions, extractSpeedAttributes, "speed"],- [- selectedAnnotationId ?? selectedBlurId,- annotationRegions,- extractAnnotationAttributes,- "annotation",- ],- ] as const;-- for (const [id, regions, extract, kind] of copyTargets) {- if (!id) continue;- const region = (regions as readonly { id: string }[]).find((r) => r.id === id);- if (!region) continue; // Stale id — try the next target so the fallback toast stays reachable.- // Each row pairs a region list with its matching extractor, so the cast is sound.- setCopiedRegion((extract as (r: never) => CopiedRegion)(region as never));- // Blur lives in annotationRegions (type "blur") but its toast must label as "blur", not "text".- const labelKind = (region as { type?: string }).type === "blur" ? "blur" : kind;- toast.success(- t("regionClipboard.copied", { region: t(`regionClipboard.kinds.${labelKind}`) }),- {- id: "regionClipboard.copied",- },- );- return;- }- toast.info(t("regionClipboard.nothingToCopy"));- }, [- selectedZoomId,- selectedSpeedId,- selectedAnnotationId,- selectedBlurId,- zoomRegions,- speedRegions,- annotationRegions,- t,- ]);-- const handlePaste = useCallback(() => {- const copied = getCopiedRegion();- // If there's nothing in the clipboard, show a message and return early.- if (!copied) {- toast.info(t("regionClipboard.nothingToPaste"));- return;- }-- // Apply onto the selected region of the same kind, keeping its timing.- if (copied.kind === "zoom" && selectedZoomId) {- pushState((prev) => ({- zoomRegions: prev.zoomRegions.map((r) =>- r.id === selectedZoomId ? buildZoomRegion(r, copied) : r,- ),- }));- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- return;- }- if (copied.kind === "speed" && selectedSpeedId) {- pushState((prev) => ({- speedRegions: prev.speedRegions.map((r) =>- r.id === selectedSpeedId ? buildSpeedRegion(r, copied) : r,- ),- }));- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- return;- }- // Blurs live in annotationRegions (type "blur"), so a selected blur is a valid target too.- if (copied.kind === "annotation" && (selectedAnnotationId || selectedBlurId)) {- const targetId = selectedAnnotationId ?? selectedBlurId;- pushState((prev) => ({- annotationRegions: prev.annotationRegions.map((r) =>- r.id === targetId ? replaceAnnotationAttributes(r, copied) : r,- ),- }));- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- return;- }-- // Nothing matching selected → create a new region at the playhead.- const totalMs = Math.round(duration * 1000);- if (totalMs <= 0) return;- const defaultDuration = Math.min(Math.max(1000, Math.round(totalMs * 0.05)), totalMs);- const startPos = Math.max(0, Math.min(Math.round(currentTime * 1000), totalMs));-- if (copied.kind === "zoom") {- const { ok, gapMs } = findFreeGapAt(zoomRegions, startPos, totalMs);- if (!ok) {- toast.error(tt("errors.cannotPlaceZoom"), {- description: tt("errors.zoomExistsAtLocation"),- });- return;- }- const id = `zoom-${nextZoomIdRef.current++}`;- const region = buildZoomRegion(- {- id,- startMs: startPos,- endMs: startPos + Math.min(defaultDuration, gapMs),- source: "manual",- },- copied,- );- pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, region] }));- handleSelectZoom(id);- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- return;- }-- if (copied.kind === "speed") {- const { ok, gapMs } = findFreeGapAt(speedRegions, startPos, totalMs);- if (!ok) {- toast.error(tt("errors.cannotPlaceSpeed"), {- description: tt("errors.speedExistsAtLocation"),- });- return;- }- const id = `speed-${nextSpeedIdRef.current++}`;- const region = buildSpeedRegion(- {- id,- startMs: startPos,- endMs: startPos + Math.min(defaultDuration, gapMs),- },- copied,- );- pushState((prev) => ({ speedRegions: [...prev.speedRegions, region] }));- handleSelectSpeed(id);- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- return;- }-- // Annotation — overlaps are allowed. A brand-new region clones the full copy- // (type, content, styling, position), unlike the styling-only overwrite above.- const id = `annotation-${nextAnnotationIdRef.current++}`;- const region = buildPastedAnnotation(- {- id,- startMs: startPos,- endMs: Math.min(startPos + defaultDuration, totalMs),- zIndex: nextAnnotationZIndexRef.current++,- },- copied,- );- pushState((prev) => ({ annotationRegions: [...prev.annotationRegions, region] }));- handleSelectAnnotation(id);- toast.success(- t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),- {- id: "regionClipboard.pasted",- },- );- }, [- selectedZoomId,- selectedSpeedId,- selectedAnnotationId,- selectedBlurId,- zoomRegions,- speedRegions,- duration,- currentTime,- pushState,- handleSelectZoom,- handleSelectSpeed,- handleSelectAnnotation,- t,- tt,- ]);-- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- const mod = e.ctrlKey || e.metaKey;- const key = e.key.toLowerCase();-- if (mod && key === "z" && !e.shiftKey) {- e.preventDefault();- e.stopPropagation();- undo();- return;- }- if (mod && (key === "y" || (key === "z" && e.shiftKey))) {- e.preventDefault();- e.stopPropagation();- redo();- return;- }-- // Copy/paste region attributes. Skipped while typing in a field so native- // text copy/paste keeps working. Also only intercepted when there's an- // actual region selected (copy) or something on the clipboard (paste);- // otherwise the browser handles native copy/paste of any page selection.- const editingText = isTextEditingTarget(e.target);- if (!editingText) {- if (matchesShortcut(e, shortcuts.copySelected, isMac)) {- const hasRegionSelected =- selectedZoomId || selectedSpeedId || selectedAnnotationId || selectedBlurId;- if (hasRegionSelected) {- e.preventDefault();- handleCopySelected();- return;- }- } else if (matchesShortcut(e, shortcuts.paste, isMac)) {- if (getCopiedRegion()) {- e.preventDefault();- handlePaste();- return;- }- }- }-- // Frame-step navigation (arrow keys, no modifiers)- if (- (e.key === "ArrowLeft" || e.key === "ArrowRight") &&- !e.ctrlKey &&- !e.metaKey &&- !e.shiftKey &&- !e.altKey- ) {- const target = e.target;- if (- target instanceof HTMLInputElement ||- target instanceof HTMLTextAreaElement ||- target instanceof HTMLSelectElement ||- (target instanceof HTMLElement &&- (target.isContentEditable ||- target.closest('[role="separator"], [role="slider"], [role="spinbutton"]')))- ) {- return;- }- e.preventDefault();- const video = videoPlaybackRef.current?.video;- if (!video) {- return;- }- const direction = e.key === "ArrowLeft" ? "backward" : "forward";- const newTime = computeFrameStepTime(- video.currentTime,- Number.isFinite(video.duration) ? video.duration : durationRef.current,- direction,- );- video.currentTime = newTime;- return;- }-- const isInput =- e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement;-- if (e.key === "Tab" && !isInput) {- e.preventDefault();- }-- if (matchesShortcut(e, shortcuts.playPause, isMac)) {- // Let space pass through inside inputs/textareas.- if (isInput) {- return;- }- e.preventDefault();- const playback = videoPlaybackRef.current;- if (playback?.video) {- playback.video.paused ? playback.play().catch(console.error) : playback.pause();- }- }- };-- window.addEventListener("keydown", handleKeyDown, { capture: true });- return () => window.removeEventListener("keydown", handleKeyDown, { capture: true });- }, [- undo,- redo,- shortcuts,- isMac,- handleCopySelected,- handlePaste,- selectedZoomId,- selectedSpeedId,- selectedAnnotationId,- selectedBlurId,- ]);-- useEffect(() => {- if (selectedZoomId && !zoomRegions.some((region) => region.id === selectedZoomId)) {- setSelectedZoomId(null);- }- }, [selectedZoomId, zoomRegions]);-- useEffect(() => {- if (- selectedCameraFullscreenId &&- !cameraFullscreenRegions.some((region) => region.id === selectedCameraFullscreenId)- ) {- setSelectedCameraFullscreenId(null);- }- }, [selectedCameraFullscreenId, cameraFullscreenRegions]);-- useEffect(() => {- if (selectedTrimId && !trimRegions.some((region) => region.id === selectedTrimId)) {- setSelectedTrimId(null);- }- }, [selectedTrimId, trimRegions]);-- useEffect(() => {- if (- selectedAnnotationId &&- !annotationOnlyRegions.some((region) => region.id === selectedAnnotationId)- ) {- setSelectedAnnotationId(null);- }- if (selectedBlurId && !blurRegions.some((region) => region.id === selectedBlurId)) {- setSelectedBlurId(null);- }- }, [selectedAnnotationId, selectedBlurId, annotationOnlyRegions, blurRegions]);-- useEffect(() => {- if (selectedSpeedId && !speedRegions.some((region) => region.id === selectedSpeedId)) {- setSelectedSpeedId(null);- }- }, [selectedSpeedId, speedRegions]);-- const handleShowExportedFile = useCallback(async (filePath: string) => {- try {- const result = await window.electronAPI.revealInFolder(filePath);- if (!result.success) {- const errorMessage = result.error || result.message || "Failed to reveal item in folder.";- console.error("Failed to reveal in folder:", errorMessage);- toast.error(errorMessage);- }- } catch (error) {- const errorMessage = String(error);- console.error("Error calling revealInFolder IPC:", errorMessage);- toast.error(`Error revealing in folder: ${errorMessage}`);- }- }, []);-- const handleExportSaved = useCallback(- (formatLabel: "GIF" | "Video", filePath: string) => {- setExportedFilePath(filePath);- const folder = parentDirectoryOf(filePath);- if (folder) {- saveUserPreferences({ exportFolder: folder });- }- toast.success(- t("export.exportedSuccessfully", {- format: formatLabel,- }),- {- description: filePath,- action: {- label: rawT("common.actions.showInFolder"),- onClick: () => {- void handleShowExportedFile(filePath);- },- },- },- );- },- [handleShowExportedFile, t, rawT],- );-- const handleSaveUnsavedExport = useCallback(async () => {- if (!unsavedExport) return;- try {- const pickResult = await window.electronAPI.pickExportSavePath(- unsavedExport.fileName,- getExportFolder(),- );- if (pickResult.canceled || !pickResult.success || !pickResult.path) {- toast.info("Export canceled");- return;- }- const saveResult = await window.electronAPI.writeExportToPath(- unsavedExport.arrayBuffer,- pickResult.path,- );- if (saveResult.success && saveResult.path) {- setUnsavedExport(null);- handleExportSaved(unsavedExport.format === "gif" ? "GIF" : "Video", saveResult.path);- } else {- toast.error(- buildSaveDiagnosticMessage(- unsavedExport.format === "gif" ? "GIF" : "Video",- saveResult.message || "Failed to save export",- ),- );- }- } catch (error) {- console.error("Error saving unsaved export:", error);- toast.error(- buildSaveDiagnosticMessage(- unsavedExport.format === "gif" ? "GIF" : "Video",- error instanceof Error ? error.message : "Failed to save exported video",- ),- );- }- }, [unsavedExport, handleExportSaved]);-- const handleExport = useCallback(- async (settings: ExportSettings) => {- if (!videoPath) {- toast.error("No video loaded");- return;- }-- const video = videoPlaybackRef.current?.video;- if (!video) {- toast.error("Video not ready");- return;- }-- // Pick the save path before exporting, otherwise the save dialog can end up- // hidden behind other windows after a long-running export.- const isGifFormat = settings.format === "gif";- const targetFileName = `export-${Date.now()}.${isGifFormat ? "gif" : "mp4"}`;- const pickResult = await window.electronAPI.pickExportSavePath(- targetFileName,- getExportFolder(),- );- if (pickResult.canceled || !pickResult.success || !pickResult.path) {- setShowExportDialog(false);- return;- }- const targetPath = pickResult.path;-- setIsExporting(true);- setExportProgress(null);- setExportError(null);- setExportedFilePath(null);-- try {- const wasPlaying = isPlaying;- if (wasPlaying) {- videoPlaybackRef.current?.pause();- }-- const sourceWidth = video.videoWidth || DEFAULT_SOURCE_DIMENSIONS.width;- const sourceHeight = video.videoHeight || DEFAULT_SOURCE_DIMENSIONS.height;- const effectiveSourceDimensions = calculateEffectiveSourceDimensions(- sourceWidth,- sourceHeight,- cropRegion,- );- const aspectRatioValue =- aspectRatio === "native"- ? getNativeAspectRatioValue(sourceWidth, sourceHeight, cropRegion)- : getAspectRatioValue(aspectRatio);-- // Preview container dimensions, used for scaling.- const playbackRef = videoPlaybackRef.current;- const containerElement = playbackRef?.containerRef?.current;- const previewWidth = containerElement?.clientWidth || DEFAULT_SOURCE_DIMENSIONS.width;- const previewHeight = containerElement?.clientHeight || DEFAULT_SOURCE_DIMENSIONS.height;-- if (settings.format === "gif" && settings.gifConfig) {- // GIF Export- const gifExporter = new GifExporter({- videoUrl: videoPath,- webcamVideoUrl: webcamVideoPath || undefined,- width: settings.gifConfig.width,- height: settings.gifConfig.height,- frameRate: settings.gifConfig.frameRate,- loop: settings.gifConfig.loop,- sizePreset: settings.gifConfig.sizePreset,- wallpaper,- zoomRegions,- cameraFullscreenRegions,- trimRegions,- speedRegions,- showShadow: shadowIntensity > 0,- shadowIntensity,- showBlur,- motionBlurAmount,- borderRadius,- padding,- videoPadding: padding,- cropRegion,- cursorRecordingData,- cursorScale: effectiveShowCursor ? cursorSize : 0,- cursorSmoothing,- cursorMotionBlur,- cursorClickBounce,- cursorClipToBounds,- cursorTheme,- annotationRegions,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- previewWidth,- previewHeight,- cursorTelemetry,- cursorClickTimestamps,- onProgress: (progress: ExportProgress) => {- setExportProgress(progress);- },- });-- exporterRef.current = gifExporter as unknown as VideoExporter;- const result = await gifExporter.export();-- if (result.success && result.blob) {- const arrayBuffer = await result.blob.arrayBuffer();-- if (result.warnings) {- for (const warning of result.warnings) {- toast.warning(warning);- }- }-- const saveResult = await window.electronAPI.writeExportToPath(arrayBuffer, targetPath);-- if (saveResult.success && saveResult.path) {- setUnsavedExport(null);- handleExportSaved("GIF", saveResult.path);- } else {- setUnsavedExport({ arrayBuffer, fileName: targetFileName, format: "gif" });- const message = buildSaveDiagnosticMessage(- "GIF",- saveResult.message || "Failed to save GIF",- );- setExportError(message);- toast.error(message);- }- } else {- const message = buildExportDiagnosticMessage({- formatLabel: "GIF",- reason: result.error || "GIF export failed",- sourcePath: videoSourcePath ?? videoPath,- width: settings.gifConfig.width,- height: settings.gifConfig.height,- frameRate: settings.gifConfig.frameRate,- });- setExportError(message);- toast.error(message);- }- } else {- // MP4 Export- const quality = settings.quality || exportQuality;- const {- width: exportWidth,- height: exportHeight,- bitrate,- } = calculateMp4ExportSettings({- quality,- sourceWidth: effectiveSourceDimensions.width,- sourceHeight: effectiveSourceDimensions.height,- aspectRatioValue,- });-- const exporter = new VideoExporter({- videoUrl: videoPath,- webcamVideoUrl: webcamVideoPath || undefined,- width: exportWidth,- height: exportHeight,- frameRate: 60,- bitrate,- codec: "avc1.640033",- wallpaper,- zoomRegions,- cameraFullscreenRegions,- trimRegions,- speedRegions,- showShadow: shadowIntensity > 0,- shadowIntensity,- showBlur,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- cursorRecordingData,- cursorScale: effectiveShowCursor ? cursorSize : 0,- cursorSmoothing,- cursorMotionBlur,- cursorClickBounce,- cursorClipToBounds,- cursorTheme,- annotationRegions,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- previewWidth,- previewHeight,- cursorTelemetry,- cursorClickTimestamps,- onProgress: (progress: ExportProgress) => {- setExportProgress(progress);- },- });-- exporterRef.current = exporter;- const result = await exporter.export();-- if (result.success && result.blob) {- const arrayBuffer = await result.blob.arrayBuffer();-- if (result.warnings) {- for (const warning of result.warnings) {- toast.warning(warning);- }- }-- const saveResult = await window.electronAPI.writeExportToPath(arrayBuffer, targetPath);-- if (saveResult.success && saveResult.path) {- setUnsavedExport(null);- handleExportSaved("Video", saveResult.path);- } else {- setUnsavedExport({ arrayBuffer, fileName: targetFileName, format: "mp4" });- const message = buildSaveDiagnosticMessage(- "Video",- saveResult.message || "Failed to save video",- );- setExportError(message);- toast.error(message);- }- } else {- const message = buildExportDiagnosticMessage({- formatLabel: "Video",- reason: result.error || "Export failed",- sourcePath: videoSourcePath ?? videoPath,- width: exportWidth,- height: exportHeight,- frameRate: 60,- codec: "avc1.640033",- bitrate,- });- setExportError(message);- toast.error(message);- }- }-- if (wasPlaying) {- videoPlaybackRef.current?.play();- }- } catch (error) {- console.error("Export error:", error);- if (error instanceof BackgroundLoadError) {- const message = t("errors.exportBackgroundLoadFailed", { url: error.displayUrl });- setExportError(message);- toast.error(message);- } else {- const errorMessage = error instanceof Error ? error.message : "Unknown error";- const message = buildExportDiagnosticMessage({- formatLabel: settings.format === "gif" ? "GIF" : "Video",- reason: errorMessage,- sourcePath: videoSourcePath ?? videoPath,- });- setExportError(message);- toast.error(t("errors.exportFailedWithError", { error: message }));- }- } finally {- setIsExporting(false);- exporterRef.current = null;- // Reset so the next export can reopen the dialog (second export- // otherwise wouldn't show the save dialog).- setShowExportDialog(false);- setExportProgress(null);- }- },- [- videoPath,- videoSourcePath,- webcamVideoPath,- wallpaper,- zoomRegions,- cameraFullscreenRegions,- trimRegions,- speedRegions,- shadowIntensity,- showBlur,- motionBlurAmount,- borderRadius,- padding,- cropRegion,- cursorRecordingData,- annotationRegions,- isPlaying,- aspectRatio,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored,- webcamReactiveZoom,- webcamSizePreset,- webcamPosition,- exportQuality,- handleExportSaved,- cursorTelemetry,- cursorClickTimestamps,- effectiveShowCursor,- cursorSize,- cursorSmoothing,- cursorMotionBlur,- cursorClickBounce,- cursorClipToBounds,- cursorTheme,- t,- ],- );-- const handleOpenExportDialog = useCallback(() => {- if (!videoPath) {- toast.error("No video loaded");- return;- }-- const video = videoPlaybackRef.current?.video;- if (!video) {- toast.error("Video not ready");- return;- }-- // Build export settings from current state- const sourceWidth = video.videoWidth || DEFAULT_SOURCE_DIMENSIONS.width;- const sourceHeight = video.videoHeight || DEFAULT_SOURCE_DIMENSIONS.height;- const effectiveSourceDimensions = calculateEffectiveSourceDimensions(- sourceWidth,- sourceHeight,- cropRegion,- );- const aspectRatioValue =- aspectRatio === "native"- ? getNativeAspectRatioValue(sourceWidth, sourceHeight, cropRegion)- : getAspectRatioValue(aspectRatio);- const gifDimensions = calculateOutputDimensions(- effectiveSourceDimensions.width,- effectiveSourceDimensions.height,- gifSizePreset,- GIF_SIZE_PRESETS,- aspectRatioValue,- );-- const settings: ExportSettings = {- format: exportFormat,- quality: exportFormat === "mp4" ? exportQuality : undefined,- gifConfig:- exportFormat === "gif"- ? {- frameRate: gifFrameRate,- loop: gifLoop,- sizePreset: gifSizePreset,- width: gifDimensions.width,- height: gifDimensions.height,- }- : undefined,- };-- setShowExportDialog(true);- setExportError(null);- setExportedFilePath(null);-- // Start export immediately- handleExport(settings);- }, [- videoPath,- exportFormat,- exportQuality,- gifFrameRate,- gifLoop,- gifSizePreset,- aspectRatio,- cropRegion,- handleExport,- ]);-- const handleCancelExport = useCallback(() => {- if (exporterRef.current) {- exporterRef.current.cancel();- toast.info("Export canceled");- setShowExportDialog(false);- setIsExporting(false);- setExportProgress(null);- setExportError(null);- setExportedFilePath(null);- }- }, []);-- const generateAutoCaptions = useCallback(- async (minWords: number, maxWords: number) => {- if (!videoPath) {- toast.error(t("errors.noVideoLoaded"));- return;- }- if (isAutoCaptioningRef.current) {- toast.error(t("autoCaptions.busy"));- return;- }- const minW = Math.max(1, Math.min(minWords, maxWords));- const maxW = Math.max(minW, maxWords);-- isAutoCaptioningRef.current = true;- setIsAutoCaptioning(true);- toast.loading(t("autoCaptions.generating"), { id: AUTO_CAPTION_PROGRESS_TOAST_ID });- try {- const { samples, truncated, durationSec } = await extractMono16kFromVideoUrl(videoPath);- if (!Number.isFinite(durationSec) || durationSec <= 0 || samples.length < 800) {- toast.dismiss(AUTO_CAPTION_PROGRESS_TOAST_ID);- toast.error(t("autoCaptions.noAudio"));- return;- }-- const { samples: speechSamples, trimSec } = trimLeadingSilenceMono16k(samples);- if (speechSamples.length < 800) {- toast.dismiss(AUTO_CAPTION_PROGRESS_TOAST_ID);- toast.error(t("autoCaptions.noAudio"));- return;- }-- const trimMs = Math.round(trimSec * 1000);- const trimRegionsForTranscribe = shiftTrimRegionsMsForCaptionBuffer(trimRegions, trimMs);-- const transcribeOptions = {- onStatus: (phase: "model" | "transcribe") => {- if (phase === "model") {- toast.loading(t("autoCaptions.loadingModel"), {- id: AUTO_CAPTION_PROGRESS_TOAST_ID,- });- } else {- toast.loading(t("autoCaptions.transcribing"), {- id: AUTO_CAPTION_PROGRESS_TOAST_ID,- });- }- },- };-- let { segments: segmentsRaw, granularity } = await transcribeMono16kToSegments(- speechSamples,- {- trimRegions: trimRegionsForTranscribe,- ...transcribeOptions,- },- );- let transcribedFromTrimmedBuffer = true;-- // Leading-silence trimming can return empty even when the full source has- // speech. Retry once against the untrimmed buffer before giving up.- if (segmentsRaw.length === 0 && trimSec > 0) {- ({ segments: segmentsRaw, granularity } = await transcribeMono16kToSegments(samples, {- trimRegions,- ...transcribeOptions,- }));- transcribedFromTrimmedBuffer = false;- }-- const segments =- transcribedFromTrimmedBuffer && trimSec > 0- ? segmentsRaw.map((s) => ({- ...s,- startSec: s.startSec + trimSec,- endSec: s.endSec + trimSec,- }))- : segmentsRaw;-- let { regions, nextNumericId, nextZIndex } = captionSegmentsToAnnotationRegions(- segments,- nextAnnotationIdRef.current,- nextAnnotationZIndexRef.current,- {- minWordsPerCaption: minW,- maxWordsPerCaption: maxW,- timestampGranularity: granularity,- },- );-- if (regions.length === 0 && segments.length > 0) {- ({ regions, nextNumericId, nextZIndex } = captionSegmentsToAnnotationRegions(- segments,- nextAnnotationIdRef.current,- nextAnnotationZIndexRef.current,- {- minWordsPerCaption: 1,- maxWordsPerCaption: Number.MAX_SAFE_INTEGER,- timestampGranularity: granularity,- },- ));- }-- if (regions.length === 0) {- toast.dismiss(AUTO_CAPTION_PROGRESS_TOAST_ID);- toast.info(t("autoCaptions.noneHeard"));- return;- }-- pushState((prev) => ({ annotationRegions: [...prev.annotationRegions, ...regions] }));- nextAnnotationIdRef.current = nextNumericId;- nextAnnotationZIndexRef.current = nextZIndex;-- toast.dismiss(AUTO_CAPTION_PROGRESS_TOAST_ID);- const minutesTrunc = String(Math.round(MAX_CAPTION_AUDIO_SEC / 60));- if (truncated) {- toast.success(t("autoCaptions.done", { count: String(regions.length) }), {- description: t("autoCaptions.truncated", { minutes: minutesTrunc }),- });- } else {- toast.success(t("autoCaptions.done", { count: String(regions.length) }));- }- } catch (e) {- console.error(e);- toast.dismiss(AUTO_CAPTION_PROGRESS_TOAST_ID);- const detail = e instanceof Error ? e.message : String(e);- toast.error(t("autoCaptions.failed"), { description: detail });- } finally {- isAutoCaptioningRef.current = false;- setIsAutoCaptioning(false);- }- },- [videoPath, trimRegions, pushState, t],- );-- const handleSaveDiagnostic = useCallback(async () => {- const result = await window.electronAPI.saveDiagnostic({- error: exportError ?? "Manual diagnostic export",- projectState: editorState,- logs: [],- });- if (result.success) {- toast.success("Diagnostic file saved");- } else if (!result.canceled) {- toast.error("Failed to save diagnostic file");- }- }, [exportError, editorState]);-- if (loading) {- return (- <div className="flex items-center justify-center h-screen bg-background">- <div className="text-foreground">{t("loadingVideo")}</div>- </div>- );- }- if (error) {- return (- <div className="flex items-center justify-center h-screen bg-background">- <div className="flex flex-col items-center gap-3">- <div className="text-destructive">{error}</div>- <button- type="button"- onClick={handleLoadProject}- className="px-3 py-1.5 rounded-md bg-[#34B27B] text-white text-sm hover:bg-[#34B27B]/90"- >- {ts("project.load")}- </button>- </div>- </div>- );- }-- return (- <div className="flex flex-col h-screen bg-[#09090b] text-slate-200 overflow-hidden selection:bg-[#34B27B]/30">- <Dialog open={showNewRecordingDialog} onOpenChange={setShowNewRecordingDialog}>- <DialogContent- className="sm:max-w-[425px]"- style={{ WebkitAppRegion: "no-drag" } as CSSProperties}- >- <DialogHeader>- <DialogTitle>{t("newRecording.title")}</DialogTitle>- <DialogDescription>{t("newRecording.description")}</DialogDescription>- </DialogHeader>- <DialogFooter>- <button- type="button"- onClick={() => setShowNewRecordingDialog(false)}- className="px-4 py-2 rounded-md bg-white/10 text-white hover:bg-white/20 text-sm font-medium transition-colors"- >- {t("newRecording.cancel")}- </button>- <button- type="button"- onClick={handleNewRecordingConfirm}- className="px-4 py-2 rounded-md bg-[#34B27B] text-white hover:bg-[#34B27B]/90 text-sm font-medium transition-colors"- >- {t("newRecording.confirm")}- </button>- </DialogFooter>- </DialogContent>- </Dialog>-- <Dialog open={showAutoCaptionsDialog} onOpenChange={setShowAutoCaptionsDialog}>- <DialogContent- className="sm:max-w-md"- style={{ WebkitAppRegion: "no-drag" } as CSSProperties}- >- <DialogHeader>- <DialogTitle>{t("autoCaptions.dialogTitle")}</DialogTitle>- <DialogDescription>{t("autoCaptions.dialogDescription")}</DialogDescription>- </DialogHeader>- <div className="grid gap-4 py-2">- <div className="grid gap-2">- <Label htmlFor="caption-min-words">{t("autoCaptions.minWords")}</Label>- <Select- value={String(captionWordsMin)}- onValueChange={(v) => {- const n = Number.parseInt(v, 10);- setCaptionWordsMin(n);- if (n > captionWordsMax) setCaptionWordsMax(n);- }}- >- <SelectTrigger id="caption-min-words" className="h-9">- <SelectValue />- </SelectTrigger>- <SelectContent>- {CAPTION_WORD_CHOICES.map((n) => (- <SelectItem key={`min-${n}`} value={String(n)}>- {t("autoCaptions.wordsCount", { count: String(n) })}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="grid gap-2">- <Label htmlFor="caption-max-words">{t("autoCaptions.maxWords")}</Label>- <Select- value={String(captionWordsMax)}- onValueChange={(v) => {- const n = Number.parseInt(v, 10);- setCaptionWordsMax(n);- if (n < captionWordsMin) setCaptionWordsMin(n);- }}- >- <SelectTrigger id="caption-max-words" className="h-9">- <SelectValue />- </SelectTrigger>- <SelectContent>- {CAPTION_WORD_CHOICES.map((n) => (- <SelectItem key={`max-${n}`} value={String(n)}>- {t("autoCaptions.wordsCount", { count: String(n) })}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>- <DialogFooter className="gap-2 sm:gap-0">- <Button- type="button"- variant="outline"- onClick={() => setShowAutoCaptionsDialog(false)}- className="border-white/20 bg-transparent text-white hover:bg-white/10"- >- {t("autoCaptions.dialogCancel")}- </Button>- <Button- type="button"- disabled={isAutoCaptioning}- onClick={() => {- setShowAutoCaptionsDialog(false);- void generateAutoCaptions(captionWordsMin, captionWordsMax);- }}- className="bg-[#34B27B] text-white hover:bg-[#34B27B]/90"- >- {t("autoCaptions.generate")}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- <div- className="h-11 flex-shrink-0 bg-[#070809]/85 backdrop-blur-xl border-b border-white/[0.07] flex items-center justify-between px-5 z-50 shadow-[0_1px_0_rgba(255,255,255,0.03)]"- style={{ WebkitAppRegion: "drag" } as CSSProperties}- >- <div- className="flex-1 flex items-center gap-1.5"- style={{ WebkitAppRegion: "no-drag" } as CSSProperties}- >- {/* Custom in-app menu bar. Replaces the native OS menu bar that is- auto-hidden on Windows/Linux (see electron/windows.ts). */}- <EditorMenuBar- isMac={isMac}- t={rawT}- onNewProject={handleNewProject}- onLoadProject={handleLoadProject}- onSaveProject={handleSaveProject}- onSaveProjectAs={handleSaveProjectAs}- onQuit={() => window.electronAPI.quitApp()}- onUndo={undo}- onRedo={redo}- onReload={() => window.location.reload()}- canUndo={canUndo}- canRedo={canRedo}- />-- <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-white/[0.08] transition-all duration-150 ml-1">- <Languages size={15} />- <select- aria-label={ts("language.title")}- value={locale}- onChange={(e) => setLocale(e.target.value as Locale)}- className="bg-transparent text-[13px] font-semibold outline-none cursor-pointer appearance-none pr-1"- style={{ color: "inherit" }}- >- {availableLocales.map((loc) => (- <option key={loc} value={loc} className="bg-[#09090b] text-white">- {getLocaleName(loc)}- </option>- ))}- </select>- <ChevronDown size={12} className="opacity-70 ml-0.5 flex-shrink-0" />- </div>- <button- type="button"- onClick={() => setShowNewRecordingDialog(true)}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-white/[0.08] transition-all duration-150 text-[13px] font-medium"- >- <Video size={15} />- {t("newRecording.title")}- </button>- <button- type="button"- onClick={handleLoadProject}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-white/[0.08] transition-all duration-150 text-[13px] font-medium"- >- <FolderOpen size={15} />- {ts("project.load")}- </button>- <button- type="button"- onClick={handleSaveProject}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-white/[0.08] transition-all duration-150 text-[13px] font-medium"- >- <Save size={15} />- {ts("project.save")}- </button>- </div>- </div>-- {/* Empty state shown when no video is loaded */}- {!videoPath && (- <div className="flex-1 min-h-0 relative">- <EditorEmptyState- onVideoImported={(path) => {- setVideoPath(toFileUrl(path));- setVideoSourcePath(path);- setWebcamVideoPath(null);- setWebcamVideoSourcePath(null);- }}- onProjectOpened={async (project, path) => {- const restored = await applyLoadedProject(project, path);- if (!restored) {- toast.error(t("project.invalidFormat"));- }- }}- />- </div>- )}-- {videoPath && (- <div className="editor-workspace flex-1 min-h-0 relative">- <PanelGroup direction="vertical" className="gap-3 min-h-0">- {/* Top section: preview and contextual settings */}- <Panel defaultSize={67} maxSize={76} minSize={46} className="min-h-[300px]">- <div className="editor-main-deck h-full min-h-0">- <div className="editor-preview-zone min-w-0 h-full">- <div- ref={playerContainerRef}- className={- isFullscreen- ? "fixed inset-0 z-[99999] w-full h-full flex flex-col items-center justify-center bg-[#09090b]"- : "editor-preview-panel w-full h-full flex flex-col items-center justify-center overflow-hidden relative"- }- >- {/* Video preview */}- <div className="w-full min-h-0 flex justify-center items-center flex-auto px-4 pt-4">- <div- className="relative flex justify-center items-center w-auto h-full max-w-full box-border"- style={{- aspectRatio:- aspectRatio === "native"- ? getNativeAspectRatioValue(- videoPlaybackRef.current?.video?.videoWidth ||- DEFAULT_SOURCE_DIMENSIONS.width,- videoPlaybackRef.current?.video?.videoHeight ||- DEFAULT_SOURCE_DIMENSIONS.height,- cropRegion,- )- : getAspectRatioValue(aspectRatio),- }}- >- <VideoPlayback- key={`${videoPath || "no-video"}:${webcamVideoPath || "no-webcam"}`}- aspectRatio={aspectRatio}- ref={videoPlaybackRef}- videoPath={videoPath || ""}- webcamVideoPath={webcamVideoPath || undefined}- webcamLayoutPreset={webcamLayoutPreset}- webcamMaskShape={webcamMaskShape}- webcamMirrored={webcamMirrored}- webcamReactiveZoom={webcamReactiveZoom}- webcamSizePreset={webcamSizePreset}- webcamPosition={webcamPosition}- onWebcamPositionChange={(pos) => updateState({ webcamPosition: pos })}- onWebcamPositionDragEnd={commitState}- onDurationChange={setDuration}- onTimeUpdate={setCurrentTime}- currentTime={currentTime}- onPlayStateChange={setIsPlaying}- onError={setError}- wallpaper={wallpaper}- zoomRegions={zoomRegions}- cameraFullscreenRegions={cameraFullscreenRegions}- selectedZoomId={selectedZoomId}- onSelectZoom={handleSelectZoom}- onZoomFocusChange={handleZoomFocusChange}- onZoomFocusDragEnd={commitState}- isPlaying={isPlaying}- showShadow={shadowIntensity > 0}- shadowIntensity={shadowIntensity}- showBlur={showBlur}- motionBlurAmount={motionBlurAmount}- borderRadius={borderRadius}- padding={padding}- cropRegion={cropRegion}- cursorRecordingData={cursorRecordingData}- trimRegions={trimRegions}- speedRegions={speedRegions}- annotationRegions={annotationOnlyRegions}- selectedAnnotationId={selectedAnnotationId}- onSelectAnnotation={handleSelectAnnotation}- onAnnotationPositionChange={handleAnnotationPositionChange}- onAnnotationSizeChange={handleAnnotationSizeChange}- blurRegions={blurRegions}- selectedBlurId={selectedBlurId}- onSelectBlur={handleSelectBlur}- onBlurPositionChange={handleAnnotationPositionChange}- onBlurSizeChange={handleAnnotationSizeChange}- onBlurDataChange={handleBlurDataPreviewChange}- onBlurDataCommit={commitState}- cursorTelemetry={cursorTelemetry}- cursorClickTimestamps={cursorClickTimestamps}- showCursor={effectiveShowCursor}- cursorSize={cursorSize}- cursorSmoothing={cursorSmoothing}- cursorMotionBlur={cursorMotionBlur}- cursorClickBounce={cursorClickBounce}- cursorClipToBounds={cursorClipToBounds}- cursorTheme={cursorTheme}- isPreviewingZoom={isPreviewingZoom}- />- </div>- </div>- {/* Playback controls */}- <div className="w-full flex justify-center items-center h-14 flex-shrink-0 px-4 py-2">- <div className="w-full max-w-[760px]">- <PlaybackControls- isPlaying={isPlaying}- currentTime={currentTime}- duration={duration}- isFullscreen={isFullscreen}- onToggleFullscreen={toggleFullscreen}- onTogglePlayPause={togglePlayPause}- onSeek={handleSeek}- />- </div>- </div>- </div>- </div>-- <div className="editor-settings-rail min-w-0 h-full">- <SettingsPanel- selected={wallpaper}- onWallpaperChange={(w) => pushState({ wallpaper: w })}- selectedZoomDepth={- selectedZoomId- ? zoomRegions.find((z) => z.id === selectedZoomId)?.depth- : null- }- onZoomDepthChange={(depth) => selectedZoomId && handleZoomDepthChange(depth)}- selectedZoomCustomScale={- selectedZoomId- ? (zoomRegions.find((z) => z.id === selectedZoomId)?.customScale ?? null)- : null- }- onZoomCustomScaleChange={handleZoomCustomScaleChange}- onZoomCustomScaleCommit={handleZoomCustomScaleCommit}- onZoomPreviewStart={() => setIsPreviewingZoom(true)}- onZoomPreviewEnd={() => setIsPreviewingZoom(false)}- selectedZoomFocusMode={- selectedZoomId- ? (zoomRegions.find((z) => z.id === selectedZoomId)?.focusMode ?? "manual")- : null- }- onZoomFocusModeChange={(mode) =>- selectedZoomId && handleZoomFocusModeChange(mode)- }- focusModeLocked={autoFocusAll}- selectedZoomFocus={- selectedZoomId- ? (zoomRegions.find((z) => z.id === selectedZoomId)?.focus ?? null)- : null- }- onZoomFocusCoordinateChange={(focus) =>- selectedZoomId && handleZoomFocusChange(selectedZoomId, focus)- }- onZoomFocusCoordinateCommit={commitState}- hasCursorTelemetry={cursorTelemetry.length > 0}- selectedZoomId={selectedZoomId}- onZoomDelete={handleZoomDelete}- selectedZoomRotationPreset={- selectedZoomId- ? (zoomRegions.find((z) => z.id === selectedZoomId)?.rotationPreset ?? null)- : null- }- onZoomRotationPresetChange={handleZoomRotationPresetChange}- selectedTrimId={selectedTrimId}- onTrimDelete={handleTrimDelete}- shadowIntensity={shadowIntensity}- onShadowChange={(v) => updateState({ shadowIntensity: v })}- onShadowCommit={commitState}- showBlur={showBlur}- onBlurChange={(v) => pushState({ showBlur: v })}- showTrimWaveform={showTrimWaveform}- onTrimWaveformChange={(v) => pushState({ showTrimWaveform: v })}- motionBlurAmount={motionBlurAmount}- onMotionBlurChange={(v) => updateState({ motionBlurAmount: v })}- onMotionBlurCommit={commitState}- borderRadius={borderRadius}- onBorderRadiusChange={(v) => updateState({ borderRadius: v })}- onBorderRadiusCommit={commitState}- padding={padding}- onPaddingChange={(v) => updateState({ padding: v })}- onPaddingCommit={commitState}- cropRegion={cropRegion}- onCropChange={(r) => pushState({ cropRegion: r })}- aspectRatio={aspectRatio}- hasWebcam={Boolean(webcamVideoPath)}- webcamLayoutPreset={webcamLayoutPreset}- onWebcamLayoutPresetChange={(preset) =>- pushState({- webcamLayoutPreset: preset,- webcamPosition: preset === "picture-in-picture" ? webcamPosition : null,- })- }- webcamMaskShape={webcamMaskShape}- onWebcamMaskShapeChange={(shape) => pushState({ webcamMaskShape: shape })}- webcamMirrored={webcamMirrored}- webcamReactiveZoom={webcamReactiveZoom}- onWebcamMirroredChange={(mirrored) => pushState({ webcamMirrored: mirrored })}- onWebcamReactiveZoomChange={(reactive) =>- pushState({ webcamReactiveZoom: reactive })- }- webcamSizePreset={webcamSizePreset}- onWebcamSizePresetChange={(v) => updateState({ webcamSizePreset: v })}- onWebcamSizePresetCommit={commitState}- videoElement={videoPlaybackRef.current?.video || null}- exportQuality={exportQuality}- onExportQualityChange={setExportQuality}- exportFormat={exportFormat}- onExportFormatChange={setExportFormat}- gifFrameRate={gifFrameRate}- onGifFrameRateChange={setGifFrameRate}- gifLoop={gifLoop}- onGifLoopChange={setGifLoop}- gifSizePreset={gifSizePreset}- onGifSizePresetChange={setGifSizePreset}- gifOutputDimensions={calculateOutputDimensions(- calculateEffectiveSourceDimensions(- videoPlaybackRef.current?.video?.videoWidth ||- DEFAULT_SOURCE_DIMENSIONS.width,- videoPlaybackRef.current?.video?.videoHeight ||- DEFAULT_SOURCE_DIMENSIONS.height,- cropRegion,- ).width,- calculateEffectiveSourceDimensions(- videoPlaybackRef.current?.video?.videoWidth ||- DEFAULT_SOURCE_DIMENSIONS.width,- videoPlaybackRef.current?.video?.videoHeight ||- DEFAULT_SOURCE_DIMENSIONS.height,- cropRegion,- ).height,- gifSizePreset,- GIF_SIZE_PRESETS,- aspectRatio === "native"- ? getNativeAspectRatioValue(- videoPlaybackRef.current?.video?.videoWidth ||- DEFAULT_SOURCE_DIMENSIONS.width,- videoPlaybackRef.current?.video?.videoHeight ||- DEFAULT_SOURCE_DIMENSIONS.height,- cropRegion,- )- : getAspectRatioValue(aspectRatio),- )}- onExport={handleOpenExportDialog}- onExportPanelOpen={() => {- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- }}- selectedAnnotationId={selectedAnnotationId}- annotationRegions={annotationOnlyRegions}- onAnnotationContentChange={handleAnnotationContentChange}- onAnnotationTypeChange={handleAnnotationTypeChange}- onAnnotationStyleChange={handleAnnotationStyleChange}- onAnnotationFigureDataChange={handleAnnotationFigureDataChange}- onAnnotationDuplicate={handleAnnotationDuplicate}- onAnnotationDelete={handleAnnotationDelete}- selectedBlurId={selectedBlurId}- blurRegions={blurRegions}- onBlurDataChange={handleBlurDataPanelChange}- onBlurDataCommit={commitState}- onBlurDelete={handleAnnotationDelete}- selectedSpeedId={selectedSpeedId}- selectedSpeedValue={- selectedSpeedId- ? (speedRegions.find((r) => r.id === selectedSpeedId)?.speed ?? null)- : null- }- onSpeedChange={handleSpeedChange}- onSpeedDelete={handleSpeedDelete}- unsavedExport={unsavedExport}- onSaveUnsavedExport={handleSaveUnsavedExport}- onSaveDiagnostic={handleSaveDiagnostic}- showCursor={showCursor}- onShowCursorChange={setShowCursor}- cursorSize={cursorSize}- onCursorSizeChange={setCursorSize}- cursorSmoothing={cursorSmoothing}- onCursorSmoothingChange={setCursorSmoothing}- cursorMotionBlur={cursorMotionBlur}- onCursorMotionBlurChange={setCursorMotionBlur}- cursorClickBounce={cursorClickBounce}- onCursorClickBounceChange={setCursorClickBounce}- cursorClipToBounds={cursorClipToBounds}- onCursorClipToBoundsChange={setCursorClipToBounds}- cursorTheme={cursorTheme}- onCursorThemeChange={setCursorTheme}- hasCursorData={- cursorTelemetry.length > 0 ||- hasNativeCursorRecordingData(cursorRecordingData)- }- showCursorSettings={showCursorSettings}- />- </div>- </div>- </Panel>-- <PanelResizeHandle className="editor-resize-handle group">- <div className="w-10 h-1 bg-white/20 rounded-full transition-colors group-hover:bg-[#34B27B]/70"></div>- </PanelResizeHandle>-- {/* Full-width timeline */}- <Panel defaultSize={33} maxSize={54} minSize={24} className="min-h-[210px]">- <div className="editor-timeline-panel h-full overflow-hidden flex flex-col">- <TimelineEditor- videoDuration={duration}- currentTime={currentTime}- getPlaybackTimeMs={getPlaybackTimeMs}- onSeek={handleSeek}- zoomRegions={zoomRegions}- onZoomAdded={handleZoomAdded}- autoZoomEnabled={autoZoomEnabled}- onToggleAutoZoom={handleToggleAutoZoom}- autoFocusAll={autoFocusAll}- onToggleAutoFocusAll={handleToggleAutoFocusAll}- onZoomSpanChange={handleZoomSpanChange}- onZoomDelete={handleZoomDelete}- selectedZoomId={selectedZoomId}- onSelectZoom={handleSelectZoom}- cameraFullscreenRegions={cameraFullscreenRegions}- onCameraFullscreenAdded={handleCameraFullscreenAdded}- onCameraFullscreenSpanChange={handleCameraFullscreenSpanChange}- onCameraFullscreenDelete={handleCameraFullscreenDelete}- selectedCameraFullscreenId={selectedCameraFullscreenId}- onSelectCameraFullscreen={handleSelectCameraFullscreen}- trimRegions={trimRegions}- onTrimAdded={handleTrimAdded}- onTrimSpanChange={handleTrimSpanChange}- onTrimDelete={handleTrimDelete}- selectedTrimId={selectedTrimId}- onSelectTrim={handleSelectTrim}- speedRegions={speedRegions}- onSpeedAdded={handleSpeedAdded}- onSpeedSpanChange={handleSpeedSpanChange}- onSpeedDelete={handleSpeedDelete}- selectedSpeedId={selectedSpeedId}- onSelectSpeed={handleSelectSpeed}- annotationRegions={annotationOnlyRegions}- onAnnotationAdded={handleAnnotationAdded}- onAnnotationSpanChange={handleAnnotationSpanChange}- onAnnotationDelete={handleAnnotationDelete}- selectedAnnotationId={selectedAnnotationId}- onSelectAnnotation={handleSelectAnnotation}- blurRegions={blurRegions}- onBlurAdded={handleBlurAdded}- onBlurSpanChange={handleAnnotationSpanChange}- onBlurDelete={handleAnnotationDelete}- selectedBlurId={selectedBlurId}- onSelectBlur={handleSelectBlur}- aspectRatio={aspectRatio}- onAspectRatioChange={(ar) =>- pushState({- aspectRatio: ar,- webcamLayoutPreset:- (isPortraitAspectRatio(ar) && webcamLayoutPreset === "dual-frame") ||- (!isPortraitAspectRatio(ar) && webcamLayoutPreset === "vertical-stack")- ? "picture-in-picture"- : webcamLayoutPreset,- })- }- videoUrl={videoPath ?? undefined}- showTrimWaveform={showTrimWaveform}- captionsLabel={t("autoCaptions.button")}- isGeneratingCaptions={isAutoCaptioning}- onGenerateCaptions={() => {- if (!videoPath) {- toast.error(t("errors.noVideoLoaded"));- return;- }- if (isAutoCaptioningRef.current) {- toast.error(t("autoCaptions.busy"));- return;- }- setShowAutoCaptionsDialog(true);- }}- />- </div>- </Panel>- </PanelGroup>- </div>- )}-- <ExportDialog- isOpen={showExportDialog}- onClose={() => setShowExportDialog(false)}- progress={exportProgress}- isExporting={isExporting}- error={exportError}- onCancel={handleCancelExport}- exportFormat={exportFormat}- exportedFilePath={exportedFilePath || undefined}- onShowInFolder={- exportedFilePath ? () => void handleShowExportedFile(exportedFilePath) : undefined- }- />-- <UnsavedChangesDialog- isOpen={showCloseConfirmDialog}- onSaveAndClose={handleCloseConfirmSave}- onDiscardAndClose={handleCloseConfirmDiscard}- onCancel={handleCloseConfirmCancel}- />-- <UnsavedChangesDialog- isOpen={confirmDialogVariant !== null}- variant={confirmDialogVariant ?? "newProject"}- onSaveAndClose={- confirmDialogVariant === "loadProject"- ? handleLoadProjectConfirmSave- : handleNewProjectConfirmSave- }- onDiscardAndClose={- confirmDialogVariant === "loadProject"- ? handleLoadProjectConfirmDiscard- : handleNewProjectConfirmDiscard- }- onCancel={() => setConfirmDialogVariant(null)}- />- </div>- );-}diff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsxdeleted file mode 100644index f1da1295c..000000000--- a/src/components/video-editor/VideoPlayback.tsx+++ /dev/null@@ -1,2333 +0,0 @@-import {- Application,- BlurFilter,- Container,- Graphics,- Sprite,- Texture,- VideoSource,-} from "pixi.js";-import { MotionBlurFilter } from "pixi-filters/motion-blur";-import type React from "react";-import {- forwardRef,- useCallback,- useEffect,- useImperativeHandle,- useMemo,- useRef,- useState,-} from "react";-import {- computeCameraFullscreenTargetRect,- getWebcamLayoutCssBoxShadow,- lerpRect,- reactiveWebcamScale,- type Size,- type StyledRenderRect,- type WebcamLayoutPreset,- type WebcamSizePreset,-} from "@/lib/compositeLayout";-import { getSmoothedCursorPath } from "@/lib/cursor/cursorPathSmoothing";-import {- createNativeCursorMotionBlurState,- getNativeCursorClickBounceProgress,- getNativeCursorClickBounceScale,- getNativeCursorMotionBlurPx,- hasNativeCursorRecordingData,- projectNativeCursorToLocal,- projectNativeCursorToStage,- resetNativeCursorMotionBlurState,- resolveInterpolatedNativeCursorFrame,- resolveNativeCursorRenderAsset,-} from "@/lib/cursor/nativeCursor";-import { classifyWallpaper, DEFAULT_WALLPAPER, resolveImageWallpaperUrl } from "@/lib/wallpaper";-import { getCssClipPath } from "@/lib/webcamMaskShapes";-import type { CursorRecordingData } from "@/native/contracts";-import {- type AspectRatio,- formatAspectRatioForCSS,- getNativeAspectRatioValue,-} from "@/utils/aspectRatioUtils";-import { AnnotationOverlay } from "./AnnotationOverlay";-import {- DEFAULT_CURSOR_SETTINGS,- DEFAULT_EDITOR_LAYOUT_SETTINGS,- DEFAULT_SOURCE_DIMENSIONS,-} from "./editorDefaults";-import {- type AnnotationRegion,- type BlurData,- type CameraFullscreenRegion,- type CursorTelemetryPoint,- computeRotation3DContainScale,- DEFAULT_CROP_REGION,- DEFAULT_ROTATION_3D,- getZoomScale,- isRotation3DIdentity,- lerpRotation3D,- MAX_NATIVE_PLAYBACK_RATE,- rotation3DPerspective,- type SpeedRegion,- type TrimRegion,- type ZoomFocus,- type ZoomRegion,-} from "./types";-import { computeCameraFullscreenProgress } from "./videoPlayback/cameraFullscreenUtils";-import { AUTO_FOLLOW_PARAMS, DEFAULT_FOCUS } from "./videoPlayback/constants";-import { advanceFollowFocus } from "./videoPlayback/cursorFollowUtils";-import {- DEFAULT_CURSOR_CONFIG,- PixiCursorOverlay,- preloadCursorAssets,-} from "./videoPlayback/cursorRenderer";-import { clampFocusToScale } from "./videoPlayback/focusUtils";-import { layoutVideoContent as layoutVideoContentUtil } from "./videoPlayback/layoutUtils";-import { clamp01 } from "./videoPlayback/mathUtils";-import { updateOverlayIndicator } from "./videoPlayback/overlayUtils";-import { createVideoEventHandlers } from "./videoPlayback/videoEventHandlers";-import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";-import { createZoomSpringState, resetZoomSpring, stepZoomSpring } from "./videoPlayback/zoomSpring";-import {- applyZoomTransform,- computeFocusFromTransform,- computeZoomTransform,- createMotionBlurState,- type MotionBlurState,-} from "./videoPlayback/zoomTransform";--interface VideoPlaybackProps {- videoPath: string;- webcamVideoPath?: string;- webcamLayoutPreset: WebcamLayoutPreset;- webcamMaskShape?: import("./types").WebcamMaskShape;- webcamMirrored?: boolean;- webcamReactiveZoom?: boolean;- webcamSizePreset?: WebcamSizePreset;- webcamPosition?: { cx: number; cy: number } | null;- onWebcamPositionChange?: (position: { cx: number; cy: number }) => void;- onWebcamPositionDragEnd?: () => void;- onDurationChange: (duration: number) => void;- onTimeUpdate: (time: number) => void;- currentTime: number;- onPlayStateChange: (playing: boolean) => void;- onError: (error: string) => void;- wallpaper?: string;- zoomRegions: ZoomRegion[];- cameraFullscreenRegions?: CameraFullscreenRegion[];- selectedZoomId: string | null;- onSelectZoom: (id: string | null) => void;- onZoomFocusChange: (id: string, focus: ZoomFocus) => void;- onZoomFocusDragEnd?: () => void;- isPlaying: boolean;- showShadow?: boolean;- shadowIntensity?: number;- showBlur?: boolean;- motionBlurAmount?: number;- borderRadius?: number;- padding?: number;- cropRegion?: import("./types").CropRegion;- trimRegions?: TrimRegion[];- speedRegions?: SpeedRegion[];- aspectRatio: AspectRatio;- cursorRecordingData?: CursorRecordingData | null;- annotationRegions?: AnnotationRegion[];- selectedAnnotationId?: string | null;- onSelectAnnotation?: (id: string | null) => void;- onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;- onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;- blurRegions?: AnnotationRegion[];- selectedBlurId?: string | null;- onSelectBlur?: (id: string | null) => void;- onBlurPositionChange?: (id: string, position: { x: number; y: number }) => void;- onBlurSizeChange?: (id: string, size: { width: number; height: number }) => void;- onBlurDataChange?: (id: string, blurData: BlurData) => void;- onBlurDataCommit?: () => void;- cursorTelemetry?: CursorTelemetryPoint[];- cursorClickTimestamps?: number[];- showCursor?: boolean;- cursorSize?: number;- cursorSmoothing?: number;- cursorMotionBlur?: number;- cursorClickBounce?: number;- cursorClipToBounds?: boolean;- cursorTheme?: string;- // Render the selected zoom at the playhead even while paused, so the editor can- // preview the effect without leaving the focus-edit view.- isPreviewingZoom?: boolean;-}--export interface VideoPlaybackRef {- video: HTMLVideoElement | null;- app: Application | null;- videoSprite: Sprite | null;- videoContainer: Container | null;- containerRef: React.RefObject<HTMLDivElement>;- play: () => Promise<void>;- pause: () => void;- /**- * Clears the memoized last-resolved-duration guard so the next metadata load- * re-syncs `duration` even if the video's real (resolved) duration happens to- * match a value already seen — needed when a caller (e.g. loading a saved- * project) sets `duration` to something else in between, which the guard has- * no other way to detect.- */- resetDurationResolution: () => void;-}--function getResolvedVideoDuration(video: HTMLVideoElement): number | null {- if (Number.isFinite(video.duration) && video.duration > 0) {- return video.duration;- }-- if (video.seekable.length > 0) {- const lastRangeIndex = video.seekable.length - 1;- const seekableEnd = video.seekable.end(lastRangeIndex);- if (Number.isFinite(seekableEnd) && seekableEnd > 0) {- return seekableEnd;- }- }-- return null;-}--function getEndedVideoDuration(video: HTMLVideoElement): number | null {- const currentTime = video.currentTime;- if (!Number.isFinite(currentTime) || currentTime <= 0) {- return null;- }-- if (video.ended) {- return currentTime;- }-- const resolvedDuration = getResolvedVideoDuration(video);- const durationEpsilonSeconds = 0.05;- if (resolvedDuration && currentTime >= resolvedDuration - durationEpsilonSeconds) {- return resolvedDuration;- }-- return null;-}--type AudioTrackListLike = {- length: number;- [index: number]: { enabled: boolean };-};--type VideoElementWithAudioTracks = HTMLVideoElement & {- audioTracks?: AudioTrackListLike;-};--function enableAllPreviewAudioTracks(video: HTMLVideoElement) {- const audioTracks = (video as VideoElementWithAudioTracks).audioTracks;- if (!audioTracks || audioTracks.length <= 1) {- return;- }-- for (let index = 0; index < audioTracks.length; index += 1) {- audioTracks[index].enabled = true;- }-}--/**- * Builds a `webglcontextlost` handler for the preview Pixi canvas.- *- * On Linux/Wayland the preview can lose its WebGL context during heavy GPU- * usage from the exporter (e.g. the VideoEncoder's hardware path on- * Mesa/EGL, or the Linux-specific CPU readback in `frameRenderer.ts`).- * Without recovery the video sprite never reappears — only the wallpaper- * (rendered to a 2D canvas) stays visible. See issue #8.- *- * `preventDefault()` opts in to the restoration attempt so Chromium can- * fire `webglcontextrestored`. The caller is expected to bump `regenerate`- * so React tears the broken app down and rebuilds from scratch on the- * next mount.- */-export function createWebGLContextLostHandler(params: {- generation: number;- regenerate: () => void;-}): (event: Event) => void {- return (event: Event) => {- event.preventDefault();- console.warn("[VideoPlayback] WebGL context lost, recreating Pixi app", {- generation: params.generation,- });- params.regenerate();- };-}--const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(- (- {- videoPath,- webcamVideoPath,- webcamLayoutPreset,- webcamMaskShape,- webcamMirrored = false,- webcamReactiveZoom = false,- webcamSizePreset,- webcamPosition,- onWebcamPositionChange,- onWebcamPositionDragEnd,- onDurationChange,- onTimeUpdate,- currentTime,- onPlayStateChange,- onError,- wallpaper,- zoomRegions,- cameraFullscreenRegions = [],- selectedZoomId,- onSelectZoom,- onZoomFocusChange,- onZoomFocusDragEnd,- isPlaying,- showShadow,- shadowIntensity = 0,- showBlur,- motionBlurAmount = 0,- borderRadius = 0,- padding = DEFAULT_EDITOR_LAYOUT_SETTINGS.padding,- cropRegion,- trimRegions = [],- speedRegions = [],- aspectRatio,- cursorRecordingData,- annotationRegions = [],- selectedAnnotationId,- onSelectAnnotation,- onAnnotationPositionChange,- onAnnotationSizeChange,- blurRegions = [],- selectedBlurId,- onSelectBlur,- onBlurPositionChange,- onBlurSizeChange,- onBlurDataChange,- onBlurDataCommit,- cursorTelemetry = [],- cursorClickTimestamps = [],- showCursor = false,- cursorSize = DEFAULT_CURSOR_SETTINGS.size,- cursorSmoothing = DEFAULT_CURSOR_SETTINGS.smoothing,- cursorMotionBlur = DEFAULT_CURSOR_SETTINGS.motionBlur,- cursorClickBounce = DEFAULT_CURSOR_SETTINGS.clickBounce,- cursorClipToBounds = DEFAULT_CURSOR_SETTINGS.clipToBounds,- cursorTheme = DEFAULT_CURSOR_SETTINGS.theme,- isPreviewingZoom = false,- },- ref,- ) => {- const videoRef = useRef<HTMLVideoElement | null>(null);- const supplementalAudioRef = useRef<HTMLAudioElement | null>(null);- const webcamVideoRef = useRef<HTMLVideoElement | null>(null);- const webcamWrapperRef = useRef<HTMLDivElement | null>(null);- const webcamReactiveZoomRef = useRef(webcamReactiveZoom);- const webcamLayoutPresetRef = useRef(webcamLayoutPreset);- const webcamPositionRef = useRef(webcamPosition);- const containerRef = useRef<HTMLDivElement | null>(null);- const appRef = useRef<Application | null>(null);- const videoSpriteRef = useRef<Sprite | null>(null);- const videoContainerRef = useRef<Container | null>(null);- const cameraContainerRef = useRef<Container | null>(null);- const timeUpdateAnimationRef = useRef<number | null>(null);- const [pixiReady, setPixiReady] = useState(false);- const [pixiGeneration, setPixiGeneration] = useState(0);- const [videoReady, setVideoReady] = useState(false);- const [supplementalAudioPath, setSupplementalAudioPath] = useState<string | null>(null);- const [overlaySize, setOverlaySize] = useState({ width: 800, height: 600 });- const [overlayElement, setOverlayElement] = useState<HTMLDivElement | null>(null);- const overlayRef = useRef<HTMLDivElement | null>(null);-- const focusIndicatorRef = useRef<HTMLDivElement | null>(null);- const composite3DRef = useRef<HTMLDivElement | null>(null);- const outerWrapperRef = useRef<HTMLDivElement | null>(null);- const [webcamLayout, setWebcamLayout] = useState<StyledRenderRect | null>(null);- const webcamLayoutRef = useRef<StyledRenderRect | null>(null);- const [webcamDimensions, setWebcamDimensions] = useState<Size | null>(null);- const currentTimeRef = useRef(0);- const zoomRegionsRef = useRef<ZoomRegion[]>([]);- const cameraFullscreenRegionsRef = useRef<CameraFullscreenRegion[]>([]);- const cursorTelemetryRef = useRef<CursorTelemetryPoint[]>([]);- const cursorClickTimestampsRef = useRef<number[]>([]);- const selectedZoomIdRef = useRef<string | null>(null);- const animationStateRef = useRef({- scale: 1,- focusX: DEFAULT_FOCUS.cx,- focusY: DEFAULT_FOCUS.cy,- progress: 0,- x: 0,- y: 0,- appliedScale: 1,- });- // Spring that chases the eased zoom target so the camera glides instead of jerking.- const zoomSpringRef = useRef(createZoomSpringState());- const prevZoomTimeMsRef = useRef<number | null>(null);- const blurFilterRef = useRef<BlurFilter | null>(null);- const motionBlurFilterRef = useRef<MotionBlurFilter | null>(null);- const isDraggingFocusRef = useRef(false);- const isDraggingWebcamRef = useRef(false);- const webcamDragOffsetRef = useRef({ dx: 0, dy: 0 });- const stageSizeRef = useRef({ width: 0, height: 0 });- const videoSizeRef = useRef({ width: 0, height: 0 });- const baseScaleRef = useRef(1);- const baseOffsetRef = useRef({ x: 0, y: 0 });- const baseMaskRef = useRef({ x: 0, y: 0, width: 0, height: 0 });- const cropBoundsRef = useRef({ startX: 0, endX: 0, startY: 0, endY: 0 });- const maskGraphicsRef = useRef<Graphics | null>(null);- const isPlayingRef = useRef(isPlaying);- const isSeekingRef = useRef(false);- const isScrubbingRef = useRef(false);- const scrubEndTimerRef = useRef<number | null>(null);- const [isScrubbing, setIsScrubbing] = useState(false);- const allowPlaybackRef = useRef(false);- // Seek-stepping state for speed regions above the native playbackRate cap (16×).- const seekSteppingRef = useRef(false);- const stepVirtualSecRef = useRef(0);- const stepLastTsRef = useRef(0);- const stepPrevMutedRef = useRef(false);- const lockedVideoDimensionsRef = useRef<{- width: number;- height: number;- } | null>(null);- const layoutVideoContentRef = useRef<(() => void) | null>(null);- const trimRegionsRef = useRef<TrimRegion[]>([]);- const speedRegionsRef = useRef<SpeedRegion[]>([]);- const motionBlurAmountRef = useRef(motionBlurAmount);- const cursorOverlayRef = useRef<PixiCursorOverlay | null>(null);- const showCursorRef = useRef(showCursor);- const cursorSizeRef = useRef(cursorSize);- const cursorSmoothingRef = useRef(cursorSmoothing);- const cursorMotionBlurRef = useRef(cursorMotionBlur);- const cursorClickBounceRef = useRef(cursorClickBounce);- const cursorClipToBoundsRef = useRef(cursorClipToBounds);- const cursorThemeRef = useRef(cursorTheme);- const isPreviewingZoomRef = useRef(isPreviewingZoom);- const motionBlurStateRef = useRef<MotionBlurState>(createMotionBlurState());- const onTimeUpdateRef = useRef(onTimeUpdate);- const onPlayStateChangeRef = useRef(onPlayStateChange);- const videoReadyRafRef = useRef<number | null>(null);- const smoothedAutoFocusRef = useRef<ZoomFocus | null>(null);- const prevTargetProgressRef = useRef(0);- const durationResolutionTimeoutRef = useRef<number | null>(null);- const lastResolvedDurationRef = useRef<number | null>(null);- const isResolvingDurationRef = useRef(false);- const hasNativeCursorRecordingRef = useRef(false);- const cursorRecordingDataRef = useRef(cursorRecordingData);- const cropRegionRef = useRef(cropRegion);- const nativeCursorSpriteRef = useRef<Sprite | null>(null);- const nativeCursorTextureIdRef = useRef<string | null>(null);- const nativeCursorImageRef = useRef<HTMLImageElement | null>(null);- const nativeCursorImageIdRef = useRef<string | null>(null);- const nativeCursorMotionBlurStateRef = useRef(createNativeCursorMotionBlurState());- const nativeCursorClipRef = useRef<HTMLDivElement | null>(null);- const borderRadiusRef = useRef<number>(0);-- const hasNativeCursorRecording = useMemo(- () => hasNativeCursorRecordingData(cursorRecordingData),- [cursorRecordingData],- );-- const syncResolvedDuration = useCallback(- (video: HTMLVideoElement) => {- const resolvedDuration = getResolvedVideoDuration(video);- if (!resolvedDuration) {- return false;- }-- const normalizedDuration = Math.round(resolvedDuration * 1000) / 1000;- if (lastResolvedDurationRef.current !== normalizedDuration) {- lastResolvedDurationRef.current = normalizedDuration;- onDurationChange(normalizedDuration);- }-- return true;- },- [onDurationChange],- );-- const forceResolveDuration = useCallback(- (video: HTMLVideoElement) => {- if (isResolvingDurationRef.current) {- return;- }-- if (video.readyState < HTMLMediaElement.HAVE_METADATA) {- return;- }-- isResolvingDurationRef.current = true;- const previousMuted = video.muted;-- const finalize = () => {- video.removeEventListener("durationchange", handleProgress);- video.removeEventListener("timeupdate", handleProgress);- video.removeEventListener("loadeddata", handleProgress);- video.removeEventListener("ended", handleProgress);- if (durationResolutionTimeoutRef.current) {- clearTimeout(durationResolutionTimeoutRef.current);- durationResolutionTimeoutRef.current = null;- }- video.muted = previousMuted;- isResolvingDurationRef.current = false;- };-- const resolveCurrentDuration = () => {- if (syncResolvedDuration(video)) {- return true;- }-- const endedDuration = getEndedVideoDuration(video);- if (endedDuration) {- lastResolvedDurationRef.current = null;- onDurationChange(Math.round(endedDuration * 1000) / 1000);- return true;- }-- return false;- };-- const handleProgress = () => {- if (!resolveCurrentDuration()) {- return;- }-- try {- video.pause();- video.currentTime = 0;- } catch {- // no-op- }- currentTimeRef.current = 0;- finalize();- };-- video.addEventListener("durationchange", handleProgress);- video.addEventListener("timeupdate", handleProgress);- video.addEventListener("loadeddata", handleProgress);- video.addEventListener("ended", handleProgress);- durationResolutionTimeoutRef.current = window.setTimeout(() => {- handleProgress();- finalize();- }, 1500);- video.muted = true;-- const playAttempt = video.play();- if (playAttempt && typeof playAttempt.catch === "function") {- playAttempt.catch(() => {- try {- video.currentTime = Math.max(video.currentTime, 0.1);- } catch {- finalize();- }- });- }-- try {- video.currentTime = Math.max(video.currentTime, 0.1);- } catch {- finalize();- }- },- [onDurationChange, syncResolvedDuration],- );-- // Clamp against getZoomScale(region), not region.depth: depth is just the preset- // slot (1x/2x/4x) and ignores customScale, which gives wrong drag bounds near the edges.- const clampFocusForRegion = useCallback((focus: ZoomFocus, region: ZoomRegion) => {- return clampFocusToScale(focus, getZoomScale(region));- }, []);-- const updateOverlayForRegion = useCallback(- (region: ZoomRegion | null, focusOverride?: ZoomFocus) => {- const overlayEl = overlayRef.current;- const indicatorEl = focusIndicatorRef.current;-- if (!overlayEl || !indicatorEl) {- return;- }-- const stageWidth = overlayEl.clientWidth;- const stageHeight = overlayEl.clientHeight;- if (stageWidth && stageHeight) {- stageSizeRef.current = { width: stageWidth, height: stageHeight };- }-- updateOverlayIndicator({- overlayEl,- indicatorEl,- region,- focusOverride,- videoSize: videoSizeRef.current,- baseScale: baseScaleRef.current,- isPlaying: isPlayingRef.current,- });- },- [],- );-- const layoutVideoContent = useCallback(() => {- const container = containerRef.current;- const app = appRef.current;- const videoSprite = videoSpriteRef.current;- const maskGraphics = maskGraphicsRef.current;- const videoElement = videoRef.current;- const cameraContainer = cameraContainerRef.current;-- if (- !container ||- !app ||- !videoSprite ||- !maskGraphics ||- !videoElement ||- !cameraContainer- ) {- return;- }-- // Lock video dimensions on first layout to prevent resize issues- if (- !lockedVideoDimensionsRef.current &&- videoElement.videoWidth > 0 &&- videoElement.videoHeight > 0- ) {- lockedVideoDimensionsRef.current = {- width: videoElement.videoWidth,- height: videoElement.videoHeight,- };- }-- const result = layoutVideoContentUtil({- container,- app,- videoSprite,- maskGraphics,- videoElement,- cropRegion,- lockedVideoDimensions: lockedVideoDimensionsRef.current,- borderRadius,- padding,- webcamDimensions,- webcamLayoutPreset,- webcamSizePreset,- webcamPosition,- webcamMaskShape,- });-- if (result) {- stageSizeRef.current = result.stageSize;- videoSizeRef.current = result.videoSize;- baseScaleRef.current = result.baseScale;- baseOffsetRef.current = result.baseOffset;- baseMaskRef.current = result.maskRect;- borderRadiusRef.current = result.maskBorderRadius;- cropBoundsRef.current = result.cropBounds;- webcamLayoutRef.current = result.webcamRect;- setWebcamLayout(result.webcamRect);-- // Reset camera container to identity- cameraContainer.scale.set(1);- cameraContainer.position.set(0, 0);-- const selectedId = selectedZoomIdRef.current;- const activeRegion = selectedId- ? (zoomRegionsRef.current.find((region) => region.id === selectedId) ?? null)- : null;-- updateOverlayForRegion(activeRegion);- }- }, [- updateOverlayForRegion,- cropRegion,- borderRadius,- padding,- webcamDimensions,- webcamLayoutPreset,- webcamSizePreset,- webcamPosition,- webcamMaskShape,- ]);-- useEffect(() => {- layoutVideoContentRef.current = layoutVideoContent;- }, [layoutVideoContent]);-- const setOverlayRefs = useCallback((node: HTMLDivElement | null) => {- overlayRef.current = node;- setOverlayElement(node);- }, []);-- const selectedZoom = useMemo(() => {- if (!selectedZoomId) return null;- return zoomRegions.find((region) => region.id === selectedZoomId) ?? null;- }, [zoomRegions, selectedZoomId]);-- useImperativeHandle(ref, () => ({- video: videoRef.current,- app: appRef.current,- videoSprite: videoSpriteRef.current,- videoContainer: videoContainerRef.current,- containerRef,- play: async () => {- const vid = videoRef.current;- if (!vid) return;- try {- allowPlaybackRef.current = true;- enableAllPreviewAudioTracks(vid);- await vid.play().catch((err) => {- console.log("PLAY ERROR:", err);- throw err;- });- const supplementalAudio = supplementalAudioRef.current;- if (supplementalAudio) {- supplementalAudio.currentTime = vid.currentTime;- // vid.playbackRate is already capped at the native ceiling; clamp- // defensively so the supplemental track never throws either.- supplementalAudio.playbackRate = Math.min(vid.playbackRate, MAX_NATIVE_PLAYBACK_RATE);- await supplementalAudio.play().catch(() => {- // The main video remains the source of truth for playback state.- });- }- } catch (error) {- allowPlaybackRef.current = false;- throw error;- }- },- pause: () => {- const video = videoRef.current;- allowPlaybackRef.current = false;- if (!video) {- return;- }- video.pause();- supplementalAudioRef.current?.pause();- },- resetDurationResolution: () => {- lastResolvedDurationRef.current = null;- // If the video element is already loaded (e.g. reloading a project that- // references the same file, so its src never actually changes and- // `loadedmetadata` won't fire again), clearing the guard alone leaves- // nothing to trigger a re-sync. Resolve immediately in that case too.- const video = videoRef.current;- if (video && video.readyState >= HTMLMediaElement.HAVE_METADATA) {- if (!syncResolvedDuration(video)) {- forceResolveDuration(video);- }- }- },- }));-- const updateFocusFromClientPoint = (clientX: number, clientY: number) => {- const overlayEl = overlayRef.current;- if (!overlayEl) return;-- const regionId = selectedZoomIdRef.current;- if (!regionId) return;-- const region = zoomRegionsRef.current.find((r) => r.id === regionId);- if (!region) return;-- const rect = overlayEl.getBoundingClientRect();- const stageWidth = rect.width;- const stageHeight = rect.height;-- if (!stageWidth || !stageHeight) {- return;- }-- stageSizeRef.current = { width: stageWidth, height: stageHeight };-- const localX = clientX - rect.left;- const localY = clientY - rect.top;-- const unclampedFocus: ZoomFocus = {- cx: clamp01(localX / stageWidth),- cy: clamp01(localY / stageHeight),- };- const clampedFocus = clampFocusForRegion(unclampedFocus, region);-- onZoomFocusChange(region.id, clampedFocus);- updateOverlayForRegion({ ...region, focus: clampedFocus }, clampedFocus);- };-- const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {- if (isPlayingRef.current) return;- const regionId = selectedZoomIdRef.current;- if (!regionId) return;- const region = zoomRegionsRef.current.find((r) => r.id === regionId);- if (!region) return;- if (region.focusMode === "auto") return;- onSelectZoom(region.id);- event.preventDefault();- isDraggingFocusRef.current = true;- event.currentTarget.setPointerCapture(event.pointerId);- updateFocusFromClientPoint(event.clientX, event.clientY);- };-- const handleOverlayPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {- if (!isDraggingFocusRef.current) return;- event.preventDefault();- updateFocusFromClientPoint(event.clientX, event.clientY);- };-- const endFocusDrag = (event: React.PointerEvent<HTMLDivElement>) => {- if (!isDraggingFocusRef.current) return;- isDraggingFocusRef.current = false;- try {- event.currentTarget.releasePointerCapture(event.pointerId);- } catch {- // Pointer may already be released.- }- onZoomFocusDragEnd?.();- };-- const handleOverlayPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {- endFocusDrag(event);- };-- const handleOverlayPointerLeave = (event: React.PointerEvent<HTMLDivElement>) => {- endFocusDrag(event);- };-- // ── Webcam PiP drag handlers ──-- const handleWebcamPointerDown = (event: React.PointerEvent<HTMLVideoElement>) => {- if (isPlayingRef.current) return;- if (webcamLayoutPreset !== "picture-in-picture") return;- event.preventDefault();- event.stopPropagation();- isDraggingWebcamRef.current = true;- event.currentTarget.setPointerCapture(event.pointerId);-- const webcamEl = event.currentTarget;- const webcamRect = webcamEl.getBoundingClientRect();- webcamDragOffsetRef.current = {- dx: event.clientX - (webcamRect.left + webcamRect.width / 2),- dy: event.clientY - (webcamRect.top + webcamRect.height / 2),- };- };-- const handleWebcamPointerMove = (event: React.PointerEvent<HTMLVideoElement>) => {- if (!isDraggingWebcamRef.current) return;- event.preventDefault();- event.stopPropagation();-- const containerEl = containerRef.current;- if (!containerEl || !onWebcamPositionChange) return;-- const containerRect = containerEl.getBoundingClientRect();- const cx = clamp01(- (event.clientX - webcamDragOffsetRef.current.dx - containerRect.left) / containerRect.width,- );- const cy = clamp01(- (event.clientY - webcamDragOffsetRef.current.dy - containerRect.top) / containerRect.height,- );- onWebcamPositionChange({ cx, cy });- };-- const handleWebcamPointerUp = (event: React.PointerEvent<HTMLVideoElement>) => {- if (!isDraggingWebcamRef.current) return;- isDraggingWebcamRef.current = false;- try {- event.currentTarget.releasePointerCapture(event.pointerId);- } catch {- // Pointer may already be released.- }- onWebcamPositionDragEnd?.();- };-- useEffect(() => {- zoomRegionsRef.current = zoomRegions;- }, [zoomRegions]);-- useEffect(() => {- cameraFullscreenRegionsRef.current = cameraFullscreenRegions;- }, [cameraFullscreenRegions]);-- useEffect(() => {- cursorTelemetryRef.current = cursorTelemetry;- }, [cursorTelemetry]);-- useEffect(() => {- cursorClickTimestampsRef.current = cursorClickTimestamps;- }, [cursorClickTimestamps]);-- useEffect(() => {- selectedZoomIdRef.current = selectedZoomId;- }, [selectedZoomId]);-- useEffect(() => {- isPlayingRef.current = isPlaying;- }, [isPlaying]);-- useEffect(() => {- trimRegionsRef.current = trimRegions;- }, [trimRegions]);-- useEffect(() => {- speedRegionsRef.current = speedRegions;- }, [speedRegions]);-- useEffect(() => {- motionBlurAmountRef.current = motionBlurAmount;- }, [motionBlurAmount]);-- useEffect(() => {- cursorTelemetryRef.current = cursorTelemetry;- }, [cursorTelemetry]);-- useEffect(() => {- showCursorRef.current = showCursor;- }, [showCursor]);-- useEffect(() => {- hasNativeCursorRecordingRef.current = hasNativeCursorRecording;- }, [hasNativeCursorRecording]);-- useEffect(() => {- cursorRecordingDataRef.current = cursorRecordingData;- resetNativeCursorMotionBlurState(nativeCursorMotionBlurStateRef.current);- }, [cursorRecordingData]);-- useEffect(() => {- cropRegionRef.current = cropRegion;- }, [cropRegion]);-- useEffect(() => {- cursorSizeRef.current = cursorSize;- }, [cursorSize]);-- useEffect(() => {- cursorSmoothingRef.current = cursorSmoothing;- }, [cursorSmoothing]);-- useEffect(() => {- cursorMotionBlurRef.current = cursorMotionBlur;- }, [cursorMotionBlur]);-- useEffect(() => {- cursorClickBounceRef.current = cursorClickBounce;- }, [cursorClickBounce]);-- useEffect(() => {- cursorClipToBoundsRef.current = cursorClipToBounds;- }, [cursorClipToBounds]);-- useEffect(() => {- cursorThemeRef.current = cursorTheme;- }, [cursorTheme]);-- useEffect(() => {- webcamReactiveZoomRef.current = webcamReactiveZoom;- webcamLayoutPresetRef.current = webcamLayoutPreset;- webcamPositionRef.current = webcamPosition;- // Clear any reactive transform when the effect is turned off or layout changes,- // so a stale shrink doesn't linger while the ticker isn't updating it.- if (- webcamWrapperRef.current &&- (!webcamReactiveZoom || webcamLayoutPreset !== "picture-in-picture")- ) {- webcamWrapperRef.current.style.transform = "";- }- }, [webcamReactiveZoom, webcamLayoutPreset, webcamPosition]);-- useEffect(() => {- isPreviewingZoomRef.current = isPreviewingZoom;- }, [isPreviewingZoom]);-- // Sync cursor overlay config when settings change- useEffect(() => {- const overlay = cursorOverlayRef.current;- if (!overlay) return;- overlay.setDotRadius(DEFAULT_CURSOR_CONFIG.dotRadius * cursorSize);- overlay.setSmoothingFactor(cursorSmoothing);- overlay.setMotionBlur(cursorMotionBlur);- overlay.setClickBounce(cursorClickBounce);- overlay.reset();- }, [cursorSize, cursorSmoothing, cursorMotionBlur, cursorClickBounce]);-- useEffect(() => {- onTimeUpdateRef.current = onTimeUpdate;- }, [onTimeUpdate]);-- useEffect(() => {- onPlayStateChangeRef.current = onPlayStateChange;- }, [onPlayStateChange]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;- const el = overlayRef.current;- if (!el) return;-- // Seed immediately so overlays never start at 800×600- setOverlaySize({ width: el.clientWidth, height: el.clientHeight });-- const observer = new ResizeObserver((entries) => {- if (!entries[0]) return;- const { width, height } = entries[0].contentRect;- setOverlaySize((prev) => {- if (prev.width === width && prev.height === height) return prev;- return { width, height };- });- });-- observer.observe(el);- return () => observer.disconnect();- }, [pixiReady, videoReady]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;- const container = containerRef.current;- if (!container) return;-- if (typeof ResizeObserver === "undefined") {- return;- }-- const observer = new ResizeObserver(() => {- layoutVideoContent();- });-- observer.observe(container);- return () => {- observer.disconnect();- };- }, [pixiReady, videoReady, layoutVideoContent]);-- // Drop canvas resolution to 1.0 while scrubbing and restore native DPR on play/idle.- // Only on scrub-state transitions; mutating renderer.resolution per-frame thrashes- // texture uploads.- useEffect(() => {- if (!pixiReady) return;- const app = appRef.current;- const container = containerRef.current;- if (!app || !container) return;-- const targetResolution = isScrubbing ? 1 : window.devicePixelRatio || 1;- if (app.renderer.resolution === targetResolution) return;-- app.renderer.resolution = targetResolution;- app.renderer.resize(container.clientWidth, container.clientHeight);- layoutVideoContentRef.current?.();- }, [isScrubbing, pixiReady]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;- updateOverlayForRegion(selectedZoom);- }, [selectedZoom, pixiReady, videoReady, updateOverlayForRegion]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;- const overlayEl = overlayElement;- if (!overlayEl) return;- if (!selectedZoom) {- overlayEl.style.cursor = "default";- overlayEl.style.pointerEvents = "none";- return;- }- overlayEl.style.cursor = isPlaying ? "not-allowed" : "grab";- overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";- }, [selectedZoom, isPlaying, pixiReady, videoReady, overlayElement]);-- useEffect(() => {- const overlayEl = overlayElement;- if (!overlayEl) return;-- const updateOverlaySize = () => {- const width = overlayEl.clientWidth || 800;- const height = overlayEl.clientHeight || 600;- setOverlaySize((prev) => {- if (prev.width === width && prev.height === height) return prev;- return { width, height };- });- };-- updateOverlaySize();-- if (typeof ResizeObserver !== "undefined") {- const observer = new ResizeObserver(() => {- updateOverlaySize();- });- observer.observe(overlayEl);- return () => observer.disconnect();- }-- window.addEventListener("resize", updateOverlaySize);- return () => window.removeEventListener("resize", updateOverlaySize);- }, [overlayElement]);-- useEffect(() => {- const container = containerRef.current;- if (!container) return;-- let mounted = true;- let app: Application | null = null;- // Declared outside the async IIFE so the cleanup function can- // detach them after Pixi tears the canvas down.- let handleContextLost: ((event: Event) => void) | null = null;- let handleContextRestored: (() => void) | null = null;-- (async () => {- let cursorOverlayEnabled = true;- try {- await preloadCursorAssets();- } catch {- cursorOverlayEnabled = false;- }-- app = new Application();-- try {- await app.init({- width: container.clientWidth,- height: container.clientHeight,- backgroundAlpha: 0,- antialias: true,- resolution: window.devicePixelRatio || 1,- autoDensity: true,- });- } catch (error) {- console.error("[VideoPlayback] Pixi init failed:", error);- return;- }-- app.ticker.maxFPS = 60;-- if (!mounted) {- app.destroy(true, {- children: true,- texture: true,- textureSource: true,- });- return;- }-- appRef.current = app;- container.appendChild(app.canvas);-- // Recover from WebGL context loss. On Linux/Wayland the preview- // Pixi app can lose its context during heavy GPU usage from the- // exporter (e.g. the VideoEncoder's hardware path on Mesa/EGL).- // Without recovery the video sprite never reappears — only the- // wallpaper (rendered to a 2D canvas) stays visible. See issue- // #8. preventDefault() opts in to the restoration attempt so- // Chromium can fire webglcontextrestored, then we tear the- // broken app down and rebuild from scratch on the next mount.- handleContextLost = createWebGLContextLostHandler({- generation: pixiGeneration,- regenerate: () => setPixiGeneration((g) => g + 1),- });- handleContextRestored = () => {- console.info("[VideoPlayback] WebGL context restored", { generation: pixiGeneration });- };- app.canvas.addEventListener("webglcontextlost", handleContextLost);- app.canvas.addEventListener("webglcontextrestored", handleContextRestored);-- // Camera container - this will be scaled/positioned for zoom- const cameraContainer = new Container();- cameraContainerRef.current = cameraContainer;- app.stage.addChild(cameraContainer);-- // Video container - holds the masked video sprite- const videoContainer = new Container();- videoContainerRef.current = videoContainer;- cameraContainer.addChild(videoContainer);-- // Cursor overlay - rendered above the masked video- if (cursorOverlayEnabled) {- const cursorOverlay = new PixiCursorOverlay({- dotRadius: DEFAULT_CURSOR_CONFIG.dotRadius * cursorSizeRef.current,- smoothingFactor: cursorSmoothingRef.current,- motionBlur: cursorMotionBlurRef.current,- clickBounce: cursorClickBounceRef.current,- });- cursorOverlayRef.current = cursorOverlay;- }-- setPixiReady(true);- })();-- return () => {- mounted = false;- setPixiReady(false);- if (cursorOverlayRef.current) {- cursorOverlayRef.current.destroy();- cursorOverlayRef.current = null;- }- nativeCursorSpriteRef.current = null;- nativeCursorTextureIdRef.current = null;- nativeCursorImageIdRef.current = null;- if (app && app.renderer) {- // Detach the recovery listeners from the canvas before the- // app tears it down so we don't leak handlers on a detached- // element.- if (handleContextLost) {- app.canvas.removeEventListener("webglcontextlost", handleContextLost);- }- if (handleContextRestored) {- app.canvas.removeEventListener("webglcontextrestored", handleContextRestored);- }- app.destroy(true, {- children: true,- texture: true,- textureSource: true,- });- }- appRef.current = null;- cameraContainerRef.current = null;- videoContainerRef.current = null;- videoSpriteRef.current = null;- };- }, [pixiGeneration]);-- useEffect(() => {- if (!videoPath) {- lastResolvedDurationRef.current = null;- isResolvingDurationRef.current = false;- setVideoReady(false);- setSupplementalAudioPath(null);- return;- }-- let cancelled = false;- window.electronAPI- ?.preparePreviewAudioTrack?.(videoPath)- .then((result) => {- if (!cancelled) {- setSupplementalAudioPath(result.success ? (result.path ?? null) : null);- }- })- .catch(() => {- if (!cancelled) {- setSupplementalAudioPath(null);- }- });-- const video = videoRef.current;- if (!video) {- return () => {- cancelled = true;- };- }- video.pause();- video.currentTime = 0;- allowPlaybackRef.current = false;- lockedVideoDimensionsRef.current = null;- lastResolvedDurationRef.current = null;- isResolvingDurationRef.current = false;- if (durationResolutionTimeoutRef.current) {- clearTimeout(durationResolutionTimeoutRef.current);- durationResolutionTimeoutRef.current = null;- }- setVideoReady(false);- if (videoReadyRafRef.current) {- cancelAnimationFrame(videoReadyRafRef.current);- videoReadyRafRef.current = null;- }- video.load();-- return () => {- cancelled = true;- };- }, [videoPath]);-- useEffect(() => {- const video = videoRef.current;- const supplementalAudio = supplementalAudioRef.current;- if (!video || !supplementalAudio || !supplementalAudioPath) {- return;- }-- const activeSpeedRegion =- speedRegions.find(- (region) => currentTime * 1000 >= region.startMs && currentTime * 1000 < region.endMs,- ) ?? null;- const activeSpeed = activeSpeedRegion ? activeSpeedRegion.speed : 1;-- // Above the native rate the main preview frame-steps silently; a media- // element can't play that fast (setting playbackRate > 16 throws), so mute- // the supplemental track by pausing it for the duration of the region.- if (activeSpeed > MAX_NATIVE_PLAYBACK_RATE) {- supplementalAudio.pause();- return;- }- supplementalAudio.playbackRate = activeSpeed;-- if (!isPlaying) {- supplementalAudio.pause();- if (Math.abs(supplementalAudio.currentTime - currentTime) > 0.05) {- supplementalAudio.currentTime = currentTime;- }- return;- }-- if (Math.abs(supplementalAudio.currentTime - video.currentTime) > 0.15) {- supplementalAudio.currentTime = video.currentTime;- }-- supplementalAudio.play().catch(() => {- // Keep video playback running even if supplemental preview audio is unavailable.- });- }, [currentTime, isPlaying, speedRegions, supplementalAudioPath]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;-- const video = videoRef.current;- const app = appRef.current;- const videoContainer = videoContainerRef.current;-- if (!video || !app || !videoContainer) return;- if (video.videoWidth === 0 || video.videoHeight === 0) return;-- const source = VideoSource.from(video);- if ("autoPlay" in source) {- (source as { autoPlay?: boolean }).autoPlay = false;- }- if ("autoUpdate" in source) {- (source as { autoUpdate?: boolean }).autoUpdate = true;- }- const videoTexture = Texture.from(source);-- const videoSprite = new Sprite(videoTexture);- videoSpriteRef.current = videoSprite;-- const maskGraphics = new Graphics();- videoContainer.addChild(videoSprite);- videoContainer.addChild(maskGraphics);- videoContainer.mask = maskGraphics;- maskGraphicsRef.current = maskGraphics;- const nativeCursorSprite = new Sprite(Texture.EMPTY);- nativeCursorSprite.visible = false;- nativeCursorSprite.eventMode = "none";- nativeCursorSpriteRef.current = nativeCursorSprite;- if (cursorOverlayRef.current) {- videoContainer.addChild(cursorOverlayRef.current.container);- }-- videoContainer.addChild(nativeCursorSprite);-- animationStateRef.current = {- scale: 1,- focusX: DEFAULT_FOCUS.cx,- focusY: DEFAULT_FOCUS.cy,- progress: 0,- x: 0,- y: 0,- appliedScale: 1,- };-- const blurFilter = new BlurFilter();- blurFilter.quality = 3;- blurFilter.resolution = app.renderer.resolution;- blurFilter.blur = 0;- const motionBlurFilter = new MotionBlurFilter([0, 0], 5, 0);- blurFilterRef.current = blurFilter;- motionBlurFilterRef.current = motionBlurFilter;-- layoutVideoContentRef.current?.();- video.pause();-- const { handlePlay, handlePause, handleSeeked, handleSeeking, dispose } =- createVideoEventHandlers({- video,- isSeekingRef,- isPlayingRef,- allowPlaybackRef,- currentTimeRef,- timeUpdateAnimationRef,- onPlayStateChange: (playing) => onPlayStateChangeRef.current(playing),- onTimeUpdate: (time) => onTimeUpdateRef.current(time),- trimRegionsRef,- speedRegionsRef,- isScrubbingRef,- scrubEndTimerRef,- onScrubChange: (scrubbing) => setIsScrubbing(scrubbing),- seekSteppingRef,- stepVirtualSecRef,- stepLastTsRef,- stepPrevMutedRef,- });-- video.addEventListener("play", handlePlay);- video.addEventListener("pause", handlePause);- video.addEventListener("ended", handlePause);- video.addEventListener("seeked", handleSeeked);- video.addEventListener("seeking", handleSeeking);-- return () => {- video.removeEventListener("play", handlePlay);- video.removeEventListener("pause", handlePause);- video.removeEventListener("ended", handlePause);- video.removeEventListener("seeked", handleSeeked);- video.removeEventListener("seeking", handleSeeking);-- if (timeUpdateAnimationRef.current) {- cancelAnimationFrame(timeUpdateAnimationRef.current);- }- dispose();-- if (videoSprite) {- videoContainer.removeChild(videoSprite);- videoSprite.destroy();- }- if (maskGraphics) {- videoContainer.removeChild(maskGraphics);- maskGraphics.destroy();- }- if (nativeCursorSpriteRef.current) {- videoContainer.removeChild(nativeCursorSpriteRef.current);- nativeCursorSpriteRef.current.destroy();- nativeCursorSpriteRef.current = null;- nativeCursorTextureIdRef.current = null;- }- videoContainer.mask = null;- maskGraphicsRef.current = null;- if (blurFilterRef.current) {- videoContainer.filters = null;- blurFilterRef.current.destroy();- blurFilterRef.current = null;- }- if (motionBlurFilterRef.current) {- motionBlurFilterRef.current.destroy();- motionBlurFilterRef.current = null;- }- videoTexture.destroy(true);-- videoSpriteRef.current = null;- };- }, [pixiReady, videoReady]);-- useEffect(() => {- if (!pixiReady || !videoReady) return;-- const app = appRef.current;- const videoSprite = videoSpriteRef.current;- const videoContainer = videoContainerRef.current;- if (!app || !videoSprite || !videoContainer) return;-- const applyTransformFn = (- transform: { scale: number; x: number; y: number },- targetFocus: ZoomFocus,- motionIntensity: number,- motionVector: { x: number; y: number },- ) => {- const cameraContainer = cameraContainerRef.current;- if (!cameraContainer) return;-- const state = animationStateRef.current;-- const appliedTransform = applyZoomTransform({- cameraContainer,- blurFilter: blurFilterRef.current,- motionBlurFilter: motionBlurFilterRef.current,- stageSize: stageSizeRef.current,- baseMask: baseMaskRef.current,- zoomScale: state.scale,- zoomProgress: state.progress,- focusX: targetFocus.cx,- focusY: targetFocus.cy,- motionIntensity,- motionVector,- isPlaying: isPlayingRef.current,- motionBlurAmount: motionBlurAmountRef.current,- transformOverride: transform,- motionBlurState: motionBlurStateRef.current,- // Content time, not wall-clock, so motion-blur velocity matches export and stays- // correct under speed regions (frameRenderer passes the same content timeMs).- frameTimeMs: currentTimeRef.current,- });-- state.x = appliedTransform.x;- state.y = appliedTransform.y;- state.appliedScale = appliedTransform.scale;-- // Scale the PiP webcam inversely with the (eased) zoom, anchored to the docked- // corner (bottom-right by default) so it stays flush instead of drifting to center.- const webcamWrapper = webcamWrapperRef.current;- if (webcamWrapper) {- const cameraFullProgress = computeCameraFullscreenProgress(- cameraFullscreenRegionsRef.current,- currentTimeRef.current,- );- const baseRect = webcamLayoutRef.current;-- if (cameraFullProgress > 0 && baseRect && baseRect.width > 0 && baseRect.height > 0) {- // Full Camera takes over the webcam's size/position entirely: it grows to- // cover the whole stage. Like the reactive-zoom branch below, this only ever- // touches `transform` (never left/top/width/height, which stay driven by the- // `webcamLayout` React state in the JSX style prop) so it can't race React's- // re-render on every currentTime update. The base rect is lerped toward a- // full-stage rect and expressed as a translate+scale from the base rect's own- // box, matching the CSS transform box (border-box, top-left origin).- const stage = stageSizeRef.current;- const targetRect = computeCameraFullscreenTargetRect(stage, baseRect);- const fullRect: StyledRenderRect = {- x: targetRect.x,- y: targetRect.y,- width: targetRect.width,- height: targetRect.height,- borderRadius: 0,- maskShape: baseRect.maskShape,- };- const drawRect = lerpRect(baseRect, fullRect, cameraFullProgress);- const scaleX = drawRect.width / baseRect.width;- const scaleY = drawRect.height / baseRect.height;- const translateX = drawRect.x - baseRect.x;- const translateY = drawRect.y - baseRect.y;- webcamWrapper.style.transformOrigin = "0% 0%";- webcamWrapper.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scaleX}, ${scaleY})`;- } else {- const reactive =- webcamReactiveZoomRef.current &&- webcamLayoutPresetRef.current === "picture-in-picture";- const factor = reactive ? reactiveWebcamScale(state.appliedScale) : 1;- if (factor < 1) {- const pos = webcamPositionRef.current;- const originX = (pos ? pos.cx >= 0.5 : true) ? "100%" : "0%";- const originY = (pos ? pos.cy >= 0.5 : true) ? "100%" : "0%";- webcamWrapper.style.transformOrigin = `${originX} ${originY}`;- webcamWrapper.style.transform = `scale(${factor})`;- } else {- webcamWrapper.style.transform = "";- }- }- }- };-- let lastMotionBlurActive: boolean | null = null;- let lastTransformIsIdentity = true;- let lastPerspectiveValue = 0;- const ticker = () => {- const { region, strength, blendedScale, rotation3D, transition } = findDominantRegion(- zoomRegionsRef.current,- currentTimeRef.current,- {- connectZooms: true,- cursorTelemetry: cursorTelemetryRef.current,- },- );-- const defaultFocus = DEFAULT_FOCUS;- let targetScaleFactor = 1;- let targetFocus = defaultFocus;- let targetProgress = 0;-- // If a zoom is selected but not playing, show the default unzoomed view.- const selectedId = selectedZoomIdRef.current;- const hasSelectedZoom = selectedId !== null;- const shouldShowUnzoomedView =- hasSelectedZoom && !isPlayingRef.current && !isPreviewingZoomRef.current;-- if (region && strength > 0 && !shouldShowUnzoomedView) {- // Use getZoomScale (customScale-aware) to match export and the magnification- // findDominantRegion resolved focus at. Falling back to the depth preset would- // zoom/pan to a different level than export.- const zoomScale = blendedScale ?? getZoomScale(region);- const regionFocus = region.focus;-- targetScaleFactor = zoomScale;- targetFocus = regionFocus;- targetProgress = strength;-- // Adaptive smoothing for auto-follow mode.- if (region.focusMode === "auto" && !transition) {- const raw = targetFocus;- const isZoomingIn =- targetProgress < 0.999 && targetProgress >= prevTargetProgressRef.current;- // Follow the cursor in content time (frame-rate independent) so the camera pans- // at the same speed in preview and export. Snap to target when not actively- // playing (paused/seek/scrub), matching the zoom spring's snap.- const focusAnimating =- isPlayingRef.current && !isSeekingRef.current && !isScrubbingRef.current;- const focusDtMs =- prevZoomTimeMsRef.current === null- ? 0- : currentTimeRef.current - prevZoomTimeMsRef.current;- if (targetProgress >= 0.999) {- // Full zoom: adaptive smoothing, faster when far, decelerating when close.- const prev = smoothedAutoFocusRef.current ?? raw;- const smoothed = focusAnimating- ? advanceFollowFocus(prev, raw, focusDtMs, AUTO_FOLLOW_PARAMS)- : raw;- smoothedAutoFocusRef.current = smoothed;- targetFocus = smoothed;- } else if (isZoomingIn) {- // Zoom-in: track cursor directly so zoom always aims at the current position;- // keep ref in sync to avoid a snap when full-zoom begins.- smoothedAutoFocusRef.current = raw;- } else {- // Zoom-out: keep smoothing for continuity to avoid a snap at zoom-out start.- const prev = smoothedAutoFocusRef.current ?? raw;- const smoothed = focusAnimating- ? advanceFollowFocus(prev, raw, focusDtMs, AUTO_FOLLOW_PARAMS)- : raw;- smoothedAutoFocusRef.current = smoothed;- targetFocus = smoothed;- }- } else if (region.focusMode !== "auto") {- smoothedAutoFocusRef.current = null;- }- prevTargetProgressRef.current = targetProgress;-- // Connected zoom transitions: pan between adjacent regions.- if (transition) {- const startTransform = computeZoomTransform({- stageSize: stageSizeRef.current,- baseMask: baseMaskRef.current,- zoomScale: transition.startScale,- zoomProgress: 1,- focusX: transition.startFocus.cx,- focusY: transition.startFocus.cy,- });- const endTransform = computeZoomTransform({- stageSize: stageSizeRef.current,- baseMask: baseMaskRef.current,- zoomScale: transition.endScale,- zoomProgress: 1,- focusX: transition.endFocus.cx,- focusY: transition.endFocus.cy,- });-- const interpolatedTransform = {- scale:- startTransform.scale +- (endTransform.scale - startTransform.scale) * transition.progress,- x: startTransform.x + (endTransform.x - startTransform.x) * transition.progress,- y: startTransform.y + (endTransform.y - startTransform.y) * transition.progress,- };-- targetScaleFactor = interpolatedTransform.scale;- targetFocus = computeFocusFromTransform({- stageSize: stageSizeRef.current,- baseMask: baseMaskRef.current,- zoomScale: interpolatedTransform.scale,- x: interpolatedTransform.x,- y: interpolatedTransform.y,- });- targetProgress = 1;- }- }-- const state = animationStateRef.current;- const prevScale = state.appliedScale;- const prevX = state.x;- const prevY = state.y;-- state.scale = targetScaleFactor;- state.focusX = targetFocus.cx;- state.focusY = targetFocus.cy;- state.progress = targetProgress;-- const projectedTransform = computeZoomTransform({- stageSize: stageSizeRef.current,- baseMask: baseMaskRef.current,- zoomScale: state.scale,- zoomProgress: state.progress,- focusX: state.focusX,- focusY: state.focusY,- });-- // Chase the eased target with a spring so the camera glides (no jerk at the steep- // start of the ease, no snap at close-region seams). Step by content time while- // playing; snap to the exact target when paused/seeking/scrubbing for crisp frames.- const nowMs = currentTimeRef.current;- const prevMs = prevZoomTimeMsRef.current;- const animating = isPlayingRef.current && !isSeekingRef.current && !isScrubbingRef.current;- const dtMs = prevMs === null ? 0 : nowMs - prevMs;- let appliedScale: number;- let appliedX: number;- let appliedY: number;- if (!animating || prevMs === null || dtMs <= 0 || dtMs > 80) {- resetZoomSpring(zoomSpringRef.current, projectedTransform);- appliedScale = projectedTransform.scale;- appliedX = projectedTransform.x;- appliedY = projectedTransform.y;- } else {- const sprung = stepZoomSpring(zoomSpringRef.current, projectedTransform, dtMs);- appliedScale = sprung.scale;- appliedX = sprung.x;- appliedY = sprung.y;- }- prevZoomTimeMsRef.current = nowMs;-- const motionIntensity = Math.max(- Math.abs(appliedScale - prevScale),- Math.abs(appliedX - prevX) / Math.max(1, stageSizeRef.current.width),- Math.abs(appliedY - prevY) / Math.max(1, stageSizeRef.current.height),- );-- const motionVector = {- x: appliedX - prevX,- y: appliedY - prevY,- };-- applyTransformFn(- { scale: appliedScale, x: appliedX, y: appliedY },- targetFocus,- motionIntensity,- motionVector,- );-- const isMotionBlurActive =- (motionBlurAmountRef.current || 0) > 0 && isPlayingRef.current && !isScrubbingRef.current;-- if (isMotionBlurActive !== lastMotionBlurActive && videoContainerRef.current) {- if (isMotionBlurActive) {- if (blurFilterRef.current && motionBlurFilterRef.current) {- videoContainerRef.current.filters = [- blurFilterRef.current,- motionBlurFilterRef.current,- ];- lastMotionBlurActive = true;- }- } else {- videoContainerRef.current.filters = null;- lastMotionBlurActive = false;- }- }-- const cursorOverlay = cursorOverlayRef.current;- if (cursorOverlay) {- const timeMs = currentTimeRef.current; // already in ms- cursorOverlay.update(- cursorTelemetryRef.current,- timeMs,- baseMaskRef.current,- showCursorRef.current && !hasNativeCursorRecordingRef.current,- !isPlayingRef.current || isSeekingRef.current,- cropRegionRef.current,- );- }-- // Keep the native cursor preview in the same transformed coordinate space as PIXI.- const nativeCursorSprite = nativeCursorSpriteRef.current;- const nativeCursorImage = nativeCursorImageRef.current;- const hideNativeCursorPreview = () => {- if (nativeCursorSprite) {- nativeCursorSprite.visible = false;- }- if (nativeCursorImage) {- nativeCursorImage.style.display = "none";- nativeCursorImage.style.filter = "none";- }- if (nativeCursorClipRef.current) {- nativeCursorClipRef.current.style.clipPath = "";- }- resetNativeCursorMotionBlurState(nativeCursorMotionBlurStateRef.current);- };- if (nativeCursorImage) {- if (hasNativeCursorRecordingRef.current && showCursorRef.current) {- const timeMs = currentTimeRef.current; // already in ms- const frame = resolveInterpolatedNativeCursorFrame(- cursorRecordingDataRef.current,- timeMs,- );- if (frame) {- // Position comes from the precomputed offline-smoothed path; the frame still- // supplies the cursor image, type, and click timing.- const smoothedPos = getSmoothedCursorPath(- cursorRecordingDataRef.current,- cursorSmoothingRef.current,- )?.sampleAt(timeMs);- const displaySample = smoothedPos- ? { ...frame.sample, cx: smoothedPos.cx, cy: smoothedPos.cy }- : frame.sample;- const cameraContainer = cameraContainerRef.current;- const videoContainer = videoContainerRef.current;- const cropRegionValue = cropRegionRef.current ?? DEFAULT_CROP_REGION;- const projectedLocalPoint = projectNativeCursorToLocal({- cropRegion: cropRegionValue,- maskRect: baseMaskRef.current,- sample: displaySample,- });- const projectedStagePoint =- cameraContainer && videoContainer- ? projectNativeCursorToStage({- cameraContainer,- cropRegion: cropRegionValue,- maskRect: baseMaskRef.current,- videoContainerPosition: {- x: videoContainer.x,- y: videoContainer.y,- },- sample: displaySample,- })- : null;- if (projectedLocalPoint && projectedStagePoint) {- // Pass deviceScaleFactor=1 since asset.scaleFactor already encodes DPR.- // Size is normalized below so preview matches export proportionally.- const renderAsset = resolveNativeCursorRenderAsset(- frame.asset,- 1,- displaySample,- cursorThemeRef.current,- );- const bounceProgress = getNativeCursorClickBounceProgress(- cursorRecordingDataRef.current,- timeMs,- );- const scale =- Math.max(0, cursorSizeRef.current) *- getNativeCursorClickBounceScale(cursorClickBounceRef.current, bounceProgress);- // Normalize cursor size to the displayed video width so the cursor- // appears at the same fraction of the video in both preview and export.- const crop = cropRegionRef.current ?? DEFAULT_CROP_REGION;- const croppedVideoWidth = (videoRef.current?.videoWidth ?? 0) * crop.width;- const sizeNorm =- croppedVideoWidth > 0 ? baseMaskRef.current.width / croppedVideoWidth : 1;- const transformedScale = scale * Math.abs(cameraContainer?.scale.x || 1) * sizeNorm;- const blurPx =- !isPlayingRef.current || isSeekingRef.current- ? 0- : getNativeCursorMotionBlurPx({- motionBlur: cursorMotionBlurRef.current,- point: projectedStagePoint,- state: nativeCursorMotionBlurStateRef.current,- timeMs,- });- if (nativeCursorImageIdRef.current !== renderAsset.id) {- nativeCursorImage.src = renderAsset.imageDataUrl;- nativeCursorImageIdRef.current = renderAsset.id;- }- nativeCursorImage.style.display = "block";- // Clip to the camera-aware video boundary. Works here because nativeCursorClipRef- // sits outside preserve-3d. When cursorClipToBounds is off, let the cursor overflow.- if (nativeCursorClipRef.current) {- if (!cursorClipToBoundsRef.current) {- nativeCursorClipRef.current.style.clipPath = "none";- } else {- const mask = baseMaskRef.current;- const stage = stageSizeRef.current;- const br = borderRadiusRef.current;- const s = cameraContainer ? Math.abs(cameraContainer.scale.x) : 1;- const camX = cameraContainer ? cameraContainer.position.x : 0;- const camY = cameraContainer ? cameraContainer.position.y : 0;- const clipLeft = camX + s * mask.x;- const clipTop = camY + s * mask.y;- const clipRight = camX + s * (mask.x + mask.width);- const clipBottom = camY + s * (mask.y + mask.height);- nativeCursorClipRef.current.style.clipPath = `inset(${clipTop}px ${stage.width - clipRight}px ${stage.height - clipBottom}px ${clipLeft}px round ${br * s}px)`;- }- }- nativeCursorImage.style.width = `${renderAsset.width * transformedScale}px`;- nativeCursorImage.style.height = `${renderAsset.height * transformedScale}px`;- nativeCursorImage.style.filter =- blurPx > 0 ? `blur(${blurPx.toFixed(2)}px)` : "none";- // translate3d is relative to nativeCursorClipRef (absolute inset-0 = stage origin).- // projectedStagePoint.x is the stage-space cursor position, so no offset is needed.- nativeCursorImage.style.transform = `translate3d(${- projectedStagePoint.x - renderAsset.hotspotX * transformedScale- }px, ${projectedStagePoint.y - renderAsset.hotspotY * transformedScale}px, 0)`;- if (nativeCursorSprite) {- nativeCursorSprite.visible = false;- if (nativeCursorTextureIdRef.current !== renderAsset.id) {- nativeCursorSprite.texture = Texture.from(renderAsset.imageDataUrl);- nativeCursorTextureIdRef.current = renderAsset.id;- }- nativeCursorSprite.position.set(- projectedLocalPoint.x - renderAsset.hotspotX * scale,- projectedLocalPoint.y - renderAsset.hotspotY * scale,- );- nativeCursorSprite.width = renderAsset.width * scale;- nativeCursorSprite.height = renderAsset.height * scale;- }- } else {- hideNativeCursorPreview();- }- } else {- hideNativeCursorPreview();- }- } else {- hideNativeCursorPreview();- }- } else {- hideNativeCursorPreview();- }-- const composite3D = composite3DRef.current;- const outerWrapper = outerWrapperRef.current;- if (composite3D && outerWrapper) {- const effectiveRotation =- region && targetProgress > 0 && !shouldShowUnzoomedView- ? lerpRotation3D(DEFAULT_ROTATION_3D, rotation3D, targetProgress)- : DEFAULT_ROTATION_3D;- const isIdentity = isRotation3DIdentity(effectiveRotation);- if (isIdentity) {- if (!lastTransformIsIdentity) {- composite3D.style.transform = "";- composite3D.style.willChange = "auto";- lastTransformIsIdentity = true;- }- if (nativeCursorClipRef.current) {- nativeCursorClipRef.current.style.transform = "";- }- if (lastPerspectiveValue !== 0) {- outerWrapper.style.perspective = "";- lastPerspectiveValue = 0;- }- } else {- const wrapperW = outerWrapper.clientWidth || 1;- const wrapperH = outerWrapper.clientHeight || 1;- const persp = rotation3DPerspective(wrapperW, wrapperH);- const containScale = computeRotation3DContainScale(- effectiveRotation,- wrapperW,- wrapperH,- persp,- );- composite3D.style.transform = `scale(${containScale}) rotateX(${effectiveRotation.rotationX}deg) rotateY(${effectiveRotation.rotationY}deg) rotateZ(${effectiveRotation.rotationZ}deg)`;- composite3D.style.willChange = "transform";- if (nativeCursorClipRef.current) {- nativeCursorClipRef.current.style.transform = composite3D.style.transform;- }- lastTransformIsIdentity = false;- if (persp !== lastPerspectiveValue) {- outerWrapper.style.perspective = `${persp}px`;- lastPerspectiveValue = persp;- }- }- }- };-- app.ticker.add(ticker);- return () => {- if (app && app.ticker) {- app.ticker.remove(ticker);- }- };- }, [pixiReady, videoReady]);-- const handleLoadedMetadata = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {- const video = e.currentTarget;- enableAllPreviewAudioTracks(video);- const hasResolvedDuration = syncResolvedDuration(video);- if (!hasResolvedDuration) {- forceResolveDuration(video);- } else {- video.currentTime = 0;- }- video.pause();- allowPlaybackRef.current = false;- currentTimeRef.current = 0;-- if (videoReadyRafRef.current) {- cancelAnimationFrame(videoReadyRafRef.current);- videoReadyRafRef.current = null;- }-- const waitForRenderableFrame = () => {- const hasDimensions = video.videoWidth > 0 && video.videoHeight > 0;- const hasData = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;- if (!syncResolvedDuration(video)) {- forceResolveDuration(video);- }- if (hasDimensions && hasData) {- videoReadyRafRef.current = null;- setVideoReady(true);- return;- }- videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);- };-- videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);- };-- const resolvedWallpaper = useMemo<string | null>(() => {- const source = wallpaper || DEFAULT_WALLPAPER;- const classified = classifyWallpaper(source);- if (classified.kind !== "image") return classified.value;- try {- return resolveImageWallpaperUrl(classified.path);- } catch (err) {- console.warn("[VideoPlayback] wallpaper resolve failed:", err);- return null;- }- }, [wallpaper]);- const webcamCssBoxShadow = useMemo(- () => getWebcamLayoutCssBoxShadow(webcamLayoutPreset),- [webcamLayoutPreset],- );-- useEffect(() => {- const webcamVideo = webcamVideoRef.current;- if (!webcamVideo || !webcamVideoPath) {- setWebcamDimensions(null);- return;- }-- const handleLoadedMetadata = () => {- if (webcamVideo.videoWidth > 0 && webcamVideo.videoHeight > 0) {- setWebcamDimensions({- width: webcamVideo.videoWidth,- height: webcamVideo.videoHeight,- });- }- };-- webcamVideo.addEventListener("loadedmetadata", handleLoadedMetadata);- handleLoadedMetadata();- return () => {- webcamVideo.removeEventListener("loadedmetadata", handleLoadedMetadata);- };- }, [webcamVideoPath]);-- useEffect(() => {- const webcamVideo = webcamVideoRef.current;- if (!webcamVideo || !webcamVideoPath) {- return;- }-- const activeSpeedRegion =- speedRegions.find(- (region) => currentTime * 1000 >= region.startMs && currentTime * 1000 < region.endMs,- ) ?? null;- // Cap the (silent) webcam element at the native rate so playbackRate never throws.- webcamVideo.playbackRate = Math.min(- activeSpeedRegion ? activeSpeedRegion.speed : 1,- MAX_NATIVE_PLAYBACK_RATE,- );-- if (!isPlaying) {- webcamVideo.pause();- if (Math.abs(webcamVideo.currentTime - currentTime) > 0.05) {- webcamVideo.currentTime = currentTime;- }- return;- }-- // While the main video is seek-stepping (>16×), the playhead advances far- // faster than this 16×-capped element can seek; resyncing every frame would- // keep its decoder perpetually mid-seek and freeze it — the same failure the- // main video's throttle fixes. Let the muted webcam play best-effort at the- // clamped rate instead (a small lag is fine).- if (!seekSteppingRef.current && Math.abs(webcamVideo.currentTime - currentTime) > 0.15) {- webcamVideo.currentTime = currentTime;- }-- webcamVideo.play().catch(() => {- // Ignore webcam autoplay restoration failures.- });- }, [currentTime, isPlaying, speedRegions, webcamVideoPath]);-- useEffect(() => {- const webcamVideo = webcamVideoRef.current;- if (!webcamVideo || !webcamVideoPath) {- return;- }-- webcamVideo.pause();- webcamVideo.currentTime = 0;- }, [webcamVideoPath]);-- useEffect(() => {- return () => {- if (videoReadyRafRef.current) {- cancelAnimationFrame(videoReadyRafRef.current);- videoReadyRafRef.current = null;- }- if (scrubEndTimerRef.current !== null) {- window.clearTimeout(scrubEndTimerRef.current);- scrubEndTimerRef.current = null;- }- if (durationResolutionTimeoutRef.current) {- clearTimeout(durationResolutionTimeoutRef.current);- durationResolutionTimeoutRef.current = null;- }- };- }, []);-- const isImageUrl = Boolean(- resolvedWallpaper &&- (resolvedWallpaper.startsWith("file://") ||- resolvedWallpaper.startsWith("http") ||- resolvedWallpaper.startsWith("/") ||- resolvedWallpaper.startsWith("data:")),- );- const backgroundStyle = isImageUrl- ? { backgroundImage: `url(${resolvedWallpaper || ""})` }- : { background: resolvedWallpaper || "" };-- return (- <div- ref={outerWrapperRef}- className="relative rounded-sm overflow-hidden"- style={{- width: "100%",- aspectRatio: formatAspectRatioForCSS(- aspectRatio,- aspectRatio === "native"- ? getNativeAspectRatioValue(- lockedVideoDimensionsRef.current?.width || DEFAULT_SOURCE_DIMENSIONS.width,- lockedVideoDimensionsRef.current?.height || DEFAULT_SOURCE_DIMENSIONS.height,- cropRegion,- )- : undefined,- ),- }}- >- {/* Background always renders as a DOM element so it can be blurred. */}- <div- className="absolute inset-0 bg-cover bg-center"- style={{- ...backgroundStyle,- filter: showBlur ? "blur(2px)" : "none",- }}- />- <div- ref={composite3DRef}- className="absolute inset-0"- style={{- transformStyle: "preserve-3d",- transformOrigin: "center center",- }}- >- <div- ref={containerRef}- className="absolute inset-0"- style={{- filter:- showShadow && shadowIntensity > 0- ? `drop-shadow(0 ${shadowIntensity * 12}px ${shadowIntensity * 48}px rgba(0,0,0,${shadowIntensity * 0.7})) drop-shadow(0 ${shadowIntensity * 4}px ${shadowIntensity * 16}px rgba(0,0,0,${shadowIntensity * 0.5})) drop-shadow(0 ${shadowIntensity * 2}px ${shadowIntensity * 8}px rgba(0,0,0,${shadowIntensity * 0.3}))`- : "none",- }}- />- {webcamVideoPath &&- (() => {- const clipPath = getCssClipPath(webcamLayout?.maskShape ?? "rectangle");- const useClipPath = !!clipPath;- return (- <div- ref={webcamWrapperRef}- className="absolute"- style={{- left: webcamLayout?.x ?? 0,- top: webcamLayout?.y ?? 0,- width: webcamLayout?.width ?? 0,- height: webcamLayout?.height ?? 0,- zIndex: 20,- opacity: webcamLayout ? 1 : 0,- filter:- useClipPath && webcamCssBoxShadow !== "none"- ? `drop-shadow(${webcamCssBoxShadow})`- : undefined,- }}- >- <video- ref={webcamVideoRef}- src={webcamVideoPath}- className={`w-full h-full object-cover ${webcamLayoutPreset === "picture-in-picture" ? "cursor-grab active:cursor-grabbing" : "pointer-events-none"}`}- style={{- borderRadius: useClipPath ? 0 : (webcamLayout?.borderRadius ?? 0),- clipPath: clipPath ?? undefined,- boxShadow: useClipPath ? "none" : webcamCssBoxShadow,- backgroundColor: "#000",- transform: webcamMirrored ? "scaleX(-1)" : undefined,- }}- onPointerDown={handleWebcamPointerDown}- onPointerMove={handleWebcamPointerMove}- onPointerUp={handleWebcamPointerUp}- onPointerLeave={handleWebcamPointerUp}- muted- preload="metadata"- playsInline- />- </div>- );- })()}- {/* Render the overlay only once PIXI and video are ready. */}- {pixiReady && videoReady && (- <div- ref={setOverlayRefs}- className="absolute inset-0 select-none"- style={{ pointerEvents: "auto", zIndex: 30 }}- onPointerDown={handleOverlayPointerDown}- onPointerMove={handleOverlayPointerMove}- onPointerUp={handleOverlayPointerUp}- onPointerLeave={handleOverlayPointerLeave}- >- <div- ref={focusIndicatorRef}- className="absolute rounded-md border border-[#34B27B]/80 bg-[#34B27B]/20 shadow-[0_0_0_1px_rgba(52,178,123,0.35)]"- style={{ display: "none", pointerEvents: "none" }}- />- {(() => {- const filteredAnnotations = (annotationRegions || []).filter((annotation) => {- if (- typeof annotation.startMs !== "number" ||- typeof annotation.endMs !== "number"- )- return false;-- if (annotation.id === selectedAnnotationId) return true;-- const timeMs = Math.round(currentTime * 1000);- return timeMs >= annotation.startMs && timeMs < annotation.endMs;- });-- const filteredBlurRegions = (blurRegions || []).filter((blurRegion) => {- if (- typeof blurRegion.startMs !== "number" ||- typeof blurRegion.endMs !== "number"- )- return false;-- if (blurRegion.id === selectedBlurId) return true;-- const timeMs = Math.round(currentTime * 1000);- return timeMs >= blurRegion.startMs && timeMs < blurRegion.endMs;- });-- const sorted = [- ...filteredAnnotations.map((annotation) => ({- kind: "annotation" as const,- region: annotation,- })),- ...filteredBlurRegions.map((blurRegion) => ({- kind: "blur" as const,- region: blurRegion,- })),- ].sort((a, b) => a.region.zIndex - b.region.zIndex);- const previewSnapshotCanvas =- filteredBlurRegions.length > 0- ? (() => {- const app = appRef.current;- if (!app?.renderer?.extract) return null;- try {- return app.renderer.extract.canvas(app.stage);- } catch {- return null;- }- })()- : null;-- // Re-clicking a selected annotation cycles through any overlapping ones.- const handleAnnotationClick = (clickedId: string) => {- if (!onSelectAnnotation) return;-- if (clickedId === selectedAnnotationId && filteredAnnotations.length > 1) {- const currentIndex = filteredAnnotations.findIndex((a) => a.id === clickedId);- const nextIndex = (currentIndex + 1) % filteredAnnotations.length;- onSelectAnnotation(filteredAnnotations[nextIndex].id);- } else {- onSelectAnnotation(clickedId);- }- };-- const handleBlurClick = (clickedId: string) => {- if (!onSelectBlur) return;-- if (clickedId === selectedBlurId && filteredBlurRegions.length > 1) {- const currentIndex = filteredBlurRegions.findIndex((a) => a.id === clickedId);- const nextIndex = (currentIndex + 1) % filteredBlurRegions.length;- onSelectBlur(filteredBlurRegions[nextIndex].id);- } else {- onSelectBlur(clickedId);- }- };-- return sorted.map((item) => (- <AnnotationOverlay- key={- item.kind === "blur"- ? `${item.region.id}-${overlaySize.width}-${overlaySize.height}-${item.region.blurData?.type ?? "blur"}-${item.region.blurData?.shape ?? "rectangle"}-${item.region.blurData?.color ?? "white"}-${Math.round(item.region.blurData?.blockSize ?? 0)}-${Math.round(item.region.blurData?.intensity ?? 0)}-${(item.region.blurData?.freehandPoints ?? []).map((p) => `${Math.round(p.x)}_${Math.round(p.y)}`).join("-")}`- : `${item.region.id}-${overlaySize.width}-${overlaySize.height}`- }- annotation={item.region}- isSelected={- item.kind === "blur"- ? item.region.id === selectedBlurId- : item.region.id === selectedAnnotationId- }- containerWidth={overlaySize.width}- containerHeight={overlaySize.height}- onPositionChange={(id, position) =>- item.kind === "blur"- ? onBlurPositionChange?.(id, position)- : onAnnotationPositionChange?.(id, position)- }- onSizeChange={(id, size) =>- item.kind === "blur"- ? onBlurSizeChange?.(id, size)- : onAnnotationSizeChange?.(id, size)- }- onBlurDataChange={- item.kind === "blur"- ? (id, blurData) => onBlurDataChange?.(id, blurData)- : undefined- }- onBlurDataCommit={item.kind === "blur" ? onBlurDataCommit : undefined}- onClick={item.kind === "blur" ? handleBlurClick : handleAnnotationClick}- zIndex={item.region.zIndex}- isSelectedBoost={- item.kind === "blur"- ? item.region.id === selectedBlurId- : item.region.id === selectedAnnotationId- }- previewSourceCanvas={previewSnapshotCanvas}- previewFrameVersion={Math.round(currentTime * 1000)}- currentTimeMs={Math.round(currentTime * 1000)}- />- ));- })()}- </div>- )}- </div>- {/* Native cursor clip. Lives outside composite3DRef (preserve-3d) so clip-path- keeps working during 3D zoom rotations; bounds are set dynamically. */}- <div- ref={nativeCursorClipRef}- className="absolute inset-0"- style={{ zIndex: 18, pointerEvents: "none" }}- >- <img- ref={nativeCursorImageRef}- alt=""- aria-hidden="true"- className="absolute left-0 top-0 select-none"- style={{- display: "none",- pointerEvents: "none",- transformOrigin: "0 0",- }}- />- </div>- <video- ref={videoRef}- src={videoPath}- className="hidden"- preload="auto"- playsInline- onLoadedMetadata={handleLoadedMetadata}- onDurationChange={(e) => {- enableAllPreviewAudioTracks(e.currentTarget);- if (!syncResolvedDuration(e.currentTarget)) {- forceResolveDuration(e.currentTarget);- }- }}- onLoadedData={(e) => {- enableAllPreviewAudioTracks(e.currentTarget);- if (!syncResolvedDuration(e.currentTarget)) {- forceResolveDuration(e.currentTarget);- }- }}- onCanPlay={(e) => {- enableAllPreviewAudioTracks(e.currentTarget);- if (!syncResolvedDuration(e.currentTarget)) {- forceResolveDuration(e.currentTarget);- }- }}- onError={() => onError("Failed to load video")}- />- {supplementalAudioPath && (- <audio ref={supplementalAudioRef} src={supplementalAudioPath} preload="auto" />- )}- </div>- );- },-);--VideoPlayback.displayName = "VideoPlayback";--export default VideoPlayback;diff --git a/src/components/video-editor/featureFlags.ts b/src/components/video-editor/featureFlags.tsindex 8bf73f726..5209db37e 100644--- a/src/components/video-editor/featureFlags.ts+++ b/src/components/video-editor/featureFlags.ts@@ -1 +1,10 @@export const BLUR_REGIONS_ENABLED = false;++// ponytail: gates ONLY the LLM/agent surface — provider settings dialog, chat+// panel, suggestions list, "Restore checkpoint" actions. Does NOT gate the+// new editing model, project panel, timeline, transcript editor, or exporter.+// Local Whisper is privacy-safe and also not gated. The new editor ships as+// the default from Phase 1 PR 1.3 onward; this flag is just the AI-features+// opt-in. Renamed from AI_EDITION_ENABLED on 2026-06-26 — see+// docs/architecture/ai-edition-merge-plan.md §0 / §5.9.+export const AI_FEATURES_ENABLED = true;diff --git a/src/components/video-editor/index.ts b/src/components/video-editor/index.tsdeleted file mode 100644index 5afe5b8bf..000000000--- a/src/components/video-editor/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export { default as PlaybackControls } from "./PlaybackControls";-export { default as SettingsPanel } from "./SettingsPanel";-export { default as TimelineEditor } from "./timeline/TimelineEditor";-export { default as VideoEditor } from "./VideoEditor";-export { default as VideoPlayback } from "./VideoPlayback";diff --git a/src/components/video-editor/timeline/BackgroundWaveform.tsx b/src/components/video-editor/timeline/BackgroundWaveform.tsxdeleted file mode 100644index d89a14c40..000000000--- a/src/components/video-editor/timeline/BackgroundWaveform.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { useTimelineContext } from "dnd-timeline";-import { useEffect, useMemo, useRef, useState } from "react";--// Perceptual curve on normalized amplitude; exponent < 1 lifts quiet passages so-// one loud spike doesn't flatten the rest.-const WAVEFORM_GAMMA = 0.6;--export interface BackgroundWaveformProps {- /** Pre-computed peaks: pairs of [min, max] per block (length = 2 * N). */- peaks: Float32Array | null;- videoDurationMs: number;- /** Inset from canvas top so the waveform aligns with item content top. Defaults to 0. */- topInset?: number;- /** Inset from canvas bottom so the waveform aligns with item content bottom. Defaults to 0. */- bottomInset?: number;-}--/**- * Renders a rectified (half-wave) audio waveform on a canvas filling its block.- * Pass as the `background` prop of `<Row>`, which already provides- * `relative overflow-hidden`.- *- * Canvas is always `inset-0` (full row height); vertical alignment comes from- * `topInset`/`bottomInset` in the draw calls, not CSS, so it's immune to- * sub-pixel layout rounding. `pointer-events: none` keeps drag-to-create working.- */-export default function BackgroundWaveform({- peaks,- videoDurationMs,- topInset = 0,- bottomInset = 0,-}: BackgroundWaveformProps) {- const { range } = useTimelineContext();- const canvasRef = useRef<HTMLCanvasElement>(null);- const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 });-- // Normalize against the track's own loudest peak so quiet recordings (mic/system- // audio rarely hit full scale) still fill the row. Recomputed only on peaks change,- // not zoom/pan, so height stays stable while scrolling.- const normFactor = useMemo(() => {- if (!peaks || peaks.length === 0) return 0;- let globalMax = 0;- for (let i = 0; i < peaks.length; i++) {- const a = Math.abs(peaks[i]);- if (a > globalMax) globalMax = a;- }- return globalMax > 0 ? 1 / globalMax : 0;- }, [peaks]);-- // Observe the canvas directly; Row's `relative overflow-hidden` parent makes- // it fill the row exactly, so no wrapper div is needed.- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas) return;- const ro = new ResizeObserver((entries) => {- const { width, height } = entries[0].contentRect;- setCanvasSize({ w: width, h: height });- });- ro.observe(canvas);- return () => ro.disconnect();- }, []);-- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas || canvasSize.w <= 0 || canvasSize.h <= 0) return;-- const dpr = window.devicePixelRatio || 1;- canvas.width = Math.round(canvasSize.w * dpr);- canvas.height = Math.round(canvasSize.h * dpr);-- const ctx = canvas.getContext("2d");- if (!ctx) return;-- ctx.scale(dpr, dpr);- ctx.clearRect(0, 0, canvasSize.w, canvasSize.h);-- if (!peaks || peaks.length === 0 || normFactor === 0) return;-- const W = canvasSize.w;- const H = canvasSize.h;- const rangeMs = range.end - range.start;- if (rangeMs <= 0 || videoDurationMs <= 0) return;-- // Draw within [topY, bottomY] so the waveform aligns with item bounds- // regardless of sub-pixel rounding on the canvas element.- const topY = topInset;- const bottomY = H - bottomInset;- const drawHeight = bottomY - topY;- if (drawHeight <= 0) return;-- const N = peaks.length / 2;- const amp = drawHeight * 0.9;-- // Rectified: amplitude = max(|min|, |max|), normalized to the loudest peak- // and gamma-curved, drawn upward from bottomY.- const colY = new Float32Array(W);- for (let x = 0; x < W; x++) {- const startMs = range.start + (x / W) * rangeMs;- const endMs = range.start + ((x + 1) / W) * rangeMs;- const lo = Math.max(0, Math.floor((startMs / videoDurationMs) * N));- const hi = Math.min(N - 1, Math.ceil((endMs / videoDurationMs) * N));-- let absMax = 0;- for (let i = lo; i <= hi; i++) {- const a = Math.abs(peaks[i * 2]);- const b = Math.abs(peaks[i * 2 + 1]);- if (a > absMax) absMax = a;- if (b > absMax) absMax = b;- }- const normalized = Math.min(1, absMax * normFactor);- const display = normalized > 0 ? normalized ** WAVEFORM_GAMMA : 0;- colY[x] = bottomY - display * amp;- }-- // Filled polygon: bottom-left, up over the silhouette, down to bottom-right.- ctx.beginPath();- ctx.moveTo(0, bottomY);- for (let x = 0; x < W; x++) {- ctx.lineTo(x, colY[x]);- }- ctx.lineTo(W, bottomY);- ctx.closePath();- ctx.fillStyle = "rgba(74, 222, 128, 0.55)";- ctx.fill();-- // Crisp top-edge stroke.- ctx.beginPath();- ctx.moveTo(0, colY[0]);- for (let x = 1; x < W; x++) {- ctx.lineTo(x, colY[x]);- }- ctx.strokeStyle = "rgba(74, 222, 128, 0.85)";- ctx.lineWidth = 1;- ctx.stroke();- }, [peaks, normFactor, range, canvasSize, videoDurationMs, topInset, bottomInset]);-- return <canvas ref={canvasRef} className="absolute inset-0 pointer-events-none w-full h-full" />;-}diff --git a/src/components/video-editor/timeline/Item.module.css b/src/components/video-editor/timeline/Item.module.cssdeleted file mode 100644index e69de29bb..000000000diff --git a/src/components/video-editor/timeline/Item.tsx b/src/components/video-editor/timeline/Item.tsxdeleted file mode 100644index ec4ca084d..000000000--- a/src/components/video-editor/timeline/Item.tsx+++ /dev/null@@ -1,202 +0,0 @@-import type { Span } from "dnd-timeline";-import { useItem } from "dnd-timeline";-import { Gauge, Maximize, MessageSquare, MousePointer2, Scissors, ZoomIn } from "lucide-react";-import { useMemo } from "react";-import { useScopedT } from "@/contexts/I18nContext";-import { cn } from "@/lib/utils";-import glassStyles from "./ItemGlass.module.css";--interface ItemProps {- id: string;- span: Span;- rowId: string;- children: React.ReactNode;- isSelected?: boolean;- onSelect?: () => void;- zoomDepth?: number;- zoomCustomScale?: number;- speedValue?: number;- isAutoFocus?: boolean;- variant?: "zoom" | "camera-fullscreen" | "trim" | "annotation" | "speed" | "blur";-}--// Map zoom depth to multiplier labels-const ZOOM_LABELS: Record<number, string> = {- 1: "1.25×",- 2: "1.5×",- 3: "1.8×",- 4: "2.2×",- 5: "3.5×",- 6: "5×",-};--function formatMs(ms: number): string {- const totalSeconds = ms / 1000;- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- if (minutes > 0) {- return `${minutes}:${seconds.toFixed(1).padStart(4, "0")}`;- }- return `${seconds.toFixed(1)}s`;-}--export default function Item({- id,- span,- rowId,- isSelected = false,- onSelect,- zoomDepth = 1,- zoomCustomScale,- speedValue,- isAutoFocus = false,- variant = "zoom",- children,-}: ItemProps) {- const t = useScopedT("timeline");- const { setNodeRef, attributes, listeners, itemStyle, itemContentStyle } = useItem({- id,- span,- data: { rowId },- });-- const isZoom = variant === "zoom";- const isCameraFullscreen = variant === "camera-fullscreen";- const isTrim = variant === "trim";- const isSpeed = variant === "speed";-- const glassClass = isZoom- ? glassStyles.glassGreen- : isCameraFullscreen- ? glassStyles.glassBlue- : isTrim- ? glassStyles.glassRed- : isSpeed- ? glassStyles.glassAmber- : glassStyles.glassYellow;-- const endCapColor = isZoom- ? "#21916A"- : isCameraFullscreen- ? "#0ea5e9"- : isTrim- ? "#ef4444"- : isSpeed- ? "#d97706"- : "#B4A046";-- const timeLabel = useMemo(- () => `${formatMs(span.start)} – ${formatMs(span.end)}`,- [span.start, span.end],- );-- // Minimum clickable width on the outer wrapper. Kept small so items keep their real- // positions; zoom in to interact with sub-second items precisely.- const MIN_ITEM_PX = 6;- const safeItemStyle = { ...itemStyle, minWidth: MIN_ITEM_PX };-- return (- <div- ref={setNodeRef}- style={safeItemStyle}- {...listeners}- {...attributes}- onPointerDownCapture={() => onSelect?.()}- className="group"- >- <div style={{ ...itemContentStyle, minWidth: 24 }}>- <div- className={cn(- glassClass,- "w-full h-full overflow-hidden flex items-center justify-center gap-1.5 cursor-grab active:cursor-grabbing relative",- isSelected && glassStyles.selected,- )}- style={{ height: 30, color: "#fff", minWidth: 24 }}- onClick={(event) => {- event.stopPropagation();- onSelect?.();- }}- >- <div- className={cn(glassStyles.zoomEndCap, glassStyles.left)}- style={{- cursor: "col-resize",- pointerEvents: "auto",- width: 8,- opacity: 0.9,- background: endCapColor,- }}- title="Resize left"- />- <div- className={cn(glassStyles.zoomEndCap, glassStyles.right)}- style={{- cursor: "col-resize",- pointerEvents: "auto",- width: 8,- opacity: 0.9,- background: endCapColor,- }}- title="Resize right"- />- {/* Content */}- <div className="relative z-10 flex min-w-0 flex-col items-center justify-center text-white/90 opacity-85 group-hover:opacity-100 transition-opacity select-none overflow-hidden px-3">- <div className="flex items-center gap-1.5">- {isZoom ? (- <>- <ZoomIn className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold whitespace-nowrap">- {zoomCustomScale != null- ? `${zoomCustomScale.toFixed(2)}×`- : ZOOM_LABELS[zoomDepth] || `${zoomDepth}×`}- </span>- {isAutoFocus && (- <MousePointer2- className="w-3 h-3 shrink-0 opacity-90"- aria-label="Cursor-follow"- />- )}- </>- ) : isCameraFullscreen ? (- <>- <Maximize className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold whitespace-nowrap">- {t("labels.cameraFullscreen")}- </span>- </>- ) : isTrim ? (- <>- <Scissors className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold whitespace-nowrap">- {t("labels.trim")}- </span>- </>- ) : isSpeed ? (- <>- <Gauge className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold whitespace-nowrap">- {speedValue !== undefined ? `${speedValue}×` : t("labels.speed")}- </span>- </>- ) : (- <>- <MessageSquare className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold truncate whitespace-nowrap">- {children}- </span>- </>- )}- </div>- <span- className={`text-[9px] tabular-nums tracking-tight whitespace-nowrap transition-opacity ${- isSelected ? "opacity-60" : "opacity-0 group-hover:opacity-40"- }`}- >- {timeLabel}- </span>- </div>- </div>- </div>- </div>- );-}diff --git a/src/components/video-editor/timeline/ItemGlass.module.css b/src/components/video-editor/timeline/ItemGlass.module.cssdeleted file mode 100644index 94fcbadee..000000000--- a/src/components/video-editor/timeline/ItemGlass.module.css+++ /dev/null@@ -1,179 +0,0 @@-.glassGreen {- position: relative;- border-radius: 10px;- -corner-smoothing: antialiased;- background: linear-gradient(180deg, rgba(52, 178, 123, 0.28), rgba(31, 115, 82, 0.2));- border: 1px solid rgba(77, 221, 157, 0.36);- box-shadow:- 0 1px 0 rgba(255, 255, 255, 0.1) inset,- 0 8px 22px rgba(0, 0, 0, 0.22);- margin: 3px 0;- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassGreen:hover {- background: linear-gradient(180deg, rgba(52, 178, 123, 0.36), rgba(31, 115, 82, 0.25));- border-color: rgba(77, 221, 157, 0.62);-}--.glassGreen.selected {- background: linear-gradient(180deg, rgba(52, 178, 123, 0.48), rgba(31, 115, 82, 0.32));- border-color: #34b27b;- box-shadow:- 0 0 0 1px rgba(52, 178, 123, 0.95),- 0 0 0 4px rgba(52, 178, 123, 0.14),- 0 12px 26px rgba(0, 0, 0, 0.28);- z-index: 10;-}--.glassRed {- position: relative;- border-radius: 10px;- -corner-smoothing: antialiased;- background: rgba(239, 68, 68, 0.15);- border: 1px solid rgba(239, 68, 68, 0.3);- box-shadow: 0 2px 12px 0 rgba(239, 68, 68, 0.1) inset;- margin: 3px 0;- backdrop-filter: blur(4px);- -webkit-backdrop-filter: blur(4px);- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassRed:hover {- background: rgba(239, 68, 68, 0.25);- border-color: rgba(239, 68, 68, 0.5);- box-shadow: 0 4px 20px 0 rgba(239, 68, 68, 0.2) inset;-}--.glassRed.selected {- background: rgba(239, 68, 68, 0.35);- border-color: #ef4444;- box-shadow:- 0 0 0 1px #ef4444,- 0 4px 20px 0 rgba(239, 68, 68, 0.3) inset;- z-index: 10;-}--.glassYellow {- position: relative;- border-radius: 10px;- -corner-smoothing: antialiased;- background: rgba(180, 160, 70, 0.15);- border: 1px solid rgba(180, 160, 70, 0.3);- box-shadow: 0 2px 12px 0 rgba(180, 160, 70, 0.1) inset;- margin: 3px 0;- backdrop-filter: blur(4px);- -webkit-backdrop-filter: blur(4px);- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassYellow:hover {- background: rgba(180, 160, 70, 0.25);- border-color: rgba(180, 160, 70, 0.5);- box-shadow: 0 4px 20px 0 rgba(180, 160, 70, 0.2) inset;-}--.glassYellow.selected {- background: rgba(180, 160, 70, 0.35);- border-color: #b4a046;- box-shadow:- 0 0 0 1px #b4a046,- 0 4px 20px 0 rgba(180, 160, 70, 0.3) inset;- z-index: 10;-}--.glassAmber {- position: relative;- border-radius: 10px;- -corner-smoothing: antialiased;- background: rgba(245, 158, 11, 0.15);- border: 1px solid rgba(245, 158, 11, 0.3);- box-shadow: 0 2px 12px 0 rgba(245, 158, 11, 0.1) inset;- margin: 3px 0;- backdrop-filter: blur(4px);- -webkit-backdrop-filter: blur(4px);- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassAmber:hover {- background: rgba(245, 158, 11, 0.25);- border-color: rgba(245, 158, 11, 0.5);- box-shadow: 0 4px 20px 0 rgba(245, 158, 11, 0.2) inset;-}--.glassAmber.selected {- background: rgba(245, 158, 11, 0.35);- border-color: #f59e0b;- box-shadow:- 0 0 0 1px #f59e0b,- 0 4px 20px 0 rgba(245, 158, 11, 0.3) inset;- z-index: 10;-}--.glassBlue {- position: relative;- border-radius: 10px;- -corner-smoothing: antialiased;- background: linear-gradient(180deg, rgba(56, 189, 248, 0.28), rgba(14, 116, 144, 0.2));- border: 1px solid rgba(56, 189, 248, 0.36);- box-shadow:- 0 1px 0 rgba(255, 255, 255, 0.1) inset,- 0 8px 22px rgba(0, 0, 0, 0.22);- margin: 3px 0;- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassBlue:hover {- background: linear-gradient(180deg, rgba(56, 189, 248, 0.36), rgba(14, 116, 144, 0.25));- border-color: rgba(56, 189, 248, 0.62);-}--.glassBlue.selected {- background: linear-gradient(180deg, rgba(56, 189, 248, 0.48), rgba(14, 116, 144, 0.32));- border-color: #38bdf8;- box-shadow:- 0 0 0 1px rgba(56, 189, 248, 0.95),- 0 0 0 4px rgba(56, 189, 248, 0.14),- 0 12px 26px rgba(0, 0, 0, 0.28);- z-index: 10;-}--.zoomEndCap {- position: absolute;- top: 0;- bottom: 0;- width: 4px;- pointer-events: none;- z-index: 2;- opacity: 0.45;- transition:- opacity 0.2s,- width 0.2s;-}--.glassGreen:hover .zoomEndCap,-.glassGreen.selected .zoomEndCap,-.glassRed:hover .zoomEndCap,-.glassRed.selected .zoomEndCap,-.glassYellow:hover .zoomEndCap,-.glassYellow.selected .zoomEndCap,-.glassAmber:hover .zoomEndCap,-.glassAmber.selected .zoomEndCap,-.glassBlue:hover .zoomEndCap,-.glassBlue.selected .zoomEndCap {- opacity: 1;-}--.zoomEndCap.left {- left: 0;- cursor: ew-resize;- border-top-left-radius: 9px;- border-bottom-left-radius: 9px;-}--.zoomEndCap.right {- right: 0;- cursor: ew-resize;- border-top-right-radius: 9px;- border-bottom-right-radius: 9px;-}diff --git a/src/components/video-editor/timeline/KeyframeMarkers.tsx b/src/components/video-editor/timeline/KeyframeMarkers.tsxdeleted file mode 100644index 9aca714a8..000000000--- a/src/components/video-editor/timeline/KeyframeMarkers.tsx+++ /dev/null@@ -1,114 +0,0 @@-import { useTimelineContext } from "dnd-timeline";-import React, { useEffect, useState } from "react";--interface Keyframe {- id: string;- time: number;-}--interface KeyframeMarkersProps {- keyframes: Keyframe[];- selectedKeyframeId: string | null;- setSelectedKeyframeId: (id: string | null) => void;- onKeyframeMove: (id: string, newTime: number) => void;- videoDurationMs: number;- timelineRef: React.RefObject<HTMLDivElement>;-}--const KeyframeMarkers: React.FC<KeyframeMarkersProps> = ({- keyframes,- selectedKeyframeId,- setSelectedKeyframeId,- onKeyframeMove,- videoDurationMs,- timelineRef,-}) => {- const { sidebarWidth, range, valueToPixels, pixelsToValue } = useTimelineContext();- const [draggingKeyframeId, setDraggingKeyframeId] = useState<string | null>(null);-- useEffect(() => {- if (!draggingKeyframeId) return;-- const handleMouseMove = (e: MouseEvent) => {- if (!timelineRef.current) return;-- const rect = timelineRef.current.getBoundingClientRect();- const clickX = e.clientX - rect.left - sidebarWidth;- const relativeMs = pixelsToValue(clickX);- const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- // Update the keyframe position in real-time- onKeyframeMove(draggingKeyframeId, absoluteMs);- };-- const handleMouseUp = () => {- setDraggingKeyframeId(null);- document.body.style.cursor = "";- };-- window.addEventListener("mousemove", handleMouseMove);- window.addEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "ew-resize";-- return () => {- window.removeEventListener("mousemove", handleMouseMove);- window.removeEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "";- };- }, [- draggingKeyframeId,- onKeyframeMove,- timelineRef,- sidebarWidth,- range.start,- videoDurationMs,- pixelsToValue,- ]);-- return (- <>- {keyframes.map((kf) => {- const offset = valueToPixels(kf.time - range.start);- const isSelected = kf.id === selectedKeyframeId;- const isDragging = kf.id === draggingKeyframeId;-- return (- <div- key={kf.id}- className={`absolute top-8 cursor-grab active:cursor-grabbing ${isSelected ? "ring-2 ring-[#34B27B]" : ""}`}- style={{- left: `${sidebarWidth + offset - 8}px`,- zIndex: isDragging ? 50 : 40,- transition: isDragging ? "none" : "left 0.1s ease-out",- }}- onMouseDown={(e) => {- e.stopPropagation();- setSelectedKeyframeId(kf.id);- setDraggingKeyframeId(kf.id);- }}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- setSelectedKeyframeId(kf.id);- }}- title={`Keyframe @ ${Math.round(kf.time)}ms (drag to move, Delete/Backspace to remove)`}- >- <div- style={{- width: "10px",- height: "10px",- background: "#ffe100ff",- transform: "rotate(45deg)",- border: "none",- opacity: isSelected ? 1 : 0.6,- transition: "opacity 0.15s",- }}- />- </div>- );- })}- </>- );-};--export default KeyframeMarkers;diff --git a/src/components/video-editor/timeline/Row.tsx b/src/components/video-editor/timeline/Row.tsxdeleted file mode 100644index a0b00c9a5..000000000--- a/src/components/video-editor/timeline/Row.tsx+++ /dev/null@@ -1,34 +0,0 @@-import type { RowDefinition } from "dnd-timeline";-import { useRow } from "dnd-timeline";--interface RowProps extends RowDefinition {- children: React.ReactNode;- hint?: string;- isEmpty?: boolean;- background?: React.ReactNode;-}--/**- * A horizontal timeline lane. Wraps dnd-timeline's `useRow` and adds an optional- * `background` layer, an empty-state hint label, and a minimum height.- */-export default function Row({ id, children, hint, isEmpty, background }: RowProps) {- const { setNodeRef, rowWrapperStyle, rowStyle } = useRow({ id });-- return (- <div- className="border-b border-white/[0.055] bg-[#101116] relative overflow-hidden"- style={{ ...rowWrapperStyle, minHeight: 36 }}- >- {background}- {isEmpty && hint && (- <div className="absolute inset-0 flex items-center justify-center pointer-events-none select-none z-10">- <span className="text-[11px] text-white/[0.12] font-medium">{hint}</span>- </div>- )}- <div ref={setNodeRef} style={rowStyle}>- {children}- </div>- </div>- );-}diff --git a/src/components/video-editor/timeline/Subrow.tsx b/src/components/video-editor/timeline/Subrow.tsxdeleted file mode 100644index 5ea7ad76a..000000000--- a/src/components/video-editor/timeline/Subrow.tsx+++ /dev/null@@ -1,17 +0,0 @@-import { cn } from "@/lib/utils";--interface SubrowProps {- children: React.ReactNode;-}--export default function Subrow({ children }: SubrowProps) {- return (- <div- className={cn(- "flex items-center min-h-[32px] gap-1 px-2 py-0.5 bg-[#23232a] rounded-md text-slate-300",- )}- >- {children}- </div>- );-}diff --git a/src/components/video-editor/timeline/TimelineEditor.tsx b/src/components/video-editor/timeline/TimelineEditor.tsxdeleted file mode 100644index 242714a86..000000000--- a/src/components/video-editor/timeline/TimelineEditor.tsx+++ /dev/null@@ -1,1873 +0,0 @@-import type { Range, Span } from "dnd-timeline";-import { useTimelineContext } from "dnd-timeline";-import {- Captions,- Check,- ChevronDown,- Gauge,- Maximize,- MessageSquare,- Plus,- ScanEye,- Scissors,- WandSparkles,- ZoomIn,-} from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { toast } from "sonner";-import { v4 as uuidv4 } from "uuid";-import { Button } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { useScopedT } from "@/contexts/I18nContext";-import { useShortcuts } from "@/contexts/ShortcutsContext";-import { useAudioPeaks } from "@/hooks/useAudioPeaks";-import { isTextEditingTarget, matchesShortcut } from "@/lib/shortcuts";-import { cn } from "@/lib/utils";-import { ASPECT_RATIOS, type AspectRatio, getAspectRatioLabel } from "@/utils/aspectRatioUtils";-import { formatShortcut } from "@/utils/platformUtils";-import { BLUR_REGIONS_ENABLED } from "../featureFlags";-import { findFreeGapAt } from "../regionPlacement";-import type {- AnnotationRegion,- CameraFullscreenRegion,- SpeedRegion,- TrimRegion,- ZoomRegion,-} from "../types";-import BackgroundWaveform from "./BackgroundWaveform";-import Item from "./Item";-import KeyframeMarkers from "./KeyframeMarkers";-import Row from "./Row";-import TimelineWrapper from "./TimelineWrapper";--const ZOOM_ROW_ID = "row-zoom";-const CAMERA_ROW_ID = "row-camera-fullscreen";-const TRIM_ROW_ID = "row-trim";-const ANNOTATION_ROW_ID = "row-annotation";-const BLUR_ROW_ID = "row-blur";-const SPEED_ROW_ID = "row-speed";-const FALLBACK_RANGE_MS = 1000;-const TARGET_MARKER_COUNT = 12;--interface TimelineEditorProps {- videoDuration: number;- hasVideoSource?: boolean;- currentTime: number;- /**- * Reads the live playhead position (ms) directly, bypassing `currentTime` React- * state. The playhead subscribes to this via its own rAF loop so it stays in sync- * with actual playback regardless of how long an ancestor's re-render takes.- */- getPlaybackTimeMs?: () => number;- onSeek?: (time: number) => void;- zoomRegions: ZoomRegion[];- onZoomAdded: (span: Span) => void;- /** Magic-wand auto-zoom toggle state + handler. */- autoZoomEnabled?: boolean;- onToggleAutoZoom?: (enabled: boolean) => void;- /** Global Auto-Focus toggle state + handler. */- autoFocusAll?: boolean;- onToggleAutoFocusAll?: (on: boolean) => void;- onZoomSpanChange: (id: string, span: Span) => void;- onZoomDelete: (id: string) => void;- selectedZoomId: string | null;- onSelectZoom: (id: string | null) => void;- cameraFullscreenRegions?: CameraFullscreenRegion[];- onCameraFullscreenAdded?: (span: Span) => void;- onCameraFullscreenSpanChange?: (id: string, span: Span) => void;- onCameraFullscreenDelete?: (id: string) => void;- selectedCameraFullscreenId?: string | null;- onSelectCameraFullscreen?: (id: string | null) => void;- trimRegions?: TrimRegion[];- onTrimAdded?: (span: Span) => void;- onTrimSpanChange?: (id: string, span: Span) => void;- onTrimDelete?: (id: string) => void;- selectedTrimId?: string | null;- onSelectTrim?: (id: string | null) => void;- annotationRegions?: AnnotationRegion[];- onAnnotationAdded?: (span: Span) => void;- onAnnotationSpanChange?: (id: string, span: Span) => void;- onAnnotationDelete?: (id: string) => void;- selectedAnnotationId?: string | null;- onSelectAnnotation?: (id: string | null) => void;- blurRegions?: AnnotationRegion[];- onBlurAdded?: (span: Span) => void;- onBlurSpanChange?: (id: string, span: Span) => void;- onBlurDelete?: (id: string) => void;- selectedBlurId?: string | null;- onSelectBlur?: (id: string | null) => void;- speedRegions?: SpeedRegion[];- onSpeedAdded?: (span: Span) => void;- onSpeedSpanChange?: (id: string, span: Span) => void;- onSpeedDelete?: (id: string) => void;- selectedSpeedId?: string | null;- onSelectSpeed?: (id: string | null) => void;- aspectRatio: AspectRatio;- onAspectRatioChange: (aspectRatio: AspectRatio) => void;- videoUrl?: string;- showTrimWaveform?: boolean;- /** Opens the auto-captions flow. When omitted, the captions button is hidden. */- onGenerateCaptions?: () => void;- isGeneratingCaptions?: boolean;- /** Localized label for the auto-captions button (lives in the `editor` namespace). */- captionsLabel?: string;-}--interface TimelineScaleConfig {- minItemDurationMs: number;- defaultItemDurationMs: number;- minVisibleRangeMs: number;-}--interface TimelineRenderItem {- id: string;- rowId: string;- span: Span;- label: string;- zoomDepth?: number;- zoomCustomScale?: number;- speedValue?: number;- isAutoFocus?: boolean;- variant: "zoom" | "camera-fullscreen" | "trim" | "annotation" | "speed" | "blur";-}--const SCALE_CANDIDATES = [- { intervalSeconds: 0.05, gridSeconds: 0.01 },- { intervalSeconds: 0.1, gridSeconds: 0.02 },- { intervalSeconds: 0.25, gridSeconds: 0.05 },- { intervalSeconds: 0.5, gridSeconds: 0.1 },- { intervalSeconds: 1, gridSeconds: 0.25 },- { intervalSeconds: 2, gridSeconds: 0.5 },- { intervalSeconds: 5, gridSeconds: 1 },- { intervalSeconds: 10, gridSeconds: 2 },- { intervalSeconds: 15, gridSeconds: 3 },- { intervalSeconds: 30, gridSeconds: 5 },- { intervalSeconds: 60, gridSeconds: 10 },- { intervalSeconds: 120, gridSeconds: 20 },- { intervalSeconds: 300, gridSeconds: 30 },- { intervalSeconds: 600, gridSeconds: 60 },- { intervalSeconds: 900, gridSeconds: 120 },- { intervalSeconds: 1800, gridSeconds: 180 },- { intervalSeconds: 3600, gridSeconds: 300 },-];--/**- * Picks the best axis interval for the currently visible time range, so marker- * density stays meaningful regardless of video length.- */-function calculateAxisScale(visibleRangeMs: number): { intervalMs: number; gridMs: number } {- const visibleSeconds = visibleRangeMs / 1000;- const candidate =- SCALE_CANDIDATES.find((c) => {- if (visibleSeconds <= 0) return true;- return visibleSeconds / c.intervalSeconds <= TARGET_MARKER_COUNT;- }) ?? SCALE_CANDIDATES[SCALE_CANDIDATES.length - 1];- return {- intervalMs: Math.round(candidate.intervalSeconds * 1000),- gridMs: Math.round(candidate.gridSeconds * 1000),- };-}--function calculateTimelineScale(durationSeconds: number): TimelineScaleConfig {- const totalMs = Math.max(0, Math.round(durationSeconds * 1000));-- // 100ms, precise enough to cut but still grabbable.- const minItemDurationMs = 100;-- // 5% of duration, clamped to 1-30s.- const defaultItemDurationMs =- totalMs > 0- ? Math.max(minItemDurationMs, Math.min(Math.round(totalMs * 0.05), 30000))- : Math.max(minItemDurationMs, 1000);-- // 300ms, enough to view 0.1s items comfortably. Axis markers adapt via- // calculateAxisScale, so there's no cap on zoom-in.- const minVisibleRangeMs = 300;-- return {- minItemDurationMs,- defaultItemDurationMs,- minVisibleRangeMs,- };-}--function createInitialRange(totalMs: number): Range {- if (totalMs > 0) {- return { start: 0, end: totalMs };- }-- return { start: 0, end: FALLBACK_RANGE_MS };-}--function clampVisibleRange(candidate: Range, totalMs: number): Range {- if (totalMs <= 0) {- return candidate;- }-- const span = Math.max(candidate.end - candidate.start, 1);-- if (span >= totalMs) {- return { start: 0, end: totalMs };- }-- const start = Math.max(0, Math.min(candidate.start, totalMs - span));- return { start, end: start + span };-}--function normalizeWheelDelta(delta: number, deltaMode: number, pageSizePx: number): number {- if (deltaMode === WheelEvent.DOM_DELTA_LINE) {- return delta * 16;- }-- if (deltaMode === WheelEvent.DOM_DELTA_PAGE) {- return delta * pageSizePx;- }-- return delta;-}--function formatTimeLabel(milliseconds: number, intervalMs: number) {- const totalSeconds = milliseconds / 1000;- const hours = Math.floor(totalSeconds / 3600);- const minutes = Math.floor((totalSeconds % 3600) / 60);- const seconds = totalSeconds % 60;-- const fractionalDigits = intervalMs < 250 ? 2 : intervalMs < 1000 ? 1 : 0;-- if (hours > 0) {- const minutesString = minutes.toString().padStart(2, "0");- const secondsString = Math.floor(seconds).toString().padStart(2, "0");- return `${hours}:${minutesString}:${secondsString}`;- }-- if (fractionalDigits > 0) {- const secondsWithFraction = seconds.toFixed(fractionalDigits);- const [wholeSeconds, fraction] = secondsWithFraction.split(".");- return `${minutes}:${wholeSeconds.padStart(2, "0")}.${fraction}`;- }-- return `${minutes}:${Math.floor(seconds).toString().padStart(2, "0")}`;-}--function formatPlayheadTime(ms: number): string {- const s = ms / 1000;- const min = Math.floor(s / 60);- const sec = s % 60;- if (min > 0) return `${min}:${sec.toFixed(1).padStart(4, "0")}`;- return `${sec.toFixed(1)}s`;-}--function shouldStartTimelineScrub(target: EventTarget | null, timelineElement: HTMLElement) {- if (!(target instanceof HTMLElement)) {- return false;- }-- for (let element: HTMLElement | null = target; element && element !== timelineElement; ) {- const className = element.className;- const classText = typeof className === "string" ? className : "";-- if (- classText.split(/\s+/).includes("group") ||- classText.includes("cursor-grab") ||- classText.includes("cursor-grabbing") ||- classText.includes("cursor-ew-resize") ||- element.style.cursor === "col-resize"- ) {- return false;- }-- element = element.parentElement;- }-- return true;-}--function PlaybackCursor({- currentTimeMs,- videoDurationMs,- getPlaybackTimeMs,- onSeek,- onRangeChange,- timelineRef,- keyframes = [],-}: {- currentTimeMs: number;- videoDurationMs: number;- getPlaybackTimeMs?: () => number;- onSeek?: (time: number) => void;- onRangeChange?: (updater: (previous: Range) => Range) => void;- timelineRef: React.RefObject<HTMLDivElement>;- keyframes?: { id: string; time: number }[];-}) {- const { sidebarWidth, direction, range, valueToPixels, pixelsToValue } = useTimelineContext();- const sideProperty = direction === "rtl" ? "right" : "left";- const [isDragging, setIsDragging] = useState(false);- const [dragPreviewTimeMs, setDragPreviewTimeMs] = useState<number | null>(null);-- // Drives the playhead position from the video element every animation frame,- // isolated from the rest of the tree: this component's own `useState` call only- // re-renders this small subtree, not TimelineEditor/VideoEditor above it. That- // decoupling is what keeps the playhead glued to actual playback even while an- // ancestor's (much heavier) re-render is in flight — see issue #111.- const [liveTimeMs, setLiveTimeMs] = useState(currentTimeMs);- const getPlaybackTimeMsRef = useRef(getPlaybackTimeMs);- useEffect(() => {- getPlaybackTimeMsRef.current = getPlaybackTimeMs;- }, [getPlaybackTimeMs]);-- useEffect(() => {- if (!getPlaybackTimeMsRef.current) {- return;- }-- let rafId: number;- const tick = () => {- const getter = getPlaybackTimeMsRef.current;- if (getter) {- const latest = getter();- setLiveTimeMs((previous) => (previous === latest ? previous : latest));- }- rafId = requestAnimationFrame(tick);- };- rafId = requestAnimationFrame(tick);-- return () => cancelAnimationFrame(rafId);- }, []);-- const resolvedTimeMs = getPlaybackTimeMs ? liveTimeMs : currentTimeMs;-- useEffect(() => {- if (!isDragging) return;-- const handleMouseMove = (e: MouseEvent) => {- if (!timelineRef.current || !onSeek) return;-- const rect = timelineRef.current.getBoundingClientRect();- const clickX = e.clientX - rect.left - sidebarWidth;- const contentWidth = Math.max(rect.width - sidebarWidth, 1);-- // Allow dragging past the edges, but clamp the value- const relativeMs = pixelsToValue(clickX);- let absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- // Snap to a keyframe within 150ms- const snapThresholdMs = 150;- const nearbyKeyframe = keyframes.find(- (kf) =>- Math.abs(kf.time - absoluteMs) <= snapThresholdMs &&- kf.time >= range.start &&- kf.time <= range.end,- );-- if (nearbyKeyframe) {- absoluteMs = nearbyKeyframe.time;- }-- setDragPreviewTimeMs(absoluteMs);-- const visibleMs = range.end - range.start;- if (onRangeChange && visibleMs > 0 && videoDurationMs > visibleMs) {- const msPerPixel = visibleMs / contentWidth;- const overflowLeftPx = Math.max(0, -clickX);- const overflowRightPx = Math.max(0, clickX - contentWidth);-- if (overflowLeftPx > 0 && range.start > 0) {- const shiftMs = overflowLeftPx * msPerPixel;- onRangeChange((previous) => {- const nextRange = clampVisibleRange(- {- start: previous.start - shiftMs,- end: previous.end - shiftMs,- },- videoDurationMs,- );- return nextRange.start === previous.start && nextRange.end === previous.end- ? previous- : nextRange;- });- } else if (overflowRightPx > 0 && range.end < videoDurationMs) {- const shiftMs = overflowRightPx * msPerPixel;- onRangeChange((previous) => {- const nextRange = clampVisibleRange(- {- start: previous.start + shiftMs,- end: previous.end + shiftMs,- },- videoDurationMs,- );- return nextRange.start === previous.start && nextRange.end === previous.end- ? previous- : nextRange;- });- }- }-- onSeek(absoluteMs / 1000);- };-- const handleMouseUp = () => {- setIsDragging(false);- setDragPreviewTimeMs(null);- document.body.style.cursor = "";- };-- window.addEventListener("mousemove", handleMouseMove);- window.addEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "ew-resize";-- return () => {- window.removeEventListener("mousemove", handleMouseMove);- window.removeEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "";- };- }, [- isDragging,- onSeek,- onRangeChange,- timelineRef,- sidebarWidth,- range.start,- range.end,- videoDurationMs,- pixelsToValue,- keyframes,- ]);-- const displayTimeMs =- isDragging && dragPreviewTimeMs !== null ? dragPreviewTimeMs : resolvedTimeMs;-- if (videoDurationMs <= 0 || displayTimeMs < 0) {- return null;- }-- const clampedTime = Math.min(displayTimeMs, videoDurationMs);-- if (clampedTime < range.start || clampedTime > range.end) {- return null;- }-- const offset = valueToPixels(clampedTime - range.start);-- return (- <div- className="absolute top-0 bottom-0 z-50 group/cursor"- style={{- [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth - 1}px`,- pointerEvents: "none", // pass clicks through to the timeline; the handle re-enables them- }}- >- <div- className="absolute top-0 bottom-0 w-[2px] bg-[#6C55FF] shadow-[0_0_18px_rgba(108,85,255,0.68)] cursor-ew-resize pointer-events-auto hover:shadow-[0_0_24px_rgba(108,85,255,0.85)] transition-shadow"- style={{- [sideProperty]: `${offset}px`,- }}- onMouseDown={(e) => {- e.stopPropagation(); // Prevent timeline click- setDragPreviewTimeMs(resolvedTimeMs);- setIsDragging(true);- }}- >- <div- className="absolute -top-2 left-1/2 -translate-x-1/2 hover:scale-110 transition-transform"- style={{ width: "20px", height: "20px" }}- >- <div className="w-4 h-4 mx-auto mt-[2px] bg-[#6C55FF] rotate-45 rounded-[5px] shadow-lg shadow-[#6C55FF]/30 border border-white/30" />- </div>- {isDragging && (- <div className="absolute -top-6 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-black/80 text-[10px] text-white/90 font-medium tabular-nums whitespace-nowrap border border-white/10 shadow-lg pointer-events-none">- {formatPlayheadTime(clampedTime)}- </div>- )}- </div>- </div>- );-}--function TimelineAxis({- videoDurationMs,- currentTimeMs,-}: {- videoDurationMs: number;- currentTimeMs: number;-}) {- const { sidebarWidth, direction, range, valueToPixels } = useTimelineContext();- const sideProperty = direction === "rtl" ? "right" : "left";-- const { intervalMs } = useMemo(- () => calculateAxisScale(range.end - range.start),- [range.end, range.start],- );-- const markers = useMemo(() => {- if (intervalMs <= 0) {- return { markers: [], minorTicks: [] };- }-- const maxTime = videoDurationMs > 0 ? videoDurationMs : range.end;- const visibleStart = Math.max(0, Math.min(range.start, maxTime));- const visibleEnd = Math.min(range.end, maxTime);- const markerTimes = new Set<number>();-- const firstMarker = Math.ceil(visibleStart / intervalMs) * intervalMs;-- for (let time = firstMarker; time <= maxTime; time += intervalMs) {- if (time >= visibleStart && time <= visibleEnd) {- markerTimes.add(Math.round(time));- }- }-- if (visibleStart <= maxTime) {- markerTimes.add(Math.round(visibleStart));- }-- if (videoDurationMs > 0) {- markerTimes.add(Math.round(videoDurationMs));- }-- const sorted = Array.from(markerTimes)- .filter((time) => time <= maxTime)- .sort((a, b) => a - b);-- // 4 minor ticks between major intervals- const minorTicks = [];- const minorInterval = intervalMs / 5;-- for (let time = firstMarker; time <= maxTime; time += minorInterval) {- if (time >= visibleStart && time <= visibleEnd) {- const isMajor = Math.abs(time % intervalMs) < 1;- if (!isMajor) {- minorTicks.push(time);- }- }- }-- return {- markers: sorted.map((time) => ({- time,- label: formatTimeLabel(time, intervalMs),- })),- minorTicks,- };- }, [intervalMs, range.end, range.start, videoDurationMs]);-- return (- <div- className="h-9 bg-[#0c0d10] border-b border-white/[0.07] relative overflow-hidden select-none"- style={{- [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth}px`,- }}- >- {/* Minor Ticks */}- {markers.minorTicks.map((time) => {- const offset = valueToPixels(time - range.start);- return (- <div- key={`minor-${time}`}- className="absolute bottom-0 h-1.5 w-[1px] bg-white/[0.07]"- style={{ [sideProperty]: `${offset}px` }}- />- );- })}-- {/* Major Markers */}- {markers.markers.map((marker) => {- const offset = valueToPixels(marker.time - range.start);- const markerStyle: React.CSSProperties = {- position: "absolute",- bottom: 0,- height: "100%",- display: "flex",- flexDirection: "row",- alignItems: "flex-end",- [sideProperty]: `${offset}px`,- };-- return (- <div key={marker.time} style={markerStyle}>- <div className="flex flex-col items-center pb-1">- <div className="h-2.5 w-[1px] bg-white/20 mb-1" />- <span- className={cn(- "text-[10px] font-medium tabular-nums tracking-tight",- marker.time === currentTimeMs ? "text-[#34B27B]" : "text-slate-500",- )}- >- {marker.label}- </span>- </div>- </div>- );- })}- </div>- );-}--function Timeline({- items,- videoDurationMs,- currentTimeMs,- getPlaybackTimeMs,- onSeek,- onRangeChange,- onSelectZoom,- onSelectCameraFullscreen,- onSelectTrim,- onSelectAnnotation,- onSelectBlur,- onSelectSpeed,- selectedZoomId,- selectedCameraFullscreenId,- selectedTrimId,- selectedAnnotationId,- selectedBlurId,- selectedSpeedId,- keyframes = [],- videoUrl,- showTrimWaveform = false,-}: {- items: TimelineRenderItem[];- videoDurationMs: number;- currentTimeMs: number;- getPlaybackTimeMs?: () => number;- onSeek?: (time: number) => void;- onRangeChange?: (updater: (previous: Range) => Range) => void;- onSelectZoom?: (id: string | null) => void;- onSelectCameraFullscreen?: (id: string | null) => void;- onSelectTrim?: (id: string | null) => void;- onSelectAnnotation?: (id: string | null) => void;- onSelectBlur?: (id: string | null) => void;- onSelectSpeed?: (id: string | null) => void;- selectedZoomId: string | null;- selectedCameraFullscreenId?: string | null;- selectedTrimId?: string | null;- selectedAnnotationId?: string | null;- selectedBlurId?: string | null;- selectedSpeedId?: string | null;- keyframes?: { id: string; time: number }[];- videoUrl?: string;- showTrimWaveform?: boolean;-}) {- const t = useScopedT("timeline");- const { setTimelineRef, style, sidebarWidth, range, pixelsToValue } = useTimelineContext();- const localTimelineRef = useRef<HTMLDivElement | null>(null);- const isScrubbingTimelineRef = useRef(false);- const scrubPointerIdRef = useRef<number | null>(null);- const peaks = useAudioPeaks(showTrimWaveform ? videoUrl : undefined);-- const setRefs = useCallback(- (node: HTMLDivElement | null) => {- setTimelineRef(node);- localTimelineRef.current = node;- },- [setTimelineRef],- );-- const seekTimelineAtClientX = useCallback(- (timelineElement: HTMLDivElement, clientX: number) => {- if (!onSeek || videoDurationMs <= 0) return false;-- const rect = timelineElement.getBoundingClientRect();- const clickX = clientX - rect.left - sidebarWidth;-- if (clickX < 0) return false;-- const relativeMs = pixelsToValue(clickX);- const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- onSeek(absoluteMs / 1000);- return true;- },- [onSeek, videoDurationMs, sidebarWidth, pixelsToValue, range.start],- );-- const clearTimelineSelection = useCallback(() => {- onSelectZoom?.(null);- onSelectCameraFullscreen?.(null);- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectBlur?.(null);- onSelectSpeed?.(null);- }, [- onSelectZoom,- onSelectCameraFullscreen,- onSelectTrim,- onSelectAnnotation,- onSelectBlur,- onSelectSpeed,- ]);-- const handleTimelineClick = useCallback(- (e: React.MouseEvent<HTMLDivElement>) => {- // Items stop propagation, so this only fires on empty space- clearTimelineSelection();- seekTimelineAtClientX(e.currentTarget, e.clientX);- },- [clearTimelineSelection, seekTimelineAtClientX],- );-- const handleTimelinePointerDown = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- if (!e.isPrimary || (e.pointerType === "mouse" && e.button !== 0)) {- return;- }-- if (!shouldStartTimelineScrub(e.target, e.currentTarget)) {- return;- }-- if (!seekTimelineAtClientX(e.currentTarget, e.clientX)) {- return;- }-- clearTimelineSelection();- isScrubbingTimelineRef.current = true;- scrubPointerIdRef.current = e.pointerId;- e.currentTarget.setPointerCapture(e.pointerId);- e.preventDefault();- },- [clearTimelineSelection, seekTimelineAtClientX],- );-- const handleTimelinePointerMove = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- if (!isScrubbingTimelineRef.current || scrubPointerIdRef.current !== e.pointerId) {- return;- }-- seekTimelineAtClientX(e.currentTarget, e.clientX);- e.preventDefault();- },- [seekTimelineAtClientX],- );-- const stopTimelineScrub = useCallback((e: React.PointerEvent<HTMLDivElement>) => {- if (!isScrubbingTimelineRef.current || scrubPointerIdRef.current !== e.pointerId) {- return;- }-- isScrubbingTimelineRef.current = false;- scrubPointerIdRef.current = null;- if (e.currentTarget.hasPointerCapture(e.pointerId)) {- e.currentTarget.releasePointerCapture(e.pointerId);- }- }, []);-- const handleTimelinePointerLeave = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- if (isScrubbingTimelineRef.current && scrubPointerIdRef.current === e.pointerId) {- seekTimelineAtClientX(e.currentTarget, e.clientX);- }- },- [seekTimelineAtClientX],- );-- const handleTimelineLostPointerCapture = useCallback((e: React.PointerEvent<HTMLDivElement>) => {- if (scrubPointerIdRef.current === e.pointerId) {- isScrubbingTimelineRef.current = false;- scrubPointerIdRef.current = null;- }- }, []);-- const handleTimelineWheel = useCallback(- (event: React.WheelEvent<HTMLDivElement>) => {- if (!onRangeChange || event.ctrlKey || event.metaKey || videoDurationMs <= 0) {- return;- }-- const visibleMs = range.end - range.start;- if (visibleMs <= 0 || videoDurationMs <= visibleMs) {- return;- }-- const dominantDelta =- Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;- if (dominantDelta === 0) {- return;- }-- event.preventDefault();-- const pageWidthPx = Math.max(event.currentTarget.clientWidth - sidebarWidth, 1);- const normalizedDeltaPx = normalizeWheelDelta(dominantDelta, event.deltaMode, pageWidthPx);- const shiftMs = pixelsToValue(normalizedDeltaPx);-- onRangeChange((previous) => {- const nextRange = clampVisibleRange(- {- start: previous.start + shiftMs,- end: previous.end + shiftMs,- },- videoDurationMs,- );-- return nextRange.start === previous.start && nextRange.end === previous.end- ? previous- : nextRange;- });- },- [onRangeChange, videoDurationMs, range.end, range.start, sidebarWidth, pixelsToValue],- );-- const zoomItems = items.filter((item) => item.rowId === ZOOM_ROW_ID);- const cameraFullscreenItems = items.filter((item) => item.rowId === CAMERA_ROW_ID);- const trimItems = items.filter((item) => item.rowId === TRIM_ROW_ID);- const annotationItems = items.filter((item) => item.rowId === ANNOTATION_ROW_ID);- const blurItems = items.filter((item) => item.rowId === BLUR_ROW_ID);- const speedItems = items.filter((item) => item.rowId === SPEED_ROW_ID);-- return (- <div- ref={setRefs}- style={{ ...style, touchAction: "none" }}- className="select-none bg-[#0b0c0f] min-h-[190px] relative cursor-pointer group"- onClick={handleTimelineClick}- onPointerDown={handleTimelinePointerDown}- onPointerMove={handleTimelinePointerMove}- onPointerUp={stopTimelineScrub}- onPointerCancel={stopTimelineScrub}- onPointerLeave={handleTimelinePointerLeave}- onLostPointerCapture={handleTimelineLostPointerCapture}- onWheel={handleTimelineWheel}- >- <div className="absolute inset-0 bg-[linear-gradient(to_right,#ffffff05_1px,transparent_1px)] bg-[length:24px_100%] pointer-events-none" />- <TimelineAxis videoDurationMs={videoDurationMs} currentTimeMs={currentTimeMs} />- <PlaybackCursor- currentTimeMs={currentTimeMs}- videoDurationMs={videoDurationMs}- getPlaybackTimeMs={getPlaybackTimeMs}- onSeek={onSeek}- onRangeChange={onRangeChange}- timelineRef={localTimelineRef}- keyframes={keyframes}- />-- <Row id={ZOOM_ROW_ID} isEmpty={zoomItems.length === 0} hint={t("hints.pressZoom")}>- {zoomItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedZoomId}- onSelect={() => onSelectZoom?.(item.id)}- zoomDepth={item.zoomDepth}- zoomCustomScale={item.zoomCustomScale}- isAutoFocus={item.isAutoFocus}- variant="zoom"- >- {item.label}- </Item>- ))}- </Row>-- <Row- id={CAMERA_ROW_ID}- isEmpty={cameraFullscreenItems.length === 0}- hint={t("hints.pressCameraFullscreen")}- >- {cameraFullscreenItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedCameraFullscreenId}- onSelect={() => onSelectCameraFullscreen?.(item.id)}- variant="camera-fullscreen"- >- {item.label}- </Item>- ))}- </Row>-- <Row- id={TRIM_ROW_ID}- isEmpty={trimItems.length === 0}- hint={t("hints.pressTrim")}- background={- showTrimWaveform ? (- <BackgroundWaveform- peaks={peaks}- videoDurationMs={videoDurationMs}- topInset={3}- bottomInset={3}- />- ) : undefined- }- >- {trimItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedTrimId}- onSelect={() => onSelectTrim?.(item.id)}- variant="trim"- >- {item.label}- </Item>- ))}- </Row>-- <Row- id={ANNOTATION_ROW_ID}- isEmpty={annotationItems.length === 0}- hint={t("hints.pressAnnotation")}- >- {annotationItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedAnnotationId}- onSelect={() => onSelectAnnotation?.(item.id)}- variant="annotation"- >- {item.label}- </Item>- ))}- </Row>-- {BLUR_REGIONS_ENABLED && (- <Row id={BLUR_ROW_ID} isEmpty={blurItems.length === 0} hint={t("hints.pressBlur")}>- {blurItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedBlurId}- onSelect={() => onSelectBlur?.(item.id)}- variant={item.variant}- >- {item.label}- </Item>- ))}- </Row>- )}-- <Row id={SPEED_ROW_ID} isEmpty={speedItems.length === 0} hint={t("hints.pressSpeed")}>- {speedItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={item.id === selectedSpeedId}- onSelect={() => onSelectSpeed?.(item.id)}- variant="speed"- speedValue={item.speedValue}- >- {item.label}- </Item>- ))}- </Row>- </div>- );-}--export default function TimelineEditor({- videoDuration,- hasVideoSource = false,- currentTime,- getPlaybackTimeMs,- onSeek,- zoomRegions,- onZoomAdded,- autoZoomEnabled = true,- onToggleAutoZoom,- autoFocusAll = false,- onToggleAutoFocusAll,- onZoomSpanChange,- onZoomDelete,- selectedZoomId,- onSelectZoom,- cameraFullscreenRegions = [],- onCameraFullscreenAdded,- onCameraFullscreenSpanChange,- onCameraFullscreenDelete,- selectedCameraFullscreenId,- onSelectCameraFullscreen,- trimRegions = [],- onTrimAdded,- onTrimSpanChange,- onTrimDelete,- selectedTrimId,- onSelectTrim,- annotationRegions = [],- onAnnotationAdded,- onAnnotationSpanChange,- onAnnotationDelete,- selectedAnnotationId,- onSelectAnnotation,- blurRegions = [],- onBlurAdded,- onBlurSpanChange,- onBlurDelete,- selectedBlurId,- onSelectBlur,- speedRegions = [],- onSpeedAdded,- onSpeedSpanChange,- onSpeedDelete,- selectedSpeedId,- onSelectSpeed,- aspectRatio,- onAspectRatioChange,- videoUrl,- showTrimWaveform = false,- onGenerateCaptions,- isGeneratingCaptions = false,- captionsLabel,-}: TimelineEditorProps) {- const t = useScopedT("timeline");- const totalMs = useMemo(() => Math.max(0, Math.round(videoDuration * 1000)), [videoDuration]);- const currentTimeMs = useMemo(() => Math.round(currentTime * 1000), [currentTime]);- const timelineScale = useMemo(() => calculateTimelineScale(videoDuration), [videoDuration]);- const safeMinDurationMs = useMemo(- () =>- totalMs > 0- ? Math.min(timelineScale.minItemDurationMs, totalMs)- : timelineScale.minItemDurationMs,- [timelineScale.minItemDurationMs, totalMs],- );-- const [range, setRange] = useState<Range>(() => createInitialRange(totalMs));- const [keyframes, setKeyframes] = useState<{ id: string; time: number }[]>([]);- const [selectedKeyframeId, setSelectedKeyframeId] = useState<string | null>(null);- const [scrollLabels, setScrollLabels] = useState({- pan: "Scroll",- zoom: "Ctrl + Scroll",- });- const timelineContainerRef = useRef<HTMLDivElement>(null);- const { shortcuts: keyShortcuts, isMac } = useShortcuts();-- useEffect(() => {- formatShortcut(["mod", "Scroll"]).then((zoom) => {- setScrollLabels({ pan: "Scroll", zoom });- });- }, []);-- const addKeyframe = useCallback(() => {- if (totalMs === 0) return;- const time = Math.max(0, Math.min(currentTimeMs, totalMs));- if (keyframes.some((kf) => Math.abs(kf.time - time) < 1)) return;- setKeyframes((prev) => [...prev, { id: uuidv4(), time }]);- }, [currentTimeMs, totalMs, keyframes]);-- const deleteSelectedKeyframe = useCallback(() => {- if (!selectedKeyframeId) return;- setKeyframes((prev) => prev.filter((kf) => kf.id !== selectedKeyframeId));- setSelectedKeyframeId(null);- }, [selectedKeyframeId]);-- const handleKeyframeMove = useCallback(- (id: string, newTime: number) => {- setKeyframes((prev) =>- prev.map((kf) =>- kf.id === id ? { ...kf, time: Math.max(0, Math.min(newTime, totalMs)) } : kf,- ),- );- },- [totalMs],- );-- const deleteSelectedZoom = useCallback(() => {- if (!selectedZoomId) return;- onZoomDelete(selectedZoomId);- onSelectZoom(null);- }, [selectedZoomId, onZoomDelete, onSelectZoom]);-- const deleteSelectedCameraFullscreen = useCallback(() => {- if (!selectedCameraFullscreenId || !onCameraFullscreenDelete || !onSelectCameraFullscreen) {- return;- }- onCameraFullscreenDelete(selectedCameraFullscreenId);- onSelectCameraFullscreen(null);- }, [selectedCameraFullscreenId, onCameraFullscreenDelete, onSelectCameraFullscreen]);-- const deleteSelectedTrim = useCallback(() => {- if (!selectedTrimId || !onTrimDelete || !onSelectTrim) return;- onTrimDelete(selectedTrimId);- onSelectTrim(null);- }, [selectedTrimId, onTrimDelete, onSelectTrim]);-- const deleteSelectedAnnotation = useCallback(() => {- if (!selectedAnnotationId || !onAnnotationDelete || !onSelectAnnotation) return;- onAnnotationDelete(selectedAnnotationId);- onSelectAnnotation(null);- }, [selectedAnnotationId, onAnnotationDelete, onSelectAnnotation]);-- const deleteSelectedBlur = useCallback(() => {- if (!selectedBlurId || !onBlurDelete || !onSelectBlur) return;- onBlurDelete(selectedBlurId);- onSelectBlur(null);- }, [selectedBlurId, onBlurDelete, onSelectBlur]);-- const deleteSelectedSpeed = useCallback(() => {- if (!selectedSpeedId || !onSpeedDelete || !onSelectSpeed) return;- onSpeedDelete(selectedSpeedId);- onSelectSpeed(null);- }, [selectedSpeedId, onSpeedDelete, onSelectSpeed]);-- useEffect(() => {- setRange(createInitialRange(totalMs));- }, [totalMs]);-- // Normalize regions only when timeline bounds change. Reading via refs avoids a- // dependency loop that would re-fire on every drag and race dnd-timeline's state.- const zoomRegionsRef = useRef(zoomRegions);- const cameraFullscreenRegionsRef = useRef(cameraFullscreenRegions);- const trimRegionsRef = useRef(trimRegions);- const speedRegionsRef = useRef(speedRegions);- // Sync refs in an effect (not during render) so render stays pure; defined before- // the normalization effect below so that effect reads the freshest region values.- useEffect(() => {- zoomRegionsRef.current = zoomRegions;- cameraFullscreenRegionsRef.current = cameraFullscreenRegions;- trimRegionsRef.current = trimRegions;- speedRegionsRef.current = speedRegions;- }, [zoomRegions, cameraFullscreenRegions, trimRegions, speedRegions]);-- useEffect(() => {- if (totalMs === 0 || safeMinDurationMs <= 0) {- return;- }-- zoomRegionsRef.current.forEach((region) => {- const clampedStart = Math.max(0, Math.min(region.startMs, totalMs));- const minEnd = clampedStart + safeMinDurationMs;- const clampedEnd = Math.min(totalMs, Math.max(minEnd, region.endMs));- const normalizedStart = Math.max(0, Math.min(clampedStart, totalMs - safeMinDurationMs));- const normalizedEnd = Math.max(minEnd, Math.min(clampedEnd, totalMs));-- if (normalizedStart !== region.startMs || normalizedEnd !== region.endMs) {- onZoomSpanChange(region.id, { start: normalizedStart, end: normalizedEnd });- }- });-- cameraFullscreenRegionsRef.current.forEach((region) => {- const clampedStart = Math.max(0, Math.min(region.startMs, totalMs));- const minEnd = clampedStart + safeMinDurationMs;- const clampedEnd = Math.min(totalMs, Math.max(minEnd, region.endMs));- const normalizedStart = Math.max(0, Math.min(clampedStart, totalMs - safeMinDurationMs));- const normalizedEnd = Math.max(minEnd, Math.min(clampedEnd, totalMs));-- if (normalizedStart !== region.startMs || normalizedEnd !== region.endMs) {- onCameraFullscreenSpanChange?.(region.id, { start: normalizedStart, end: normalizedEnd });- }- });-- trimRegionsRef.current.forEach((region) => {- const clampedStart = Math.max(0, Math.min(region.startMs, totalMs));- const minEnd = clampedStart + safeMinDurationMs;- const clampedEnd = Math.min(totalMs, Math.max(minEnd, region.endMs));- const normalizedStart = Math.max(0, Math.min(clampedStart, totalMs - safeMinDurationMs));- const normalizedEnd = Math.max(minEnd, Math.min(clampedEnd, totalMs));-- if (normalizedStart !== region.startMs || normalizedEnd !== region.endMs) {- onTrimSpanChange?.(region.id, { start: normalizedStart, end: normalizedEnd });- }- });-- speedRegionsRef.current.forEach((region) => {- const clampedStart = Math.max(0, Math.min(region.startMs, totalMs));- const minEnd = clampedStart + safeMinDurationMs;- const clampedEnd = Math.min(totalMs, Math.max(minEnd, region.endMs));- const normalizedStart = Math.max(0, Math.min(clampedStart, totalMs - safeMinDurationMs));- const normalizedEnd = Math.max(minEnd, Math.min(clampedEnd, totalMs));-- if (normalizedStart !== region.startMs || normalizedEnd !== region.endMs) {- onSpeedSpanChange?.(region.id, { start: normalizedStart, end: normalizedEnd });- }- });- }, [- totalMs,- safeMinDurationMs,- onZoomSpanChange,- onCameraFullscreenSpanChange,- onTrimSpanChange,- onSpeedSpanChange,- ]);-- const hasOverlap = useCallback(- (newSpan: Span, excludeId?: string): boolean => {- const isZoomItem = zoomRegions.some((r) => r.id === excludeId);- const isCameraFullscreenItem = cameraFullscreenRegions.some((r) => r.id === excludeId);- const isTrimItem = trimRegions.some((r) => r.id === excludeId);- const isAnnotationItem = annotationRegions.some((r) => r.id === excludeId);- const isBlurItem = blurRegions.some((r) => r.id === excludeId);- const isSpeedItem = speedRegions.some((r) => r.id === excludeId);-- if (isAnnotationItem || isBlurItem) {- return false;- }-- const checkOverlap = (- regions: (ZoomRegion | CameraFullscreenRegion | TrimRegion | SpeedRegion)[],- ) => {- return regions.some((region) => {- if (region.id === excludeId) return false;- // True intersection, adjacency is allowed- return newSpan.end > region.startMs && newSpan.start < region.endMs;- });- };-- if (isZoomItem) {- return checkOverlap(zoomRegions);- }-- if (isCameraFullscreenItem) {- return checkOverlap(cameraFullscreenRegions);- }-- if (isTrimItem) {- return checkOverlap(trimRegions);- }-- if (isSpeedItem) {- return checkOverlap(speedRegions);- }-- return false;- },- [- zoomRegions,- cameraFullscreenRegions,- trimRegions,- annotationRegions,- blurRegions,- speedRegions,- ],- );-- // 5% of the timeline or 1000ms, whichever is larger, so it's wide enough to grab.- const defaultRegionDurationMs = useMemo(- () => Math.max(1000, Math.round(totalMs * 0.05)),- [totalMs],- );-- const handleAddZoom = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const { ok, gapMs } = findFreeGapAt(zoomRegions, startPos, totalMs);- if (!ok) {- toast.error(t("errors.cannotPlaceZoom"), {- description: t("errors.zoomExistsAtLocation"),- });- return;- }-- const actualDuration = Math.min(defaultRegionDurationMs, gapMs);- onZoomAdded({ start: startPos, end: startPos + actualDuration });- }, [videoDuration, totalMs, currentTimeMs, zoomRegions, onZoomAdded, defaultRegionDurationMs, t]);-- const handleAddCameraFullscreen = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onCameraFullscreenAdded) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const { ok, gapMs } = findFreeGapAt(cameraFullscreenRegions, startPos, totalMs);- if (!ok) {- toast.error(t("errors.cannotPlaceCameraFullscreen"), {- description: t("errors.cameraFullscreenExistsAtLocation"),- });- return;- }-- const actualDuration = Math.min(defaultRegionDurationMs, gapMs);- onCameraFullscreenAdded({ start: startPos, end: startPos + actualDuration });- }, [- videoDuration,- totalMs,- currentTimeMs,- cameraFullscreenRegions,- onCameraFullscreenAdded,- defaultRegionDurationMs,- t,- ]);-- const handleAddTrim = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onTrimAdded) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const { ok, gapMs } = findFreeGapAt(trimRegions, startPos, totalMs);- if (!ok) {- toast.error(t("errors.cannotPlaceTrim"), {- description: t("errors.trimExistsAtLocation"),- });- return;- }-- const actualDuration = Math.min(defaultRegionDurationMs, gapMs);- onTrimAdded({ start: startPos, end: startPos + actualDuration });- }, [videoDuration, totalMs, currentTimeMs, trimRegions, onTrimAdded, defaultRegionDurationMs, t]);-- const handleAddSpeed = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onSpeedAdded) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const { ok, gapMs } = findFreeGapAt(speedRegions, startPos, totalMs);- if (!ok) {- toast.error(t("errors.cannotPlaceSpeed"), {- description: t("errors.speedExistsAtLocation"),- });- return;- }-- const actualDuration = Math.min(defaultRegionDurationMs, gapMs);- onSpeedAdded({ start: startPos, end: startPos + actualDuration });- }, [- videoDuration,- totalMs,- currentTimeMs,- speedRegions,- onSpeedAdded,- defaultRegionDurationMs,- t,- ]);-- const handleAddAnnotation = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onAnnotationAdded) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- // Multiple annotations can exist at the same timestamp- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const endPos = Math.min(startPos + defaultDuration, totalMs);-- onAnnotationAdded({ start: startPos, end: endPos });- }, [videoDuration, totalMs, currentTimeMs, onAnnotationAdded, defaultRegionDurationMs]);-- const handleAddBlur = useCallback(() => {- if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onBlurAdded) {- return;- }-- const defaultDuration = Math.min(defaultRegionDurationMs, totalMs);- if (defaultDuration <= 0) {- return;- }-- const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const endPos = Math.min(startPos + defaultDuration, totalMs);- onBlurAdded({ start: startPos, end: endPos });- }, [videoDuration, totalMs, currentTimeMs, onBlurAdded, defaultRegionDurationMs]);-- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (isTextEditingTarget(e.target)) {- return;- }-- if (matchesShortcut(e, keyShortcuts.addKeyframe, isMac)) {- addKeyframe();- }- if (matchesShortcut(e, keyShortcuts.addZoom, isMac)) {- handleAddZoom();- }- if (matchesShortcut(e, keyShortcuts.addTrim, isMac)) {- handleAddTrim();- }- if (matchesShortcut(e, keyShortcuts.addAnnotation, isMac)) {- handleAddAnnotation();- }- if (BLUR_REGIONS_ENABLED && matchesShortcut(e, keyShortcuts.addBlur, isMac)) {- handleAddBlur();- }- if (matchesShortcut(e, keyShortcuts.addSpeed, isMac)) {- handleAddSpeed();- }- if (matchesShortcut(e, keyShortcuts.addCameraFullscreen, isMac)) {- handleAddCameraFullscreen();- }-- // Tab cycles through overlapping annotations at the current time- if (e.key === "Tab" && annotationRegions.length > 0) {- const currentTimeMs = Math.round(currentTime * 1000);- const overlapping = annotationRegions- .filter((a) => currentTimeMs >= a.startMs && currentTimeMs <= a.endMs)- .sort((a, b) => a.zIndex - b.zIndex);-- if (overlapping.length > 0) {- e.preventDefault();-- if (!selectedAnnotationId || !overlapping.some((a) => a.id === selectedAnnotationId)) {- onSelectAnnotation?.(overlapping[0].id);- } else {- const currentIndex = overlapping.findIndex((a) => a.id === selectedAnnotationId);- const nextIndex = e.shiftKey- ? (currentIndex - 1 + overlapping.length) % overlapping.length // Shift+Tab steps backward- : (currentIndex + 1) % overlapping.length;- onSelectAnnotation?.(overlapping[nextIndex].id);- }- }- }- // Delete key or Ctrl+D / Cmd+D- if (- e.key === "Delete" ||- e.key === "Backspace" ||- matchesShortcut(e, keyShortcuts.deleteSelected, isMac)- ) {- if (selectedKeyframeId) {- deleteSelectedKeyframe();- } else if (selectedZoomId) {- deleteSelectedZoom();- } else if (selectedCameraFullscreenId) {- deleteSelectedCameraFullscreen();- } else if (selectedTrimId) {- deleteSelectedTrim();- } else if (selectedAnnotationId) {- deleteSelectedAnnotation();- } else if (selectedBlurId) {- deleteSelectedBlur();- } else if (selectedSpeedId) {- deleteSelectedSpeed();- }- }- };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [- addKeyframe,- handleAddZoom,- handleAddTrim,- handleAddAnnotation,- handleAddBlur,- handleAddSpeed,- handleAddCameraFullscreen,- deleteSelectedKeyframe,- deleteSelectedZoom,- deleteSelectedCameraFullscreen,- deleteSelectedTrim,- deleteSelectedAnnotation,- deleteSelectedBlur,- deleteSelectedSpeed,- selectedKeyframeId,- selectedZoomId,- selectedCameraFullscreenId,- selectedTrimId,- selectedAnnotationId,- selectedBlurId,- selectedSpeedId,- annotationRegions,- currentTime,- onSelectAnnotation,- keyShortcuts,- isMac,- ]);-- const clampedRange = useMemo<Range>(() => {- if (totalMs === 0) {- return range;- }-- return {- start: Math.max(0, Math.min(range.start, totalMs)),- end: Math.min(range.end, totalMs),- };- }, [range, totalMs]);-- const timelineItems = useMemo<TimelineRenderItem[]>(() => {- const zooms: TimelineRenderItem[] = zoomRegions.map((region, index) => ({- id: region.id,- rowId: ZOOM_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label: t("labels.zoomItem", { index: String(index + 1) }),- zoomDepth: region.depth,- zoomCustomScale: region.customScale,- isAutoFocus: region.focusMode === "auto",- variant: "zoom",- }));-- const cameraFullscreens: TimelineRenderItem[] = cameraFullscreenRegions.map(- (region, index) => ({- id: region.id,- rowId: CAMERA_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label: t("labels.cameraFullscreenItem", { index: String(index + 1) }),- variant: "camera-fullscreen",- }),- );-- const trims: TimelineRenderItem[] = trimRegions.map((region, index) => ({- id: region.id,- rowId: TRIM_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label: t("labels.trimItem", { index: String(index + 1) }),- variant: "trim",- }));-- const annotations: TimelineRenderItem[] = annotationRegions.map((region) => {- let label: string;-- if (region.type === "text") {- const preview = region.content.trim() || t("labels.emptyText");- label = preview.length > 20 ? `${preview.substring(0, 20)}...` : preview;- } else if (region.type === "image") {- label = t("labels.imageItem");- } else {- label = t("labels.annotationItem");- }-- return {- id: region.id,- rowId: ANNOTATION_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label,- variant: "annotation",- };- });-- const blurs: TimelineRenderItem[] = blurRegions.map((region, index) => ({- id: region.id,- rowId: BLUR_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label: t("labels.blurItem", { index: String(index + 1) }),- variant: "blur",- }));-- const speeds: TimelineRenderItem[] = speedRegions.map((region, index) => ({- id: region.id,- rowId: SPEED_ROW_ID,- span: { start: region.startMs, end: region.endMs },- label: t("labels.speedItem", { index: String(index + 1) }),- speedValue: region.speed,- variant: "speed",- }));-- return [...zooms, ...cameraFullscreens, ...trims, ...annotations, ...blurs, ...speeds];- }, [- zoomRegions,- cameraFullscreenRegions,- trimRegions,- annotationRegions,- blurRegions,- speedRegions,- t,- ]);-- // Spans that participate in overlap resolution (clampToNeighbours). Annotation- // and blur are excluded since they may overlap and shouldn't constrain a drag.- const allRegionSpans = useMemo(() => {- const zooms = zoomRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- const cameraFullscreens = cameraFullscreenRegions.map((r) => ({- id: r.id,- start: r.startMs,- end: r.endMs,- }));- const trims = trimRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- const speeds = speedRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- return [...zooms, ...cameraFullscreens, ...trims, ...speeds];- }, [zoomRegions, cameraFullscreenRegions, trimRegions, speedRegions]);-- // Snap targets whose edges pull during a snap but don't push anyone away.- const softSnapSpans = useMemo(() => {- const annotations = annotationRegions.map((r) => ({- id: r.id,- start: r.startMs,- end: r.endMs,- }));- const blurs = blurRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- return [...annotations, ...blurs];- }, [annotationRegions, blurRegions]);-- const keyframeTimesMs = useMemo(() => keyframes.map((kf) => kf.time), [keyframes]);-- const handleItemSpanChange = useCallback(- (id: string, span: Span) => {- if (zoomRegions.some((r) => r.id === id)) {- onZoomSpanChange(id, span);- } else if (cameraFullscreenRegions.some((r) => r.id === id)) {- onCameraFullscreenSpanChange?.(id, span);- } else if (trimRegions.some((r) => r.id === id)) {- onTrimSpanChange?.(id, span);- } else if (speedRegions.some((r) => r.id === id)) {- onSpeedSpanChange?.(id, span);- } else if (annotationRegions.some((r) => r.id === id)) {- onAnnotationSpanChange?.(id, span);- } else if (blurRegions.some((r) => r.id === id)) {- onBlurSpanChange?.(id, span);- }- },- [- zoomRegions,- cameraFullscreenRegions,- trimRegions,- speedRegions,- annotationRegions,- blurRegions,- onZoomSpanChange,- onCameraFullscreenSpanChange,- onTrimSpanChange,- onSpeedSpanChange,- onAnnotationSpanChange,- onBlurSpanChange,- ],- );-- if (!videoDuration || videoDuration === 0) {- return (- <div className="flex-1 flex flex-col items-center justify-center rounded-lg bg-[#09090b] gap-3">- <div className="w-12 h-12 rounded-full bg-white/5 flex items-center justify-center">- <Plus className="w-6 h-6 text-slate-600" />- </div>- <div className="text-center">- <p className="text-sm font-medium text-slate-300">- {hasVideoSource ? "Loading Timeline" : "No Video Loaded"}- </p>- <p className="text-xs text-slate-500 mt-1">- {hasVideoSource- ? "Video opened, waiting for duration metadata"- : "Drag and drop a video to start editing"}- </p>- </div>- </div>- );- }-- return (- <div className="flex-1 min-h-0 flex flex-col bg-[#09090b] overflow-hidden">- <div className="flex items-center gap-2 px-3 py-1.5 border-b border-white/[0.06] bg-[#08090b]/95">- <div className="flex items-center gap-0.5 rounded-xl border border-white/[0.06] bg-white/[0.025] p-0.5">- <Button- onClick={handleAddZoom}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#34B27B] hover:bg-[#34B27B]/10 transition-all"- title={t("buttons.addZoom")}- >- <ZoomIn className="w-4 h-4" />- </Button>- <Button- onClick={handleAddCameraFullscreen}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#38bdf8] hover:bg-[#38bdf8]/10 transition-all"- title={t("buttons.addCameraFullscreen")}- >- <Maximize className="w-4 h-4" />- </Button>- <Button- onClick={() => onToggleAutoZoom?.(!autoZoomEnabled)}- variant="ghost"- size="icon"- aria-pressed={autoZoomEnabled}- className={cn(- "h-7 w-7 rounded-lg transition-all hover:bg-[#34B27B]/10 hover:text-[#34B27B]",- autoZoomEnabled ? "bg-[#34B27B]/15 text-[#34B27B]" : "text-slate-400",- )}- title={autoZoomEnabled ? t("buttons.autoZoomOn") : t("buttons.autoZoomOff")}- >- <WandSparkles className="w-4 h-4" />- </Button>- <Button- onClick={() => onToggleAutoFocusAll?.(!autoFocusAll)}- variant="ghost"- size="icon"- aria-pressed={autoFocusAll}- className={cn(- "h-7 w-7 rounded-lg transition-all hover:bg-[#34B27B]/10 hover:text-[#34B27B]",- autoFocusAll ? "bg-[#34B27B]/15 text-[#34B27B]" : "text-slate-400",- )}- title={autoFocusAll ? t("buttons.autoFocusAllOn") : t("buttons.autoFocusAllOff")}- >- <ScanEye className="w-4 h-4" />- </Button>- <Button- onClick={handleAddTrim}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#ef4444] hover:bg-[#ef4444]/10 transition-all"- title={t("buttons.addTrim")}- >- <Scissors className="w-4 h-4" />- </Button>- <Button- onClick={handleAddAnnotation}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#B4A046] hover:bg-[#B4A046]/10 transition-all"- title={t("buttons.addAnnotation")}- >- <MessageSquare className="w-4 h-4" />- </Button>- {BLUR_REGIONS_ENABLED && (- <Button- onClick={handleAddBlur}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#7dd3fc] hover:bg-[#7dd3fc]/10 transition-all"- title={t("buttons.addBlur")}- >- <svg- className="w-4 h-4"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <circle cx="8" cy="12" r="3" />- <circle cx="16" cy="12" r="3" />- <path d="M6 6h12M6 18h12" />- </svg>- </Button>- )}- <Button- onClick={handleAddSpeed}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#d97706] hover:bg-[#d97706]/10 transition-all"- title={t("buttons.addSpeed")}- >- <Gauge className="w-4 h-4" />- </Button>- {onGenerateCaptions && (- <Button- onClick={onGenerateCaptions}- disabled={isGeneratingCaptions || !videoUrl}- variant="ghost"- size="icon"- className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#a78bfa] hover:bg-[#a78bfa]/10 transition-all"- title={captionsLabel}- >- <Captions className="w-4 h-4" />- </Button>- )}- </div>- <div className="flex items-center gap-1.5 min-w-0">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="ghost"- size="sm"- className="h-7 px-2 rounded-lg text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/[0.07] transition-all gap-1"- >- <span className="font-medium">{getAspectRatioLabel(aspectRatio)}</span>- <ChevronDown className="w-3 h-3" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="bg-[#1a1a1a] border-white/10">- {ASPECT_RATIOS.map((ratio) => (- <DropdownMenuItem- key={ratio}- onClick={() => onAspectRatioChange(ratio)}- className="text-slate-300 hover:text-white hover:bg-white/10 cursor-pointer flex items-center justify-between gap-3"- >- <span>{getAspectRatioLabel(ratio)}</span>- {aspectRatio === ratio && <Check className="w-3 h-3 text-[#34B27B]" />}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- <div className="flex-1" />- <div className="hidden md:flex items-center gap-3 text-[10px] text-slate-500 font-medium">- <span className="flex items-center gap-1.5">- <kbd className="px-1.5 py-0.5 bg-white/5 border border-white/10 rounded text-[#34B27B] font-sans">- {scrollLabels.pan}- </kbd>- <span>{t("labels.pan")}</span>- </span>- <span className="flex items-center gap-1.5">- <kbd className="px-1.5 py-0.5 bg-white/5 border border-white/10 rounded text-[#34B27B] font-sans">- {scrollLabels.zoom}- </kbd>- <span>{t("labels.zoom")}</span>- </span>- </div>- </div>- <div- ref={timelineContainerRef}- className="flex-1 min-h-0 overflow-auto custom-scrollbar bg-[#09090b] relative"- onClick={() => setSelectedKeyframeId(null)}- >- <TimelineWrapper- range={clampedRange}- videoDuration={videoDuration}- hasOverlap={hasOverlap}- onRangeChange={setRange}- minItemDurationMs={timelineScale.minItemDurationMs}- minVisibleRangeMs={timelineScale.minVisibleRangeMs}- onItemSpanChange={handleItemSpanChange}- allRegionSpans={allRegionSpans}- softSnapSpans={softSnapSpans}- currentTimeMs={currentTimeMs}- keyframeTimesMs={keyframeTimesMs}- >- <KeyframeMarkers- keyframes={keyframes}- selectedKeyframeId={selectedKeyframeId}- setSelectedKeyframeId={setSelectedKeyframeId}- onKeyframeMove={handleKeyframeMove}- videoDurationMs={totalMs}- timelineRef={timelineContainerRef}- />- <Timeline- items={timelineItems}- videoDurationMs={totalMs}- currentTimeMs={currentTimeMs}- getPlaybackTimeMs={getPlaybackTimeMs}- onSeek={onSeek}- onRangeChange={setRange}- onSelectZoom={onSelectZoom}- onSelectCameraFullscreen={onSelectCameraFullscreen}- onSelectTrim={onSelectTrim}- onSelectAnnotation={onSelectAnnotation}- onSelectBlur={onSelectBlur}- onSelectSpeed={onSelectSpeed}- selectedZoomId={selectedZoomId}- selectedCameraFullscreenId={selectedCameraFullscreenId}- selectedTrimId={selectedTrimId}- selectedAnnotationId={selectedAnnotationId}- selectedBlurId={selectedBlurId}- selectedSpeedId={selectedSpeedId}- keyframes={keyframes}- videoUrl={videoUrl}- showTrimWaveform={showTrimWaveform}- />- </TimelineWrapper>- </div>- </div>- );-}diff --git a/src/components/video-editor/timeline/TimelineWrapper.tsx b/src/components/video-editor/timeline/TimelineWrapper.tsxdeleted file mode 100644index 9cd71cb05..000000000--- a/src/components/video-editor/timeline/TimelineWrapper.tsx+++ /dev/null@@ -1,545 +0,0 @@-import type {- DragEndEvent,- DragMoveEvent,- DragStartEvent,- Range,- ResizeEndEvent,- ResizeMoveEvent,- Span,-} from "dnd-timeline";-import { TimelineContext, useTimelineContext } from "dnd-timeline";-import type { Dispatch, ReactNode, SetStateAction } from "react";-import { forwardRef, useCallback, useImperativeHandle, useRef } from "react";--interface TimelineWrapperProps {- children: ReactNode;- range: Range;- videoDuration: number;- hasOverlap: (newSpan: Span, excludeId?: string) => boolean;- onRangeChange: Dispatch<SetStateAction<Range>>;- minItemDurationMs: number;- minVisibleRangeMs: number;- gridSizeMs?: number;- onItemSpanChange: (id: string, span: Span) => void;- // Hard overlap constraints (zoom/trim/speed), used by clampToNeighbours and as snap targets.- allRegionSpans?: { id: string; start: number; end: number }[];- // Snap targets only (annotation/blur); never push other items during overlap resolution.- softSnapSpans?: { id: string; start: number; end: number }[];- currentTimeMs?: number;- keyframeTimesMs?: number[];-}--interface SnapGuideHandle {- showAt: (timeMs: number) => void;- hide: () => void;-}--// Lives inside TimelineContext to read valueToPixels. Updates the DOM directly via-// an imperative handle (like the drag tooltip) to avoid re-rendering on every pointer move.-const SnapGuide = forwardRef<SnapGuideHandle>((_, ref) => {- const { sidebarWidth, direction, range, valueToPixels } = useTimelineContext();- const elRef = useRef<HTMLDivElement>(null);- const sideProperty = direction === "rtl" ? "right" : "left";-- useImperativeHandle(- ref,- () => ({- showAt(timeMs: number) {- const el = elRef.current;- if (!el) return;- const offset = valueToPixels(timeMs - range.start) + sidebarWidth;- el.style[sideProperty] = `${offset}px`;- el.style.opacity = "1";- },- hide() {- const el = elRef.current;- if (!el) return;- el.style.opacity = "0";- },- }),- [range.start, sidebarWidth, sideProperty, valueToPixels],- );-- return (- <div- ref={elRef}- className="absolute top-0 bottom-0 w-[2px] bg-[#fbbf24] shadow-[0_0_10px_rgba(251,191,36,0.85),0_0_2px_rgba(251,191,36,1)] pointer-events-none z-[55]"- style={{ opacity: 0, transition: "opacity 0.08s" }}- >- <div- className="absolute -top-[1px] left-1/2 -translate-x-1/2 w-0 h-0"- style={{- borderLeft: "4px solid transparent",- borderRight: "4px solid transparent",- borderTop: "6px solid #fbbf24",- }}- />- <div- className="absolute -bottom-[1px] left-1/2 -translate-x-1/2 w-0 h-0"- style={{- borderLeft: "4px solid transparent",- borderRight: "4px solid transparent",- borderBottom: "6px solid #fbbf24",- }}- />- </div>- );-});-SnapGuide.displayName = "SnapGuide";--export default function TimelineWrapper({- children,- range,- videoDuration,- hasOverlap,- onRangeChange,- minItemDurationMs,- minVisibleRangeMs,- gridSizeMs: _gridSizeMs,- onItemSpanChange,- allRegionSpans = [],- softSnapSpans = [],- currentTimeMs,- keyframeTimesMs = [],-}: TimelineWrapperProps) {- const totalMs = Math.max(0, Math.round(videoDuration * 1000));-- const clampSpanToBounds = useCallback(- (span: Span): Span => {- const rawDuration = Math.max(span.end - span.start, 0);- const normalizedStart = Number.isFinite(span.start) ? span.start : 0;-- if (totalMs === 0) {- const minDuration = Math.max(minItemDurationMs, 1);- const duration = Math.max(rawDuration, minDuration);- const start = Math.max(0, normalizedStart);- return {- start,- end: start + duration,- };- }-- const minDuration = Math.min(Math.max(minItemDurationMs, 1), totalMs);- const duration = Math.min(Math.max(rawDuration, minDuration), totalMs);-- const start = Math.max(0, Math.min(normalizedStart, totalMs - duration));- const end = Math.min(start + duration, totalMs);-- return { start, end };- },- [minItemDurationMs, totalMs],- );-- const clampRange = useCallback(- (candidate: Range): Range => {- if (totalMs === 0) {- const minSpan = Math.max(minVisibleRangeMs, 1);- const span = Math.max(candidate.end - candidate.start, minSpan);- const start = Math.max(0, Math.min(candidate.start, candidate.end - span));- return { start, end: start + span };- }-- const rawStart = Math.max(0, candidate.start);- const rawEnd = candidate.end;- const clampedEnd = Math.min(rawEnd, totalMs);-- const minSpan = Math.min(Math.max(minVisibleRangeMs, 1), totalMs);- const desiredSpan = clampedEnd - rawStart;- const span = Math.min(Math.max(desiredSpan, minSpan), totalMs);-- let finalStart = rawStart;- let finalEnd = finalStart + span;-- if (finalEnd > totalMs) {- finalEnd = totalMs;- finalStart = Math.max(0, finalEnd - span);- }-- return { start: finalStart, end: finalEnd };- },- [minVisibleRangeMs, totalMs],- );-- // When a span overlaps neighbours, clamp it to the nearest boundary- const clampToNeighbours = useCallback(- (span: Span, activeItemId: string): Span => {- const siblings = allRegionSpans.filter((r) => r.id !== activeItemId);- let { start, end } = span;-- for (const r of siblings) {- // Span's right edge crossed into a region to the right- if (end > r.start && start < r.start) {- end = r.start;- }- // Span's left edge crossed into a region to the left- if (start < r.end && end > r.end) {- start = r.end;- }- }-- // Ensure minimum duration after clamping- const minDur = Math.min(minItemDurationMs, totalMs || minItemDurationMs);- if (end - start < minDur) {- // Try extending in the direction that has room- if (end + minDur - (end - start) <= totalMs) {- end = start + minDur;- } else {- start = end - minDur;- }- }-- return { start: Math.max(0, start), end: Math.min(end, totalMs || end) };- },- [allRegionSpans, minItemDurationMs, totalMs],- );-- const snapGuideRef = useRef<SnapGuideHandle>(null);-- // Pull the active span's edges to nearby region boundaries, timeline bounds, playhead,- // and keyframes. Threshold scales with zoom (~1% of visible range, min 50ms). Returns- // the snapped span plus the snap target used (for guide rendering).- const snapSpanToTargets = useCallback(- (- span: Span,- activeItemId: string,- mode: "drag" | "resize-left" | "resize-right",- ): { span: Span; snapPoint: number | null } => {- if (totalMs === 0) return { span, snapPoint: null };-- const visibleMs = Math.max(range.end - range.start, 1);- const thresholdMs = Math.max(50, Math.round(visibleMs / 100));-- const targetSet = new Set<number>();- targetSet.add(0);- targetSet.add(totalMs);- for (const r of allRegionSpans) {- if (r.id === activeItemId) continue;- targetSet.add(r.start);- targetSet.add(r.end);- }- for (const r of softSnapSpans) {- if (r.id === activeItemId) continue;- targetSet.add(r.start);- targetSet.add(r.end);- }- if (currentTimeMs !== undefined) targetSet.add(currentTimeMs);- for (const kf of keyframeTimesMs) targetSet.add(kf);- const targets = Array.from(targetSet);-- const findNearest = (value: number): number | null => {- let best: number | null = null;- let bestDistance = thresholdMs;- for (const target of targets) {- const distance = Math.abs(target - value);- if (distance <= bestDistance) {- best = target;- bestDistance = distance;- }- }- return best;- };-- if (mode === "resize-left") {- const snap = findNearest(span.start);- if (snap === null || span.end - snap < minItemDurationMs) {- return { span, snapPoint: null };- }- return { span: { start: snap, end: span.end }, snapPoint: snap };- }-- if (mode === "resize-right") {- const snap = findNearest(span.end);- if (snap === null || snap - span.start < minItemDurationMs) {- return { span, snapPoint: null };- }- return { span: { start: span.start, end: snap }, snapPoint: snap };- }-- // Drag: preserve duration; snap whichever edge is closer to a target.- const startSnap = findNearest(span.start);- const endSnap = findNearest(span.end);- const startDelta = startSnap !== null ? Math.abs(startSnap - span.start) : Infinity;- const endDelta = endSnap !== null ? Math.abs(endSnap - span.end) : Infinity;-- if (startDelta === Infinity && endDelta === Infinity) {- return { span, snapPoint: null };- }-- const duration = span.end - span.start;- if (startDelta <= endDelta && startSnap !== null) {- return {- span: { start: startSnap, end: startSnap + duration },- snapPoint: startSnap,- };- }- if (endSnap !== null) {- return {- span: { start: endSnap - duration, end: endSnap },- snapPoint: endSnap,- };- }- return { span, snapPoint: null };- },- [- allRegionSpans,- softSnapSpans,- currentTimeMs,- keyframeTimesMs,- minItemDurationMs,- range.end,- range.start,- totalMs,- ],- );-- // dnd-timeline's resize event doesn't expose direction, so compare the live span to- // the committed one (committed only updates on commit, so it's the pre-resize state).- // Returns null when deltas are equal (including the common clamped both-0 case): we- // can't tell which handle was grabbed, and guessing wrong snaps the other edge.- const inferResizeMode = useCallback(- (activeItemId: string, span: Span): "resize-left" | "resize-right" | null => {- const old =- allRegionSpans.find((r) => r.id === activeItemId) ??- softSnapSpans.find((r) => r.id === activeItemId);- if (!old) return "resize-right";- const startDelta = Math.abs(old.start - span.start);- const endDelta = Math.abs(old.end - span.end);- if (startDelta === endDelta) return null;- return startDelta > endDelta ? "resize-left" : "resize-right";- },- [allRegionSpans, softSnapSpans],- );-- const updateSnapGuide = useCallback(- (snapPoint: number | null) => {- if (snapPoint === null) {- snapGuideRef.current?.hide();- return;- }- // Hide the amber guide when it would coincide with the green playhead.- if (currentTimeMs !== undefined && Math.abs(snapPoint - currentTimeMs) < 1) {- snapGuideRef.current?.hide();- return;- }- snapGuideRef.current?.showAt(snapPoint);- },- [currentTimeMs],- );-- const onResizeEnd = useCallback(- (event: ResizeEndEvent) => {- const updatedSpan = event.active.data.current.getSpanFromResizeEvent?.(event);- if (!updatedSpan) return;-- const activeItemId = event.active.id as string;- let clampedSpan = clampSpanToBounds(updatedSpan);-- const mode = inferResizeMode(activeItemId, clampedSpan);- if (mode !== null) {- clampedSpan = snapSpanToTargets(clampedSpan, activeItemId, mode).span;- }-- const effectiveMinDuration =- totalMs > 0 ? Math.min(minItemDurationMs, totalMs) : minItemDurationMs;- if (clampedSpan.end - clampedSpan.start < effectiveMinDuration) {- return;- }-- // Clamp to neighbour boundaries instead of rejecting- if (hasOverlap(clampedSpan, activeItemId)) {- clampedSpan = clampToNeighbours(clampedSpan, activeItemId);- // If still overlapping after clamping, fall back to original position- if (hasOverlap(clampedSpan, activeItemId)) {- return;- }- }-- onItemSpanChange(activeItemId, clampedSpan);- },- [- clampSpanToBounds,- clampToNeighbours,- hasOverlap,- inferResizeMode,- minItemDurationMs,- onItemSpanChange,- snapSpanToTargets,- totalMs,- ],- );-- const onDragEnd = useCallback(- (event: DragEndEvent) => {- const activeRowId = event.over?.id as string;- const updatedSpan = event.active.data.current.getSpanFromDragEvent?.(event);- if (!updatedSpan || !activeRowId) return;-- const activeItemId = event.active.id as string;- let clampedSpan = clampSpanToBounds(updatedSpan);-- clampedSpan = snapSpanToTargets(clampedSpan, activeItemId, "drag").span;-- // Clamp to neighbour boundaries instead of rejecting- if (hasOverlap(clampedSpan, activeItemId)) {- clampedSpan = clampToNeighbours(clampedSpan, activeItemId);- if (hasOverlap(clampedSpan, activeItemId)) {- return;- }- }-- onItemSpanChange(activeItemId, clampedSpan);- },- [clampSpanToBounds, clampToNeighbours, hasOverlap, onItemSpanChange, snapSpanToTargets],- );-- // Drag/resize tooltip (direct DOM updates, no re-renders)- const tooltipRef = useRef<HTMLDivElement>(null);-- const formatTooltipMs = useCallback((ms: number) => {- const s = ms / 1000;- const min = Math.floor(s / 60);- const sec = s % 60;- return min > 0 ? `${min}:${sec.toFixed(1).padStart(4, "0")}` : `${sec.toFixed(1)}s`;- }, []);-- const showTooltip = useCallback(- (span: { start: number; end: number } | null, screenX?: number) => {- const el = tooltipRef.current;- if (!el) return;- if (!span) {- el.style.opacity = "0";- return;- }- el.textContent = `${formatTooltipMs(span.start)} – ${formatTooltipMs(span.end)}`;- el.style.opacity = "1";- if (screenX !== undefined) {- const parent = el.parentElement;- if (parent) {- const rect = parent.getBoundingClientRect();- const x = Math.max(0, Math.min(screenX - rect.left, rect.width - 100));- el.style.left = `${x}px`;- }- }- },- [formatTooltipMs],- );-- const onDragStart = useCallback(- (event: DragStartEvent) => {- const span = event.active.data.current.getSpanFromDragEvent?.(event);- if (span) showTooltip(span);- },- [showTooltip],- );-- const onDragMove = useCallback(- (event: DragMoveEvent) => {- const rawSpan = event.active.data.current.getSpanFromDragEvent?.(event);- if (!rawSpan) return;- const activeItemId = event.active.id as string;- const clamped = totalMs > 0 ? clampSpanToBounds(rawSpan) : rawSpan;- const { span, snapPoint } = snapSpanToTargets(clamped, activeItemId, "drag");- updateSnapGuide(snapPoint);- const screenX =- event.activatorEvent && "clientX" in event.activatorEvent- ? (event.activatorEvent as PointerEvent).clientX + (event.delta?.x ?? 0)- : undefined;- showTooltip(span, screenX);- },- [clampSpanToBounds, showTooltip, snapSpanToTargets, totalMs, updateSnapGuide],- );-- const onResizeMove = useCallback(- (event: ResizeMoveEvent) => {- const rawSpan = event.active.data.current.getSpanFromResizeEvent?.(event);- if (!rawSpan) return;- const activeItemId = event.active.id as string;- const clamped = totalMs > 0 ? clampSpanToBounds(rawSpan) : rawSpan;- const mode = inferResizeMode(activeItemId, clamped);- const { span, snapPoint } =- mode !== null- ? snapSpanToTargets(clamped, activeItemId, mode)- : { span: clamped, snapPoint: null };- updateSnapGuide(snapPoint);- const screenX =- event.activatorEvent && "clientX" in event.activatorEvent- ? (event.activatorEvent as PointerEvent).clientX + (event.delta?.x ?? 0)- : undefined;- showTooltip(span, screenX);- },- [clampSpanToBounds, inferResizeMode, showTooltip, snapSpanToTargets, totalMs, updateSnapGuide],- );-- const hideTooltip = useCallback(() => showTooltip(null), [showTooltip]);-- const hideOverlays = useCallback(() => {- hideTooltip();- snapGuideRef.current?.hide();- }, [hideTooltip]);-- const onResizeEndWithTooltip = useCallback(- (event: ResizeEndEvent) => {- hideOverlays();- onResizeEnd(event);- },- [hideOverlays, onResizeEnd],- );-- const onDragEndWithTooltip = useCallback(- (event: DragEndEvent) => {- hideOverlays();- onDragEnd(event);- },- [hideOverlays, onDragEnd],- );-- const handleRangeChange = useCallback(- (updater: (previous: Range) => Range) => {- onRangeChange((prev) => {- const normalized = totalMs > 0 ? clampRange(prev) : prev;- const desired = updater(normalized);-- if (totalMs > 0) {- const clamped = clampRange(desired);-- if (clamped.end > totalMs) {- const span = Math.min(clamped.end - clamped.start, totalMs);- return {- start: Math.max(0, totalMs - span),- end: totalMs,- };- }-- return clamped;- }-- return desired;- });- },- [clampRange, onRangeChange, totalMs],- );-- return (- <TimelineContext- range={range}- onRangeChanged={handleRangeChange}- onResizeEnd={onResizeEndWithTooltip}- onResizeMove={onResizeMove}- onDragStart={onDragStart}- onDragMove={onDragMove}- onDragEnd={onDragEndWithTooltip}- autoScroll={{ enabled: false }}- >- <div className="relative">- {children}- <SnapGuide ref={snapGuideRef} />- {/* Floating tooltip shown during drag/resize */}- <div- ref={tooltipRef}- className="absolute top-1 pointer-events-none z-[60] px-1.5 py-0.5 rounded bg-black/80 text-[10px] text-white/90 font-medium tabular-nums whitespace-nowrap border border-white/10 shadow-lg"- style={{ opacity: 0, transition: "opacity 0.1s" }}- />- </div>- </TimelineContext>- );-}diff --git a/src/components/video-editor/timeline/zoomSuggestionUtils.ts b/src/components/video-editor/timeline/zoomSuggestionUtils.tsdeleted file mode 100644index f083a7f7c..000000000--- a/src/components/video-editor/timeline/zoomSuggestionUtils.ts+++ /dev/null@@ -1,156 +0,0 @@-import type { CursorTelemetryPoint, ZoomFocus } from "../types";--export const MIN_DWELL_DURATION_MS = 450;-export const MAX_DWELL_DURATION_MS = 2600;-export const DWELL_MOVE_THRESHOLD = 0.02;-/** Minimum spacing between two accepted suggestion centres. */-export const SUGGESTION_SPACING_MS = 1800;--export interface ZoomDwellCandidate {- centerTimeMs: number;- focus: ZoomFocus;- strength: number;-}--function normalizeTelemetrySample(- sample: CursorTelemetryPoint,- totalMs: number,-): CursorTelemetryPoint {- return {- timeMs: Math.max(0, Math.min(sample.timeMs, totalMs)),- cx: Math.max(0, Math.min(sample.cx, 1)),- cy: Math.max(0, Math.min(sample.cy, 1)),- };-}--export function normalizeCursorTelemetry(- telemetry: CursorTelemetryPoint[],- totalMs: number,-): CursorTelemetryPoint[] {- return [...telemetry]- .filter(- (sample) =>- Number.isFinite(sample.timeMs) && Number.isFinite(sample.cx) && Number.isFinite(sample.cy),- )- .sort((a, b) => a.timeMs - b.timeMs)- .map((sample) => normalizeTelemetrySample(sample, totalMs));-}--export function detectZoomDwellCandidates(samples: CursorTelemetryPoint[]): ZoomDwellCandidate[] {- if (samples.length < 2) {- return [];- }-- const dwellCandidates: ZoomDwellCandidate[] = [];- let runStart = 0;-- const pushRunIfDwell = (startIndex: number, endIndexExclusive: number) => {- if (endIndexExclusive - startIndex < 2) {- return;- }-- const start = samples[startIndex];- const end = samples[endIndexExclusive - 1];- const runDuration = end.timeMs - start.timeMs;- if (runDuration < MIN_DWELL_DURATION_MS || runDuration > MAX_DWELL_DURATION_MS) {- return;- }-- const runSamples = samples.slice(startIndex, endIndexExclusive);- const avgCx = runSamples.reduce((sum, sample) => sum + sample.cx, 0) / runSamples.length;- const avgCy = runSamples.reduce((sum, sample) => sum + sample.cy, 0) / runSamples.length;-- dwellCandidates.push({- centerTimeMs: Math.round((start.timeMs + end.timeMs) / 2),- focus: { cx: avgCx, cy: avgCy },- strength: runDuration,- });- };-- for (let index = 1; index < samples.length; index += 1) {- const prev = samples[index - 1];- const curr = samples[index];- const distance = Math.hypot(curr.cx - prev.cx, curr.cy - prev.cy);-- if (distance > DWELL_MOVE_THRESHOLD) {- pushRunIfDwell(runStart, index);- runStart = index;- }- }- pushRunIfDwell(runStart, samples.length);-- return dwellCandidates;-}--export interface AutoZoomSuggestion {- span: { start: number; end: number };- focus: ZoomFocus;-}--/**- * Build non-overlapping zoom suggestions from cursor telemetry: detect dwell moments,- * rank by duration, space by SUGGESTION_SPACING_MS, drop any overlapping an existing- * region. Pure, shared by the magic-wand toggle and the on-load auto-suggest pass.- */-export function buildAutoZoomSuggestions(options: {- cursorTelemetry: CursorTelemetryPoint[];- totalMs: number;- existingRegions: { startMs: number; endMs: number }[];- defaultDurationMs: number;-}): AutoZoomSuggestion[] {- const { cursorTelemetry, totalMs, existingRegions, defaultDurationMs } = options;- if (totalMs <= 0 || cursorTelemetry.length < 2) {- return [];- }-- const defaultDuration = Math.min(defaultDurationMs, totalMs);- if (defaultDuration <= 0) {- return [];- }-- const normalizedSamples = normalizeCursorTelemetry(cursorTelemetry, totalMs);- if (normalizedSamples.length < 2) {- return [];- }-- const dwellCandidates = detectZoomDwellCandidates(normalizedSamples);- if (dwellCandidates.length === 0) {- return [];- }-- const reservedSpans = existingRegions- .map((region) => ({ start: region.startMs, end: region.endMs }))- .sort((a, b) => a.start - b.start);-- const sortedCandidates = [...dwellCandidates].sort((a, b) => b.strength - a.strength);- const acceptedCenters: number[] = [];- const suggestions: AutoZoomSuggestion[] = [];-- for (const candidate of sortedCandidates) {- const tooCloseToAccepted = acceptedCenters.some(- (center) => Math.abs(center - candidate.centerTimeMs) < SUGGESTION_SPACING_MS,- );- if (tooCloseToAccepted) {- continue;- }-- const centeredStart = Math.round(candidate.centerTimeMs - defaultDuration / 2);- const candidateStart = Math.max(0, Math.min(centeredStart, totalMs - defaultDuration));- const candidateEnd = candidateStart + defaultDuration;- const hasOverlap = reservedSpans.some(- (span) => candidateEnd > span.start && candidateStart < span.end,- );- if (hasOverlap) {- continue;- }-- reservedSpans.push({ start: candidateStart, end: candidateEnd });- acceptedCenters.push(candidate.centerTimeMs);- suggestions.push({- span: { start: candidateStart, end: candidateEnd },- focus: candidate.focus,- });- }-- return suggestions;-}diff --git a/src/components/video-editor/videoPlayback/index.ts b/src/components/video-editor/videoPlayback/index.tsdeleted file mode 100644index 06cf42edf..000000000--- a/src/components/video-editor/videoPlayback/index.ts+++ /dev/null@@ -1,8 +0,0 @@-export * from "./constants";-export * from "./focusUtils";-export * from "./layoutUtils";-export * from "./mathUtils";-export * from "./overlayUtils";-export * from "./videoEventHandlers";-export * from "./zoomRegionUtils";-export * from "./zoomTransform";diff --git a/src/components/video-editor/videoPlayback/layoutUtils.ts b/src/components/video-editor/videoPlayback/layoutUtils.tsdeleted file mode 100644index bdedf6a2f..000000000--- a/src/components/video-editor/videoPlayback/layoutUtils.ts+++ /dev/null@@ -1,155 +0,0 @@-import { Application, Graphics, Sprite } from "pixi.js";-import {- computeCompositeLayout,- type RenderRect,- type Size,- type StyledRenderRect,- type WebcamLayoutPreset,- type WebcamSizePreset,-} from "@/lib/compositeLayout";-import type { CropRegion, WebcamMaskShape } from "../types";--interface LayoutParams {- container: HTMLDivElement;- app: Application;- videoSprite: Sprite;- maskGraphics: Graphics;- videoElement: HTMLVideoElement;- cropRegion?: CropRegion;- lockedVideoDimensions?: { width: number; height: number } | null;- borderRadius?: number;- padding?: number;- webcamDimensions?: Size | null;- webcamLayoutPreset?: WebcamLayoutPreset;- webcamSizePreset?: WebcamSizePreset;- webcamPosition?: { cx: number; cy: number } | null;- webcamMaskShape?: WebcamMaskShape;-}--interface LayoutResult {- stageSize: { width: number; height: number };- videoSize: { width: number; height: number };- baseScale: number;- baseOffset: { x: number; y: number };- maskRect: RenderRect;- maskBorderRadius: number;- webcamRect: StyledRenderRect | null;- cropBounds: { startX: number; endX: number; startY: number; endY: number };-}--export function layoutVideoContent(params: LayoutParams): LayoutResult | null {- const {- container,- app,- videoSprite,- maskGraphics,- videoElement,- cropRegion,- lockedVideoDimensions,- borderRadius = 0,- padding = 0,- webcamDimensions,- webcamLayoutPreset,- webcamSizePreset,- webcamPosition,- webcamMaskShape,- } = params;-- const videoWidth = lockedVideoDimensions?.width || videoElement.videoWidth;- const videoHeight = lockedVideoDimensions?.height || videoElement.videoHeight;-- if (!videoWidth || !videoHeight) {- return null;- }-- const width = container.clientWidth;- const height = container.clientHeight;-- if (!width || !height) {- return null;- }-- app.renderer.resize(width, height);- app.canvas.style.width = "100%";- app.canvas.style.height = "100%";-- const crop = cropRegion || { x: 0, y: 0, width: 1, height: 1 };-- const croppedVideoWidth = videoWidth * crop.width;- const croppedVideoHeight = videoHeight * crop.height;-- const cropStartX = crop.x * videoWidth;- const cropStartY = crop.y * videoHeight;- const cropEndX = cropStartX + croppedVideoWidth;- const cropEndY = cropStartY + croppedVideoHeight;-- // Padding is a percent (0-100); 50 matches the original VIEWPORT_SCALE of 0.8.- // Vertical stack is full-bleed, so it ignores padding.- const effectivePadding = webcamLayoutPreset === "vertical-stack" ? 0 : padding;- const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;- const maxDisplayWidth = width * paddingScale;- const maxDisplayHeight = height * paddingScale;-- const compositeLayout = computeCompositeLayout({- canvasSize: { width, height },- maxContentSize: { width: maxDisplayWidth, height: maxDisplayHeight },- screenSize: { width: croppedVideoWidth, height: croppedVideoHeight },- webcamSize: webcamDimensions,- layoutPreset: webcamLayoutPreset,- webcamSizePreset,- webcamPosition,- webcamMaskShape,- });-- if (!compositeLayout) {- return null;- }-- const screenRect = compositeLayout.screenRect;-- // Cover mode: scale to fill the rect (may crop), otherwise fit-to-width- let scale: number;- if (compositeLayout.screenCover) {- scale = Math.max(screenRect.width / croppedVideoWidth, screenRect.height / croppedVideoHeight);- } else {- scale = screenRect.width / croppedVideoWidth;- }-- videoSprite.scale.set(scale);-- const fullVideoDisplayWidth = videoWidth * scale;- const fullVideoDisplayHeight = videoHeight * scale;-- // Position the video so the cropped region is centered within screenRect.- const croppedDisplayWidth = croppedVideoWidth * scale;- const croppedDisplayHeight = croppedVideoHeight * scale;- const offsetX = screenRect.x + (screenRect.width - croppedDisplayWidth) / 2;- const offsetY = screenRect.y + (screenRect.height - croppedDisplayHeight) / 2;- const spriteX = offsetX - crop.x * fullVideoDisplayWidth;- const spriteY = offsetY - crop.y * fullVideoDisplayHeight;-- videoSprite.position.set(spriteX, spriteY);-- // Mask clips the video to screenRect, with border radius.- maskGraphics.clear();- maskGraphics.roundRect(- screenRect.x,- screenRect.y,- screenRect.width,- screenRect.height,- compositeLayout.screenBorderRadius ?? (compositeLayout.screenCover ? 0 : borderRadius),- );- maskGraphics.fill({ color: 0xffffff });-- return {- stageSize: { width, height },- videoSize: { width: croppedVideoWidth, height: croppedVideoHeight },- baseScale: scale,- baseOffset: { x: spriteX, y: spriteY },- maskRect: compositeLayout.screenRect,- maskBorderRadius:- compositeLayout.screenBorderRadius ?? (compositeLayout.screenCover ? 0 : borderRadius),- webcamRect: compositeLayout.webcamRect,- cropBounds: { startX: cropStartX, endX: cropEndX, startY: cropStartY, endY: cropEndY },- };-}diff --git a/src/components/video-editor/videoPlayback/overlayUtils.ts b/src/components/video-editor/videoPlayback/overlayUtils.tsdeleted file mode 100644index 085993493..000000000--- a/src/components/video-editor/videoPlayback/overlayUtils.ts+++ /dev/null@@ -1,64 +0,0 @@-import { getZoomScale, type ZoomFocus, type ZoomRegion } from "../types";-import { clampFocusToScale } from "./focusUtils";--interface OverlayUpdateParams {- overlayEl: HTMLDivElement;- indicatorEl: HTMLDivElement;- region: ZoomRegion | null;- focusOverride?: ZoomFocus;- videoSize: { width: number; height: number };- baseScale: number;- isPlaying: boolean;-}--export function updateOverlayIndicator(params: OverlayUpdateParams) {- const { overlayEl, indicatorEl, region, focusOverride, videoSize, baseScale, isPlaying } = params;-- if (!region || region.focusMode === "auto") {- indicatorEl.style.display = "none";- overlayEl.style.pointerEvents = "none";- return;- }-- const stageWidth = overlayEl.clientWidth;- const stageHeight = overlayEl.clientHeight;-- if (!stageWidth || !stageHeight) {- indicatorEl.style.display = "none";- overlayEl.style.pointerEvents = "none";- return;- }-- if (!videoSize.width || !videoSize.height || baseScale <= 0) {- indicatorEl.style.display = "none";- overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";- return;- }-- const zoomScale = getZoomScale(region);- const focus = clampFocusToScale(focusOverride ?? region.focus, zoomScale);-- // Zoom window shows the stage area that will be visible after zooming (1/zoomScale of stage dimensions)- const indicatorWidth = stageWidth / zoomScale;- const indicatorHeight = stageHeight / zoomScale;-- const rawLeft = focus.cx * stageWidth - indicatorWidth / 2;- const rawTop = focus.cy * stageHeight - indicatorHeight / 2;-- const adjustedLeft =- indicatorWidth >= stageWidth- ? (stageWidth - indicatorWidth) / 2- : Math.max(0, Math.min(stageWidth - indicatorWidth, rawLeft));-- const adjustedTop =- indicatorHeight >= stageHeight- ? (stageHeight - indicatorHeight) / 2- : Math.max(0, Math.min(stageHeight - indicatorHeight, rawTop));-- indicatorEl.style.display = "block";- indicatorEl.style.width = `${indicatorWidth}px`;- indicatorEl.style.height = `${indicatorHeight}px`;- indicatorEl.style.left = `${adjustedLeft}px`;- indicatorEl.style.top = `${adjustedTop}px`;- overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";-}diff --git a/src/components/video-editor/videoPlayback/videoEventHandlers.ts b/src/components/video-editor/videoPlayback/videoEventHandlers.tsdeleted file mode 100644index aac2785cf..000000000--- a/src/components/video-editor/videoPlayback/videoEventHandlers.ts+++ /dev/null@@ -1,344 +0,0 @@-import type React from "react";-import { MAX_NATIVE_PLAYBACK_RATE, type SpeedRegion, type TrimRegion } from "../types";-import { createRafCoalescer } from "./rafCoalescer";--// Keep "scrub mode" on for a brief tail after `seeked`: rapid drag-scrubbing fires-// `seeking`/`seeked` dozens of times a second and toggling effects each time would flicker.-const SCRUB_END_DEBOUNCE_MS = 150;-// When seek-stepping crosses a speed region's end, land this far past it so the next-// frame's `currentTimeMs < endMs` check exits the region. A plain clamp to endMs/1000-// can stall: (endMs/1000)*1000 may read back below endMs. 0.5 ms is imperceptible and-// dominates any floating-point round-trip error.-const REGION_EXIT_MARGIN_SEC = 0.0005;-// Minimum forward distance (seconds) before seek-stepping issues a seek, so a no-op-// seek to the element's current position never arms the in-flight throttle.-const STEP_MIN_SEEK_SEC = 0.01;-// Recover the throttle if a step seek never reports `seeked` (e.g. seeking past a-// non-finite-duration source's buffered end) rather than freezing for the session.-const STEP_SEEK_TIMEOUT_MS = 500;--interface VideoEventHandlersParams {- video: HTMLVideoElement;- isSeekingRef: React.MutableRefObject<boolean>;- isPlayingRef: React.MutableRefObject<boolean>;- allowPlaybackRef: React.MutableRefObject<boolean>;- currentTimeRef: React.MutableRefObject<number>;- timeUpdateAnimationRef: React.MutableRefObject<number | null>;- onPlayStateChange: (playing: boolean) => void;- onTimeUpdate: (time: number) => void;- trimRegionsRef: React.MutableRefObject<TrimRegion[]>;- speedRegionsRef: React.MutableRefObject<SpeedRegion[]>;- isScrubbingRef?: React.MutableRefObject<boolean>;- scrubEndTimerRef?: React.MutableRefObject<number | null>;- onScrubChange?: (scrubbing: boolean) => void;- // Seek-stepping state for speed regions above the native playbackRate cap (16×):- // the element can't play that fast, so the rAF loop advances a virtual clock and- // forward-seeks the muted element to it each frame.- seekSteppingRef: React.MutableRefObject<boolean>;- stepVirtualSecRef: React.MutableRefObject<number>;- stepLastTsRef: React.MutableRefObject<number>;- stepPrevMutedRef: React.MutableRefObject<boolean>;-}--export function createVideoEventHandlers(params: VideoEventHandlersParams) {- const {- video,- isSeekingRef,- isPlayingRef,- allowPlaybackRef,- currentTimeRef,- timeUpdateAnimationRef,- onPlayStateChange,- onTimeUpdate,- trimRegionsRef,- speedRegionsRef,- isScrubbingRef,- scrubEndTimerRef,- onScrubChange,- seekSteppingRef,- stepVirtualSecRef,- stepLastTsRef,- stepPrevMutedRef,- } = params;-- // True while a seek-stepping forward seek is in flight (cleared by its `seeked`).- // Prevents issuing the next seek before the element has presented the current- // frame — seeking every rAF frame keeps a slow decoder perpetually mid-seek so- // the preview freezes. Local to the handler set (recreated when the video rewires).- let stepSeekInFlight = false;- let stepSeekIssuedAtMs = 0;- // One-shot: suppress scrub-mode for the internal catch-up seek issued when stepping- // hands back to native playback (that seek must not soften the preview / snap effects).- let suppressSeekScrubOnce = false;-- const clearScrubEndTimer = () => {- if (scrubEndTimerRef && scrubEndTimerRef.current !== null) {- window.clearTimeout(scrubEndTimerRef.current);- scrubEndTimerRef.current = null;- }- };-- // currentTimeRef is updated synchronously on every call (cheap; other imperative- // consumers like the Pixi renderer read it directly). The React state commit- // (`onTimeUpdate`) is coalesced to at most once per animation frame so a burst of- // `seeking` events (fast timeline drag) or the per-frame rAF playback loop can't- // force more than one parent re-render per frame.- const timeUpdateCoalescer = createRafCoalescer<number>(onTimeUpdate);-- const emitTime = (timeValue: number) => {- currentTimeRef.current = timeValue * 1000;- timeUpdateCoalescer.schedule(timeValue);- };-- const findActiveTrimRegion = (currentTimeMs: number): TrimRegion | null => {- const trimRegions = trimRegionsRef.current;- return (- trimRegions.find(- (region) => currentTimeMs >= region.startMs && currentTimeMs < region.endMs,- ) || null- );- };-- const findActiveSpeedRegion = (currentTimeMs: number): SpeedRegion | null => {- return (- speedRegionsRef.current.find(- (region) => currentTimeMs >= region.startMs && currentTimeMs < region.endMs,- ) || null- );- };-- // Enter seek-stepping: mute the element, cap its rate to the native ceiling, and- // seed the virtual clock from the current position. The element keeps "playing"- // (paused would tear the rAF loop down) but every frame we override its time.- const beginSeekStepping = (fromSec: number, nowMs: number) => {- stepVirtualSecRef.current = fromSec;- stepLastTsRef.current = nowMs;- stepPrevMutedRef.current = video.muted;- video.muted = true;- // Clear any real/trim seek that was still pending when stepping began — our- // per-frame step-seeks are suppressed in handleSeeked, so its `seeked` would- // otherwise never run and isSeekingRef would strand true (blocking the next play).- isSeekingRef.current = false;- try {- video.playbackRate = MAX_NATIVE_PLAYBACK_RATE;- } catch {- /* some elements reject rate changes mid-seek; the forward seek still drives time */- }- stepSeekInFlight = false;- seekSteppingRef.current = true;- };-- // Leave seek-stepping and restore the element's prior mute state so native- // playback (≤16×) resumes with sound.- const endSeekStepping = () => {- if (!seekSteppingRef.current) return;- seekSteppingRef.current = false;- video.muted = stepPrevMutedRef.current;- };-- function updateTime(now?: number) {- if (!video) return;-- const nowMs = now ?? performance.now();- // While stepping, the virtual clock — not the lagging element time — is the- // authority for which region is active and where the playhead sits.- const authoritativeSec = seekSteppingRef.current- ? stepVirtualSecRef.current- : video.currentTime;- const currentTimeMs = authoritativeSec * 1000;- const activeTrimRegion = findActiveTrimRegion(currentTimeMs);-- // In a trim region during playback: skip to its end- if (activeTrimRegion && !video.paused && !video.ended) {- const skipToTime = activeTrimRegion.endMs / 1000;-- // Pause if the skip would run past the end- if (skipToTime >= video.duration) {- endSeekStepping();- video.pause();- } else {- video.currentTime = skipToTime;- if (seekSteppingRef.current) {- stepVirtualSecRef.current = skipToTime;- stepLastTsRef.current = nowMs;- stepSeekInFlight = false;- }- emitTime(skipToTime);- }- } else {- const activeSpeedRegion = findActiveSpeedRegion(currentTimeMs);- const speed = activeSpeedRegion ? activeSpeedRegion.speed : 1;-- if (speed <= MAX_NATIVE_PLAYBACK_RATE) {- // Native path (unchanged for ≤16×): let the element play at `speed`.- if (seekSteppingRef.current) {- endSeekStepping();- // Snap the (possibly seek-lagged) element up to the virtual playhead so- // native playback resumes exactly where the playhead is, no backward jump.- // Flag it so the async seeking/seeked don't flip on scrub mode (which would- // soften the preview and snap effects for ~150ms at the boundary).- if (Math.abs(video.currentTime - stepVirtualSecRef.current) > STEP_MIN_SEEK_SEC) {- suppressSeekScrubOnce = true;- video.currentTime = stepVirtualSecRef.current;- }- }- video.playbackRate = speed;- emitTime(video.currentTime);- } else {- // Seek-stepping: advance a virtual clock at the true speed and yank the- // muted element forward to it each frame.- if (!seekSteppingRef.current) beginSeekStepping(video.currentTime, nowMs);- const dtSec = Math.max(0, (nowMs - stepLastTsRef.current) / 1000);- stepLastTsRef.current = nowMs;- // A non-finite duration (some WebM sources report Infinity until fully- // buffered) is not an end boundary — keep stepping until the region exits.- const endSec = Number.isFinite(video.duration) ? video.duration : Number.POSITIVE_INFINITY;- // Bound the advance to the active region so a fast frame doesn't overshoot- // far into the next region and skip its content — but land just *past* the- // end (not exactly on it) so the region is actually exited next frame.- const regionEndSec = activeSpeedRegion ? activeSpeedRegion.endMs / 1000 : endSec;- const rawNextSec = stepVirtualSecRef.current + speed * dtSec;- const nextSec = Math.min(- rawNextSec > regionEndSec ? regionEndSec + REGION_EXIT_MARGIN_SEC : rawNextSec,- endSec,- );-- if (nextSec >= endSec) {- stepVirtualSecRef.current = endSec;- video.currentTime = endSec;- emitTime(endSec);- endSeekStepping();- video.pause();- return;- }- stepVirtualSecRef.current = nextSec;- // The playhead advances at the true speed every frame; the muted element- // is seeked toward it only when the previous seek has landed (its `seeked`- // fired), so a slow decoder still presents/steps frames instead of freezing- // perpetually mid-seek. Require a real forward jump so a no-op seek (e.g. the- // first frame, where dt≈0) can't leave the in-flight flag stuck with no `seeked`.- // Recover if a prior seek never reported `seeked` (would otherwise strand the- // throttle and freeze the frame for the rest of the session).- if (stepSeekInFlight && nowMs - stepSeekIssuedAtMs > STEP_SEEK_TIMEOUT_MS) {- stepSeekInFlight = false;- }- if (!stepSeekInFlight && nextSec - video.currentTime > STEP_MIN_SEEK_SEC) {- stepSeekInFlight = true;- stepSeekIssuedAtMs = nowMs;- video.currentTime = nextSec;- }- emitTime(nextSec);- }- }-- if (!video.paused && !video.ended) {- timeUpdateAnimationRef.current = requestAnimationFrame(updateTime);- }- }-- const handlePlay = () => {- if (isSeekingRef.current) {- video.pause();- return;- }-- if (!allowPlaybackRef.current) {- video.pause();- return;- }-- isPlayingRef.current = true;- onPlayStateChange(true);- if (timeUpdateAnimationRef.current) {- cancelAnimationFrame(timeUpdateAnimationRef.current);- }- timeUpdateAnimationRef.current = requestAnimationFrame(updateTime);- };-- const handlePause = () => {- endSeekStepping();- isPlayingRef.current = false;- onPlayStateChange(false);- if (timeUpdateAnimationRef.current) {- cancelAnimationFrame(timeUpdateAnimationRef.current);- timeUpdateAnimationRef.current = null;- }- emitTime(video.currentTime);- };-- const handleSeeked = () => {- // Our own stepping seek landed (frame presented): allow the next one, then- // ignore the event — the rAF loop is the sole time authority while stepping.- if (seekSteppingRef.current) {- stepSeekInFlight = false;- return;- }- isSeekingRef.current = false;-- if (isScrubbingRef && scrubEndTimerRef) {- clearScrubEndTimer();- scrubEndTimerRef.current = window.setTimeout(() => {- isScrubbingRef.current = false;- scrubEndTimerRef.current = null;- onScrubChange?.(false);- }, SCRUB_END_DEBOUNCE_MS);- }-- const currentTimeMs = video.currentTime * 1000;- const activeTrimRegion = findActiveTrimRegion(currentTimeMs);-- // Seeked into a trim region while playing: skip to the end- if (activeTrimRegion && isPlayingRef.current && !video.paused) {- const skipToTime = activeTrimRegion.endMs / 1000;-- if (skipToTime >= video.duration) {- video.pause();- } else {- video.currentTime = skipToTime;- emitTime(skipToTime);- }- } else {- if (!isPlayingRef.current && !video.paused) {- video.pause();- }- emitTime(video.currentTime);- }- };-- const handleSeeking = () => {- // Our per-frame forward seeks must not flip the element into scrub mode- // (which would disable zoom/blur effects every frame during stepping).- // Known limitation: while a >16× region is actively playing, the virtual clock- // owns the playhead, so scrubbing mid-playback is overridden on the next frame —- // pause first to reposition. (Distinguishing a user scrub from our own large- // async forward seeks reliably isn't feasible, so we don't try.)- if (seekSteppingRef.current) return;- // The internal catch-up seek on stepping->native handback must not enter scrub.- if (suppressSeekScrubOnce) {- suppressSeekScrubOnce = false;- return;- }- isSeekingRef.current = true;-- if (isScrubbingRef) {- clearScrubEndTimer();- if (!isScrubbingRef.current) {- isScrubbingRef.current = true;- onScrubChange?.(true);- }- }-- if (!isPlayingRef.current && !video.paused) {- video.pause();- }- emitTime(video.currentTime);- };-- return {- handlePlay,- handlePause,- handleSeeked,- handleSeeking,- dispose: () => timeUpdateCoalescer.cancel(),- };-}diff --git a/src/hooks/recorderHandle.ts b/src/hooks/recorderHandle.tsindex 6264b9be5..e4c60bfdb 100644--- a/src/hooks/recorderHandle.ts+++ b/src/hooks/recorderHandle.ts@@ -96,10 +96,16 @@ export function createRecorderHandle();const recordedBlobPromise = new Promise<Blob>((resolve, reject) => {+ let _chunkCount = 0;+ let _totalBytes = 0;+ let firstChunkArrived = false;recorder.ondataavailable = (event: BlobEvent) => {if (!event.data || event.data.size === 0) {return;}+ _chunkCount += 1;+ _totalBytes += event.data.size;+ firstChunkArrived = true;if (mode === "streaming") {enqueueWrite(event.data);} else {@@ -115,6 +121,49 @@ export function createRecorderHandle(recorder.onstop = () => {resolve(finalizeBlob());};++ // ponytail: watchdog for the encoder-stall failure. Chromium's+ // WebM/H.264 software encoder can silently stop producing output if+ // over-driven (e.g. 4K@60fps with too-high videoBitsPerSecond). The+ // symptom is `ondataavailable` never firing while state stays+ // "recording" and the stream is live. The bitrate cap in+ // useScreenRecorder prevents this in normal use, but the watchdog+ // catches any future regression (different codec, different+ // encoder, etc.). The first chunk clears the timer; stop() also+ // clears it via the recorder.onstop path.+ const watchdogMs = 3000;+ const watchdog = setTimeout(() => {+ if (firstChunkArrived) return;+ if (recorder.state === "inactive") return;+ const err = new Error(+ `Recorder produced no data within ${watchdogMs}ms of start(). ` ++ `State=${recorder.state} mode=${mode} ` ++ `streamActive=${stream.active} ` ++ `videoReadyStates=${stream+ .getVideoTracks()+ .map((t) => t.readyState)+ .join(",")}. ` ++ `This usually means the encoder stalled (over-driven bitrate) or the source stream has no frames.`,+ );+ try {+ if (recorder.state === "recording" || recorder.state === "paused") {+ recorder.stop();+ }+ } catch {+ // already stopped+ }+ reject(err);+ }, watchdogMs);+ const origOnStop = recorder.onstop;+ recorder.onstop = (event: Event) => {+ clearTimeout(watchdog);+ if (origOnStop) (origOnStop as (e: Event) => void)(event);+ };+ const origOnError = recorder.onerror;+ recorder.onerror = (event: Event) => {+ clearTimeout(watchdog);+ if (origOnError) (origOnError as (e: Event) => void)(event);+ };});async function finalizeBlob(): Promise<Blob> {diff --git a/src/hooks/rendererConsoleForwarder.ts b/src/hooks/rendererConsoleForwarder.tsnew file mode 100644index 000000000..4fde445f3--- /dev/null+++ b/src/hooks/rendererConsoleForwarder.ts@@ -0,0 +1,38 @@+// ponytail: forward console.warn/error/log from the renderer to the main+// process so the diagnostic lines in `src/hooks/recorderHandle.ts` (and any+// other renderer-side logging) show up in `npm run dev` output. Without+// this, the renderer's `console.*` only goes to DevTools.+//+// Safe to ship: one-way, no backpressure, no return value. Silently no-ops+// if the preload bridge isn't available (e.g. unit tests in jsdom).++const api = (+ typeof window !== "undefined"+ ? (+ window as {+ electronAPI?: {+ rendererConsole?: (channel: "log" | "warn" | "error", args: unknown[]) => void;+ };+ }+ ).electronAPI+ : undefined+)?.rendererConsole;++if (api) {+ const wrap = (channel: "log" | "warn" | "error") => {+ const original = console[channel].bind(console);+ console[channel] = (...args: unknown[]) => {+ try {+ api(channel, args);+ } catch {+ // ponytail: never let the forwarder break the caller's logging.+ }+ original(...args);+ };+ };+ wrap("log");+ wrap("warn");+ wrap("error");+}++export {};diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex af95b4722..c682005cb 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -2,7 +2,6 @@ import { fixWebmDuration } from "@fix-webm-duration/fix";import { useCallback, useEffect, useRef, useState } from "react";import { toast } from "sonner";import { useScopedT } from "@/contexts/I18nContext";-import { MIC_GAIN_BOOST, mixAudioTracks } from "@/lib/audioMix";import {type NativeMacRecordingRequest,parseMacDisplayIdFromSourceId,@@ -14,7 +13,6 @@ import {} from "@/lib/nativeWindowsRecording";import type { CursorCaptureMode, RecordedVideoAssetInput } from "@/lib/recordingSession";import { requestCameraAccess } from "@/lib/requestCameraAccess";-import { loadUserPreferences, saveUserPreferences } from "@/lib/userPreferences";import { createRecorderHandle, type RecorderHandle } from "./recorderHandle";const TARGET_FRAME_RATE = 60;@@ -31,6 +29,12 @@ const BITRATE_QHD = 28_000_000;const BITRATE_BASE = 18_000_000;const HIGH_FRAME_RATE_THRESHOLD = 60;const HIGH_FRAME_RATE_BOOST = 1.7;+// ponytail: Chromium's WebM/H.264 software encoder silently stalls (no+// ondataavailable) when the requested videoBitsPerSecond exceeds what it can+// produce in real time — see recorderHandle.ts watchdog for the symptoms.+// Cap at 30 Mbps (Netflix 4K HDR is ~25 Mbps) so the encoder is never+// over-driven, regardless of resolution or frame rate.+const MAX_BITRATE = 30_000_000;const DEFAULT_WIDTH = 1920;const DEFAULT_HEIGHT = 1080;@@ -46,6 +50,7 @@ const WEBCAM_FILE_SUFFIX = "-webcam";const AUDIO_BITRATE_VOICE = 128_000;const AUDIO_BITRATE_SYSTEM = 192_000;+const MIC_GAIN_BOOST = 1.4;const WEBCAM_TARGET_FRAME_RATE = 30;type UseScreenRecorderReturn = {@@ -74,8 +79,6 @@ type UseScreenRecorderReturn = {setWebcamEnabled: (enabled: boolean) => Promise<boolean>;cursorCaptureMode: CursorCaptureMode;setCursorCaptureMode: (mode: CursorCaptureMode) => void;- softwareEncoderFallbackNoticeVisible: boolean;- dismissSoftwareEncoderFallbackNotice: (dontShowAgain?: boolean) => void;};type NativeWindowsRecordingHandle = {@@ -105,8 +108,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {const [systemAudioEnabled, setSystemAudioEnabled] = useState(false);const [webcamEnabled, setWebcamEnabledState] = useState(false);const [cursorCaptureMode, setCursorCaptureMode] = useState<CursorCaptureMode>("editable-overlay");- const [softwareEncoderFallbackNoticeVisible, setSoftwareEncoderFallbackNoticeVisible] =- useState(false);const screenRecorder = useRef<RecorderHandle | null>(null);const webcamRecorder = useRef<RecorderHandle | null>(null);const nativeWindowsRecording = useRef<NativeWindowsRecordingHandle | null>(null);@@ -161,15 +162,17 @@ export function useScreenRecorder(): UseScreenRecorderReturn {const highFrameRateBoost =TARGET_FRAME_RATE >= HIGH_FRAME_RATE_THRESHOLD ? HIGH_FRAME_RATE_BOOST : 1;+ let bitrate: number;if (pixels >= FOUR_K_PIXELS) {- return Math.round(BITRATE_4K * highFrameRateBoost);+ bitrate = BITRATE_4K * highFrameRateBoost;+ } else if (pixels >= QHD_PIXELS) {+ bitrate = BITRATE_QHD * highFrameRateBoost;+ } else {+ bitrate = BITRATE_BASE * highFrameRateBoost;}-- if (pixels >= QHD_PIXELS) {- return Math.round(BITRATE_QHD * highFrameRateBoost);- }-- return Math.round(BITRATE_BASE * highFrameRateBoost);+ // ponytail: cap so Chromium's H.264 software encoder doesn't stall on+ // 4K@60fps. See recorderHandle.ts for the failure mode.+ return Math.round(Math.min(bitrate, MAX_BITRATE));};const teardownMedia = useCallback(() => {@@ -395,6 +398,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!result.success) {console.error("Failed to store recording session:", result.message);+ toast.error(result.message ?? "Recording failed to save", {+ description: "Try recording again. If the problem persists, restart the app.",+ });return;}// store-recorded-session has flushed and closed the saved streams.@@ -849,7 +855,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}const request: NativeWindowsRecordingRequest = {recordingId: activeRecordingId,- preferSoftwareEncoder: loadUserPreferences().preferSoftwareEncoder,source: {type: sourceType,sourceId: selectedSource.id,@@ -895,13 +900,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {throw new Error(result.error ?? "Native Windows capture failed.");}- // Tell the user when the helper silently switched away from the default- // GPU encoder; an explicit software-preferred selection needs no notice.- setSoftwareEncoderFallbackNoticeVisible(- result.videoEncoderSelection === "software-fallback" &&- !loadUserPreferences().hideSoftwareEncoderFallbackNotice,- );-recordingId.current = result.recordingId;nativeWindowsRecording.current = {recordingId: result.recordingId,@@ -974,12 +972,20 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!isCountdownRunActive(countdownRunToken)) {return true;}- if (!webcamStream.current) {+ if (webcamStream.current) {+ nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {+ mimeType: selectMimeType(),+ videoBitsPerSecond: BITRATE_BASE,+ });+ } else {webcamAcquireId.current++;setWebcamEnabledState(false);}}if (!isCountdownRunActive(countdownRunToken)) {+ if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {+ nativeWebcamRecorder.recorder.stop();+ }return true;}const request: NativeMacRecordingRequest = {@@ -1026,33 +1032,19 @@ export function useScreenRecorder(): UseScreenRecorderReturn {};const result = await window.electronAPI.startNativeMacRecording(request);if (!result.success || !result.recordingId) {+ if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {+ nativeWebcamRecorder.recorder.stop();+ }throw new Error(result.error ?? "Native macOS capture failed.");}if (!isCountdownRunActive(countdownRunToken)) {+ if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {+ nativeWebcamRecorder.recorder.stop();+ }await window.electronAPI.stopNativeMacRecording(true);return true;}- // Start the webcam recorder only after the helper has emitted- // recording-started (startNativeMacRecording resolves on that event).- // Starting it earlier bakes the helper's capture startup latency- // (~1s of pre-roll) into the webcam file, desyncing it from the- // screen/mic recording that the editor and exporter align at t=0.- if (webcamEnabled && webcamStream.current) {- try {- nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {- mimeType: selectMimeType(),- videoBitsPerSecond: BITRATE_BASE,- });- } catch (webcamError) {- // The native helper is already recording at this point; stop it before- // surfacing the error so we don't leave it running with no handle to- // finalize it (this creation moved after startNativeMacRecording).- await window.electronAPI.stopNativeMacRecording(true);- throw webcamError;- }- }-recordingId.current = result.recordingId;nativeMacRecording.current = {recordingId: result.recordingId,@@ -1187,33 +1179,37 @@ export function useScreenRecorder(): UseScreenRecorderReturn {return;}- // Capture screen + microphone in parallel: the gap between the two- // `getUserMedia` calls is the dominant source of the mic-vs-video lag at the- // start of the recording (issue #57).- const screenCapture = (async (): Promise<MediaStream> => {- const platform = await window.electronAPI.getPlatform();-- if (platform === "win32") {- // getDisplayMedia + setDisplayMediaRequestHandler (main.ts) supplies the- // pre-selected source. Editable cursor mode excludes the system cursor so- // the editor can render a replacement; system mode bakes it into the video.- return navigator.mediaDevices.getDisplayMedia({- video: {- cursor: cursorCaptureMode === "editable-overlay" ? "never" : "always",- width: { max: TARGET_WIDTH },- height: { max: TARGET_HEIGHT },- frameRate: { ideal: TARGET_FRAME_RATE },- } as MediaTrackConstraints,- audio: systemAudioEnabled,- } as DisplayMediaStreamOptions);- }+ let screenMediaStream: MediaStream;+ const platform = await window.electronAPI.getPlatform();+ if (platform === "win32") {+ // getDisplayMedia + setDisplayMediaRequestHandler (main.ts) supplies the+ // pre-selected source. Editable cursor mode excludes the system cursor so+ // the editor can render a replacement; system mode bakes it into the video.+ // ponytail: use `ideal: 1920×1080` so the capture matches the display's+ // physical content (avoiding 4K upscaling on a 1080p display with+ // 200% DPI scaling, which is what was over-driving the H.264 encoder+ // and producing 0-byte files). Cap the max at 1920×1080 so a 4K+ // display also captures at 1080p — keeps bitrate low and the+ // encoder real-time. A higher-res path can be opt-in later.+ screenMediaStream = await navigator.mediaDevices.getDisplayMedia({+ video: {+ cursor: cursorCaptureMode === "editable-overlay" ? "never" : "always",+ width: { ideal: 1920, max: 1920 },+ height: { ideal: 1080, max: 1080 },+ frameRate: { ideal: TARGET_FRAME_RATE, max: TARGET_FRAME_RATE },+ } as MediaTrackConstraints,+ audio: systemAudioEnabled,+ } as DisplayMediaStreamOptions);+ } else {const videoConstraints = {mandatory: {chromeMediaSource: CHROME_MEDIA_SOURCE,chromeMediaSourceId: selectedSource.id,- maxWidth: TARGET_WIDTH,- maxHeight: TARGET_HEIGHT,+ // ponytail: see the Windows path — keep the capture at+ // 1080p so the H.264 encoder can keep up in real time.+ maxWidth: 1920,+ maxHeight: 1080,maxFrameRate: TARGET_FRAME_RATE,minFrameRate: MIN_FRAME_RATE,},@@ -1221,7 +1217,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (systemAudioEnabled) {try {- return navigator.mediaDevices.getUserMedia({+ screenMediaStream = await navigator.mediaDevices.getUserMedia({audio: {mandatory: {chromeMediaSource: CHROME_MEDIA_SOURCE,@@ -1233,66 +1229,48 @@ export function useScreenRecorder(): UseScreenRecorderReturn {} catch (audioErr) {console.warn("System audio capture failed, falling back to video-only:", audioErr);toast.error(t("recording.systemAudioUnavailable"));- return navigator.mediaDevices.getUserMedia({+ screenMediaStream = await navigator.mediaDevices.getUserMedia({audio: false,video: videoConstraints,} as unknown as MediaStreamConstraints);}+ } else {+ screenMediaStream = await navigator.mediaDevices.getUserMedia({+ audio: false,+ video: videoConstraints,+ } as unknown as MediaStreamConstraints);}+ }+ screenStream.current = screenMediaStream;- return navigator.mediaDevices.getUserMedia({- audio: false,- video: videoConstraints,- } as unknown as MediaStreamConstraints);- })();-- const micCapture: Promise<MediaStream | null> = microphoneEnabled- ? (async () => {- try {- return await navigator.mediaDevices.getUserMedia({- audio: microphoneDeviceId- ? {- deviceId: { exact: microphoneDeviceId },- echoCancellation: true,- noiseSuppression: true,- autoGainControl: true,- }- : {- echoCancellation: true,- noiseSuppression: true,- autoGainControl: true,- },- video: false,- });- } catch (audioError) {- console.warn("Failed to get microphone access:", audioError);- toast.error(t("recording.microphoneDenied"));- setMicrophoneEnabled(false);- return null;- }- })()- : Promise.resolve(null);+ if (!isCountdownRunActive(countdownRunToken)) {+ teardownMedia();+ return;+ }- // Await both in-flight captures. If the screen capture rejects it would- // otherwise orphan a mic stream that resolved in parallel (leaving the- // screen/mic indicator on), so stop that stream before rethrowing.- let screenMediaStream: MediaStream;- try {- screenMediaStream = await screenCapture;- } catch (error) {- void micCapture- .then((micStream) => micStream?.getTracks().forEach((track) => track.stop()))- .catch(() => {- // Mic capture itself failed too; nothing left to stop.+ if (microphoneEnabled) {+ try {+ microphoneStream.current = await navigator.mediaDevices.getUserMedia({+ audio: microphoneDeviceId+ ? {+ deviceId: { exact: microphoneDeviceId },+ echoCancellation: true,+ noiseSuppression: true,+ autoGainControl: true,+ }+ : {+ echoCancellation: true,+ noiseSuppression: true,+ autoGainControl: true,+ },+ video: false,});- throw error;+ } catch (audioError) {+ console.warn("Failed to get microphone access:", audioError);+ toast.error(t("recording.microphoneDenied"));+ setMicrophoneEnabled(false);+ }}- const micMediaStream = await micCapture;-- // Assign the refs before the cancellation check below so teardownMedia() can- // stop the freshly acquired streams if the countdown was cancelled mid-capture.- screenStream.current = screenMediaStream;- microphoneStream.current = micMediaStream;if (!isCountdownRunActive(countdownRunToken)) {teardownMedia();@@ -1335,15 +1313,21 @@ export function useScreenRecorder(): UseScreenRecorderReturn {const systemAudioTrack = screenMediaStream.getAudioTracks()[0];const micAudioTrack = microphoneStream.current?.getAudioTracks()[0];- const { context: mixingCtx, track: mixedTrack } = mixAudioTracks({- systemAudioTrack,- micAudioTrack,- });- if (mixingCtx) {- mixingContext.current = mixingCtx;- }- if (mixedTrack) {- stream.current.addTrack(mixedTrack);+ if (systemAudioTrack && micAudioTrack) {+ const ctx = new AudioContext();+ mixingContext.current = ctx;+ const systemSource = ctx.createMediaStreamSource(new MediaStream([systemAudioTrack]));+ const micSource = ctx.createMediaStreamSource(new MediaStream([micAudioTrack]));+ const micGain = ctx.createGain();+ micGain.gain.value = MIC_GAIN_BOOST;+ const destination = ctx.createMediaStreamDestination();+ systemSource.connect(destination);+ micSource.connect(micGain).connect(destination);+ stream.current.addTrack(destination.stream.getAudioTracks()[0]);+ } else if (systemAudioTrack) {+ stream.current.addTrack(systemAudioTrack);+ } else if (micAudioTrack) {+ stream.current.addTrack(micAudioTrack);}try {@@ -1715,13 +1699,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}};- const dismissSoftwareEncoderFallbackNotice = (dontShowAgain = false) => {- if (dontShowAgain) {- saveUserPreferences({ hideSoftwareEncoderFallbackNotice: true });- }- setSoftwareEncoderFallbackNoticeVisible(false);- };-return {recording,paused,@@ -1748,7 +1725,5 @@ export function useScreenRecorder(): UseScreenRecorderReturn {setWebcamEnabled,cursorCaptureMode,setCursorCaptureMode,- softwareEncoderFallbackNoticeVisible,- dismissSoftwareEncoderFallbackNotice,};}diff --git a/src/hooks/useTheme.ts b/src/hooks/useTheme.tsnew file mode 100644index 000000000..1b27a5c2b--- /dev/null+++ b/src/hooks/useTheme.ts@@ -0,0 +1,45 @@+import { useCallback, useEffect, useState } from "react";++export type Theme = "light" | "dark";++const STORAGE_KEY = "openscreen-theme";++function readStoredTheme(): Theme {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ return raw === "dark" ? "dark" : "light";+ } catch {+ return "light";+ }+}++function applyTheme(theme: Theme) {+ if (theme === "dark") {+ document.documentElement.setAttribute("data-theme", "dark");+ } else {+ document.documentElement.removeAttribute("data-theme");+ }+}++export function useTheme(): { theme: Theme; toggle: () => void; setTheme: (t: Theme) => void } {+ const [theme, setThemeState] = useState<Theme>(() => readStoredTheme());++ useEffect(() => {+ applyTheme(theme);+ try {+ localStorage.setItem(STORAGE_KEY, theme);+ } catch {+ // ponytail: storage may be unavailable in private browsing+ }+ }, [theme]);++ const toggle = useCallback(() => {+ setThemeState((prev) => (prev === "dark" ? "light" : "dark"));+ }, []);++ const setTheme = useCallback((t: Theme) => {+ setThemeState(t);+ }, []);++ return { theme, toggle, setTheme };+}diff --git a/src/lib/ai-edition/document/ids.ts b/src/lib/ai-edition/document/ids.tsnew file mode 100644index 000000000..cd8fcb170--- /dev/null+++ b/src/lib/ai-edition/document/ids.ts@@ -0,0 +1,8 @@+import { v4 as uuidv4 } from "uuid";++// ponytail: stable id format `${prefix}_${uuid}` — readable in stored documents+// and grep-friendly. Replacement for axcut's packages/axcut-schema ids helper+// until the full schema package lands in-tree.+export function createId(prefix: string): string {+ return `${prefix}_${uuidv4()}`;+}diff --git a/src/lib/ai-edition/document/migrate.test.ts b/src/lib/ai-edition/document/migrate.test.tsnew file mode 100644index 000000000..bf2131c01--- /dev/null+++ b/src/lib/ai-edition/document/migrate.test.ts@@ -0,0 +1,305 @@+import { describe, expect, it } from "vitest";+import type { EditorProjectData } from "@/components/video-editor/projectPersistence";+import { migrateAxcutDocumentToProjectData, migrateProjectDataToAxcutDocument } from "./migrate";++function makeV2Project(overrides: Partial<EditorProjectData> = {}): EditorProjectData {+ return {+ version: 2,+ media: { screenVideoPath: "/recordings/screen.webm" },+ editor: {+ wallpaper: "/wallpapers/wallpaper1.jpg",+ shadowIntensity: 0,+ showBlur: false,+ showTrimWaveform: true,+ motionBlurAmount: 0,+ borderRadius: 0,+ padding: 50,+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },+ zoomRegions: [],+ autoZoomEnabled: false,+ autoFocusAll: false,+ trimRegions: [],+ speedRegions: [],+ annotationRegions: [],+ aspectRatio: "16:9",+ webcamLayoutPreset: "picture-in-picture",+ webcamMaskShape: "circle",+ webcamMirrored: true,+ webcamReactiveZoom: true,+ webcamSizePreset: 25,+ webcamPosition: { cx: 0.5, cy: 0.5 },+ exportQuality: "good",+ exportFormat: "mp4",+ gifFrameRate: 15,+ gifLoop: true,+ gifSizePreset: "medium",+ cursorTheme: "default",+ },+ ...overrides,+ };+}++describe("migrateProjectDataToAxcutDocument", () => {+ it("produces a v3 document with one asset and one clip from a v2 single-recording project", () => {+ const doc = migrateProjectDataToAxcutDocument(makeV2Project());++ expect(doc.schemaVersion).toBe(3);+ expect(doc.assets).toHaveLength(1);+ const asset = doc.assets[0];+ expect(asset.kind).toBe("video");+ expect(asset.originalPath).toBe("/recordings/screen.webm");+ expect(doc.project.primaryAssetId).toBe(asset.id);++ expect(doc.timeline.clips).toHaveLength(1);+ const clip = doc.timeline.clips[0];+ expect(clip.assetId).toBe(asset.id);+ expect(clip.sourceStartSec).toBe(0);+ expect(clip.sourceEndSec).toBeUndefined();+ });++ it("converts trimRegions to skipRanges on the primary asset (1.5s cut)", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ editor: {+ ...makeV2Project().editor,+ trimRegions: [{ id: "trim_a", startMs: 1000, endMs: 2500 }],+ },+ }),+ );++ expect(doc.timeline.skipRanges).toHaveLength(1);+ const skip = doc.timeline.skipRanges[0];+ expect(skip.assetId).toBe(doc.assets[0].id);+ expect(skip.startSec).toBeCloseTo(1.0, 3);+ expect(skip.endSec).toBeCloseTo(2.5, 3);+ expect(skip.origin).toBe("user");+ });++ it("converts speedRegions to timeline.speedRanges in seconds", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ editor: {+ ...makeV2Project().editor,+ speedRegions: [{ id: "spd_a", startMs: 5000, endMs: 8000, speed: 2 }],+ },+ }),+ );+ expect(doc.timeline.speedRanges).toHaveLength(1);+ expect(doc.timeline.speedRanges[0].startSec).toBeCloseTo(5.0, 3);+ expect(doc.timeline.speedRanges[0].endSec).toBeCloseTo(8.0, 3);+ });++ it("converts zoomRegions to seconds with focus normalized", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ editor: {+ ...makeV2Project().editor,+ zoomRegions: [+ {+ id: "z_1",+ startMs: 0,+ endMs: 2000,+ depth: 4,+ focus: { cx: 1.5, cy: -0.5 },+ focusMode: "manual",+ rotationPreset: "iso",+ customScale: 2.5,+ source: "manual",+ },+ ],+ },+ }),+ );+ expect(doc.zoomRanges).toHaveLength(1);+ const z = doc.zoomRanges[0];+ expect(z.depth).toBe(4);+ expect(z.focus.cx).toBe(1);+ expect(z.focus.cy).toBe(0);+ expect(z.startMs).toBe(0);+ expect(z.endMs).toBe(2000);+ expect(z.customScale).toBe(2.5);+ expect(z.rotationPreset).toBe("iso");+ });++ it("converts annotationRegions to seconds with type and content preserved", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ editor: {+ ...makeV2Project().editor,+ annotationRegions: [+ {+ id: "ann_1",+ startMs: 1000,+ endMs: 3000,+ type: "text",+ content: "Hello",+ position: { x: 4, y: 86 },+ size: { width: 92, height: 12 },+ style: {+ color: "#fff",+ backgroundColor: "transparent",+ fontSize: 24,+ fontFamily: "Inter",+ fontWeight: "bold",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+ },+ zIndex: 1,+ annotationSource: "auto-caption",+ },+ ],+ },+ }),+ );+ expect(doc.annotations).toHaveLength(1);+ const a = doc.annotations[0];+ expect(a.type).toBe("text");+ expect(a.startMs).toBe(1000);+ expect(a.endMs).toBe(3000);+ expect(a.annotationSource).toBe("auto-caption");+ });++ it("stores the v2 editor shape under legacyEditor for round-trip", () => {+ const v2 = makeV2Project();+ const doc = migrateProjectDataToAxcutDocument(v2);+ expect(doc.legacyEditor).toMatchObject({+ wallpaper: "/wallpapers/wallpaper1.jpg",+ cursorTheme: "default",+ autoZoomEnabled: false,+ });+ });++ it("handles missing media by creating an empty document", () => {+ const doc = migrateProjectDataToAxcutDocument({+ version: 2,+ editor: makeV2Project().editor,+ });+ expect(doc.assets).toEqual([]);+ expect(doc.timeline.clips).toEqual([]);+ expect(doc.project.primaryAssetId).toBeUndefined();+ });++ it("supports a legacy v1 videoPath-only project", () => {+ const doc = migrateProjectDataToAxcutDocument({+ version: 1,+ videoPath: "/legacy/recording.webm",+ editor: makeV2Project().editor,+ });+ expect(doc.assets).toHaveLength(1);+ expect(doc.assets[0].originalPath).toBe("/legacy/recording.webm");+ });++ it("ignores webcamPath on forward migration (renderer-side concern)", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ media: {+ screenVideoPath: "/screen.webm",+ webcamVideoPath: "/webcam.webm",+ cursorCaptureMode: "editable-overlay",+ },+ }),+ );+ expect(doc.assets).toHaveLength(1);+ expect(doc.assets[0].originalPath).toBe("/screen.webm");+ });+});++describe("migrateAxcutDocumentToProjectData", () => {+ it("round-trips skipRanges back to trimRegions", () => {+ const v2 = makeV2Project({+ editor: {+ ...makeV2Project().editor,+ trimRegions: [{ id: "trim_a", startMs: 1000, endMs: 2500 }],+ },+ });+ const doc = migrateProjectDataToAxcutDocument(v2);+ const back = migrateAxcutDocumentToProjectData(doc);+ expect(back.editor.trimRegions).toHaveLength(1);+ expect(back.editor.trimRegions[0].startMs).toBe(1000);+ expect(back.editor.trimRegions[0].endMs).toBe(2500);+ });++ it("round-trips legacyEditor fields back into editor.*", () => {+ const v2 = makeV2Project();+ const doc = migrateProjectDataToAxcutDocument(v2);+ const back = migrateAxcutDocumentToProjectData(doc);+ expect(back.editor.wallpaper).toBe("/wallpapers/wallpaper1.jpg");+ expect(back.editor.cursorTheme).toBe("default");+ expect(back.editor.webcamMaskShape).toBe("circle");+ });++ it("round-trips zoomRegions and annotationRegions back to ms", () => {+ const v2 = makeV2Project({+ editor: {+ ...makeV2Project().editor,+ zoomRegions: [+ {+ id: "z_1",+ startMs: 0,+ endMs: 2000,+ depth: 4,+ focus: { cx: 0.5, cy: 0.5 },+ },+ ],+ annotationRegions: [+ {+ id: "ann_1",+ startMs: 1000,+ endMs: 3000,+ type: "text",+ content: "Hello",+ position: { x: 50, y: 50 },+ size: { width: 30, height: 20 },+ style: {+ color: "#fff",+ backgroundColor: "transparent",+ fontSize: 24,+ fontFamily: "Inter",+ fontWeight: "bold",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+ },+ zIndex: 1,+ },+ ],+ },+ });+ const doc = migrateProjectDataToAxcutDocument(v2);+ const back = migrateAxcutDocumentToProjectData(doc);+ expect(back.editor.zoomRegions[0].startMs).toBe(0);+ expect(back.editor.zoomRegions[0].endMs).toBe(2000);+ expect(back.editor.annotationRegions[0].startMs).toBe(1000);+ expect(back.editor.annotationRegions[0].endMs).toBe(3000);+ });++ it("rebuilds media.screenVideoPath from the primary asset", () => {+ const v2 = makeV2Project();+ const doc = migrateProjectDataToAxcutDocument(v2);+ const back = migrateAxcutDocumentToProjectData(doc);+ expect(back.media?.screenVideoPath).toBe("/recordings/screen.webm");+ expect(back.videoPath).toBe("/recordings/screen.webm");+ });++ it("clamps bad zoom focus to [0, 1] on forward migration", () => {+ const doc = migrateProjectDataToAxcutDocument(+ makeV2Project({+ editor: {+ ...makeV2Project().editor,+ zoomRegions: [+ {+ id: "z_1",+ startMs: 0,+ endMs: 1000,+ depth: 1,+ focus: { cx: 2.5, cy: -0.5 },+ },+ ],+ },+ }),+ );+ expect(doc.zoomRanges[0].focus.cx).toBe(1);+ expect(doc.zoomRanges[0].focus.cy).toBe(0);+ });+});diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.tsnew file mode 100644index 000000000..b66aa5350--- /dev/null+++ b/src/lib/ai-edition/document/migrate.ts@@ -0,0 +1,333 @@+// Bidirectional migration between OpenScreen's v2 EditorProjectData and the+// new v3 AxcutDocument. See docs/architecture/ai-edition-merge-plan.md §2.1+// for the field-by-field mapping. The migration is pure (no DOM, no fs, no+// network) — the renderer probes asset duration at runtime.+//+// ponytail: this is the only code path that produces v3 documents today. Phase 1+// adds direct v3 writers (recording -> asset + clip) and the migration becomes+// the back-compat reader. Until then it is the front door for AI-edition.++import {+ type EditorProjectData,+ PROJECT_VERSION,+ type ProjectEditorState,+} from "@/components/video-editor/projectPersistence";+import type {+ AnnotationRegion,+ CropRegion,+ SpeedRegion,+ TrimRegion,+ ZoomRegion,+} from "@/components/video-editor/types";+import type { ProjectMedia } from "@/lib/recordingSession";+import {+ type AxcutAnnotationRegion,+ type AxcutDocument,+ type AxcutLegacyEditor,+ type AxcutSkipRange,+ type AxcutZoomRegion,+ documentSchema,+} from "../schema";+import { createId } from "./ids";++const MS_TO_SEC = 1 / 1000;+const SEC_TO_MS = 1000;++interface MigrationOptions {+ projectId?: string;+ title?: string;+ createdAt?: string;+}++function msToSec(ms: number): number {+ return Math.round(ms * MS_TO_SEC * 1000) / 1000;+}++function secToMs(sec: number): number {+ return Math.round(sec * SEC_TO_MS);+}++function clampSec(sec: number): number {+ if (!Number.isFinite(sec) || sec < 0) return 0;+ return Math.round(sec * 1000) / 1000;+}++function toLegacyMedia(input: ProjectMedia | undefined): ProjectMedia | null {+ if (!input) return null;+ const media: ProjectMedia = { screenVideoPath: input.screenVideoPath };+ if (input.webcamVideoPath) media.webcamVideoPath = input.webcamVideoPath;+ if (input.cursorCaptureMode) media.cursorCaptureMode = input.cursorCaptureMode;+ return media;+}++/**+ * Migrate a v2 EditorProjectData into a v3 AxcutDocument. The single recording+ * becomes one asset + one clip spanning the source. trimRegions become+ * skipRanges on that asset (semantically identical: both are cuts).+ */+export function migrateProjectDataToAxcutDocument(+ input: EditorProjectData,+ options: MigrationOptions = {},+): AxcutDocument {+ const now = options.createdAt ?? new Date().toISOString();+ const projectId = options.projectId ?? createId("proj");+ const title = options.title ?? (input.editor?.wallpaper?.trim() || "Untitled Project");++ const screenPath =+ typeof input.media?.screenVideoPath === "string" && input.media.screenVideoPath+ ? input.media.screenVideoPath+ : typeof input.videoPath === "string" && input.videoPath+ ? input.videoPath+ : null;++ const assets = screenPath+ ? [+ {+ id: createId("asset"),+ kind: "video" as const,+ label: screenPath.split(/[\\/]/).pop() || "Recording",+ originalPath: screenPath,+ },+ ]+ : [];++ const primaryAssetId = assets[0]?.id;++ const trimRegions: TrimRegion[] = Array.isArray(input.editor?.trimRegions)+ ? input.editor.trimRegions+ : [];+ const speedRegions: SpeedRegion[] = Array.isArray(input.editor?.speedRegions)+ ? input.editor.speedRegions+ : [];+ const zoomRegions: ZoomRegion[] = Array.isArray(input.editor?.zoomRegions)+ ? input.editor.zoomRegions+ : [];+ const annotationRegions: AnnotationRegion[] = Array.isArray(input.editor?.annotationRegions)+ ? input.editor.annotationRegions+ : [];++ const clip = primaryAssetId+ ? {+ id: createId("clip"),+ assetId: primaryAssetId,+ sourceStartSec: 0,+ timelineStartSec: 0,+ timelineEndSec: 0,+ wordRefs: [] as string[],+ origin: "system" as const,+ reason: "migrated from v2",+ }+ : null;++ const skipRanges: AxcutSkipRange[] = primaryAssetId+ ? trimRegions+ .filter((region) => region && typeof region.id === "string")+ .map((region) => {+ const startMs = Math.max(0, Math.min(region.startMs ?? 0, region.endMs ?? 0));+ const endMs = Math.max(startMs + 1, region.endMs ?? startMs + 1);+ return {+ id: createId("skip"),+ assetId: primaryAssetId,+ startSec: clampSec(msToSec(startMs)),+ endSec: clampSec(msToSec(endMs)),+ origin: "user" as const,+ reason: "migrated from v2 trimRegion",+ };+ })+ : [];++ // ponytail: speedRegions stay on the legacy editor envelope — axcut's+ // rangeSchema doesn't carry a speed value, and Phase 1 timeline rewrite is+ // when speed becomes a first-class timeline concept.+ const speedRanges = speedRegions.map((region) => ({+ startSec: clampSec(msToSec(Math.max(0, region.startMs ?? 0))),+ endSec: clampSec(msToSec(Math.max((region.startMs ?? 0) + 1, region.endMs ?? 0))),+ reason: "migrated from v2 speedRegion",+ }));++ // ponytail: annotations[] and zoomRanges[] mirror editor.annotationRegions+ // and editor.zoomRegions directly (same ms units) so the renderer can swap+ // them in/out without conversion. The timeline (skipRanges, speedRanges,+ // clip) uses axcut's seconds because the new timeline ops land there.+ const migratedZoomRanges: AxcutZoomRegion[] = zoomRegions+ .filter((region) => region && typeof region.id === "string")+ .map((region) => ({+ id: region.id,+ startMs: Math.max(0, region.startMs ?? 0),+ endMs: Math.max((region.startMs ?? 0) + 1, region.endMs ?? 0),+ depth: [1, 2, 3, 4, 5, 6].includes(region.depth) ? region.depth : 3,+ focus: {+ cx: Math.min(1, Math.max(0, region.focus?.cx ?? 0.5)),+ cy: Math.min(1, Math.max(0, region.focus?.cy ?? 0.5)),+ },+ ...(region.focusMode === "auto" ? { focusMode: "auto" as const } : {}),+ ...(region.rotationPreset ? { rotationPreset: region.rotationPreset } : {}),+ ...(typeof region.customScale === "number" ? { customScale: region.customScale } : {}),+ ...(region.source === "auto" || region.source === "manual" ? { source: region.source } : {}),+ }));++ const migratedAnnotations: AxcutAnnotationRegion[] = annotationRegions+ .filter((region) => region && typeof region.id === "string")+ .map((region) => ({+ id: region.id,+ startMs: Math.max(0, region.startMs ?? 0),+ endMs: Math.max((region.startMs ?? 0) + 1, region.endMs ?? 0),+ type: region.type,+ content: region.content ?? "",+ ...(region.textContent ? { textContent: region.textContent } : {}),+ ...(region.imageContent ? { imageContent: region.imageContent } : {}),+ position: region.position,+ size: region.size,+ style: region.style,+ zIndex: region.zIndex,+ ...(region.annotationSource === "auto-caption"+ ? { annotationSource: "auto-caption" as const }+ : {}),+ ...(region.figureData ? { figureData: region.figureData } : {}),+ ...(region.blurData ? { blurData: region.blurData } : {}),+ }));++ const legacyEditor: AxcutLegacyEditor = input.editor ? { ...input.editor } : null;++ const draft: AxcutDocument = {+ schemaVersion: 3 as const,+ project: {+ id: projectId,+ title,+ createdAt: now,+ updatedAt: now,+ ...(primaryAssetId ? { primaryAssetId } : {}),+ },+ assets,+ cameraTrack: null,+ transcript: null,+ transcripts: [],+ timeline: {+ clips: clip ? [clip] : [],+ gaps: [],+ skipRanges,+ muteRanges: [],+ speedRanges,+ captionRanges: [],+ },+ annotations: migratedAnnotations,+ zoomRanges: migratedZoomRanges,+ legacyEditor,+ agent: {+ pendingQuestions: [],+ suggestions: [],+ lastAppliedOperations: [],+ },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+ };++ return documentSchema.parse(draft);+}++/**+ * Migrate a v3 AxcutDocument back to a v2 EditorProjectData. Used when the+ * user toggles AI-edition off after a project was opened as v3. Round-trip is+ * not perfectly lossless — skipRanges map back to trimRegions (1:1), but the+ * timeline rebuild for clip ranges is best-effort and the speed regions remain+ * in the legacyEditor envelope where the migration put them.+ */+export function migrateAxcutDocumentToProjectData(input: AxcutDocument): EditorProjectData {+ const document = input;+ const assets = Array.isArray(document.assets) ? document.assets : [];+ const primary = document.project?.primaryAssetId+ ? assets.find((a) => a.id === document.project.primaryAssetId)+ : assets[0];+ // ponytail: surface the camera track back to v2 so the legacy VideoEditor+ // can still find the webcam path through `media.webcamVideoPath`.+ const media: ProjectMedia | null = primary+ ? toLegacyMedia({+ screenVideoPath: primary.originalPath,+ ...(document.cameraTrack?.sourcePath+ ? { webcamVideoPath: document.cameraTrack.sourcePath }+ : {}),+ })+ : null;++ const trimRegions: TrimRegion[] = (document.timeline?.skipRanges ?? []).map((region, index) => ({+ id: region.id ?? `trim-${index + 1}`,+ startMs: secToMs(clampSec(region.startSec ?? 0)),+ endMs: secToMs(Math.max(clampSec(region.startSec ?? 0) + 0.001, clampSec(region.endSec ?? 0))),+ }));++ const editor: ProjectEditorState = {+ wallpaper: "",+ shadowIntensity: 0,+ showBlur: false,+ showTrimWaveform: true,+ motionBlurAmount: 0,+ borderRadius: 0,+ padding: 50,+ cropRegion: { x: 0, y: 0, width: 1, height: 1 } as CropRegion,+ zoomRegions: [],+ autoZoomEnabled: false,+ autoFocusAll: false,+ trimRegions,+ speedRegions: [],+ annotationRegions: [],+ aspectRatio: "16:9",+ webcamLayoutPreset: "picture-in-picture",+ webcamMaskShape: "rectangle",+ webcamMirrored: false,+ webcamReactiveZoom: true,+ webcamSizePreset: 25,+ webcamPosition: null,+ exportQuality: "good",+ exportFormat: "mp4",+ gifFrameRate: 15,+ gifLoop: true,+ gifSizePreset: "medium",+ cursorTheme: "",+ };++ const legacy = document.legacyEditor;+ if (legacy && typeof legacy === "object") {+ Object.assign(editor, legacy);+ }++ const reverseZoomRegions: ZoomRegion[] = (document.zoomRanges ?? []).map((region) => ({+ id: region.id,+ startMs: region.startMs ?? 0,+ endMs: region.endMs ?? region.startMs ?? 0,+ depth: region.depth,+ focus: region.focus,+ ...(region.focusMode ? { focusMode: region.focusMode } : {}),+ ...(region.rotationPreset ? { rotationPreset: region.rotationPreset } : {}),+ ...(typeof region.customScale === "number" ? { customScale: region.customScale } : {}),+ ...(region.source ? { source: region.source } : {}),+ }));+ editor.zoomRegions = reverseZoomRegions;++ const reverseAnnotationRegions: AnnotationRegion[] = (document.annotations ?? []).map(+ (region) => ({+ id: region.id,+ startMs: region.startMs ?? 0,+ endMs: region.endMs ?? region.startMs ?? 0,+ type: region.type,+ content: region.content,+ ...(region.textContent ? { textContent: region.textContent } : {}),+ ...(region.imageContent ? { imageContent: region.imageContent } : {}),+ position: region.position,+ size: region.size,+ style: region.style,+ zIndex: region.zIndex,+ ...(region.annotationSource ? { annotationSource: region.annotationSource } : {}),+ ...(region.figureData ? { figureData: region.figureData } : {}),+ ...(region.blurData ? { blurData: region.blurData } : {}),+ }),+ );+ editor.annotationRegions = reverseAnnotationRegions;++ return {+ version: PROJECT_VERSION,+ ...(media ? { media } : {}),+ editor,+ ...(primary ? { videoPath: primary.originalPath } : {}),+ };+}diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsnew file mode 100644index 000000000..1524c5487--- /dev/null+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -0,0 +1,230 @@+import { describe, expect, it } from "vitest";+import type { AxcutDocument } from "../schema";+import {+ buildTimelineFromIntervals,+ invertIntervals,+ normalizeIntervals,+ primaryAssetDuration,+ replaceTimeline,+ restoreFullTimeline,+ subtractInterval,+ timelineIntervals,+} from "./timeline";++function makeDoc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {+ return {+ schemaVersion: 3,+ project: {+ id: "proj_1",+ title: "Test",+ createdAt: "2026-06-26T10:00:00Z",+ updatedAt: "2026-06-26T10:00:00Z",+ primaryAssetId: "asset_1",+ },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "screen.mp4",+ originalPath: "/tmp/screen.mp4",+ durationSec: 60,+ },+ ],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+ ...overrides,+ };+}++describe("timeline pure functions", () => {+ describe("normalizeIntervals", () => {+ it("sorts and merges overlapping intervals", () => {+ const result = normalizeIntervals(100, [+ { startSec: 10, endSec: 20 },+ { startSec: 5, endSec: 15 },+ { startSec: 30, endSec: 40 },+ ]);+ expect(result).toEqual([+ { startSec: 5, endSec: 20 },+ { startSec: 30, endSec: 40 },+ ]);+ });++ it("clamps to duration", () => {+ const result = normalizeIntervals(50, [{ startSec: -10, endSec: 200 }]);+ expect(result).toEqual([{ startSec: 0, endSec: 50 }]);+ });++ it("drops zero-length intervals", () => {+ const result = normalizeIntervals(100, [+ { startSec: 10, endSec: 10 },+ { startSec: 5, endSec: 8 },+ ]);+ expect(result).toEqual([{ startSec: 5, endSec: 8 }]);+ });+ });++ describe("subtractInterval", () => {+ it("splits an interval in two when the cut is in the middle", () => {+ const result = subtractInterval([{ startSec: 0, endSec: 60 }], { startSec: 20, endSec: 30 });+ expect(result).toEqual([+ { startSec: 0, endSec: 20 },+ { startSec: 30, endSec: 60 },+ ]);+ });++ it("trims the start when the cut overlaps the beginning", () => {+ const result = subtractInterval([{ startSec: 10, endSec: 60 }], { startSec: 0, endSec: 20 });+ expect(result).toEqual([{ startSec: 20, endSec: 60 }]);+ });++ it("returns the original when there is no overlap", () => {+ const result = subtractInterval([{ startSec: 0, endSec: 10 }], { startSec: 20, endSec: 30 });+ expect(result).toEqual([{ startSec: 0, endSec: 10 }]);+ });+ });++ describe("invertIntervals", () => {+ it("produces the complementary cuts", () => {+ const cuts = invertIntervals(+ [+ { startSec: 0, endSec: 20 },+ { startSec: 30, endSec: 60 },+ ],+ 60,+ );+ expect(cuts).toEqual([{ startSec: 20, endSec: 30 }]);+ });++ it("produces a full cut when intervals are empty", () => {+ expect(invertIntervals([], 60)).toEqual([{ startSec: 0, endSec: 60 }]);+ });+ });++ describe("buildTimelineFromIntervals", () => {+ it("assigns sequential timelineStart/End and clip ids", () => {+ const clips = buildTimelineFromIntervals(+ "asset_1",+ [+ { startSec: 0, endSec: 10 },+ { startSec: 20, endSec: 30 },+ ],+ { origin: "user", reason: "test", transcript: null },+ );+ expect(clips).toHaveLength(2);+ expect(clips[0]).toMatchObject({+ id: "clip_1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ });+ expect(clips[1]).toMatchObject({+ id: "clip_2",+ sourceStartSec: 20,+ sourceEndSec: 30,+ timelineStartSec: 10,+ timelineEndSec: 20,+ });+ });+ });++ describe("replaceTimeline", () => {+ it("rebuilds clips and derives skipRanges from the inverse", () => {+ const doc = makeDoc();+ const updated = replaceTimeline(+ doc,+ [+ { startSec: 0, endSec: 20 },+ { startSec: 30, endSec: 60 },+ ],+ "test cut",+ );+ expect(updated.timeline.clips).toHaveLength(2);+ expect(updated.timeline.skipRanges).toHaveLength(1);+ expect(updated.timeline.skipRanges[0]).toMatchObject({+ startSec: 20,+ endSec: 30,+ });+ expect(updated.preview.revision).toBe(1);+ });++ it("throws when there is no primary asset", () => {+ const doc = makeDoc({+ assets: [],+ project: { id: "p", title: "t", createdAt: "", updatedAt: "", primaryAssetId: undefined },+ });+ expect(() => replaceTimeline(doc, [], "x")).toThrow();+ });+ });++ describe("restoreFullTimeline", () => {+ it("sets a single interval spanning the full duration", () => {+ const doc = makeDoc({+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [+ { id: "s1", assetId: "asset_1", startSec: 10, endSec: 20, origin: "user", reason: "" },+ ],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ });+ const restored = restoreFullTimeline(doc);+ expect(restored.timeline.clips).toHaveLength(1);+ expect(restored.timeline.clips[0]).toMatchObject({+ sourceStartSec: 0,+ sourceEndSec: 60,+ });+ expect(restored.timeline.skipRanges).toHaveLength(0);+ });+ });++ describe("primaryAssetDuration + timelineIntervals", () => {+ it("reads durationSec from the primary asset", () => {+ expect(primaryAssetDuration(makeDoc())).toBe(60);+ });+ it("extracts intervals from existing clips", () => {+ const doc = makeDoc({+ timeline: {+ clips: [+ {+ id: "c1",+ assetId: "asset_1",+ sourceStartSec: 5,+ sourceEndSec: 15,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ });+ expect(timelineIntervals(doc)).toEqual([{ startSec: 5, endSec: 15 }]);+ });+ });+});diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsnew file mode 100644index 000000000..3ac884300--- /dev/null+++ b/src/lib/ai-edition/document/timeline.ts@@ -0,0 +1,174 @@+// Ported from axcut/apps/server/src/lib/timeline.ts — pure interval math for+// the clip/skip model. No DOM, no IPC, no side effects. The caller (store,+// exporter, agent) feeds an AxcutDocument and gets back intervals or a new+// document with updated clips.+//+// ponytail: only the ops Phase 1 needs (replaceTimeline, dropRange, restore).+// The full 11-op dispatcher lands in Phase 6 with the agent runtime.++import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";++function byStart(a: { startSec: number }, b: { startSec: number }): number {+ return a.startSec - b.startSec;+}++export interface Interval {+ startSec: number;+ endSec: number;+}++export function normalizeIntervals(durationSec: number, intervals: Interval[]): Interval[] {+ const bounded = intervals+ .map((item) => ({+ startSec: Math.max(0, Math.min(durationSec, item.startSec)),+ endSec: Math.max(0, Math.min(durationSec, item.endSec)),+ }))+ .filter((item) => item.endSec > item.startSec)+ .sort(byStart);++ const merged: Interval[] = [];+ for (const item of bounded) {+ const last = merged.at(-1);+ if (!last || item.startSec > last.endSec) {+ merged.push({ ...item });+ continue;+ }+ last.endSec = Math.max(last.endSec, item.endSec);+ }+ return merged;+}++export function primaryAssetDuration(document: AxcutDocument): number {+ const asset =+ document.assets.find((item) => item.id === document.project.primaryAssetId) ??+ document.assets[0];+ return asset?.durationSec ?? 0;+}++export function timelineIntervals(document: AxcutDocument): Interval[] {+ return normalizeIntervals(+ primaryAssetDuration(document),+ document.timeline.clips.map((clip) => ({+ startSec: clip.sourceStartSec,+ endSec: clip.sourceEndSec ?? primaryAssetDuration(document),+ })),+ );+}++export function buildTimelineFromIntervals(+ assetId: string,+ intervals: Interval[],+ options: {+ origin: "system" | "agent" | "user";+ reason: string;+ transcript: AxcutTranscript | null;+ },+): AxcutClip[] {+ let cursor = 0;+ return intervals.map((interval, index) => {+ const duration = interval.endSec - interval.startSec;+ const timelineStartSec = cursor;+ const timelineEndSec = cursor + duration;+ cursor = timelineEndSec;+ return {+ id: `clip_${index + 1}`,+ assetId,+ sourceStartSec: interval.startSec,+ sourceEndSec: interval.endSec,+ timelineStartSec,+ timelineEndSec,+ wordRefs: collectWordRefs(options.transcript, interval.startSec, interval.endSec),+ origin: options.origin,+ reason: options.reason,+ };+ });+}++function collectWordRefs(+ transcript: AxcutTranscript | null,+ startSec: number,+ endSec: number,+): string[] {+ if (!transcript) return [];+ return transcript.words+ .filter((word) => word.endSec > startSec && word.startSec < endSec)+ .map((word) => word.id);+}++export function subtractInterval(intervals: Interval[], cut: Interval): Interval[] {+ const output: Interval[] = [];+ for (const interval of intervals) {+ if (cut.endSec <= interval.startSec || cut.startSec >= interval.endSec) {+ output.push(interval);+ continue;+ }+ if (cut.startSec > interval.startSec) {+ output.push({ startSec: interval.startSec, endSec: cut.startSec });+ }+ if (cut.endSec < interval.endSec) {+ output.push({ startSec: cut.endSec, endSec: interval.endSec });+ }+ }+ return output;+}++export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {+ const cuts: Interval[] = [];+ let cursor = 0;+ for (const interval of normalizeIntervals(durationSec, intervals)) {+ if (interval.startSec > cursor) {+ cuts.push({ startSec: cursor, endSec: interval.startSec });+ }+ cursor = Math.max(cursor, interval.endSec);+ }+ if (cursor < durationSec) {+ cuts.push({ startSec: cursor, endSec: durationSec });+ }+ return cuts;+}++export function replaceTimeline(+ document: AxcutDocument,+ intervals: Interval[],+ reason: string,+ origin: "system" | "agent" | "user" = "user",+): AxcutDocument {+ const assetId = document.project.primaryAssetId ?? document.assets[0]?.id;+ if (!assetId) {+ throw new Error("Cannot update timeline without a primary asset.");+ }+ const duration = primaryAssetDuration(document);+ const normalized = normalizeIntervals(duration, intervals);+ const clips = buildTimelineFromIntervals(assetId, normalized, {+ origin,+ reason,+ transcript: document.transcript,+ });+ const skipRanges = invertIntervals(normalized, duration).map((cut, i) => ({+ id: `skip_${i + 1}`,+ assetId,+ startSec: cut.startSec,+ endSec: cut.endSec,+ origin,+ reason,+ }));+ return {+ ...document,+ timeline: {+ ...document.timeline,+ clips,+ skipRanges,+ gaps: [],+ },+ preview: {+ ...document.preview,+ revision: document.preview.revision + 1,+ },+ };+}++export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {+ const duration = primaryAssetDuration(document);+ if (duration <= 0) return document;+ return replaceTimeline(document, [{ startSec: 0, endSec: duration }], "Restore full timeline");+}diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.tsnew file mode 100644index 000000000..725f507d6--- /dev/null+++ b/src/lib/ai-edition/document/transcribe.ts@@ -0,0 +1,100 @@+// Adapter: wraps OpenScreen's existing local Whisper pipeline (transformers.js,+// src/lib/captioning/) as a transcribeAsset function that returns an+// AxcutTranscript and persists it into the document.+//+// ponytail: reuses extractMono16kFromVideoUrl + transcribeMono16kToSegments+// verbatim. No Python, no faster-whisper, no network calls. Privacy-safe.++import { toFileUrl } from "@/components/video-editor/projectPersistence";+import { extractMono16kFromVideoUrl, transcribeMono16kToSegments } from "@/lib/captioning";+import type { AxcutDocument, AxcutTranscript, AxcutTranscriptSegment, AxcutWord } from "../schema";++export interface TranscribeAssetOptions {+ language?: string;+ onStatus?: (status: string) => void;+ signal?: AbortSignal;+}++export async function transcribeAsset(+ document: AxcutDocument,+ assetId: string,+ options: TranscribeAssetOptions = {},+): Promise<AxcutTranscript> {+ const asset = document.assets.find((a) => a.id === assetId);+ if (!asset) {+ throw new Error(`Asset ${assetId} not found in document.`);+ }++ const videoUrl = toFileUrl(asset.originalPath);++ options.onStatus?.("extracting-audio");+ const audioResult = await extractMono16kFromVideoUrl(videoUrl, {+ signal: options.signal,+ });++ options.onStatus?.("transcribing");+ const result = await transcribeMono16kToSegments(audioResult.samples, {+ trimRegions: [],+ signal: options.signal,+ });++ const segments: AxcutTranscriptSegment[] = [];+ const words: AxcutWord[] = [];++ for (let segIndex = 0; segIndex < result.segments.length; segIndex++) {+ const seg = result.segments[segIndex];+ const segId = `seg_${segIndex + 1}`;+ const wordIds: string[] = [];++ const tokens = seg.text.trim().split(/\s+/).filter(Boolean);+ if (tokens.length === 0) continue;++ const wordDuration = (seg.endSec - seg.startSec) / tokens.length;+ for (let w = 0; w < tokens.length; w++) {+ const wordId = `word_${words.length + 1}`;+ const startSec = seg.startSec + w * wordDuration;+ const endSec = startSec + wordDuration;+ words.push({+ id: wordId,+ segmentId: segId,+ startSec,+ endSec,+ text: tokens[w],+ });+ wordIds.push(wordId);+ }++ segments.push({+ id: segId,+ kind: "speech" as const,+ startSec: seg.startSec,+ endSec: seg.endSec,+ text: seg.text,+ wordIds,+ });+ }++ return {+ assetId,+ language: options.language ?? "auto",+ segments,+ words,+ };+}++export function withTranscript(+ document: AxcutDocument,+ transcript: AxcutTranscript,+): AxcutDocument {+ const transcripts = [+ ...document.transcripts.filter((t) => t.assetId !== transcript.assetId),+ transcript,+ ];+ return {+ ...document,+ transcript:+ document.project.primaryAssetId === transcript.assetId ? transcript : document.transcript,+ transcripts,+ preview: { ...document.preview, revision: document.preview.revision + 1 },+ };+}diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.tsnew file mode 100644index 000000000..45bf476f6--- /dev/null+++ b/src/lib/ai-edition/exporter/documentExporter.ts@@ -0,0 +1,225 @@+// Adapter: feeds an AxcutDocument into the existing VideoExporter / GifExporter+// by mapping document fields → VideoExporterConfig. No rewrite of the export+// pipeline — the existing FrameRenderer + StreamingVideoDecoder + muxer handle+// all the rendering (annotations, zoom, blur, webcam, cursor).+//+// ponytail: the existing exporter already accepts trimRegions (gaps in source+// time). Clips define what to KEEP. The inverse of clips = trimRegions. We+// also pull zoom/annotations from the document (ms units, same as legacy) and+// appearance/cursor/webcam from legacyEditor (passthrough blob). The webcam+// file path lives on the document's cameraTrack (auto-linked from the+// recording session.json when an asset is imported).++import { toFileUrl } from "@/components/video-editor/projectPersistence";+import {+ type AnnotationRegion,+ type CropRegion,+ type SpeedRegion,+ type TrimRegion,+ type ZoomRegion,+} from "@/components/video-editor/types";+import {+ type ExportFormat,+ type ExportQuality,+ GifExporter,+ type GifFrameRate,+ type GifSizePreset,+ VideoExporter,+} from "@/lib/exporter";+import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";+import type { ExportProgress } from "@/lib/exporter/types";+import type { CursorRecordingData, CursorTelemetryPoint } from "@/native/contracts";+import { primaryAssetDuration, timelineIntervals } from "../document/timeline";+import type { AxcutDocument } from "../schema";++export interface DocumentExportOptions {+ quality: ExportQuality;+ format: ExportFormat;+ frameRate?: number;+ gifFrameRate?: GifFrameRate;+ gifLoop?: boolean;+ gifSizePreset?: GifSizePreset;+ sourceWidth?: number;+ sourceHeight?: number;+ webcamVideoUrl?: string;+ cursorRecordingData?: CursorRecordingData | null;+ cursorTelemetry?: CursorTelemetryPoint[];+ cursorClickTimestamps?: number[];+ cursorScale?: number;+ cursorSmoothing?: number;+ cursorMotionBlur?: number;+ cursorClickBounce?: number;+ cursorClipToBounds?: boolean;+ previewWidth?: number;+ previewHeight?: number;+ onProgress?: (progress: ExportProgress) => void;+}++function clipsToTrimRanges(+ sourceDurationSec: number,+ clips: AxcutDocument["timeline"]["clips"],+): TrimRegion[] {+ const intervals = timelineIntervals({+ ...({} as AxcutDocument),+ timeline: {+ clips,+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ assets: [],+ project: { primaryAssetId: "" },+ } as unknown as AxcutDocument);+ const trims: TrimRegion[] = [];+ let cursor = 0;+ for (const interval of intervals) {+ if (interval.startSec > cursor) {+ trims.push({+ id: `trim_${trims.length + 1}`,+ startMs: Math.round(cursor * 1000),+ endMs: Math.round(interval.startSec * 1000),+ });+ }+ cursor = Math.max(cursor, interval.endSec);+ }+ if (cursor < sourceDurationSec) {+ trims.push({+ id: `trim_${trims.length + 1}`,+ startMs: Math.round(cursor * 1000),+ endMs: Math.round(sourceDurationSec * 1000),+ });+ }+ return trims;+}++function extractLegacyField<T>(+ legacy: Record<string, unknown> | null,+ key: string,+ fallback: T,+): T {+ if (legacy && typeof legacy[key] === typeof fallback) {+ return legacy[key] as T;+ }+ return fallback;+}++export async function exportAxcutDocument(+ document: AxcutDocument,+ options: DocumentExportOptions,+): Promise<ExportResult> {+ const asset =+ document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];+ if (!asset) {+ return { success: false, error: "No asset to export." };+ }++ const videoUrl = toFileUrl(asset.originalPath);+ const sourceDurationSec = asset.durationSec ?? primaryAssetDuration(document);+ const trimRegions = clipsToTrimRanges(sourceDurationSec, document.timeline.clips);+ const zoomRegions: ZoomRegion[] = document.zoomRanges as unknown as ZoomRegion[];+ const annotationRegions: AnnotationRegion[] =+ document.annotations as unknown as AnnotationRegion[];+ const legacy = document.legacyEditor as Record<string, unknown> | null;++ const wallpaper = extractLegacyField(legacy, "wallpaper", "");+ const shadowIntensity = extractLegacyField(legacy, "shadowIntensity", 0);+ const showBlur = extractLegacyField(legacy, "showBlur", false);+ const motionBlurAmount = extractLegacyField(legacy, "motionBlurAmount", 0);+ const borderRadius = extractLegacyField(legacy, "borderRadius", 0);+ const padding = extractLegacyField(legacy, "padding", 50);+ const cropRegion = extractLegacyField<CropRegion>(legacy, "cropRegion", {+ x: 0,+ y: 0,+ width: 1,+ height: 1,+ });+ const webcamLayoutPreset = extractLegacyField(legacy, "webcamLayoutPreset", "picture-in-picture");+ const webcamMaskShape = extractLegacyField(legacy, "webcamMaskShape", "rectangle");+ const webcamMirrored = extractLegacyField(legacy, "webcamMirrored", false);+ const webcamReactiveZoom = extractLegacyField(legacy, "webcamReactiveZoom", true);+ const webcamSizePreset = extractLegacyField(legacy, "webcamSizePreset", 25);+ const webcamPosition = extractLegacyField(legacy, "webcamPosition", null);+ const cursorTheme = extractLegacyField(legacy, "cursorTheme", "");+ const speedRegions: SpeedRegion[] = extractLegacyField(legacy, "speedRegions", []);++ const sourceWidth = options.sourceWidth || 1920;+ const sourceHeight = options.sourceHeight || 1080;+ const aspectRatioValue = 16 / 9;++ const settings = calculateMp4ExportSettings({+ quality: options.quality,+ sourceWidth,+ sourceHeight,+ aspectRatioValue,+ });++ const commonConfig = {+ videoUrl,+ // ponytail: the camera is a derived stream from cameraTrack; the legacy+ // exporter accepts webcamVideoUrl as a visual-only second source.+ webcamVideoUrl:+ document.cameraTrack && document.cameraTrack.visible && document.cameraTrack.sourcePath+ ? toFileUrl(document.cameraTrack.sourcePath)+ : options.webcamVideoUrl,+ wallpaper,+ zoomRegions,+ trimRegions,+ speedRegions,+ showShadow: shadowIntensity > 0,+ shadowIntensity,+ showBlur,+ motionBlurAmount,+ borderRadius,+ padding,+ cropRegion,+ annotationRegions,+ webcamLayoutPreset: webcamLayoutPreset as+ | "picture-in-picture"+ | "no-webcam"+ | "vertical-stack"+ | "dual-frame",+ webcamMaskShape: webcamMaskShape as "rectangle" | "circle" | "square" | "rounded",+ webcamMirrored,+ webcamReactiveZoom,+ webcamSizePreset,+ webcamPosition,+ cursorRecordingData: options.cursorRecordingData ?? null,+ cursorScale: options.cursorScale ?? 0,+ cursorSmoothing: options.cursorSmoothing,+ cursorMotionBlur: options.cursorMotionBlur,+ cursorClickBounce: options.cursorClickBounce,+ cursorClipToBounds: options.cursorClipToBounds,+ cursorTheme,+ cursorTelemetry: options.cursorTelemetry,+ cursorClickTimestamps: options.cursorClickTimestamps,+ previewWidth: options.previewWidth,+ previewHeight: options.previewHeight,+ onProgress: options.onProgress,+ };++ if (options.format === "gif") {+ const exporter = new GifExporter({+ ...commonConfig,+ width: 1280,+ height: 720,+ frameRate: options.gifFrameRate ?? 15,+ loop: options.gifLoop ?? true,+ sizePreset: options.gifSizePreset ?? "medium",+ } as unknown as ConstructorParameters<typeof GifExporter>[0]);+ return exporter.export();+ }++ const exporter = new VideoExporter({+ ...commonConfig,+ width: settings.width,+ height: settings.height,+ frameRate: options.frameRate ?? 60,+ bitrate: settings.bitrate,+ codec: "avc1.640033",+ });+ return exporter.export();+}++import type { ExportResult } from "@/lib/exporter/types";diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.tsnew file mode 100644index 000000000..1456b45b0--- /dev/null+++ b/src/lib/ai-edition/schema/index.test.ts@@ -0,0 +1,264 @@+import { describe, expect, it } from "vitest";+import {+ annotationRegionSchema,+ assetSchema,+ axcutSchemaVersion,+ clipSchema,+ createEmptyDocument,+ documentSchema,+ ensureDocument,+ legacyEditorSchema,+ rangeSchema,+ skipRangeSchema,+ timelineSchema,+ zoomRegionSchema,+} from "./index";++describe("axcut-schema v3", () => {+ it("uses schema version 3", () => {+ expect(axcutSchemaVersion).toBe(3);+ });++ it("rejects unknown schema versions", () => {+ expect(() =>+ documentSchema.parse({+ ...createEmptyDocument({ projectId: "p", title: "t" }),+ schemaVersion: 2,+ }),+ ).toThrow();+ });++ it("createEmptyDocument returns a valid v3 doc with empty collections", () => {+ const doc = createEmptyDocument({ projectId: "proj_1", title: "Demo" });+ expect(doc.schemaVersion).toBe(3);+ expect(doc.assets).toEqual([]);+ expect(doc.timeline.clips).toEqual([]);+ expect(doc.timeline.skipRanges).toEqual([]);+ expect(doc.timeline.speedRanges).toEqual([]);+ expect(doc.timeline.muteRanges).toEqual([]);+ expect(doc.timeline.captionRanges).toEqual([]);+ expect(doc.annotations).toEqual([]);+ expect(doc.zoomRanges).toEqual([]);+ expect(doc.transcripts).toEqual([]);+ expect(doc.legacyEditor).toBeNull();+ expect(doc.history.revisions).toEqual([]);+ });++ it("ensureDocument rejects garbage", () => {+ expect(() => ensureDocument({ schemaVersion: 3, project: "not-an-object" })).toThrow();+ });++ it("accepts a clip with sourceEndSec undefined (asset duration unknown at migration time)", () => {+ const clip = clipSchema.parse({+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ timelineStartSec: 0,+ timelineEndSec: 0,+ origin: "system",+ });+ expect(clip.sourceEndSec).toBeUndefined();+ });++ it("rejects negative clip times", () => {+ expect(() =>+ clipSchema.parse({+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: -1,+ timelineStartSec: 0,+ timelineEndSec: 0,+ origin: "system",+ }),+ ).toThrow();+ });++ it("assetSchema requires kind = 'video'", () => {+ expect(() =>+ assetSchema.parse({+ id: "asset_1",+ kind: "audio",+ label: "x",+ originalPath: "/x.mp4",+ }),+ ).toThrow();+ });++ it("skipRangeSchema carries assetId and origin", () => {+ const skip = skipRangeSchema.parse({+ id: "skip_1",+ assetId: "asset_1",+ startSec: 1.5,+ endSec: 3.0,+ origin: "user",+ });+ expect(skip.assetId).toBe("asset_1");+ expect(skip.origin).toBe("user");+ });++ it("rangeSchema has no required fields beyond startSec/endSec", () => {+ const r = rangeSchema.parse({ startSec: 0, endSec: 1 });+ expect(r.reason).toBe("");+ });++ it("timelineSchema defaults skipRanges to []", () => {+ const t = timelineSchema.parse({});+ expect(t.skipRanges).toEqual([]);+ expect(t.muteRanges).toEqual([]);+ expect(t.captionRanges).toEqual([]);+ });++ it("annotationRegionSchema accepts OpenScreen-shape regions", () => {+ const region = annotationRegionSchema.parse({+ id: "ann_1",+ startMs: 0,+ endMs: 1500,+ type: "text",+ content: "hello",+ position: { x: 4, y: 86 },+ size: { width: 92, height: 12 },+ style: {+ color: "#ffffff",+ backgroundColor: "transparent",+ fontSize: 24,+ fontFamily: "Inter",+ fontWeight: "bold",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+ },+ zIndex: 1,+ });+ expect(region.type).toBe("text");+ expect(region.annotationSource).toBeUndefined();+ });++ it("zoomRegionSchema rejects unknown depths", () => {+ expect(() =>+ zoomRegionSchema.parse({+ id: "z_1",+ startMs: 0,+ endMs: 1000,+ depth: 7,+ focus: { cx: 0.5, cy: 0.5 },+ }),+ ).toThrow();+ });++ it("zoomRegionSchema accepts depth 1..6", () => {+ for (const d of [1, 2, 3, 4, 5, 6] as const) {+ const z = zoomRegionSchema.parse({+ id: `z_${d}`,+ startMs: 0,+ endMs: 1000,+ depth: d,+ focus: { cx: 0.5, cy: 0.5 },+ });+ expect(z.depth).toBe(d);+ }+ });++ it("legacyEditorSchema accepts arbitrary passthrough keys", () => {+ const legacy = legacyEditorSchema.parse({+ wallpaper: "/wallpapers/wallpaper1.jpg",+ autoZoomEnabled: true,+ someFutureField: "preserved",+ });+ expect(legacy?.someFutureField).toBe("preserved");+ });++ it("documentSchema defaults missing v3 envelopes on a v3 document", () => {+ expect(() =>+ documentSchema.parse({+ schemaVersion: 3,+ project: {+ id: "p",+ title: "t",+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ },+ assets: [],+ transcript: null,+ timeline: {},+ agent: {},+ preview: {},+ export: {},+ history: {},+ }),+ ).not.toThrow();+ });++ describe("range ordering validation", () => {+ it("rangeSchema rejects endSec < startSec", () => {+ expect(() => rangeSchema.parse({ startSec: 10, endSec: 5 })).toThrow();+ expect(rangeSchema.parse({ startSec: 5, endSec: 10 })).toBeTruthy();+ expect(rangeSchema.parse({ startSec: 5, endSec: 5 })).toBeTruthy();+ });++ it("skipRangeSchema rejects endSec < startSec", () => {+ expect(() =>+ skipRangeSchema.parse({+ id: "s1",+ assetId: "a1",+ startSec: 10,+ endSec: 5,+ origin: "user",+ }),+ ).toThrow();+ });++ it("clipSchema rejects timelineEndSec < timelineStartSec or sourceEndSec < sourceStartSec", () => {+ const validBase = {+ id: "c1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ origin: "user" as const,+ };+ expect(() => clipSchema.parse({ ...validBase, timelineEndSec: -1 })).toThrow();+ expect(() => clipSchema.parse({ ...validBase, sourceEndSec: -1 })).toThrow();+ expect(() =>+ clipSchema.parse({ ...validBase, sourceStartSec: 10, sourceEndSec: 5 }),+ ).toThrow();+ expect(() =>+ clipSchema.parse({ ...validBase, timelineStartSec: 10, timelineEndSec: 5 }),+ ).toThrow();+ });++ it("zoomRegionSchema rejects endMs < startMs", () => {+ expect(() =>+ zoomRegionSchema.parse({+ id: "z1",+ startMs: 100,+ endMs: 50,+ depth: 1,+ focus: { cx: 0.5, cy: 0.5 },+ }),+ ).toThrow();+ });++ it("annotationRegionSchema rejects endMs < startMs", () => {+ expect(() =>+ annotationRegionSchema.parse({+ id: "a1",+ startMs: 100,+ endMs: 50,+ type: "text",+ position: { x: 10, y: 10 },+ size: { width: 100, height: 100 },+ style: {+ fontFamily: "Inter",+ fontSize: 14,+ color: "#ffffff",+ backgroundColor: "#000000",+ },+ zIndex: 1,+ figureData: {},+ blurData: {},+ }),+ ).toThrow();+ });+ });+});diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsnew file mode 100644index 000000000..7686ed3ec--- /dev/null+++ b/src/lib/ai-edition/schema/index.ts@@ -0,0 +1,551 @@+// Vendored from @axcut/schema (https://github.com/EtienneLescot/axcut) —+// original file: packages/axcut-schema/src/index.ts. Modifications for+// OpenScreen's AI-edition merge (Phase 0, see docs/architecture/ai-edition-merge-plan.md):+//+// 1. axcutSchemaVersion bumped 2 -> 3.+// 2. clip.sourceEndSec made optional (duration is unknown until asset is probed).+// 3. documentSchema gains annotations[], zoomRanges[], legacyEditor envelopes+// so OpenScreen's existing regions + appearance settings survive the merge.+//+// ponytail: this exists as the SSOT project model. Phase 0 only touches the+// shape — runtime ops, IPC, and exporter integration land in Phase 1+.++import { z } from "zod";++export const axcutSchemaVersion = 3;++export const isoDateSchema = z.string().datetime({ offset: true });++export const wordSchema = z+ .object({+ id: z.string().min(1),+ segmentId: z.string().min(1),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ text: z.string(),+ })+ .refine((data) => data.endSec >= data.startSec, {+ message: "endSec must be greater than or equal to startSec",+ path: ["endSec"],+ });++export const transcriptSegmentSchema = z+ .object({+ id: z.string().min(1),+ kind: z.enum(["speech", "silence"]),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ text: z.string(),+ wordIds: z.array(z.string().min(1)).default([]),+ })+ .refine((data) => data.endSec >= data.startSec, {+ message: "endSec must be greater than or equal to startSec",+ path: ["endSec"],+ });++export const transcriptSchema = z.object({+ assetId: z.string().min(1),+ language: z.string().min(1),+ sourceDslPath: z.string().optional(),+ sourceJsonPath: z.string().optional(),+ segments: z.array(transcriptSegmentSchema).default([]),+ words: z.array(wordSchema).default([]),+});++export const assetVideoSchema = z.object({+ codec: z.string().default("unknown"),+ width: z.number().int().nonnegative().default(0),+ height: z.number().int().nonnegative().default(0),+ fps: z.number().nonnegative().default(0),+});++export const assetAudioSchema = z.object({+ codec: z.string().default("unknown"),+ sampleRate: z.number().int().nonnegative().default(0),+ channels: z.number().int().nonnegative().default(0),+});++export const assetSchema = z.object({+ id: z.string().min(1),+ kind: z.literal("video"),+ label: z.string().min(1),+ originalPath: z.string().min(1),+ proxyPath: z.string().optional(),+ waveformPath: z.string().optional(),+ durationSec: z.number().nonnegative().optional(),+ video: assetVideoSchema.optional(),+ audio: assetAudioSchema.optional(),+});++export const clipSchema = z+ .object({+ id: z.string().min(1),+ assetId: z.string().min(1),+ sourceStartSec: z.number().nonnegative(),+ // ponytail: optional because v2 migrations have unknown asset duration at+ // migration time. The renderer fills this in once StreamingVideoDecoder probes+ // the file (Phase 1+).+ sourceEndSec: z.number().nonnegative().optional(),+ timelineStartSec: z.number().nonnegative(),+ timelineEndSec: z.number().nonnegative(),+ wordRefs: z.array(z.string().min(1)).default([]),+ origin: z.enum(["system", "agent", "user"]),+ reason: z.string().default(""),+ })+ .refine((data) => data.timelineEndSec >= data.timelineStartSec, {+ message: "timelineEndSec must be greater than or equal to timelineStartSec",+ path: ["timelineEndSec"],+ })+ .refine((data) => data.sourceEndSec === undefined || data.sourceEndSec >= data.sourceStartSec, {+ message: "sourceEndSec must be greater than or equal to sourceStartSec",+ path: ["sourceEndSec"],+ });++export const gapSchema = z+ .object({+ id: z.string().min(1),+ timelineStartSec: z.number().nonnegative(),+ timelineEndSec: z.number().nonnegative(),+ reason: z.string().default(""),+ })+ .refine((data) => data.timelineEndSec >= data.timelineStartSec, {+ message: "timelineEndSec must be greater than or equal to timelineStartSec",+ path: ["timelineEndSec"],+ });++export const rangeSchema = z+ .object({+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ reason: z.string().default(""),+ })+ .refine((data) => data.endSec >= data.startSec, {+ message: "endSec must be greater than or equal to startSec",+ path: ["endSec"],+ });++// ponytail: skipRanges reference asset source-time (not timeline). trimRegions+// in v2 are the inverse — a skip = the region inside the source we DON'T keep.+export const skipRangeSchema = z+ .object({+ id: z.string().min(1),+ assetId: z.string().min(1),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ reason: z.string().default(""),+ origin: z.enum(["system", "agent", "user"]),+ })+ .refine((data) => data.endSec >= data.startSec, {+ message: "endSec must be greater than or equal to startSec",+ path: ["endSec"],+ });++export const timelineSchema = z.object({+ clips: z.array(clipSchema).default([]),+ gaps: z.array(gapSchema).default([]),+ skipRanges: z.array(skipRangeSchema).default([]),+ muteRanges: z.array(rangeSchema).default([]),+ speedRanges: z.array(rangeSchema).default([]),+ captionRanges: z.array(rangeSchema).default([]),+});++export const pendingQuestionSchema = z.object({+ id: z.string().min(1),+ question: z.string().min(1),+ reason: z.string().default(""),+ startWordId: z.string().optional(),+ endWordId: z.string().optional(),+});++export const previewSchema = z.object({+ strategy: z.enum(["seek", "mse-proxy"]).default("seek"),+ revision: z.number().int().nonnegative().default(0),+});++export const exportStateSchema = z.object({+ preset: z.enum(["preview-low", "final-balanced", "final-high"]).default("final-balanced"),+ lastJobId: z.string().nullable().default(null),+});++export const timelineOperationSchema = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("replace_timeline"),+ reason: z.string().default(""),+ intervals: z+ .array(z.object({ startSec: z.number().nonnegative(), endSec: z.number().nonnegative() }))+ .default([]),+ }),+ z.object({+ type: z.literal("drop_range"),+ reason: z.string().default(""),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ }),+ z.object({+ type: z.literal("drop_word_range"),+ reason: z.string().default(""),+ startWordId: z.string().min(1),+ endWordId: z.string().min(1),+ }),+ z.object({+ type: z.literal("add_skip_range"),+ reason: z.string().default(""),+ assetId: z.string().min(1),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ }),+ z.object({+ type: z.literal("update_skip_range"),+ reason: z.string().default(""),+ skipRangeId: z.string().min(1),+ startSec: z.number().nonnegative(),+ endSec: z.number().nonnegative(),+ }),+ z.object({+ type: z.literal("remove_skip_range"),+ reason: z.string().default(""),+ skipRangeId: z.string().min(1),+ }),+ z.object({+ type: z.literal("update_clip_range"),+ reason: z.string().default(""),+ clipId: z.string().min(1),+ sourceStartSec: z.number().nonnegative(),+ sourceEndSec: z.number().nonnegative().optional(),+ }),+ z.object({+ type: z.literal("duplicate_clip"),+ reason: z.string().default(""),+ clipId: z.string().min(1),+ }),+ z.object({+ type: z.literal("move_clip"),+ reason: z.string().default(""),+ clipId: z.string().min(1),+ timelineStartSec: z.number().nonnegative(),+ }),+ z.object({+ type: z.literal("insert_asset_clip"),+ reason: z.string().default(""),+ assetId: z.string().min(1),+ beforeClipId: z.string().min(1).nullable(),+ afterClipId: z.string().min(1).nullable(),+ sourceStartSec: z.number().nonnegative(),+ sourceEndSec: z.number().nonnegative().optional(),+ }),+ z.object({+ type: z.literal("restore_full_timeline"),+ reason: z.string().default(""),+ }),+]);++export const suggestionSchema = z.object({+ id: z.string().min(1),+ status: z.enum(["pending", "approved", "rejected"]).default("pending"),+ category: z+ .enum(["cut_candidate", "style", "delivery", "topic_focus", "clarification"])+ .default("cut_candidate"),+ suggestion: z.string().min(1),+ reason: z.string().default(""),+ startWordId: z.string().optional(),+ endWordId: z.string().optional(),+ startSec: z.number().nonnegative().optional(),+ endSec: z.number().nonnegative().optional(),+ proposedOperation: timelineOperationSchema.optional(),+});++export const agentStateSchema = z.object({+ baseIntent: z.string().optional(),+ pendingQuestions: z.array(pendingQuestionSchema).default([]),+ suggestions: z.array(suggestionSchema).default([]),+ lastAppliedOperations: z.array(z.string()).default([]),+ lastReasoningSummary: z.string().optional(),+});++export const operationSchema = z.discriminatedUnion("type", [+ ...timelineOperationSchema.options,+ z.object({+ type: z.literal("approve_suggestion"),+ reason: z.string().default(""),+ suggestionId: z.string().min(1),+ }),+ z.object({+ type: z.literal("reject_suggestion"),+ reason: z.string().default(""),+ suggestionId: z.string().min(1),+ }),+]);++export const revisionSchema = z.object({+ id: z.string().min(1),+ createdAt: isoDateSchema,+ author: z.enum(["system", "agent", "user"]),+ summary: z.string().min(1),+ operations: z.array(operationSchema).default([]),+});++// OpenScreen additions to the axcut document. Mirrors src/components/video-editor/types.ts+// (AnnotationRegion / ZoomRegion) — duplicated here so the schema package has no+// dependency on the React editor module.++const blurDataSchema = z+ .object({+ type: z.enum(["blur", "mosaic"]).default("mosaic"),+ shape: z.enum(["rectangle", "oval", "freehand"]).default("rectangle"),+ color: z.enum(["white", "black"]).default("white"),+ intensity: z.number().nonnegative().default(12),+ blockSize: z.number().nonnegative().default(12),+ freehandPoints: z+ .array(z.object({ x: z.number().nonnegative(), y: z.number().nonnegative() }))+ .optional(),+ })+ .optional();++const figureDataSchema = z+ .object({+ arrowDirection: z+ .enum(["up", "down", "left", "right", "up-right", "up-left", "down-right", "down-left"])+ .default("right"),+ color: z.string().default("#34B27B"),+ strokeWidth: z.number().nonnegative().default(4),+ })+ .optional();++const annotationStyleSchema = z.object({+ color: z.string().default("#ffffff"),+ backgroundColor: z.string().default("transparent"),+ fontSize: z.number().nonnegative().default(32),+ fontFamily: z.string().default("Inter"),+ fontWeight: z.enum(["normal", "bold"]).default("bold"),+ fontStyle: z.enum(["normal", "italic"]).default("normal"),+ textDecoration: z.enum(["none", "underline"]).default("none"),+ textAlign: z.enum(["left", "center", "right"]).default("center"),+ textAnimation: z+ .enum(["none", "fade", "rise", "pop", "slide-left", "typewriter", "pulse"])+ .optional(),+});++export const annotationRegionSchema = z+ .object({+ id: z.string().min(1),+ startMs: z.number().nonnegative(),+ endMs: z.number().nonnegative(),+ type: z.enum(["text", "image", "figure", "blur"]),+ content: z.string().default(""),+ textContent: z.string().optional(),+ imageContent: z.string().optional(),+ position: z.object({+ x: z.number().min(0).max(100),+ y: z.number().min(0).max(100),+ }),+ size: z.object({+ width: z.number().positive(),+ height: z.number().positive(),+ }),+ style: annotationStyleSchema,+ zIndex: z.number().int().nonnegative(),+ annotationSource: z.literal("auto-caption").optional(),+ figureData: figureDataSchema,+ blurData: blurDataSchema,+ })+ .refine((data) => data.endMs >= data.startMs, {+ message: "endMs must be greater than or equal to startMs",+ path: ["endMs"],+ });++export const zoomRegionSchema = z+ .object({+ id: z.string().min(1),+ startMs: z.number().nonnegative(),+ endMs: z.number().nonnegative(),+ depth: z.union([+ z.literal(1),+ z.literal(2),+ z.literal(3),+ z.literal(4),+ z.literal(5),+ z.literal(6),+ ]),+ focus: z.object({+ cx: z.number().min(0).max(1),+ cy: z.number().min(0).max(1),+ }),+ focusMode: z.enum(["manual", "auto"]).optional(),+ rotationPreset: z.enum(["iso", "left", "right"]).optional(),+ customScale: z.number().positive().optional(),+ source: z.enum(["auto", "manual"]).optional(),+ })+ .refine((data) => data.endMs >= data.startMs, {+ message: "endMs must be greater than or equal to startMs",+ path: ["endMs"],+ });++// Legacy OpenScreen appearance / export settings that the v3 schema doesn't+// normalize into the timeline / assets model. They are applied at export time+// by the existing pipeline (see docs/architecture/ai-edition-merge-plan.md §2.1).+//+// ponytail: passthrough blob — v2 ProjectEditorState carries ~25 fields, several+// of which (autoZoomEnabled, autoFocusAll, cursorTheme, …) have no first-class+// home yet. Phase 1 timeline rewrite + Phase 9 settings sync will tighten this.+// Round-trip through the migration must be lossless for now.+export const legacyEditorSchema = z.object({}).passthrough().nullable().default(null);++// ponytail: the webcam is a derived stream — it is NOT edited. Cut / zoom /+// speed live on the main timeline and apply to the camera as a render of the+// same source-time progression. Source path comes from the recording+// session sidecar (auto-linked when an asset is imported from a recording).+// `offsetMs` accounts for the camera starting before/after the screen.+export const cameraTrackSchema = z+ .object({+ sourcePath: z.string().min(1),+ startMs: z.number().nonnegative().default(0),+ offsetMs: z.number().int().default(0),+ visible: z.boolean().default(true),+ })+ .nullable()+ .default(null);++export const documentSchema = z.object({+ schemaVersion: z.literal(axcutSchemaVersion),+ project: z.object({+ id: z.string().min(1),+ title: z.string().min(1),+ createdAt: isoDateSchema,+ updatedAt: isoDateSchema,+ primaryAssetId: z.string().optional(),+ }),+ assets: z.array(assetSchema).default([]),+ cameraTrack: cameraTrackSchema,+ transcript: transcriptSchema.nullable().default(null),+ transcripts: z.array(transcriptSchema).default([]),+ timeline: timelineSchema.default({+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ }),+ annotations: z.array(annotationRegionSchema).default([]),+ zoomRanges: z.array(zoomRegionSchema).default([]),+ legacyEditor: legacyEditorSchema.nullable().default(null),+ agent: agentStateSchema.default({+ pendingQuestions: [],+ suggestions: [],+ lastAppliedOperations: [],+ }),+ preview: previewSchema.default({ strategy: "seek", revision: 0 }),+ export: exportStateSchema.default({ preset: "final-balanced", lastJobId: null }),+ history: z+ .object({+ revisions: z.array(revisionSchema).default([]),+ })+ .default({ revisions: [] }),+});++export const createProjectInputSchema = z.object({+ title: z.string().trim().min(1).default("Untitled Project"),+});++export const addAssetInputSchema = z.object({+ path: z.string().trim().min(1),+ label: z.string().trim().optional(),+ autoTranscribe: z.boolean().default(true),+});++export const chatInputSchema = z.object({+ sessionId: z.string().trim().min(1).optional(),+ message: z.string().trim().min(1),+});++export const transcriptLanguageSchema = z.enum([+ "auto",+ "en",+ "fr",+ "de",+ "es",+ "it",+ "pt",+ "nl",+ "ja",+ "ko",+ "zh",+]);++export const transcribeInputSchema = z.object({+ language: transcriptLanguageSchema.default("auto"),+});++export const exportInputSchema = z.object({+ preset: exportStateSchema.shape.preset.default("final-balanced"),+});++export const applyOperationInputSchema = z.object({+ operation: operationSchema,+ sessionId: z.string().min(1).optional(),+ conversationMessage: z.string().min(1).optional(),+});++export type AxcutWord = z.infer<typeof wordSchema>;+export type AxcutTranscriptSegment = z.infer<typeof transcriptSegmentSchema>;+export type AxcutTranscript = z.infer<typeof transcriptSchema>;+export type AxcutAsset = z.infer<typeof assetSchema>;+export type AxcutClip = z.infer<typeof clipSchema>;+export type AxcutGap = z.infer<typeof gapSchema>;+export type AxcutSkipRange = z.infer<typeof skipRangeSchema>;+export type AxcutTimeline = z.infer<typeof timelineSchema>;+export type AxcutSuggestion = z.infer<typeof suggestionSchema>;+export type AxcutAgentState = z.infer<typeof agentStateSchema>;+export type AxcutTimelineOperation = z.infer<typeof timelineOperationSchema>;+export type AxcutOperation = z.infer<typeof operationSchema>;+export type AxcutRevision = z.infer<typeof revisionSchema>;+export type AxcutAnnotationRegion = z.infer<typeof annotationRegionSchema>;+export type AxcutZoomRegion = z.infer<typeof zoomRegionSchema>;+export type AxcutCameraTrack = z.infer<typeof cameraTrackSchema>;+export type AxcutLegacyEditor = z.infer<typeof legacyEditorSchema>;+export type AxcutDocument = z.infer<typeof documentSchema>;+export type AxcutDocumentInput = z.input<typeof documentSchema>;+export type CreateProjectInput = z.infer<typeof createProjectInputSchema>;+export type AddAssetInput = z.infer<typeof addAssetInputSchema>;+export type ChatInput = z.infer<typeof chatInputSchema>;+export type TranscribeInput = z.infer<typeof transcribeInputSchema>;+export type ExportInput = z.infer<typeof exportInputSchema>;+export type ApplyOperationInput = z.infer<typeof applyOperationInputSchema>;++export function createEmptyDocument(+ input: CreateProjectInput & { projectId: string; createdAt?: string },+): AxcutDocument {+ const createdAt = input.createdAt ?? new Date().toISOString();+ return documentSchema.parse({+ schemaVersion: axcutSchemaVersion,+ project: {+ id: input.projectId,+ title: input.title,+ createdAt,+ updatedAt: createdAt,+ },+ assets: [],+ cameraTrack: null,+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+ });+}++export function ensureDocument(value: unknown): AxcutDocument {+ return documentSchema.parse(value);+}diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.tsnew file mode 100644index 000000000..5338d1dd6--- /dev/null+++ b/src/lib/ai-edition/store/editorSettings.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_CROP_REGION,+ DEFAULT_CURSOR_SIZE,+ DEFAULT_WEBCAM_LAYOUT_PRESET,+ DEFAULT_WEBCAM_MASK_SHAPE,+} from "@/components/video-editor/types";+import type { AxcutDocument } from "../schema";+import { DEFAULT_EDITOR_SETTINGS, getEditorSettings, patchEditorSettings } from "./editorSettings";++const baseDoc: AxcutDocument = {+ schemaVersion: 3,+ project: { id: "p1", title: "Test", primaryAssetId: "a1" },+ assets: [{ id: "a1", kind: "video", label: "clip", originalPath: "/x.mp4" }],+ timeline: { clips: [], skipRanges: [] },+ annotations: [],+ zoomRanges: [],+ transcripts: [],+ transcript: null,+ preview: { revision: 0 },+ legacyEditor: null,+};++describe("getEditorSettings", () => {+ it("returns the defaults when the document has no legacyEditor", () => {+ const snap = getEditorSettings(baseDoc);+ expect(snap.wallpaper).toBe(DEFAULT_EDITOR_SETTINGS.wallpaper);+ expect(snap.aspectRatio).toBe("16:9");+ expect(snap.shadowIntensity).toBe(0);+ expect(snap.showBlur).toBe(false);+ expect(snap.showTrimWaveform).toBe(true);+ expect(snap.webcamLayoutPreset).toBe(DEFAULT_WEBCAM_LAYOUT_PRESET);+ expect(snap.webcamMaskShape).toBe(DEFAULT_WEBCAM_MASK_SHAPE);+ expect(snap.cursor.size).toBe(DEFAULT_CURSOR_SIZE);+ });++ it("returns the defaults when the document is null", () => {+ const snap = getEditorSettings(null);+ expect(snap).toEqual(DEFAULT_EDITOR_SETTINGS);+ });++ it("reads overrides from legacyEditor", () => {+ const doc: AxcutDocument = {+ ...baseDoc,+ legacyEditor: {+ wallpaper: "linear-gradient(red, blue)",+ aspectRatio: "9:16",+ shadowIntensity: 0.5,+ showBlur: true,+ webcamLayoutPreset: "side-by-side",+ webcamMaskShape: "circle",+ cursorSize: 5,+ cursorSmoothing: 0.8,+ },+ };+ const snap = getEditorSettings(doc);+ expect(snap.wallpaper).toBe("linear-gradient(red, blue)");+ expect(snap.aspectRatio).toBe("9:16");+ expect(snap.shadowIntensity).toBe(0.5);+ expect(snap.showBlur).toBe(true);+ expect(snap.webcamLayoutPreset).toBe("side-by-side");+ expect(snap.webcamMaskShape).toBe("circle");+ expect(snap.cursor.size).toBe(5);+ expect(snap.cursor.smoothing).toBe(0.8);+ });++ it("falls back to defaults for unknown or wrong-type values", () => {+ const doc: AxcutDocument = {+ ...baseDoc,+ legacyEditor: { showBlur: "not-a-bool" as unknown as boolean },+ };+ const snap = getEditorSettings(doc);+ expect(snap.showBlur).toBe(false);+ });+});++describe("patchEditorSettings", () => {+ it("writes a single field and leaves others intact", () => {+ const next = patchEditorSettings(baseDoc, { showBlur: true });+ const snap = getEditorSettings(next);+ expect(snap.showBlur).toBe(true);+ expect(snap.shadowIntensity).toBe(0);+ expect(snap.cropRegion).toEqual(DEFAULT_CROP_REGION);+ });++ it("merges into an existing legacyEditor envelope", () => {+ const seed = patchEditorSettings(baseDoc, { showBlur: true });+ const next = patchEditorSettings(seed, { shadowIntensity: 0.7 });+ const snap = getEditorSettings(next);+ expect(snap.showBlur).toBe(true);+ expect(snap.shadowIntensity).toBe(0.7);+ });++ it("patches nested cursor settings without clobbering siblings", () => {+ const seed = patchEditorSettings(baseDoc, { cursor: { size: 4 } });+ const next = patchEditorSettings(seed, { cursor: { smoothing: 0.9 } });+ const snap = getEditorSettings(next);+ expect(snap.cursor.size).toBe(4);+ expect(snap.cursor.smoothing).toBe(0.9);+ });++ it("does not mutate the source document", () => {+ const before = getEditorSettings(baseDoc);+ patchEditorSettings(baseDoc, { showBlur: true });+ const after = getEditorSettings(baseDoc);+ expect(after).toEqual(before);+ });++ it("round-trips webcamPosition through legacyEditor", () => {+ const dragged = patchEditorSettings(baseDoc, {+ webcamPosition: { cx: 0.32, cy: 0.71 },+ });+ const snap = getEditorSettings(dragged);+ expect(snap.webcamPosition).toEqual({ cx: 0.32, cy: 0.71 });+ });++ it("clamps out-of-range webcamPosition when reading", () => {+ const doc: AxcutDocument = {+ ...baseDoc,+ legacyEditor: { webcamPosition: { cx: 1.7, cy: -0.4 } },+ };+ const snap = getEditorSettings(doc);+ expect(snap.webcamPosition).toEqual({ cx: 1, cy: 0 });+ });+});diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.tsnew file mode 100644index 000000000..85d7838a7--- /dev/null+++ b/src/lib/ai-edition/store/editorSettings.ts@@ -0,0 +1,240 @@+// Typed read/write layer over `document.legacyEditor`.+//+// The v3 schema keeps `legacyEditor` as a `Record<string, unknown>` envelope so+// v2 projects round-trip without losing fields. The right panes and the+// per-region inspectors need a typed surface — this module provides it.+//+// The shape mirrors the legacy editor's `ProjectEditorState` so the same names+// are used everywhere; values that v3 owns directly (zoomRanges, annotations,+// transcripts, clips) stay in their dedicated fields.++import {+ type CropRegion,+ type CursorVisualSettings,+ DEFAULT_CROP_REGION,+ DEFAULT_CURSOR_CLICK_BOUNCE,+ DEFAULT_CURSOR_CLIP_TO_BOUNDS,+ DEFAULT_CURSOR_MOTION_BLUR,+ DEFAULT_CURSOR_SIZE,+ DEFAULT_CURSOR_SMOOTHING,+ DEFAULT_WEBCAM_LAYOUT_PRESET,+ DEFAULT_WEBCAM_MASK_SHAPE,+ DEFAULT_WEBCAM_MIRRORED,+ DEFAULT_WEBCAM_POSITION,+ DEFAULT_WEBCAM_REACTIVE_ZOOM,+ DEFAULT_WEBCAM_SIZE_PRESET,+ type WebcamLayoutPreset,+ type WebcamMaskShape,+ type WebcamPosition,+ type WebcamSizePreset,+} from "@/components/video-editor/types";+import { DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";+import { DEFAULT_WALLPAPER } from "@/lib/wallpaper";+import type { AspectRatio } from "@/utils/aspectRatioUtils";+import type { AxcutDocument } from "../schema";++// ponytail: avoid dragging in lib/exporter full surface here — we only+// need the type names. Wallpaper + cursor theme are stored as plain strings+// for the same reason (their canonical types live in lib/wallpaper and+// lib/cursor/cursorThemes as the source of truth).++export interface EditorSettingsSnapshot {+ wallpaper: string;+ aspectRatio: AspectRatio;+ shadowIntensity: number;+ showBlur: boolean;+ showTrimWaveform: boolean;+ motionBlurAmount: number;+ borderRadius: number;+ padding: number;+ cropRegion: CropRegion;+ webcamLayoutPreset: WebcamLayoutPreset;+ webcamMaskShape: WebcamMaskShape;+ webcamMirrored: boolean;+ webcamReactiveZoom: boolean;+ webcamSizePreset: WebcamSizePreset;+ webcamPosition: WebcamPosition | null;+ cursor: CursorVisualSettings;+ cursorShow: boolean;+ cursorTheme: string;+ autoFocusAll: boolean;+}++export const DEFAULT_EDITOR_SETTINGS: EditorSettingsSnapshot = {+ wallpaper: DEFAULT_WALLPAPER,+ aspectRatio: "16:9",+ shadowIntensity: 0,+ showBlur: false,+ showTrimWaveform: true,+ motionBlurAmount: 0,+ borderRadius: 0,+ padding: 50,+ cropRegion: DEFAULT_CROP_REGION,+ webcamLayoutPreset: DEFAULT_WEBCAM_LAYOUT_PRESET,+ webcamMaskShape: DEFAULT_WEBCAM_MASK_SHAPE,+ webcamMirrored: DEFAULT_WEBCAM_MIRRORED,+ webcamReactiveZoom: DEFAULT_WEBCAM_REACTIVE_ZOOM,+ webcamSizePreset: DEFAULT_WEBCAM_SIZE_PRESET,+ webcamPosition: DEFAULT_WEBCAM_POSITION,+ cursor: {+ size: DEFAULT_CURSOR_SIZE,+ smoothing: DEFAULT_CURSOR_SMOOTHING,+ motionBlur: DEFAULT_CURSOR_MOTION_BLUR,+ clickBounce: DEFAULT_CURSOR_CLICK_BOUNCE,+ clipToBounds: DEFAULT_CURSOR_CLIP_TO_BOUNDS,+ },+ cursorShow: true,+ cursorTheme: DEFAULT_CURSOR_THEME_ID,+ autoFocusAll: false,+};++interface LegacyShape {+ wallpaper?: string;+ aspectRatio?: AspectRatio;+ shadowIntensity?: number;+ showBlur?: boolean;+ showTrimWaveform?: boolean;+ motionBlurAmount?: number;+ borderRadius?: number;+ padding?: number;+ cropRegion?: CropRegion;+ webcamLayoutPreset?: WebcamLayoutPreset;+ webcamMaskShape?: WebcamMaskShape;+ webcamMirrored?: boolean;+ webcamReactiveZoom?: boolean;+ webcamSizePreset?: WebcamSizePreset;+ webcamPosition?: WebcamPosition | null;+ cursorSize?: number;+ cursorSmoothing?: number;+ cursorMotionBlur?: number;+ cursorClickBounce?: number;+ cursorClipToBounds?: boolean;+ cursorShow?: boolean;+ cursorTheme?: string;+ autoFocusAll?: boolean;+}+function isShape(value: unknown): value is LegacyShape {+ return typeof value === "object" && value !== null;+}++function isNumber(v: unknown): v is number {+ return typeof v === "number" && Number.isFinite(v);+}+function isBoolean(v: unknown): v is boolean {+ return typeof v === "boolean";+}+function isString(v: unknown): v is string {+ return typeof v === "string";+}++export function getEditorSettings(doc: AxcutDocument | null | undefined): EditorSettingsSnapshot {+ const legacy = isShape(doc?.legacyEditor) ? (doc.legacyEditor as LegacyShape) : null;+ const num = (v: unknown, fallback: number) => (isNumber(v) ? v : fallback);+ const bool = (v: unknown, fallback: boolean) => (isBoolean(v) ? v : fallback);+ const str = (v: unknown, fallback: string) => (isString(v) ? v : fallback);++ const cursor: CursorVisualSettings = {+ size: num(legacy?.cursorSize, DEFAULT_EDITOR_SETTINGS.cursor.size),+ smoothing: num(legacy?.cursorSmoothing, DEFAULT_EDITOR_SETTINGS.cursor.smoothing),+ motionBlur: num(legacy?.cursorMotionBlur, DEFAULT_EDITOR_SETTINGS.cursor.motionBlur),+ clickBounce: num(legacy?.cursorClickBounce, DEFAULT_EDITOR_SETTINGS.cursor.clickBounce),+ clipToBounds: bool(legacy?.cursorClipToBounds, DEFAULT_EDITOR_SETTINGS.cursor.clipToBounds),+ };+ return {+ wallpaper: str(legacy?.wallpaper, DEFAULT_EDITOR_SETTINGS.wallpaper),+ aspectRatio: legacy?.aspectRatio ?? DEFAULT_EDITOR_SETTINGS.aspectRatio,+ shadowIntensity: num(legacy?.shadowIntensity, DEFAULT_EDITOR_SETTINGS.shadowIntensity),+ showBlur: bool(legacy?.showBlur, DEFAULT_EDITOR_SETTINGS.showBlur),+ showTrimWaveform: bool(legacy?.showTrimWaveform, DEFAULT_EDITOR_SETTINGS.showTrimWaveform),+ motionBlurAmount: num(legacy?.motionBlurAmount, DEFAULT_EDITOR_SETTINGS.motionBlurAmount),+ borderRadius: num(legacy?.borderRadius, DEFAULT_EDITOR_SETTINGS.borderRadius),+ padding: num(legacy?.padding, DEFAULT_EDITOR_SETTINGS.padding),+ cropRegion: legacy?.cropRegion ?? DEFAULT_EDITOR_SETTINGS.cropRegion,+ webcamLayoutPreset: legacy?.webcamLayoutPreset ?? DEFAULT_EDITOR_SETTINGS.webcamLayoutPreset,+ webcamMaskShape: legacy?.webcamMaskShape ?? DEFAULT_EDITOR_SETTINGS.webcamMaskShape,+ webcamMirrored: bool(legacy?.webcamMirrored, DEFAULT_EDITOR_SETTINGS.webcamMirrored),+ webcamReactiveZoom: bool(+ legacy?.webcamReactiveZoom,+ DEFAULT_EDITOR_SETTINGS.webcamReactiveZoom,+ ),+ webcamSizePreset: num(legacy?.webcamSizePreset, DEFAULT_EDITOR_SETTINGS.webcamSizePreset),+ webcamPosition: normaliseWebcamPosition(legacy?.webcamPosition),+ cursor,+ cursorShow: bool(legacy?.cursorShow, DEFAULT_EDITOR_SETTINGS.cursorShow),+ cursorTheme: str(legacy?.cursorTheme, DEFAULT_EDITOR_SETTINGS.cursorTheme),+ autoFocusAll: bool(legacy?.autoFocusAll, DEFAULT_EDITOR_SETTINGS.autoFocusAll),+ };+}+export interface EditorSettingsPatch {+ wallpaper?: string;+ aspectRatio?: AspectRatio;+ shadowIntensity?: number;+ showBlur?: boolean;+ showTrimWaveform?: boolean;+ motionBlurAmount?: number;+ borderRadius?: number;+ padding?: number;+ cropRegion?: CropRegion;+ webcamLayoutPreset?: WebcamLayoutPreset;+ webcamMaskShape?: WebcamMaskShape;+ webcamMirrored?: boolean;+ webcamReactiveZoom?: boolean;+ webcamSizePreset?: WebcamSizePreset;+ webcamPosition?: WebcamPosition | null;+ cursor?: Partial<CursorVisualSettings> & { theme?: string; show?: boolean };+ autoFocusAll?: boolean;+}++function nextLegacy(current: LegacyShape | null, patch: EditorSettingsPatch): LegacyShape {+ const base: LegacyShape = current ?? {};+ const next: LegacyShape = { ...base };+ if (patch.wallpaper !== undefined) next.wallpaper = patch.wallpaper;+ if (patch.aspectRatio !== undefined) next.aspectRatio = patch.aspectRatio;+ if (patch.shadowIntensity !== undefined) next.shadowIntensity = patch.shadowIntensity;+ if (patch.showBlur !== undefined) next.showBlur = patch.showBlur;+ if (patch.showTrimWaveform !== undefined) next.showTrimWaveform = patch.showTrimWaveform;+ if (patch.motionBlurAmount !== undefined) next.motionBlurAmount = patch.motionBlurAmount;+ if (patch.borderRadius !== undefined) next.borderRadius = patch.borderRadius;+ if (patch.padding !== undefined) next.padding = patch.padding;+ if (patch.cropRegion !== undefined) next.cropRegion = patch.cropRegion;+ if (patch.webcamLayoutPreset !== undefined) next.webcamLayoutPreset = patch.webcamLayoutPreset;+ if (patch.webcamMaskShape !== undefined) next.webcamMaskShape = patch.webcamMaskShape;+ if (patch.webcamMirrored !== undefined) next.webcamMirrored = patch.webcamMirrored;+ if (patch.webcamReactiveZoom !== undefined) next.webcamReactiveZoom = patch.webcamReactiveZoom;+ if (patch.webcamSizePreset !== undefined) next.webcamSizePreset = patch.webcamSizePreset;+ if (patch.webcamPosition !== undefined) next.webcamPosition = patch.webcamPosition;+ if (patch.autoFocusAll !== undefined) next.autoFocusAll = patch.autoFocusAll;+ if (patch.cursor) {+ const c = patch.cursor;+ if (c.size !== undefined) next.cursorSize = c.size;+ if (c.smoothing !== undefined) next.cursorSmoothing = c.smoothing;+ if (c.motionBlur !== undefined) next.cursorMotionBlur = c.motionBlur;+ if (c.clickBounce !== undefined) next.cursorClickBounce = c.clickBounce;+ if (c.clipToBounds !== undefined) next.cursorClipToBounds = c.clipToBounds;+ if (c.theme !== undefined) next.cursorTheme = c.theme;+ if (c.show !== undefined) next.cursorShow = c.show;+ }+ return next;+}++export function patchEditorSettings(doc: AxcutDocument, patch: EditorSettingsPatch): AxcutDocument {+ const current = isShape(doc.legacyEditor) ? (doc.legacyEditor as LegacyShape) : null;+ return {+ ...doc,+ legacyEditor: nextLegacy(current, patch) as Record<string, unknown>,+ };+}++// Normalise a webcam position from legacy storage. Anything outside 0-1 is+// clamped so a malformed `legacyEditor` doesn't seed the drag with bad coords.+function normaliseWebcamPosition(value: unknown): WebcamPosition | null {+ if (!value || typeof value !== "object") return DEFAULT_WEBCAM_POSITION;+ const candidate = value as Record<string, unknown>;+ const cxRaw = candidate.cx;+ const cyRaw = candidate.cy;+ if (typeof cxRaw !== "number" || typeof cyRaw !== "number") return DEFAULT_WEBCAM_POSITION;+ return {+ cx: Math.min(1, Math.max(0, cxRaw)),+ cy: Math.min(1, Math.max(0, cyRaw)),+ };+}diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsnew file mode 100644index 000000000..74dea9054--- /dev/null+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -0,0 +1,141 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProjectStore } from "./projectStore";++const bridgeMocks = vi.hoisted(() => ({+ get: vi.fn(),+ create: vi.fn(),+ save: vi.fn(),+ addAsset: vi.fn(),+ removeAsset: vi.fn(),+ listProjects: vi.fn(),+}));++vi.mock("@/native/client", () => ({+ nativeBridgeClient: {+ aiEdition: {+ get: bridgeMocks.get,+ create: bridgeMocks.create,+ save: bridgeMocks.save,+ addAsset: bridgeMocks.addAsset,+ removeAsset: bridgeMocks.removeAsset,+ listProjects: bridgeMocks.listProjects,+ },+ },+}));++const sampleDoc = {+ schemaVersion: 3,+ project: {+ id: "proj_test",+ title: "Test",+ createdAt: "2026-06-25T10:00:00.000Z",+ updatedAt: "2026-06-25T10:00:00.000Z",+ },+ assets: [],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+};++describe("useProjectStore", () => {+ beforeEach(() => {+ useProjectStore.getState().clear();+ for (const mock of Object.values(bridgeMocks)) {+ mock.mockReset();+ }+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("createProject stores the returned document and bumps revision", async () => {+ bridgeMocks.create.mockResolvedValue({ success: true, document: sampleDoc });++ const doc = await useProjectStore.getState().createProject("Test");++ expect(doc.project.id).toBe("proj_test");+ const state = useProjectStore.getState();+ expect(state.projectId).toBe("proj_test");+ expect(state.document?.project.title).toBe("Test");+ expect(state.revision).toBe(1);+ expect(state.status).toBe("ready");+ });++ it("loadProject handles a failed bridge response by setting error status", async () => {+ bridgeMocks.get.mockResolvedValue({ success: false, error: "not found" });++ await useProjectStore.getState().loadProject("proj_x");++ const state = useProjectStore.getState();+ expect(state.status).toBe("error");+ expect(state.error).toBe("not found");+ });++ it("addAsset replaces the document and bumps revision", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ });+ const updatedDoc = {+ ...sampleDoc,+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "screen.webm",+ originalPath: "/tmp/screen.webm",+ },+ ],+ project: { ...sampleDoc.project, primaryAssetId: "asset_1" },+ };+ bridgeMocks.addAsset.mockResolvedValue({ assetId: "asset_1", document: updatedDoc });++ const asset = await useProjectStore.getState().addAsset("/tmp/screen.webm");++ expect(asset?.id).toBe("asset_1");+ expect(useProjectStore.getState().revision).toBe(2);+ expect(useProjectStore.getState().document?.assets).toHaveLength(1);+ });++ it("removeAsset requires a loaded project", async () => {+ await expect(useProjectStore.getState().removeAsset("asset_x")).rejects.toThrow(+ "No project loaded",+ );+ });++ it("clear resets the store", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 5,+ status: "ready",+ error: null,+ });+ useProjectStore.getState().clear();+ expect(useProjectStore.getState()).toMatchObject({+ projectId: null,+ document: null,+ revision: 0,+ status: "idle",+ error: null,+ });+ });+});diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsnew file mode 100644index 000000000..7bb247ca1--- /dev/null+++ b/src/lib/ai-edition/store/projectStore.ts@@ -0,0 +1,265 @@+import { create } from "zustand";+import { nativeBridgeClient } from "@/native/client";+import {+ type Interval,+ replaceTimeline as replaceTimelineOp,+ restoreFullTimeline as restoreFullTimelineOp,+} from "../document/timeline";+import {+ type AxcutAsset,+ type AxcutDocument,+ type AxcutTranscript,+ documentSchema,+} from "../schema";++// ponytail: thin Zustand wrapper over the native-bridge client. Keeps the+// current project + revision counter in renderer memory; mutations round-trip+// through the main process via the bridge so disk state stays authoritative.++export type ProjectStatus = "idle" | "loading" | "ready" | "error";++export interface ProjectState {+ projectId: string | null;+ document: AxcutDocument | null;+ revision: number;+ status: ProjectStatus;+ error: string | null;+ sourceDurationSec: number;+ currentTimeSec: number;+ /** True when the in-memory document has local changes that haven't been written to disk yet. */+ dirty: boolean;+ /** Timestamp of the most recent successful save (used by the titlebar indicator). */+ lastSavedAt: Date | null;++ loadProject: (projectId: string) => Promise<void>;+ createProject: (title: string) => Promise<AxcutDocument>;+ refresh: () => Promise<void>;+ addAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;+ removeAsset: (assetId: string) => Promise<void>;+ saveDocument: (document: AxcutDocument) => Promise<void>;+ setDocument: (document: AxcutDocument) => void;+ replaceTimeline: (intervals: Interval[], reason: string) => Promise<void>;+ restoreFullTimeline: () => Promise<void>;+ setTranscript: (transcript: AxcutTranscript) => Promise<void>;+ setSourceDuration: (sec: number) => void;+ setCurrentTime: (sec: number) => void;+ markClean: () => void;+ clear: () => void;+}++function parseDocument(value: unknown): AxcutDocument {+ return documentSchema.parse(value);+}++export const useProjectStore = create<ProjectState>((set, get) => ({+ projectId: null,+ document: null,+ revision: 0,+ status: "idle",+ error: null,+ sourceDurationSec: 0,+ currentTimeSec: 0,+ dirty: false,+ lastSavedAt: null,++ async loadProject(projectId) {+ set({ status: "loading", error: null });+ try {+ const result = await nativeBridgeClient.aiEdition.get(projectId);+ if (!result.success || !result.document) {+ throw new Error(result.error ?? "Failed to load project");+ }+ const document = parseDocument(result.document);+ set({+ projectId,+ document,+ revision: get().revision + 1,+ status: "ready",+ error: null,+ dirty: false,+ lastSavedAt: new Date(),+ });+ void import("./undo").then(({ clearHistory }) => clearHistory());+ } catch (error) {+ set({+ status: "error",+ error: error instanceof Error ? error.message : String(error),+ });+ }+ },++ async createProject(title) {+ set({ status: "loading", error: null });+ try {+ const result = await nativeBridgeClient.aiEdition.create(title);+ if (!result.success || !result.document) {+ throw new Error(result.error ?? "Failed to create project");+ }+ const document = parseDocument(result.document);+ set({+ projectId: document.project.id,+ document,+ revision: get().revision + 1,+ status: "ready",+ error: null,+ dirty: false,+ lastSavedAt: new Date(),+ });+ void import("./undo").then(({ clearHistory }) => clearHistory());+ return document;+ } catch (error) {+ set({+ status: "error",+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ },++ async refresh() {+ const { projectId } = get();+ if (!projectId) return;+ await get().loadProject(projectId);+ },++ async addAsset(path, label) {+ const { projectId } = get();+ if (!projectId) throw new Error("No project loaded");+ const result = await nativeBridgeClient.aiEdition.addAsset(projectId, path, label);+ let document = parseDocument(result.document);+ const addedAsset =+ document.assets.find((a) => a.originalPath === path && (label ? a.label === label : true)) ??+ document.assets.at(-1) ??+ null;++ // ponytail: auto-link the camera track from the recording session+ // sidecar when the imported path is a recording's screen file. The+ // camera DSL is read-only — cuts/zoom/speed live on the main timeline+ // and apply to the camera via the shared source-time progression.+ if (addedAsset && document.cameraTrack === null && window.electronAPI?.findRecordingCamera) {+ try {+ const camera = await window.electronAPI.findRecordingCamera(addedAsset.originalPath);+ if (camera.success && camera.webcamVideoPath) {+ const linked = {+ sourcePath: camera.webcamVideoPath,+ startMs: 0,+ offsetMs: camera.offsetMs ?? 0,+ visible: true,+ };+ const next = { ...document, cameraTrack: linked };+ await get().saveDocument(next);+ document = parseDocument(next);+ }+ } catch {+ // ponytail: silent — no camera, no problem.+ }+ }++ set({+ document,+ revision: get().revision + 1,+ dirty: false,+ lastSavedAt: new Date(),+ });+ return addedAsset;+ },++ async removeAsset(assetId) {+ const { projectId } = get();+ if (!projectId) throw new Error("No project loaded");+ const result = await nativeBridgeClient.aiEdition.removeAsset(projectId, assetId);+ const document = parseDocument(result.document);+ set({+ document,+ revision: get().revision + 1,+ dirty: false,+ lastSavedAt: new Date(),+ });+ },++ async saveDocument(document) {+ const result = await nativeBridgeClient.aiEdition.save(document);+ if (!result.success || !result.document) {+ throw new Error(result.error ?? "Failed to save project");+ }+ const parsed = parseDocument(result.document);+ set({+ document: parsed,+ revision: get().revision + 1,+ dirty: false,+ lastSavedAt: new Date(),+ });+ },++ setDocument(document) {+ const prev = get().document;+ if (prev && prev !== document) {+ // ponytail: push snapshot to undo history. Defer import to avoid+ // pulling the undo module into the store at module-load time.+ void import("./undo").then(({ pushHistory }) => {+ pushHistory({ projectId: prev.project.id, doc: structuredClone(prev) });+ });+ }+ set({+ document,+ revision: get().revision + 1,+ dirty: true,+ });+ },++ async replaceTimeline(intervals, reason) {+ const doc = get().document;+ if (!doc) throw new Error("No project loaded");+ const next = replaceTimelineOp(doc, intervals, reason);+ await get().saveDocument(next);+ },++ async restoreFullTimeline() {+ const doc = get().document;+ if (!doc) throw new Error("No project loaded");+ const next = restoreFullTimelineOp(doc);+ await get().saveDocument(next);+ },++ async setTranscript(transcript) {+ const doc = get().document;+ if (!doc) throw new Error("No project loaded");+ const transcripts = [+ ...doc.transcripts.filter((t) => t.assetId !== transcript.assetId),+ transcript,+ ];+ const next: AxcutDocument = {+ ...doc,+ transcript: doc.project.primaryAssetId === transcript.assetId ? transcript : doc.transcript,+ transcripts,+ preview: { ...doc.preview, revision: doc.preview.revision + 1 },+ };+ await get().saveDocument(next);+ },++ setSourceDuration(sec) {+ set({ sourceDurationSec: sec });+ },++ setCurrentTime(sec) {+ set({ currentTimeSec: sec });+ },++ clear() {+ set({+ projectId: null,+ document: null,+ revision: 0,+ status: "idle",+ error: null,+ sourceDurationSec: 0,+ currentTimeSec: 0,+ dirty: false,+ lastSavedAt: null,+ });+ },++ markClean() {+ set({ dirty: false, lastSavedAt: new Date() });+ },+}));diff --git a/src/lib/ai-edition/store/regionClipboard.ts b/src/lib/ai-edition/store/regionClipboard.tsnew file mode 100644index 000000000..f9130aefa--- /dev/null+++ b/src/lib/ai-edition/store/regionClipboard.ts@@ -0,0 +1,45 @@+// Per-region copy/paste clipboard. Backed by module-level state so Cmd+C in+// one component can be picked up by Cmd+V in another. Mirrors the legacy+// regionClipboard pattern but keeps it focused on zoom/annotation/speed+// regions (skip is stored in the timeline directly, so it doesn't go through+// this path).++import { useCallback, useEffect, useState } from "react";++export type RegionSnapshot =+ | { kind: "zoom"; region: Record<string, unknown> }+ | { kind: "annotation"; region: Record<string, unknown> }+ | { kind: "speed"; region: Record<string, unknown> };++let clipboard: RegionSnapshot | null = null;+const listeners = new Set<() => void>();+function notify() {+ for (const fn of listeners) fn();+}+export function copyRegion(snap: RegionSnapshot) {+ clipboard = { ...snap };+ notify();+}+export function pasteClipboard(): RegionSnapshot | null {+ return clipboard;+}+export function useRegionClipboard() {+ const [, force] = useState(0);+ useEffect(() => {+ const fn = () => force((n) => n + 1);+ listeners.add(fn);+ return () => {+ listeners.delete(fn);+ };+ }, []);+ return {+ hasContent: clipboard !== null,+ kind: clipboard?.kind ?? null,+ read: () => clipboard,+ };+}++// React-friendly hook for components to use a stable callback reference.+export function useCopyRegion() {+ return useCallback((snap: RegionSnapshot) => copyRegion(snap), []);+}diff --git a/src/lib/ai-edition/store/undo.ts b/src/lib/ai-edition/store/undo.tsnew file mode 100644index 000000000..6742697a3--- /dev/null+++ b/src/lib/ai-edition/store/undo.ts@@ -0,0 +1,84 @@+// Lightweight undo/redo for the project document. The store fires+// `documentChanged` whenever `setDocument` is called; subscribers record+// snapshots up to a bounded history. Cmd+Z / Cmd+Shift+Z use the snapshot+// stack to roll back / roll forward. Designed to be small and side-effect+// free so it works in any renderer.++import { useEffect, useRef } from "react";+import { useProjectStore } from "./projectStore";++type Snapshot = { projectId: string; doc: unknown };++const MAX_HISTORY = 50;+const past: Snapshot[] = [];+const future: Snapshot[] = [];++let enabled = true;++export function pushHistory(snapshot: Snapshot) {+ if (!enabled) return;+ past.push(snapshot);+ if (past.length > MAX_HISTORY) past.shift();+ future.length = 0;+}++export function clearHistory() {+ past.length = 0;+ future.length = 0;+}++export function undo(): boolean {+ const prev = past.pop();+ if (!prev) return false;+ const state = useProjectStore.getState();+ if (!state.projectId || state.projectId !== prev.projectId) {+ clearHistory();+ return false;+ }+ const doc = state.document;+ if (doc) future.push({ projectId: prev.projectId, doc: structuredClone(doc) });+ enabled = false;+ state.setDocument(prev.doc as never);+ enabled = true;+ return true;+}++export function redo(): boolean {+ const next = future.pop();+ if (!next) return false;+ const state = useProjectStore.getState();+ if (!state.projectId || state.projectId !== next.projectId) {+ clearHistory();+ return false;+ }+ const doc = state.document;+ if (doc) past.push({ projectId: doc.project.id, doc: structuredClone(doc) });+ enabled = false;+ state.setDocument(next.doc as never);+ enabled = true;+ return true;+}++export function useUndoRedoShortcuts(onAfter: () => void) {+ const onAfterRef = useRef(onAfter);+ onAfterRef.current = onAfter;+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLInputElement) return;+ if (e.target instanceof HTMLElement && e.target.isContentEditable) return;+ const ctrl = e.ctrlKey || e.metaKey;+ if (ctrl && e.shiftKey && e.key.toLowerCase() === "z") {+ e.preventDefault();+ if (redo()) onAfterRef.current();+ return;+ }+ if (ctrl && e.key === "z") {+ e.preventDefault();+ if (undo()) onAfterRef.current();+ return;+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);+}diff --git a/src/lib/ai-edition/store/useEditorSettings.ts b/src/lib/ai-edition/store/useEditorSettings.tsnew file mode 100644index 000000000..8dade1065--- /dev/null+++ b/src/lib/ai-edition/store/useEditorSettings.ts@@ -0,0 +1,72 @@+// React binding over the editor-settings pure module.+//+// Usage:+// const { settings, set, setLive } = useEditorSettings();+// - `settings` is a typed snapshot of the document's legacy settings.+// - `set(patch)` writes + commits to disk (use for toggles, selects, on+// slider release).+// - `setLive(patch)` writes only (use while dragging a slider for the+// preview to update without round-tripping every pixel).+//+// The hook is intentionally thin: it reads from the project store, applies+// the patch through `patchEditorSettings`, and persists via the store. No+// extra state, no caches — the document is the single source of truth.++import { useCallback, useMemo } from "react";+import {+ type EditorSettingsPatch,+ type EditorSettingsSnapshot,+ getEditorSettings,+ patchEditorSettings,+} from "./editorSettings";+import { useProjectStore } from "./projectStore";++export interface UseEditorSettingsResult {+ settings: EditorSettingsSnapshot;+ /** True when there's a project loaded — `set`/`setLive` are no-ops otherwise. */+ hasDocument: boolean;+ /** Apply a patch, persist to disk. */+ set: (patch: EditorSettingsPatch) => Promise<void>;+ /** Apply a patch, no persist. Pair with `commit` on slider release. */+ setLive: (patch: EditorSettingsPatch) => void;+ /** Force-flush the current document to disk. */+ commit: () => Promise<void>;+}++export function useEditorSettings(): UseEditorSettingsResult {+ const document = useProjectStore((s) => s.document);+ const setDocument = useProjectStore((s) => s.setDocument);+ const saveDocument = useProjectStore((s) => s.saveDocument);++ const hasDocument = document !== null;++ const settings = useMemo(() => getEditorSettings(document), [document]);++ const set = useCallback(+ async (patch: EditorSettingsPatch) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const next = patchEditorSettings(doc, patch);+ setDocument(next);+ await saveDocument(next);+ },+ [setDocument, saveDocument],+ );++ const setLive = useCallback(+ (patch: EditorSettingsPatch) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ setDocument(patchEditorSettings(doc, patch));+ },+ [setDocument],+ );++ const commit = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ await saveDocument(doc);+ }, [saveDocument]);++ return { settings, hasDocument, set, setLive, commit };+}diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsnew file mode 100644index 000000000..e278f949d--- /dev/null+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -0,0 +1,327 @@+// Hook: region mutations for the new editor shell. Wraps the project store+// with typed add/remove/select operations for zoom, skip, annotation, and+// speed regions. Each add creates a 2-second region at the current playhead+// (a reasonable default for the user to then resize).++import { useCallback, useState } from "react";+import type { AnnotationRegion, AnnotationType } from "@/components/video-editor/types";+import { createId } from "../document/ids";+import type { AxcutDocument } from "../schema";+import { useProjectStore } from "./projectStore";++type RegionKind = "zoom" | "skip" | "annotation" | "speed";++interface RegionHandle {+ kind: RegionKind;+ id: string;+}++export function useTimeline() {+ const document = useProjectStore((s) => s.document);+ const projectId = useProjectStore((s) => s.projectId);+ const currentTimeSec = useProjectStore((s) => s.currentTimeSec);+ const saveDocument = useProjectStore((s) => s.saveDocument);+ const [selection, setSelection] = useState<RegionHandle | null>(null);++ const hasDoc = document !== null && projectId !== null;++ const addZoom = useCallback(async () => {+ if (!document) return;+ const timeMs = Math.round(currentTimeSec * 1000);+ const next: AxcutDocument = {+ ...document,+ zoomRanges: [+ ...document.zoomRanges,+ {+ id: createId("zoom"),+ startMs: timeMs,+ endMs: timeMs + 2000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ focusMode: "manual" as const,+ },+ ] as AxcutDocument["zoomRanges"],+ };+ await saveDocument(next);+ }, [document, currentTimeSec, saveDocument]);++ const addSkip = useCallback(async () => {+ if (!document) return;+ const asset =+ document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];+ if (!asset) return;+ const id = createId("skip");+ const next: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ skipRanges: [+ ...document.timeline.skipRanges,+ {+ id,+ assetId: asset.id,+ startSec: currentTimeSec,+ endSec: currentTimeSec + 2,+ reason: "manual",+ origin: "user" as const,+ },+ ],+ },+ };+ await saveDocument(next);+ }, [document, currentTimeSec, saveDocument]);++ const addAnnotation = useCallback(async () => {+ if (!document) return;+ const timeMs = Math.round(currentTimeSec * 1000);+ const ann: AnnotationRegion = {+ id: createId("ann"),+ startMs: timeMs,+ endMs: timeMs + 2000,+ type: "text" as AnnotationType,+ content: "New annotation",+ textContent: "New annotation",+ position: { x: 50, y: 50 },+ size: { width: 30, height: 20 },+ style: {+ color: "#ffffff",+ backgroundColor: "transparent",+ fontSize: 32,+ fontFamily: "Inter",+ fontWeight: "bold",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+ textAnimation: "none",+ },+ zIndex: document.annotations.length + 1,+ };+ const next: AxcutDocument = {+ ...document,+ annotations: [...document.annotations, ann] as unknown as AxcutDocument["annotations"],+ };+ await saveDocument(next);+ }, [document, currentTimeSec, saveDocument]);++ const addSpeed = useCallback(async () => {+ if (!document) return;+ const timeMs = Math.round(currentTimeSec * 1000);+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = (legacy.speedRegions as unknown[]) ?? [];+ const next: AxcutDocument = {+ ...document,+ legacyEditor: {+ ...legacy,+ speedRegions: [+ ...prev,+ {+ id: createId("speed"),+ startMs: timeMs,+ endMs: timeMs + 2000,+ speed: 1.5 as const,+ },+ ],+ },+ };+ await saveDocument(next);+ }, [document, currentTimeSec, saveDocument]);++ const removeRegion = useCallback(+ async (kind: RegionKind, id: string) => {+ if (!document) return;+ let next: AxcutDocument;+ if (kind === "zoom") {+ next = {+ ...document,+ zoomRanges: document.zoomRanges.filter((z) => z.id !== id) as AxcutDocument["zoomRanges"],+ };+ } else if (kind === "skip") {+ next = {+ ...document,+ timeline: {+ ...document.timeline,+ skipRanges: document.timeline.skipRanges.filter((s) => s.id !== id),+ },+ };+ } else if (kind === "annotation") {+ next = {+ ...document,+ annotations: document.annotations.filter((a) => a.id !== id),+ };+ } else {+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = ((legacy.speedRegions as unknown[]) ?? []).filter(+ (s) => (s as { id: string }).id !== id,+ );+ next = {+ ...document,+ legacyEditor: { ...legacy, speedRegions: prev },+ };+ }+ await saveDocument(next);+ if (selection?.id === id) setSelection(null);+ },+ [document, selection, saveDocument],+ );++ const selectRegion = useCallback((kind: RegionKind, id: string) => {+ setSelection({ kind, id });+ }, []);++ const clearSelection = useCallback(() => setSelection(null), []);++ const addClipBefore = useCallback(+ async (assetId: string) => {+ if (!document) return;+ const asset = document.assets.find((a) => a.id === assetId);+ if (!asset) return;+ const duration = asset.durationSec ?? 30;+ const newClip: AxcutDocument["timeline"]["clips"][number] = {+ id: createId("clip"),+ assetId,+ sourceStartSec: 0,+ sourceEndSec: duration,+ timelineStartSec: 0,+ timelineEndSec: duration,+ wordRefs: [],+ origin: "user",+ reason: "Inserted before all clips",+ };+ const shifted = document.timeline.clips.map((c) => ({+ ...c,+ timelineStartSec: c.timelineStartSec + duration,+ timelineEndSec: c.timelineEndSec + duration,+ }));+ const next: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ clips: [newClip, ...shifted],+ },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ const addClipAfter = useCallback(+ async (assetId: string) => {+ if (!document) return;+ const asset = document.assets.find((a) => a.id === assetId);+ if (!asset) return;+ const duration = asset.durationSec ?? 30;+ const lastEnd = document.timeline.clips.at(-1)?.timelineEndSec ?? 0;+ const newClip: AxcutDocument["timeline"]["clips"][number] = {+ id: createId("clip"),+ assetId,+ sourceStartSec: 0,+ sourceEndSec: duration,+ timelineStartSec: lastEnd,+ timelineEndSec: lastEnd + duration,+ wordRefs: [],+ origin: "user",+ reason: "Inserted after all clips",+ };+ const next: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ clips: [...document.timeline.clips, newClip],+ },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ const splitAndInsert = useCallback(+ async (assetId: string, splitTimeSec: number) => {+ if (!document) return;+ const asset = document.assets.find((a) => a.id === assetId);+ if (!asset) return;+ const duration = asset.durationSec ?? 30;+ const targetIdx = document.timeline.clips.findIndex(+ (c) => c.timelineStartSec <= splitTimeSec && c.timelineEndSec >= splitTimeSec,+ );+ if (targetIdx === -1) {+ await addClipAfter(assetId);+ return;+ }+ const target = document.timeline.clips[targetIdx];+ const left = {+ id: createId("clip"),+ assetId: target.assetId,+ sourceStartSec: target.sourceStartSec,+ sourceEndSec: splitTimeSec,+ timelineStartSec: target.timelineStartSec,+ timelineEndSec: splitTimeSec,+ wordRefs: [] as string[],+ origin: "user" as const,+ reason: "Split left",+ };+ const insert = {+ id: createId("clip"),+ assetId,+ sourceStartSec: 0,+ sourceEndSec: duration,+ timelineStartSec: splitTimeSec,+ timelineEndSec: splitTimeSec + duration,+ wordRefs: [] as string[],+ origin: "user" as const,+ reason: "Inserted between splits",+ };+ const right = {+ id: createId("clip"),+ assetId: target.assetId,+ sourceStartSec: target.sourceStartSec + splitTimeSec - target.timelineStartSec,+ sourceEndSec: target.sourceEndSec,+ timelineStartSec: splitTimeSec + duration,+ timelineEndSec: target.timelineEndSec + duration,+ wordRefs: [] as string[],+ origin: "user" as const,+ reason: "Split right",+ };+ const nextClips: AxcutDocument["timeline"]["clips"] = [+ ...document.timeline.clips.slice(0, targetIdx),+ left,+ insert,+ right as (typeof document.timeline.clips)[number],+ ...document.timeline.clips.slice(targetIdx + 1),+ ];+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: nextClips },+ };+ await saveDocument(next);+ },+ [document, saveDocument, addClipAfter],+ );++ const speedRegions = hasDoc+ ? (((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as Array<{+ id: string;+ startMs: number;+ endMs: number;+ speed: number;+ }>) ?? [])+ : [];++ return {+ zoomRegions: document?.zoomRanges ?? [],+ skipRanges: document?.timeline.skipRanges ?? [],+ annotationRegions: (document?.annotations ?? []) as unknown as AnnotationRegion[],+ speedRegions,+ hasDoc,+ selection,+ addZoom,+ addSkip,+ addAnnotation,+ addSpeed,+ removeRegion,+ selectRegion,+ clearSelection,+ addClipBefore,+ addClipAfter,+ splitAndInsert,+ };+}diff --git a/src/lib/ai-edition/timeline/virtual-preview.test.ts b/src/lib/ai-edition/timeline/virtual-preview.test.tsnew file mode 100644index 000000000..172503778--- /dev/null+++ b/src/lib/ai-edition/timeline/virtual-preview.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from "vitest";+import type { AxcutClip } from "../schema";+import {+ clampVirtualTime,+ formatSeconds,+ keptWordIdSet,+ locateSourcePosition,+ locateVirtualPosition,+ totalVirtualDuration,+} from "./virtual-preview";++const clips: AxcutClip[] = [+ {+ id: "clip_1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: ["w1", "w2"],+ origin: "system",+ reason: "",+ },+ {+ id: "clip_2",+ assetId: "a1",+ sourceStartSec: 20,+ sourceEndSec: 30,+ timelineStartSec: 10,+ timelineEndSec: 20,+ wordRefs: ["w3"],+ origin: "system",+ reason: "",+ },+];++describe("virtual-preview pure functions", () => {+ it("totalVirtualDuration returns the last clip's timelineEndSec", () => {+ expect(totalVirtualDuration(clips)).toBe(20);+ expect(totalVirtualDuration([])).toBe(0);+ });++ it("clampVirtualTime bounds to [0, total]", () => {+ expect(clampVirtualTime(clips, -5)).toBe(0);+ expect(clampVirtualTime(clips, 999)).toBe(20);+ expect(clampVirtualTime(clips, 15)).toBe(15);+ });++ it("locateVirtualPosition maps virtual time to source time", () => {+ const pos = locateVirtualPosition(clips, 12);+ expect(pos).not.toBeNull();+ expect(pos?.clipIndex).toBe(1);+ expect(pos?.sourceTimeSec).toBe(22);+ });++ it("locateVirtualPosition returns null for empty clips", () => {+ expect(locateVirtualPosition([], 0)).toBeNull();+ });++ it("locateSourcePosition maps source time back to virtual time", () => {+ const pos = locateSourcePosition(clips, 25);+ expect(pos).not.toBeNull();+ expect(pos?.virtualTimeSec).toBe(15);+ });++ it("locateSourcePosition returns null for source time in a cut", () => {+ expect(locateSourcePosition(clips, 15)).toBeNull();+ });++ it("keptWordIdSet flattens wordRefs from all clips", () => {+ expect(keptWordIdSet(clips)).toEqual(new Set(["w1", "w2", "w3"]));+ });++ it("formatSeconds formats mm:ss.s and h:mm:ss.s", () => {+ expect(formatSeconds(0)).toBe("0:00.0");+ expect(formatSeconds(65.4)).toBe("1:05.4");+ expect(formatSeconds(3661.5)).toBe("1:01:01.5");+ });++ it("locateSourcePosition filters by assetId when provided", () => {+ const multiClips: AxcutClip[] = [+ {+ id: "clip_1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "system",+ reason: "",+ },+ {+ id: "clip_2",+ assetId: "a2",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 10,+ timelineEndSec: 20,+ wordRefs: [],+ origin: "system",+ reason: "",+ },+ ];+ const pos1 = locateSourcePosition(multiClips, 5, "a1");+ expect(pos1?.clip.id).toBe("clip_1");++ const pos2 = locateSourcePosition(multiClips, 5, "a2");+ expect(pos2?.clip.id).toBe("clip_2");++ const posNone = locateSourcePosition(multiClips, 5, "a3");+ expect(posNone).toBeNull();+ });+});diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.tsnew file mode 100644index 000000000..cd4625003--- /dev/null+++ b/src/lib/ai-edition/timeline/virtual-preview.ts@@ -0,0 +1,86 @@+// Ported from axcut/apps/web/src/lib/virtual-preview.ts — pure time-mapping+// functions shared by the VirtualPreview component and the timeline math.++import type { AxcutClip } from "../schema";++export type VirtualPosition = {+ clip: AxcutClip;+ clipIndex: number;+ virtualTimeSec: number;+ sourceTimeSec: number;+};++export function totalVirtualDuration(clips: AxcutClip[]): number {+ return clips.at(-1)?.timelineEndSec ?? 0;+}++export function clampVirtualTime(clips: AxcutClip[], value: number): number {+ if (clips.length === 0) return 0;+ return Math.max(0, Math.min(totalVirtualDuration(clips), value));+}++export function locateVirtualPosition(+ clips: AxcutClip[],+ virtualTimeSec: number,+): VirtualPosition | null {+ if (clips.length === 0) return null;+ const clamped = clampVirtualTime(clips, virtualTimeSec);+ const clipIndex = clips.findIndex((clip, index) => {+ const isLast = index === clips.length - 1;+ return clamped >= clip.timelineStartSec && (clamped < clip.timelineEndSec || isLast);+ });+ const resolvedIndex = clipIndex >= 0 ? clipIndex : clips.length - 1;+ const clip = clips[resolvedIndex];+ const clipDuration = (clip.sourceEndSec ?? 0) - clip.sourceStartSec;+ const clipOffset = Math.max(0, Math.min(clipDuration, clamped - clip.timelineStartSec));+ return {+ clip,+ clipIndex: resolvedIndex,+ virtualTimeSec: clamped,+ sourceTimeSec: clip.sourceStartSec + clipOffset,+ };+}++export function locateSourcePosition(+ clips: AxcutClip[],+ sourceTimeSec: number,+ assetId?: string,+ epsilon = 0.05,+): VirtualPosition | null {+ const clipIndex = clips.findIndex((clip, index) => {+ if (assetId && clip.assetId !== assetId) return false;+ const lowerBound = clip.sourceStartSec - epsilon;+ const upperBound =+ index === clips.length - 1+ ? (clip.sourceEndSec ?? 0) + epsilon+ : (clip.sourceEndSec ?? 0) - epsilon;+ return sourceTimeSec >= lowerBound && sourceTimeSec <= upperBound;+ });+ if (clipIndex < 0) return null;+ const clip = clips[clipIndex];+ const sourceOffset = Math.max(+ 0,+ Math.min((clip.sourceEndSec ?? 0) - clip.sourceStartSec, sourceTimeSec - clip.sourceStartSec),+ );+ return {+ clip,+ clipIndex,+ virtualTimeSec: clip.timelineStartSec + sourceOffset,+ sourceTimeSec,+ };+}++export function keptWordIdSet(clips: AxcutClip[]): Set<string> {+ return new Set(clips.flatMap((clip) => clip.wordRefs));+}++export function formatSeconds(value: number): string {+ const safe = Math.max(0, value);+ const hours = Math.floor(safe / 3600);+ const minutes = Math.floor((safe % 3600) / 60);+ const seconds = safe % 60;+ if (hours > 0) {+ return `${hours}:${String(minutes).padStart(2, "0")}:${seconds.toFixed(1).padStart(4, "0")}`;+ }+ return `${minutes}:${seconds.toFixed(1).padStart(4, "0")}`;+}diff --git a/src/lib/compositeLayout.test.ts b/src/lib/compositeLayout.test.tsindex 2cdef3245..46dff87eb 100644--- a/src/lib/compositeLayout.test.ts+++ b/src/lib/compositeLayout.test.ts@@ -170,15 +170,41 @@ describe("computeCompositeLayout", () => {});expect(layout).not.toBeNull();- // Webcam is full-width at the bottom+ // ponytail: padding insets the content vertically. `maxContentSize` is+ // 1536x864 (canvasSize × paddingFit=0.8), so the content area is+ // 1536×864 centered at y=(1080−864)/2=108. Everything inside the+ // stack is computed against this content area, not the canvas.expect(layout!.webcamRect).not.toBeNull();- expect(layout!.webcamRect!.x).toBe(0);- expect(layout!.webcamRect!.width).toBe(1920);- expect(layout!.webcamRect!.borderRadius).toBe(0);- // Screen fills remaining space at the top (cover mode)- expect(layout!.screenRect.x).toBe(0);- expect(layout!.screenRect.y).toBe(0);- expect(layout!.screenRect.width).toBe(1920);+ const contentHeight = 864;+ const webcamCapHeight = Math.min(1280 / (1280 / 720), Math.round(contentHeight * 0.4));+ const webcamHeight = Math.round(webcamCapHeight);+ const webcamWidth = Math.round(webcamHeight * (1280 / 720));+ const gap = Math.max(8, Math.round(1536 * 0.02));+ const contentY = Math.floor((1080 - contentHeight) / 2);+ // Camera is centered horizontally inside the content area, which is+ // itself centered in the canvas. Sits at contentY + (contentHeight+ // − webcamHeight − gap) — i.e. with the gap between it and the+ // screen, all inside the padded band.+ const screenHeight = contentHeight - webcamHeight - gap;+ const contentX = Math.floor((1920 - 1536) / 2);+ const camOffsetInContent = Math.floor((1536 - webcamWidth) / 2);+ expect(layout!.webcamRect!.x).toBe(contentX + camOffsetInContent);+ expect(layout!.webcamRect!.y).toBe(contentY + screenHeight + gap);+ expect(layout!.webcamRect!.width).toBe(webcamWidth);+ expect(layout!.webcamRect!.height).toBe(webcamHeight);+ // Border-radius follows the preset fraction (max:24, min:8, fraction:0.06)+ // on min(width, height) — gives soft rounded corners instead of 0.+ const expectedRadius = Math.min(+ 24,+ Math.max(8, Math.round(Math.min(webcamWidth, webcamHeight) * 0.06)),+ );+ expect(layout!.webcamRect!.borderRadius).toBe(expectedRadius);+ // Screen fills the padded band above the gap, centered horizontally+ // in the canvas. (cover mode.)+ expect(layout!.screenRect.x).toBe(contentX);+ expect(layout!.screenRect.y).toBe(contentY);+ expect(layout!.screenRect.width).toBe(1536);+ expect(layout!.screenRect.height).toBe(screenHeight);expect(layout!.screenCover).toBe(true);});diff --git a/src/lib/compositeLayout.ts b/src/lib/compositeLayout.tsindex 04c52c8b8..4a99da975 100644--- a/src/lib/compositeLayout.ts+++ b/src/lib/compositeLayout.ts@@ -125,7 +125,8 @@ interface OverlayTransform {interface StackTransform {type: "stack";- gap: number;+ gapFraction: number;+ minGap: number;}interface SplitTransform {@@ -185,12 +186,13 @@ const WEBCAM_LAYOUT_PRESET_MAP: Record<WebcamLayoutPreset, WebcamLayoutPresetDeflabel: "Vertical Stack",transform: {type: "stack",- gap: 0,+ gapFraction: 0.02,+ minGap: 8,},borderRadius: {- max: 0,- min: 0,- fraction: 0,+ max: 24,+ min: 8,+ fraction: 0.06,},shadow: null,},@@ -302,27 +304,82 @@ export function computeCompositeLayout(params: {};}- // Webcam: full width at the bottom, keeping aspect ratio.+ // ponytail: padding insets the content vertically (like dual-frame+ // insets it horizontally). `maxContentSize` from `PreviewCanvas` is+ // already padded to `canvasSize × paddingFit`; we derive a content+ // area, vertically center the screen+gap+camera stack inside it, and+ // keep the wallpaper visible at the top and bottom of the canvas.+ const contentHeight = Math.min(+ canvasHeight,+ Math.max(1, Math.round(maxContentSize?.height ?? canvasHeight)),+ );+ const contentWidth = Math.min(+ canvasWidth,+ Math.max(1, Math.round(maxContentSize?.width ?? canvasWidth)),+ );+ const contentY = Math.max(0, Math.floor((canvasHeight - contentHeight) / 2));++ // ponytail: gap between screen and camera, scaled off the padded+ // content width so the proportional spacing stays consistent.+ const gap = Math.max(+ preset.transform.minGap,+ Math.round(contentWidth * preset.transform.gapFraction),+ );++ // Webcam: full content width at the bottom, capped at 40% of the+ // padded content area so the screen always has room (otherwise a+ // 16:9 webcam in a 16:9 canvas collapses the screen to 0px). Aspect+ // is preserved when the request overflows the cap. The 40% follows the+ // same 1-of-N ratio the dual-frame preset uses for screenUnits/webcamUnits.const webcamAspect = webcamWidth / webcamHeight;- const resolvedWebcamWidth = canvasWidth;- const resolvedWebcamHeight = Math.round(canvasWidth / webcamAspect);+ const requestedWebcamWidth = contentWidth;+ const requestedWebcamHeight = Math.round(requestedWebcamWidth / webcamAspect);+ const stackCapHeight = Math.max(1, Math.round(contentHeight * 0.4));+ const resolvedWebcamHeight = Math.min(requestedWebcamHeight, stackCapHeight);+ const resolvedWebcamWidth = Math.round(resolvedWebcamHeight * webcamAspect);++ // Screen: fills remaining space above the camera + gap, content width.+ const screenRectHeight = Math.max(0, contentHeight - resolvedWebcamHeight - gap);- // Screen: fills remaining space at the top (cover mode, may crop sides).- const screenRectHeight = canvasHeight - resolvedWebcamHeight;+ // Camera border-radius follows the same preset fraction rule as+ // dual-frame so the strip gets gentle rounded corners.+ const webcamBorderRadius = Math.min(+ preset.borderRadius.max,+ Math.max(+ preset.borderRadius.min,+ Math.round(+ Math.min(resolvedWebcamWidth, resolvedWebcamHeight) * preset.borderRadius.fraction,+ ),+ ),+ );return {screenRect: {- x: 0,- y: 0,- width: canvasWidth,- height: Math.max(0, screenRectHeight),+ // ponytail: the content area (padded by `maxContentSize`) is+ // centered in the canvas — top/bottom from the canvas, and+ // left/right from the canvas when `maxContentSize` is narrower+ // than canvasWidth. This matches the dual-frame pattern where+ // padding = canvas-margin.+ x: Math.max(0, Math.floor((canvasWidth - contentWidth) / 2)),+ y: contentY,+ width: contentWidth,+ height: screenRectHeight,},webcamRect: {- x: 0,- y: Math.max(0, screenRectHeight),+ // ponytail: legacy hardcoded x:0 which left-aligned the camera+ // strip in the bottom-left when its aspect produced a narrower+ // width than the canvas. Center the strip horizontally within+ // the padded content area when there's room to spare, and+ // match the screen's horizontal inset.+ x:+ Math.max(0, Math.floor((canvasWidth - contentWidth) / 2)) ++ Math.floor((contentWidth - resolvedWebcamWidth) / 2),+ // ponytail: place camera BELOW the gap inside the padded area so+ // screen and camera don't touch.+ y: contentY + screenRectHeight + gap,width: resolvedWebcamWidth,height: resolvedWebcamHeight,- borderRadius: 0,+ borderRadius: webcamBorderRadius,},screenCover: true,};diff --git a/src/components/video-editor/videoPlayback/cursorRenderer.ts b/src/lib/cursor/pixiCursorRenderer.tssimilarity index 92%rename from src/components/video-editor/videoPlayback/cursorRenderer.tsrename to src/lib/cursor/pixiCursorRenderer.tsindex 4b2ba3a8a..d3bf6d8ab 100644--- a/src/components/video-editor/videoPlayback/cursorRenderer.ts+++ b/src/lib/cursor/pixiCursorRenderer.ts@@ -1,12 +1,12 @@import { Assets, BlurFilter, Container, Graphics, Sprite, Texture } from "pixi.js";import { MotionBlurFilter } from "pixi-filters/motion-blur";-import { type CropRegion, type CursorTelemetryPoint, DEFAULT_CROP_REGION } from "../types";+import type { CursorTelemetryPoint } from "@/components/video-editor/types";import {createSpringState,getCursorSpringConfig,resetSpringState,stepSpringValue,-} from "./motionSmoothing";+} from "@/components/video-editor/videoPlayback/motionSmoothing";import { UPLOADED_CURSOR_SAMPLE_SIZE, uploadedCursorAssets } from "./uploadedCursorAssets";type CursorAssetKey = NonNullable<CursorTelemetryPoint["cursorType"]>;@@ -389,40 +389,6 @@ function getCursorViewportScale(viewport: CursorViewportRect) {return Math.max(MIN_CURSOR_VIEWPORT_SCALE, viewport.width / REFERENCE_WIDTH);}-/**- * Maps a cursor position normalized to the full (uncropped) video into pixel- * coordinates inside the cropped viewport. Cursor telemetry is always stored- * relative to the full frame, so after a crop the normalized position must be- * re-normalized against the crop rect before it is projected onto the viewport- * (which already represents just the cropped area). Returns `null` when the- * position falls outside the visible crop, so callers can hide the cursor.- *- * Mirrors getCroppedCursorPosition / projectNativeCursorToLocal in the native- * cursor path (src/lib/cursor/nativeCursor.ts).- */-export function mapCursorToCroppedViewport(- normX: number,- normY: number,- viewport: CursorViewportRect,- cropRegion: CropRegion,-): { px: number; py: number } | null {- if (cropRegion.width <= 0 || cropRegion.height <= 0) {- return null;- }-- const croppedX = (normX - cropRegion.x) / cropRegion.width;- const croppedY = (normY - cropRegion.y) / cropRegion.height;-- if (croppedX < 0 || croppedX > 1 || croppedY < 0 || croppedY > 1) {- return null;- }-- return {- px: viewport.x + croppedX * viewport.width,- py: viewport.y + croppedY * viewport.height,- };-}-function getCursorVisualState(samples: CursorTelemetryPoint[], timeMs: number) {const latestClick = findLatestInteractionSample(samples, timeMs);const interactionType = latestClick?.interactionType;@@ -617,7 +583,6 @@ export class PixiCursorOverlay {viewport: CursorViewportRect,visible: boolean,freeze = false,- cropRegion?: CropRegion,): void {if (!visible || samples.length === 0 || viewport.width <= 0 || viewport.height <= 0) {this.container.visible = false;@@ -627,8 +592,6 @@ export class PixiCursorOverlay {return;}- const crop = cropRegion ?? DEFAULT_CROP_REGION;-const target = interpolateCursorPosition(samples, timeMs);if (!target) {this.container.visible = false;@@ -648,21 +611,10 @@ export class PixiCursorOverlay {} else {this.state.update(target.cx, target.cy, timeMs);}- // Telemetry positions are normalized to the full (uncropped) video. Remap them- // into the cropped viewport so the cursor stays aligned after a crop, and hide- // the cursor when it moves outside the visible crop (matching the native path).- const mapped = mapCursorToCroppedViewport(this.state.x, this.state.y, viewport, crop);- if (!mapped) {- this.container.visible = false;- this.lastRenderedPoint = null;- this.lastRenderedTimeMs = null;- this.cursorMotionBlurFilter.velocity = { x: 0, y: 0 };- return;- }-this.container.visible = true;- const { px, py } = mapped;+ const px = viewport.x + this.state.x * viewport.width;+ const py = viewport.y + this.state.y * viewport.height;const h = this.config.dotRadius * getCursorViewportScale(viewport);const { cursorType, clickBounceProgress, clickProgress } = getCursorVisualState(samples,diff --git a/src/components/video-editor/videoPlayback/uploadedCursorAssets.ts b/src/lib/cursor/uploadedCursorAssets.tssimilarity index 69%rename from src/components/video-editor/videoPlayback/uploadedCursorAssets.tsrename to src/lib/cursor/uploadedCursorAssets.tsindex 4a0cd29bc..eb529c31b 100644--- a/src/components/video-editor/videoPlayback/uploadedCursorAssets.ts+++ b/src/lib/cursor/uploadedCursorAssets.ts@@ -1,12 +1,12 @@-import crosshairUrl from "../../../assets/cursors/Cursor=Cross.svg";-import arrowUrl from "../../../assets/cursors/Cursor=Default.svg";-import closedHandUrl from "../../../assets/cursors/Cursor=Hand-(Grabbing).svg";-import openHandUrl from "../../../assets/cursors/Cursor=Hand-(Open).svg";-import pointerUrl from "../../../assets/cursors/Cursor=Hand-(Pointing).svg";-import resizeNsUrl from "../../../assets/cursors/Cursor=Resize-North-South.svg";-import resizeEwUrl from "../../../assets/cursors/Cursor=Resize-West-East.svg";-import textUrl from "../../../assets/cursors/Cursor=Text-Cursor.svg";-import type { CursorTelemetryPoint } from "../types";+import crosshairUrl from "@/assets/cursors/Cursor=Cross.svg";+import arrowUrl from "@/assets/cursors/Cursor=Default.svg";+import closedHandUrl from "@/assets/cursors/Cursor=Hand-(Grabbing).svg";+import openHandUrl from "@/assets/cursors/Cursor=Hand-(Open).svg";+import pointerUrl from "@/assets/cursors/Cursor=Hand-(Pointing).svg";+import resizeNsUrl from "@/assets/cursors/Cursor=Resize-North-South.svg";+import resizeEwUrl from "@/assets/cursors/Cursor=Resize-West-East.svg";+import textUrl from "@/assets/cursors/Cursor=Text-Cursor.svg";+import type { CursorTelemetryPoint } from "@/components/video-editor/types";type CursorAssetKey = NonNullable<CursorTelemetryPoint["cursorType"]>;diff --git a/src/main.tsx b/src/main.tsxindex 28d128507..99b6efdb9 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -2,7 +2,11 @@ import React from "react";import ReactDOM from "react-dom/client";import App from "./App.tsx";import { I18nProvider } from "./contexts/I18nContext";+<<<<<<< HEADimport { clearStaleSourceCache } from "./lib/exporter/localSourceFile";+=======+import "./hooks/rendererConsoleForwarder";+>>>>>>> a46ac8c (feat(ai-edition): make the Axcut editor the only editor + fix 0-byte recording + wire cursor panel + dead-code purge)import "./index.css";const windowType = new URLSearchParams(window.location.search).get("windowType") || "";diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsnew file mode 100644index 000000000..646cdce93--- /dev/null+++ b/src/native/browserShim.ts@@ -0,0 +1,186 @@+// Browser-mode shim: when running in a plain browser (no Electron shell), provide+// stubs for window.electronAPI + nativeBridgeClient so the renderer renders.+// The dev server at http://localhost:5173 can be opened in Chrome/Firefox for+// rapid iteration without the Electron window overhead.++import { nativeBridgeClient as realClient } from "./client";++function detectBrowserMode(): boolean {+ if (typeof window === "undefined") return false;+ if (window.electronAPI) return false; // Electron present, no shim needed+ const params = new URLSearchParams(window.location.search);+ return params.has("browser") || params.get("windowType") === "editor";+}++function isBrowserMode(): boolean {+ return detectBrowserMode();+}++function createShimElectronAPI() {+ return {+ assetBaseUrl: "",+ openVideoFilePicker: () => Promise.resolve({ success: false, canceled: true }),+ openProjectFile: () => Promise.resolve({ success: false, canceled: true }),+ pickExportSavePath: () => Promise.resolve({ success: false, canceled: true }),+ writeExportToPath: () => Promise.resolve({ success: false }),+ getCurrentRecordingSession: () => Promise.resolve({ success: false, session: null }),+ switchToHud: () => Promise.resolve({ success: true }),+ switchToEditor: () => Promise.resolve({ success: true }),+ startNewRecording: () => Promise.resolve({ success: true }),+ openSourceSelector: () => Promise.resolve({ success: true }),+ invokeNativeBridge: (req: { domain: string; action: string; payload?: unknown }) => {+ console.info("[browser-shim] invokeNativeBridge", req.domain, req.action, req.payload);+ return Promise.resolve({+ ok: true,+ data: null,+ meta: { version: 1, requestId: "shim", timestampMs: Date.now() },+ });+ },+ };+}++function createShimBridgeClient() {+ const storageKey = "browser-shim-document";+ const loadFromStorage = (): unknown | null => {+ try {+ const raw = localStorage.getItem(storageKey);+ return raw ? JSON.parse(raw) : null;+ } catch {+ return null;+ }+ };+ const saveToStorage = (doc: unknown) => {+ try {+ localStorage.setItem(storageKey, JSON.stringify(doc));+ } catch {+ // ponytail: localStorage may be full or unavailable; silently skip+ }+ };+ const list: Array<{ id: string; title: string; updatedAt: string; assetCount: number }> = (() => {+ try {+ const raw = localStorage.getItem("browser-shim-projects");+ return raw ? JSON.parse(raw) : [];+ } catch {+ return [];+ }+ })();+ const saveList = () => {+ try {+ localStorage.setItem("browser-shim-projects", JSON.stringify(list));+ } catch {+ // ponytail: same as saveToStorage+ }+ };+ let currentDoc: unknown = loadFromStorage();++ return {+ aiEdition: {+ listProjects: () => Promise.resolve(list),+ get: () => Promise.resolve({ success: true, document: currentDoc }),+ create: (title?: string) => {+ const doc = {+ schemaVersion: 3,+ project: {+ id: `proj_${Math.random().toString(36).slice(2, 10)}`,+ title: title || "Untitled Project",+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ },+ assets: [],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [],+ gaps: [],+ skipRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ annotations: [],+ zoomRanges: [],+ legacyEditor: null,+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },+ preview: { strategy: "seek", revision: 0 },+ export: { preset: "final-balanced", lastJobId: null },+ history: { revisions: [] },+ };+ list.unshift({+ id: doc.project.id,+ title: doc.project.title,+ updatedAt: doc.project.updatedAt,+ assetCount: 0,+ });+ saveList();+ return Promise.resolve({ success: true, document: doc });+ },+ save: (doc: unknown) => {+ currentDoc = doc;+ saveToStorage(doc);+ return Promise.resolve({ success: true, document: doc });+ },+ delete: () => Promise.resolve({ success: true }),+ addAsset: () =>+ Promise.resolve({ success: true, assetId: "asset_shim", document: currentDoc }),+ removeAsset: () => Promise.resolve({ success: true, assetId: "", document: currentDoc }),+ llmGetSnapshot: () =>+ Promise.resolve({+ config: null,+ connectedProviders: [],+ availableProviders: [+ { id: "anthropic", label: "Claude", authKind: "api-key" },+ { id: "openai", label: "OpenAI", authKind: "api-key" },+ ],+ }),+ llmSetConfig: () => Promise.resolve({ success: true }),+ llmSetApiKey: () => Promise.resolve({ success: true }),+ llmRemoveApiKey: () => Promise.resolve({ success: true }),+ chatRun: () =>+ Promise.resolve({+ success: true,+ assistantMessage: {+ id: `msg_${Date.now()}`,+ role: "assistant",+ content:+ "[browser-shim] AI features need real LLM deps. Configure a provider in Settings, install the LangChain packages, then chat will work for real.",+ createdAt: new Date().toISOString(),+ },+ }),+ chatHistory: () => Promise.resolve([]),+ chatClear: () => Promise.resolve({ success: true }),+ },+ project: {+ getCurrentContext: () =>+ Promise.resolve({ currentProjectPath: null, currentVideoPath: null }),+ loadProjectFile: () => Promise.resolve({ success: false, canceled: true }),+ },+ };+}++export function installBrowserShims(): void {+ if (typeof window === "undefined") return;+ if (!isBrowserMode()) return;+ if (!(window as unknown as { electronAPI?: unknown }).electronAPI) {+ (window as unknown as { electronAPI: unknown }).electronAPI = createShimElectronAPI();+ }+ // ponytail: replace the nativeBridgeClient on the window object. Components+ // import it from "@/native/client" at module load, so we patch the exported+ // object's methods to return shim responses. This keeps the import unchanged.+ const shim = createShimBridgeClient();+ const realKeys = Object.keys(realClient) as Array<keyof typeof realClient>;+ for (const domain of realKeys) {+ const realDomain = realClient[domain];+ const shimDomain = (shim as unknown as Record<string, unknown>)[domain as string];+ if (typeof realDomain === "object" && realDomain && shimDomain) {+ for (const action of Object.keys(realDomain) as Array<keyof typeof realDomain>) {+ const shimAction = (shimDomain as Record<string, unknown>)[action as string];+ if (typeof shimAction === "function") {+ (realDomain as Record<string, unknown>)[action as string] = shimAction;+ }+ }+ }+ }+ console.info("[openscreen] browser-mode shims active (no Electron)");+}++export { isBrowserMode };diff --git a/src/native/client.ts b/src/native/client.tsindex 8d15c324d..9f777b592 100644--- a/src/native/client.ts+++ b/src/native/client.ts@@ -1,4 +1,11 @@import {+ type AiEditionAssetResult,+ type AiEditionChatMessage,+ type AiEditionChatResult,+ type AiEditionDocumentResult,+ type AiEditionLlmConfig,+ type AiEditionLlmSnapshot,+ type AiEditionProjectSummary,type CursorCapabilities,type CursorRecordingData,type CursorTelemetryPoint,@@ -137,4 +144,88 @@ export const nativeBridgeClient = {payload: videoPath ? { videoPath } : {},}),},+ aiEdition: {+ listProjects: () =>+ requireNativeBridgeData<AiEditionProjectSummary[]>({+ domain: "aiEdition",+ action: "document.listProjects",+ }),+ get: (projectId: string) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "document.get",+ payload: { projectId },+ }),+ create: (title?: string) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "document.create",+ payload: { title },+ }),+ save: (document: unknown) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "document.save",+ payload: { document },+ }),+ delete: (projectId: string) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "document.delete",+ payload: { projectId },+ }),+ addAsset: (projectId: string, path: string, label?: string) =>+ requireNativeBridgeData<AiEditionAssetResult>({+ domain: "aiEdition",+ action: "document.addAsset",+ payload: { projectId, path, label },+ }),+ removeAsset: (projectId: string, assetId: string) =>+ requireNativeBridgeData<AiEditionAssetResult>({+ domain: "aiEdition",+ action: "document.removeAsset",+ payload: { projectId, assetId },+ }),+ llmGetSnapshot: () =>+ requireNativeBridgeData<AiEditionLlmSnapshot>({+ domain: "aiEdition",+ action: "llm.getSnapshot",+ }),+ llmSetConfig: (config: AiEditionLlmConfig) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "llm.setConfig",+ payload: { config },+ }),+ llmSetApiKey: (providerId: string, apiKey: string) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "llm.setApiKey",+ payload: { providerId, apiKey },+ }),+ llmRemoveApiKey: (providerId: string) =>+ requireNativeBridgeData<AiEditionDocumentResult>({+ domain: "aiEdition",+ action: "llm.removeApiKey",+ payload: { providerId },+ }),+ chatRun: (projectId: string, message: string) =>+ requireNativeBridgeData<AiEditionChatResult>({+ domain: "aiEdition",+ action: "chat.run",+ payload: { projectId, message },+ }),+ chatHistory: (projectId: string) =>+ requireNativeBridgeData<AiEditionChatMessage[]>({+ domain: "aiEdition",+ action: "chat.history",+ payload: { projectId },+ }),+ chatClear: (projectId: string) =>+ requireNativeBridgeData<{ success: boolean }>({+ domain: "aiEdition",+ action: "chat.clear",+ payload: { projectId },+ }),+ },};diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex 60075d397..eba32e5e0 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -90,6 +90,55 @@ export interface ProjectFileResult {error?: string;}+// ---- AI Edition domain (Phase 1+) -----------------------------------------+// v3 AxcutDocument projects live under userData/projects/<id>.axcut. Project+// ids are uuid-prefixed strings (e.g. "proj_<uuid>"). Asset ids likewise.++export interface AiEditionProjectSummary {+ id: string;+ title: string;+ updatedAt: string;+ assetCount: number;+}++export interface AiEditionAssetResult {+ assetId: string;+ document: unknown;+}++export interface AiEditionDocumentResult {+ success: boolean;+ document?: unknown;+ error?: string;+}++export interface AiEditionLlmConfig {+ provider: string;+ model: string;+ baseUrl?: string;+ reasoningEffort?: string;+}++export interface AiEditionLlmSnapshot {+ config: AiEditionLlmConfig | null;+ connectedProviders: string[];+ availableProviders: Array<{ id: string; label: string; authKind: string }>;+}++export interface AiEditionChatMessage {+ id: string;+ role: "user" | "assistant";+ content: string;+ createdAt: string;+}++export interface AiEditionChatResult {+ success: boolean;+ assistantMessage?: AiEditionChatMessage;+ document?: unknown;+ error?: string;+}+export type NativeBridgeErrorCode =| "INVALID_REQUEST"| "UNSUPPORTED_ACTION"@@ -225,6 +274,90 @@ export type NativeBridgeRequest =videoPath?: string;};requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.listProjects";+ payload?: EmptyPayload;+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.get";+ payload: { projectId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.create";+ payload: { title?: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.save";+ payload: { document: unknown };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.delete";+ payload: { projectId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.addAsset";+ payload: { projectId: string; path: string; label?: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "document.removeAsset";+ payload: { projectId: string; assetId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.getSnapshot";+ payload?: EmptyPayload;+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.setConfig";+ payload: { config: AiEditionLlmConfig };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.setApiKey";+ payload: { providerId: string; apiKey: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.removeApiKey";+ payload: { providerId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.run";+ payload: { projectId: string; message: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.history";+ payload: { projectId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.clear";+ payload: { projectId: string };+ requestId?: string;};export type NativeBridgeEventName =diff --git a/src/styles/design-tokens.css b/src/styles/design-tokens.cssnew file mode 100644index 000000000..97a90e832--- /dev/null+++ b/src/styles/design-tokens.css@@ -0,0 +1,204 @@+/* OpenScreen design system — light + dark.+ * Single source of truth for tokens used by the new editor shell.+ * Mint #10b981 is the sole chromatic accent. Red is reserved for+ * REC / cut / skip / trim / transcript-highlight only. */++:root {+ /* canvas */+ --bg: #f8fafc;+ --bg-grad: radial-gradient(ellipse 1200px 800px at 50% -200px, #ffffff 0%, #f1f5f9 80%);+ --surface: #ffffff;+ --surface-1: #f1f5f9;+ --surface-2: #e2e8f0;+ --surface-3: #cbd5e1;+ --surface-warm: #f1f5f9;++ /* lines */+ --border: #e2e8f0;+ --border-soft: #f1f5f9;+ --border-hi: #cbd5e1;+ --border-dark: #0f172a;++ /* foreground */+ --fg: #0f172a;+ --fg-2: #334155;+ --fg-emphasis: #020617;+ --muted: #64748b;+ --muted-soft: #94a3b8;+ --meta: #94a3b8;+ --dim: #cbd5e1;++ /* mint brand */+ --brand: #10b981;+ --brand-lo: #059669;+ --brand-glow: rgba(16, 185, 129, 0.35);+ --brand-soft: rgba(16, 185, 129, 0.10);+ --accent: #10b981;+ --accent-on: #04221a;+ --accent-soft: rgba(16, 185, 129, 0.10);+ --accent-wash: rgba(16, 185, 129, 0.06);++ /* semantic */+ --danger: #ef4444;+ --danger-lo: #dc2626;+ --danger-soft: rgba(239, 68, 68, 0.10);+ --danger-wash: rgba(239, 68, 68, 0.06);+ --danger-hatch: rgba(239, 68, 68, 0.32);+ --warn: #f59e0b;+ --warn-soft: rgba(245, 158, 11, 0.12);++ /* timeline pills */+ --annotation: #eab308;+ --annotation-soft: rgba(234, 179, 8, 0.14);+ --speed: #f97316;+ --speed-soft: rgba(249, 115, 22, 0.14);++ --success: #10b981;+ --success-soft: rgba(16, 185, 129, 0.10);++ /* macOS traffic lights */+ --light-red: #ff5f57;+ --light-yellow: #febc2e;+ --light-green: #28c840;++ /* preview scene placeholders */+ --scene-sky-hi: #eaebed;+ --scene-sky-mid: #bcc0c6;+ --scene-foliage: #6b7280;+ --scene-foliage-d: #16171d;+ --scene-overlay: rgba(22, 23, 29, 0.18);++ --pip-bg-1: #16171d;+ --pip-bg-2: #16171d;+ --pip-bg-3: #16171d;+ --pip-skin-hi: #bcc0c6;+ --pip-skin-lo: #6b7280;+ --pip-hair: #16171d;+ --pip-shadow: rgba(22, 23, 29, 0.30);++ --overlay-dark: rgba(22, 23, 29, 0.45);+ --overlay-light: rgba(255, 255, 255, 0.85);+ --overlay-text: rgba(255, 255, 255, 0.60);+ --overlay-text-2: rgba(255, 255, 255, 0.55);+ --overlay-border: rgba(22, 23, 29, 0.06);++ /* typography */+ --font-display: system-ui, -apple-system, "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --font-body: system-ui, -apple-system, "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --font-mono: ui-monospace, "SF Mono", Menlo, Monaco, Consolas, monospace;++ /* size */+ --fs-app: 13px;+ --fs-app-sm: 12px;+ --fs-app-lg: 14px;+ --fs-title: 16px;+ --fs-section: 11px;+ --fs-display: 24px;++ /* spacing */+ --sp-1: 4px;+ --sp-2: 8px;+ --sp-3: 12px;+ --sp-4: 16px;+ --sp-5: 20px;+ --sp-6: 24px;++ /* radius */+ --r-xs: 4px;+ --r-sm: 6px;+ --r-md: 8px;+ --r-lg: 12px;+ --r-pill: 9999px;++ /* layout */+ --titlebar-h: 34px;+ --rail-w: 48px;+ --panel-w-left: 320px;+ --panel-w-right: 320px;+ --handle-w: 6px;+ --handle-h: 6px;+ --bottom-h: 224px;++ /* elevation */+ --elev-card: 0 1px 2px rgba(15, 23, 42, 0.03), 0 2px 8px -2px rgba(15, 23, 42, 0.05);+ --elev-card-soft: 0 1px 2px rgba(15, 23, 42, 0.03);+ --elev-pop: 0 8px 24px -8px rgba(15, 23, 42, 0.10), 0 2px 4px rgba(15, 23, 42, 0.04);++ --focus-ring: 0 0 0 3px rgba(16, 185, 129, 0.18);++ --motion-fast: 120ms;+ --motion-base: 180ms;+ --ease: cubic-bezier(0.2, 0, 0, 1);+}++:root[data-theme="dark"] {+ --bg: #0a0d12;+ --bg-grad: radial-gradient(ellipse at 50% 0%, #13171f 0%, #0a0d12 60%);+ --surface: #14181f;+ --surface-1: #14181f;+ --surface-2: #1c2029;+ --surface-3: #252a35;+ --surface-warm: #1c2029;++ --border: #252a35;+ --border-soft: #1c2029;+ --border-hi: #3a4150;+ --border-dark: #0a0d12;++ --fg: #e6e9ef;+ --fg-2: #f3f5f8;+ --muted: #8b95a3;+ --meta: #5b6470;+ --dim: #1c2029;++ --brand: #10b981;+ --brand-lo: #34d399;+ --brand-glow: rgba(16, 185, 129, 0.40);+ --brand-soft: rgba(16, 185, 129, 0.14);+ --accent: #10b981;+ --accent-on: #0a0d12;+ --accent-soft: rgba(16, 185, 129, 0.14);+ --accent-wash: rgba(16, 185, 129, 0.06);++ --danger: #f87171;+ --danger-lo: #ef4444;+ --danger-soft: rgba(248, 113, 113, 0.14);+ --danger-wash: rgba(248, 113, 113, 0.08);+ --danger-hatch: rgba(248, 113, 113, 0.40);++ --warn: #fbbf24;+ --warn-soft: rgba(251, 191, 36, 0.14);++ --annotation: #fbbf24;+ --annotation-soft: rgba(251, 191, 36, 0.16);+ --speed: #fb923c;+ --speed-soft: rgba(251, 146, 60, 0.16);++ --success: #10b981;+ --success-soft: rgba(16, 185, 129, 0.14);++ --scene-sky-hi: #2e3440;+ --scene-sky-mid: #252a35;+ --scene-foliage: #14181f;+ --scene-foliage-d: #0a0d12;+ --scene-overlay: rgba(0, 0, 0, 0.30);++ --pip-bg-1: #14181f;+ --pip-bg-2: #0a0d12;+ --pip-bg-3: #252a35;+ --pip-skin-hi: #bcc0c6;+ --pip-skin-lo: #8b95a3;+ --pip-hair: #0a0d12;+ --pip-shadow: rgba(0, 0, 0, 0.50);++ --overlay-dark: rgba(0, 0, 0, 0.55);+ --overlay-light: rgba(20, 24, 31, 0.85);+ --overlay-text: rgba(230, 233, 239, 0.80);+ --overlay-text-2: rgba(230, 233, 239, 0.70);+ --overlay-border: rgba(255, 255, 255, 0.08);++ --elev-card: 0 1px 2px rgba(0, 0, 0, 0.40), 0 4px 12px -4px rgba(0, 0, 0, 0.50);+ --elev-card-soft: 0 1px 2px rgba(0, 0, 0, 0.30);+ --elev-pop: 0 8px 24px -8px rgba(0, 0, 0, 0.60);+ --focus-ring: 0 0 0 3px rgba(16, 185, 129, 0.30);+}diff --git a/vite.config.ts b/vite.config.tsindex 213e44711..5011add3f 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -11,6 +11,10 @@ export default defineConfig({main: {entry: "electron/main.ts",onstart({ startup }) {+ if (process.env.NO_ELECTRON) {+ console.log("NO_ELECTRON is set, skipping Electron startup.");+ return;+ }const env = { ...process.env };delete env.ELECTRON_RUN_AS_NODE;return startup(["."], { env });