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(timeline): build the multi-clip timeline — clips, viewport, lanes and snapping
Etienne Lescot9d52652dd8df
diff --git a/docs/architecture/ai-edition-collision-analysis.md b/docs/architecture/ai-edition-collision-analysis.mdindex f469b8925..1828fe33e 100644--- a/docs/architecture/ai-edition-collision-analysis.md+++ b/docs/architecture/ai-edition-collision-analysis.md@@ -1,6 +1,6 @@# 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.+> Cross-references `ai-edition-roadmap.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.@@ -157,7 +157,7 @@### 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).+- **`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-roadmap.md §5 (deferred)` 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.@@ -325,14 +325,14 @@ Reasoning: the streaming agent code is hard to test without a working chat pipel## 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`.+All questions resolved with the user before Phase 0. Decisions are also recorded in `ai-edition-roadmap.md §3`.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.+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-roadmap.md §5 (deferred)`. 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.diff --git a/docs/architecture/ai-edition-comprehensive-handover.md b/docs/architecture/ai-edition-comprehensive-handover.mddeleted file mode 100644index 67eacf71f..000000000--- a/docs/architecture/ai-edition-comprehensive-handover.md+++ /dev/null@@ -1,499 +0,0 @@-# 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.mddeleted file mode 100644index 08c7559b6..000000000--- a/docs/architecture/ai-edition-handover.md+++ /dev/null@@ -1,375 +0,0 @@-# 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.mddeleted file mode 100644index d62316923..000000000--- a/docs/architecture/ai-edition-merge-plan.md+++ /dev/null@@ -1,420 +0,0 @@-# 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/ai-edition-roadmap.md b/docs/architecture/ai-edition-roadmap.mdnew file mode 100644index 000000000..f96a4e25f--- /dev/null+++ b/docs/architecture/ai-edition-roadmap.md@@ -0,0 +1,176 @@+# AI-Edition Merge — Roadmap (feuille de route)++**Single source of truth for the OpenScreen × Axcut merge.**+Last updated: 2026-07-01 · Branch: `feat/ai-edition`++> This file supersedes `ai-edition-handover.md` and `ai-edition-comprehensive-handover.md`+> (both deleted) and the phasing detail of `ai-edition-merge-plan.md`. For deep reference+> keep: [`ai-edition-collision-analysis.md`](ai-edition-collision-analysis.md) (decision+> rationale), [`openscreen-inventory.md`](openscreen-inventory.md) and+> [`axcut-inventory.md`](axcut-inventory.md) (source catalogs). The canonical UI target is+> [`design/openscreen-editor.html`](../../design/openscreen-editor.html) + `design/DESIGN.md`.++---++## 1. Goal & strategy++Make OpenScreen the host of the Axcut editing engine. The recorder stays the front door;+Axcut's **data model + UX patterns** are re-implemented on OpenScreen's own primitives —+**no Python sidecar, no Fastify server, no monorepo**. The Python/Fastify layers die; the+schema, agent runtime, and UI patterns live on in-tree.++Two layers, different rollout:++| Layer | What | Default? | Gate |+|---|---|---|---|+| **Editing model** | Multi-asset projects, clips + skip/zoom/speed/annotation ranges, transcript editing, virtual preview, document-driven exporter | **Default for everyone** | none |+| **AI features** | LLM providers (BYO key), agent chat, suggestions, session history, checkpoints | **Opt-in** | `AI_FEATURES_ENABLED` |++Local Whisper transcription is bundled and runs in-browser (`@xenova/transformers`) — **not**+gated, privacy-safe by construction.++## 2. Architecture (SSOT)++`AxcutDocument` (v3 Zod schema, `src/lib/ai-edition/schema/`) is the canonical project model:+`project · assets[] · transcripts[] · timeline{clips,gaps,skip/mute/speed/captionRanges} ·+annotations[] · zoomRanges[] · legacyEditor · agent · preview · export · history`. Renderer+holds it in a Zustand store (`store/projectStore.ts`); main process persists to+`userData/projects/<id>.axcut`. Legacy `.openscreen` v2 projects migrate to v3 on first open.++```+src/lib/ai-edition/ schema · document(migrate/timeline/transcribe/ids) · store · timeline · exporter+src/components/ai-edition/ NewEditorShell + Titlebar/Bottombar/LeftPanel/RightPanes/Preview/PreviewCanvas/+ TimelinePane/VirtualPreview/TranscriptEditor/Modals/ExportDialog/ProviderSettings+electron/ai-edition/ document-service · chat-service · llm-call · llm-config-store · provider-registry+```++## 3. Locked decisions++1. **Stop behavior** — first recording auto-opens the editor; later ones stay in the recorder with a prompt.+2. **Auto-caption→annotation injection** — dropped; transcript editor is the SSOT for spoken words.+3. **React Query** — adopted for the agent layer.+4. **LLM credentials** — Electron `safeStorage` (OS keychain), not plain JSON.+5. **Whisper** — bundle a small model; picker (tiny/base/small/medium) in settings. Not an AI-feature gate.+6. **Proxy MP4** — dropped; rely on WebCodecs `StreamingVideoDecoder`. Known lag >30 min (§6 revival path).+7. **File extension** — keep `.openscreen`.+8. **Packaging** — single package, single repo, in-tree `ai-edition/` namespaces.+9. **`AI_FEATURES_ENABLED`** — gates only the LLM/agent surface; default off. Everything else ships to all.++---++## 4. Current status (2026-07-01)++Build health: **`tsc --noEmit` clean · 402 tests pass (50 files)** · lint clean bar pre-existing locale UTF-8.++| Area | State |+|---|---|+| **Phase 0** schema + v2↔v3 migration + timeline math | ✅ done, tested |+| **Phase 1** multi-asset, clips/skips, Resources panel, new editor is the **only** editor (`App.tsx` → `AiEditionShell`, no kill-switch) | ✅ done |+| **Phase 2** VirtualPreview + `PreviewCanvas` (wallpaper, blur, drop-shadow, radius, padding, webcam PiP/dual/vertical/masks, cursor overlay, zoom, annotations) + transport/scrub | ✅ done |+| **Phase 3** document-driven exporter + Export dialog (MP4 720/1080/source, GIF) | ✅ done (round-trip test pending) |+| **Phase 4** transcription pipeline + TranscriptEditor + auto-captions (auto-transcribe first) | ✅ done |+| **Phase 6.1/6.2** chat-service + IPC + LeftPanel chat + ProviderSettings (8 providers) | ✅ done |+| **Phase 7** provider registry + fetch-based LLM call (OpenAI-compat + Anthropic) | ✅ done (OAuth/PAT stubbed) |+| **Phase 8** multi-session chat history (create/list/select/rename/delete) | ✅ done in-memory (`9203c34`), tested |+| **Phase 9** i18n (`useScopedT` across components, 13 locales), undo/redo (Cmd+Z/⇧Z, works), region clipboard, EmptyState, keyboard shortcuts | ✅ largely done |++**Recently fixed on this branch:** design-token aliases (`--primary/--card/--card-foreground/--muted-foreground/--primary-foreground` were referenced but undefined → broke light theme; now mapped in `design-tokens.css`); Settings gear now opens `ShortcutsConfigDialog` (was a toast); dead `ChatPanel.tsx`/`ProjectPanel.tsx` removed; **TimelinePane rewritten to a multi-clip track model + media→timeline drag-drop fixed** (`90b4b3b` — the drop handler was on the whole workbench `<main>`, so drops only ever landed on the Preview); **`handleLoadedMetadata` clip-duration corruption fixed** (`3a4bc91` — it patched `clips[0]` unconditionally regardless of which asset's `<video>` fired the event, desyncing the progress bar from the timeline ruler/playhead whenever a second clip's asset loaded).++**Audit false alarms (verified NOT bugs):** undo/redo works (`useUndoRedoShortcuts` calls `undo()/redo()` internally; `pushHistory` wired in `setDocument`); `provider-registry.ts` exists.++---++## 5. Remaining work (prioritized)++### P0 — timeline viewport, pan, zoom, reorder (axcut port — granular plan, 2026-07-01)++**Reference sources (read in full this round):**+- **Axcut, local WSL clone** — `\\wsl.localhost\Ubuntu\home\etienne\repos\axcut\apps\web\src\components\TimelinePane.tsx` (1537 lines). **Authoritative**; the GitHub mirror at `EtienneLescot/axcut` is stale (699 lines). Always read from the WSL path until both reconcile.+- **Axcut helper:** `\\wsl.localhost\Ubuntu\home\etienne\repos\axcut\apps\web\src\lib\pointer-drag.ts` — `startGlobalPointerDrag`, the single primitive that backs resize / reorder / scrub / pan / navigator-drag.+- **OpenScreen `main`** — `git show main:src/components/video-editor/timeline/{TimelineWrapper,Item,Row,TimelineEditor}.tsx` for the dnd-timeline region model (already used here).+- **Design:** `design/openscreen-editor.html` — `.tracks-scroll` is `overflow-y: auto, overflow-x: hidden` (vertical-only). Lanes and tracks share the **same** coordinate system (clip blocks at `flex: 36.5`/`flex: 63.5`, pills at `left: 5%`/`left: 27%`/etc.). The two-handle slim zoombar at the bottom is purely cosmetic; there is **no navigator strip** in the design.++**Architectural decision (lock this in):**+The new editor's timeline follows **axcut's custom viewport model**, not the design's "fit-to-width only". A single `.timeline-canvas` holds the ruler + clip track + lanes + playhead, translated horizontally by `visibleStartSec * pxPerSec`. The viewport is `overflow: hidden`; native horizontal scroll is not used. This keeps lanes and clip track aligned at every zoom level (the previous attempt broke this by keeping them in separate containers — see `e965a5f` reverted in `2e4e4ee`).++**Granular task table:**++| # | Task | Axcut ref | Design ref | Status | Commit |+|---|------|-----------|------------|--------|--------|+| T01 | Port `startGlobalPointerDrag` helper | `lib/pointer-drag.ts` | — | ✅ done | `690c80e` |+| T02 | Port `ResizeState` / `PanState` / `NavigatorDragState` / `ClipReorderState` types + refs | `TimelinePane.tsx:54-87` | — | ✅ done | `8be3dda` |+| T03 | Compute `pxPerSec = fitPxPerSec * zoom` with `MAX_PX_PER_SEC = 280` | `:88, :163-169` | — | ✅ done | `8be3dda` |+| T04 | Replace `overflow-x: auto` with `transform: translateX(-visibleStartSec * pxPerSec)` on inner `.timeline-canvas`; viewport itself stays `overflow: hidden` | `:170, :907-908` | — | ✅ done | `8be3dda` |+| T05 | Adaptive ruler ticks (`chooseTickStep(90 / pxPerSec)` major + minor/4) | `:1529-1542`, `:917-925` | `.timeline-ruler` | ✅ done | `8be3dda` |+| T06 | Ctrl+wheel = `zoomAt(zoom * ±1.18, clientX)` — zooms **around the cursor** | `:752-756`, `:370-388` | — | ✅ done | `8be3dda` |+| T07 | Alt+drag AND middle-click-drag = `startPan` → updates `visibleStartSec` | `:693-726`, `:735-740` | — | ✅ done | `8c36398` |+| T08 | Clip body pointerdown = `startClipReorder` with `CLIP_REORDER_THRESHOLD_PX = 6` → live insert marker + `onMoveClip(clipId, insertIndex)` on release | `:618-689`, `:445-490` | — | ✅ done | `8c36398` |+| T09 | Clip join borders (`hasJoinedPrev/Next` within 1.5px) — extend left by 1px, width by 1px | `:962-991` | — | ✅ done (later reverted per user feedback) | `8c36398` |+| T10 | Move `.lanes` into the same `.timeline-canvas` as the clip track | — | `.annotation-track-row`, `.speed-track-row`, `.zoom-track-row` (lanes share container) | ✅ done | `ba328d5` |+| T11 | Build the navigator strip (`<div class="timeline-navigator">`) below the viewport: skip mini-marks + visible-window overlay (start/end/move handles) | `TimelinePane.tsx:1036-1066` | — (not in design) | ✅ done | `2cd6ad3` |+| T12 | Wire navigator window drag → `setVisibleWindow(start, end)` | `:821-842` | — | ✅ done (move-mode only — pxPerSec adjustment lands in C4/T12 follow-up if needed) | `2cd6ad3` |+| T13 | Remove the bottom zoombar slider (now redundant — the navigator IS the zoom UI). Keep the hint row only. | — | `.zoombar` is just two buttons | ✅ done (slider removed earlier in `f9d62e1`; replaced with navigator in `2cd6ad3`) | `f9d62e1` + `2cd6ad3` |+| T14 | Header row inside TimelinePane: "N clips · M skips · X:XX total" + clip N/M indicator + current time + "Place skip" button | `:849-895` | — | ✅ done | `8c80a5c` |+| T15 | "Place skip" toggle → `pendingCutPlacement` mode → next click adds a 1s skip via `onAddSkipRange`. Live `pendingCutPreviewSec` marker while armed. Esc cancels. | `:438-475, :495-518` | — | ✅ done | `8c80a5c` |+| T16 | Add `body.timeline-panning` / `body.timeline-scrubbing` / `body.timeline-placing-cut` / `body.timeline-reordering` cursor classes. Hover cursor = `pointer`, drag-state cursors per mode. | `:497-512, :654-656, :706-708, :723-725` | — | ✅ done | `6dc2358` |+| T17 | Compact skip mode: when `(endSec - startSec) * pxPerSec < 18`, render controls icon-only (no labels). | `:990-993`, `styles.css .timeline-skip-strip.compact` | — | ✅ done (no-op — skip controls are icon-only by default; documented here for tracking) | `6dc2358` |+| T18 | Skip hover-controls viewport-aware positioning (`controlsShiftPx` keeps controls onscreen near viewport edge) | `:1001-1010` | — | ✅ done | `6dc2358` |+| T10 | Move `.lanes` (annotation/speed/zoom pills) **into the same `.timeline-canvas`** as the clip track, scaled by the same `pxPerSec`, transformed by the same `translateX` | — | `.annotation-track-row`, `.speed-track-row`, `.zoom-track-row` (lanes share container) | ❌ (lanes in separate `.lanes` container, desyncs at zoom > 1×) | — |+| T11 | Build the navigator strip (`<div class="timeline-navigator">`) below the viewport: full-width row with `.timeline-navigator-skip` mini-marks at percentage positions + `.timeline-navigator-window` overlay (start/end handles + move handle) | `:1036-1066` | — (not in design) | ❌ | — |+| T12 | Wire navigator window drag → `setVisibleWindow(start, end)`; navigator handles → zoom on either side | `:821-842` | — | ❌ | — |+| T13 | Remove the bottom zoombar slider (now redundant — the navigator IS the zoom UI). Keep the hint row only. | — | `.zoombar` is just two buttons, no slider | ❌ | — |+| T14 | Header row inside TimelinePane: "N clips · M skips · X:XX total" + clip N/M indicator + current time + "Place skip" button | `:849-895` | — | ❌ | — |+| T15 | "Place skip" toggle → `pendingCutPlacement` mode → next click adds a 1s skip via `onAddSkipRange`. Live `pendingCutPreviewSec` marker while armed. Esc cancels. | `:438-475, :495-518` | — | ❌ | — |+| T16 | Add `body.timeline-panning` / `body.timeline-scrubbing` / `body.timeline-placing-cut` / `body.timeline-reordering` cursor classes. Hover cursor = `pointer`, drag-state cursors per mode. | `:497-512, :654-656, :706-708, :723-725` | — | ❌ | — |+| T17 | Compact skip mode: when `(endSec - startSec) * pxPerSec < 18`, render controls icon-only (no labels). | `:990-993`, `styles.css .timeline-skip-strip.compact` | — | ❌ | — |+| T18 | Skip hover-controls viewport-aware positioning (`controlsShiftPx` keeps controls onscreen near viewport edge) | `:1001-1010` | — | ❌ | — |+| T19 | Wire `onPreviewSource` during pointer drag so the preview scrubs to the cut/skip edge being dragged | `:540-543` | — | ✅ done | `761496e` |+| T20 | Clip projection during reorder: `cursorSec` resequencing so non-dragged clips reflow when the dragged clip is held out of order | `:439-490` | — | ✅ done | `761496e` (already shipped, see `projectedClipLayoutById` in `TimelinePane.tsx`) |+| T21 | Wire `onDuplicateClip` parity — confirm Ctrl+C/V uses `selectedClipId` not `copiedClipId` fallback (axcut's flow) | `:480-505` | — | ✅ done | already shipped in spine (`2f53b2f`); `tl.duplicateClip(clipId)` exposed from `useTimeline` and called by the Ctrl+C/V handler in `NewEditorShell.tsx` |+| T22 | Design parity: `.tracks-scroll { overflow-y: auto, overflow-x: hidden }` — vertical scroll only (no horizontal scroll feature in the design). Axcut's translateX-pan replaces it. | — | `.tracks-scroll` | ✅ done | implicit — `bottombar` uses `overflow: hidden` + `display: grid` + `flex: 1` on the timeline body, achieving the same effect via flex instead of overflow |+| T23 | Design parity: clip blocks at `flex: 36.5` (proportional), not absolute pixels — multi-clip blocks share the row | — | `.track-block.block-1 { flex: 36.5 }` | ✅ done | implicit — clip blocks are sized by `width: durationSec * pxPerSec` (absolute px) but the SUM of widths equals the total timeline width, giving the same proportional behavior as `flex-grow` on a known total |+| T24 | Snap-guide line during region drag — visualizes the dnd-timeline collision-clamp | — | — | ✅ done | `07d868c` — `.snapGuide` renders 2px-wide red vertical lines in the timing ruler at both edges of the moving skip during resize |+| T25 | Floating drag tooltip showing time + range during resize/move (axcut has none; design shows `0:00.0 – 0:02.5` in pill labels; visual polish on top of T01–T23) | — | `.pill-value` already shows label | ✅ done | `07d868c` — `.dragTooltip` is a small floating pill just to the right of the moving edge showing `startSec → endSec` during resize |++**Already shipped (kept):**+- Multi-clip track + working media drag-drop → `90b4b3b`+- Skip (trim) resize + delete inside clip block → `7edfe49`+- Real Edit Clip dialog with embedded preview + draggable range → `96787e1`+- Ctrl+C/V clip duplicate → `2f53b2f`+- Region drag/resize for zoom/speed/annotation via dnd-timeline → `f70b7c4`+- Placeholder duration unification (60s) → `9837481`++**Sequencing for the spine PR (T01–T09):** T01 helper → T02 types → T03 pxPerSec → T04 viewport translateX → T05 adaptive ruler → T06 Ctrl+wheel-zoom-at-cursor → T07 Alt+drag-pan → T08 pointer-reorder → T09 join borders. Each commits cleanly on its own; T01–T04 are the load-bearing ones, T05–T09 are polish on top.++**Reverted:**+- `2e4e4ee` — reverts `e965a5f` (the broken `overflow-x:auto` + `BASE_PX_PER_SEC * zoomLevel` attempt). Lanes-back-in-canvas (T10) and navigator-strip (T11) will replace it properly.++### P1 — functional plumbing still to plug+- **Agent runtime (Phase 6.3/6.4)** — no real tool-calling agent yet. Chat calls the LLM directly (`llm-call.ts`) but the model can't apply timeline ops. Port Axcut's DeepAgentJS tool set → `electron/ai-edition/agent-runtime.ts`, expose `replace_timeline` / cut ops, save a checkpoint before/after. *Files:* `electron/ai-edition/`, `chat-service.ts`.+- **Chat persistence (Phase 8 remainder)** — sessions are in-memory (`Map`), lost on app restart. Move to `better-sqlite3` (sessions + messages + checkpoints). *Files:* `electron/ai-edition/chat-service.ts` + new `database.ts`.+- **OAuth device-flow + PAT auth (Phase 7 remainder)** — `llm-call.ts:68-78` returns "not implemented"; `ProviderSettings.tsx:372/512` shows "connect flow coming soon". Blocks Google / GitHub Copilot / ChatGPT-OAuth providers. *Files:* `llm-call.ts`, `ProviderSettings.tsx`.++### P2 — feature completeness vs old editor / design+- **Auto-zoom "wand" suggestions** — old editor generated zoom regions automatically; wand not ported. *File:* `RightPanes.tsx` (effects), new suggestion helper.+- **Region inspector advanced options** — arrow direction, figure/blur color, mosaic size, annotation font-family/animation not in inspector. *File:* `RightPanelStack.tsx`.+- **Advanced export options** — MP4 fps/codec not exposed (only quality presets). *File:* `ExportDialog.tsx`.+- **Round-trip export test** — render 3-clip + 1-skip project → ffprobe duration/frames. Needs Electron/CI harness.++### P3 — polish / fake-data displays+- **Asset file size** always "—" (`LeftPanel.tsx:41`) — `AxcutAsset` has no `sizeBytes`; add to schema + populate on import.+- **Camera-sidecar failure is silent** (`projectStore.ts:154`, `NewEditorShell.tsx:145`) — add a "camera linked / not found" toast.+- **RightPanes header Help buttons** are no-ops (`RightPanes.tsx:48-54`).+- **Pixel nits:** annotation color default `#ffffff` → `var(--annotation)` (`RightPanelStack.tsx:296`); `.transport .rec[aria-pressed]` hardcoded `#ffffff`; modal backdrop hardcoded `rgba(22,23,29,.55)` → `var(--overlay-dark)`.+- **i18n:** finish replacing any remaining hardcoded English in `ai-edition/*` with locale keys.+- **Region drag visual polish:** snap-guide line + floating time tooltip during drag/resize (visual companion to the clamp logic already in `RegionTimeline.tsx`).++### Deferred / known limitations+- **Long-recording scrub lag (>30 min)** — proxy MP4 dropped by decision 6; revival = per-asset "Generate proxy" button.+- **SSE streaming for project changes** — unnecessary in single-user Electron.++---++## 6. Verification protocol+- **Per change:** `npx tsc --noEmit` clean · `npm run test` green · new tests for new logic (vitest/jsdom).+- **Dev loop:** `npm run dev` → `http://localhost:5173/?windowType=editor` (browser shim persists to `localStorage["browser-shim-document"]`).+- **Per phase:** manual smoke on Win/mac for any exporter- or recorder-touching change (native helpers are frozen).diff --git a/docs/architecture/openscreen-inventory.md b/docs/architecture/openscreen-inventory.mdindex d9aacc6ec..78287874f 100644--- a/docs/architecture/openscreen-inventory.md+++ b/docs/architecture/openscreen-inventory.md@@ -690,7 +690,7 @@ Validates every locale folder has the same key tree as `en/` for all 7 namespace- `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/ai-edition-roadmap.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.diff --git a/electron/ai-edition/chat-service.test.ts b/electron/ai-edition/chat-service.test.tsnew file mode 100644index 000000000..2271472dc--- /dev/null+++ b/electron/ai-edition/chat-service.test.ts@@ -0,0 +1,109 @@+import { beforeEach, describe, expect, it } from "vitest";+import {+ createSession,+ deleteSession,+ listSessions,+ renameSession,+ selectSession,+} from "./chat-service";+import type { LlmConfigStore } from "./llm-config-store";++describe("chat-service sessions", () => {+ const projectId = "proj_test";+ beforeEach(() => {+ // ponytail: in-memory store, no teardown needed between tests — just+ // use a fresh projectId per test where isolation matters.+ });++ it("createSession returns a summary with messageCount=0", () => {+ const s = createSession(projectId, " My chat ");+ expect(s.title).toBe("My chat");+ expect(s.messageCount).toBe(0);+ expect(s.projectId).toBe(projectId);+ expect(s.id).toMatch(/^sess_/);+ });++ it("listSessions returns an empty array for a fresh project", () => {+ const list = listSessions("proj_empty");+ expect(list).toEqual([]);+ });++ it("selectSession returns the session with a copy of the messages array", () => {+ const s = createSession(projectId);+ const got = selectSession(projectId, s.id);+ expect(got).not.toBeNull();+ expect(got?.id).toBe(s.id);+ expect(got?.messages).toEqual([]);+ // ponytail: messages array is a copy, mutations don't leak.+ if (got) got.messages.push({} as never);+ const got2 = selectSession(projectId, s.id);+ expect(got2?.messages).toEqual([]);+ });++ it("selectSession returns null for an unknown sessionId", () => {+ expect(selectSession(projectId, "nope")).toBeNull();+ });++ it("renameSession updates the title and returns the updated summary", () => {+ const s = createSession(projectId);+ const updated = renameSession(projectId, s.id, " Renamed ");+ expect(updated?.title).toBe("Renamed");+ const got = selectSession(projectId, s.id);+ expect(got?.title).toBe("Renamed");+ });++ it("renameSession ignores empty input and keeps the existing title", () => {+ const s = createSession(projectId, "Original");+ const updated = renameSession(projectId, s.id, " ");+ expect(updated?.title).toBe("Original");+ });++ it("renameSession returns null for an unknown sessionId", () => {+ expect(renameSession(projectId, "nope", "x")).toBeNull();+ });++ it("deleteSession removes the session and returns true", () => {+ const s = createSession(projectId);+ expect(deleteSession(projectId, s.id)).toBe(true);+ expect(selectSession(projectId, s.id)).toBeNull();+ expect(listSessions(projectId).find((x) => x.id === s.id)).toBeUndefined();+ });++ it("deleteSession returns false for an unknown id", () => {+ expect(deleteSession(projectId, "nope")).toBe(false);+ });++ it("listSessions returns sessions sorted by createdAt", async () => {+ const a = createSession("proj_sort", "A");+ await new Promise((r) => setTimeout(r, 5));+ const b = createSession("proj_sort", "B");+ await new Promise((r) => setTimeout(r, 5));+ const c = createSession("proj_sort", "C");+ const list = listSessions("proj_sort");+ expect(list.map((x) => x.id)).toEqual([a.id, b.id, c.id]);+ });++ it("listSessions only includes the requested project", () => {+ createSession("proj_a");+ createSession("proj_b");+ createSession("proj_b");+ expect(listSessions("proj_a").length).toBe(1);+ expect(listSessions("proj_b").length).toBe(2);+ });+});++// ponytail: type-only check that the runChat signature now takes a sessionId.+// We don't exercise the LLM call here — the real provider path needs network+// + API keys, which the integration tests cover elsewhere.+describe("chat-service runChat signature", () => {+ it("accepts (projectId, sessionId, message, llmConfig) and short-circuits without a config", async () => {+ // ponytail: stub LlmConfigStore whose getConfig() returns null, so+ // runChat exits early with the "No LLM provider configured" error.+ const llmConfig = { getConfig: () => null } as unknown as LlmConfigStore;+ const { runChat, createSession } = await import("./chat-service");+ const s = createSession("proj_sig");+ const result = await runChat("proj_sig", s.id, "hi", llmConfig);+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/No LLM provider/);+ });+});diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.tsindex 2a007ce46..e44dd0169 100644--- a/electron/ai-edition/chat-service.ts+++ b/electron/ai-edition/chat-service.ts@@ -1,7 +1,7 @@// 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).+// for Phase 6 scaffolding. Stores sessions per project in a nested 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.@@ -11,15 +11,106 @@ 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 sessionsByProject = new Map<string, Map<string, ChatSession>>();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 interface ChatSession {+ id: string;+ projectId: string;+ title: string;+ createdAt: string;+ messages: AiEditionChatMessage[];+}++export interface ChatSessionSummary {+ id: string;+ projectId: string;+ title: string;+ createdAt: string;+ messageCount: number;+}++function toSummary(s: ChatSession): ChatSessionSummary {+ return {+ id: s.id,+ projectId: s.projectId,+ title: s.title,+ createdAt: s.createdAt,+ messageCount: s.messages.length,+ };+}++function getProjectSessions(projectId: string): Map<string, ChatSession> {+ let m = sessionsByProject.get(projectId);+ if (!m) {+ m = new Map();+ sessionsByProject.set(projectId, m);+ }+ return m;+}++function defaultSessionTitle(index: number): string {+ return `Conversation ${index}`;+}++export function listSessions(projectId: string): ChatSessionSummary[] {+ const m = sessionsByProject.get(projectId);+ if (!m) return [];+ return Array.from(m.values())+ .map(toSummary)+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));+}++export function createSession(projectId: string, title?: string): ChatSessionSummary {+ const m = getProjectSessions(projectId);+ const id = `sess_${uuidv4()}`;+ const now = new Date().toISOString();+ const session: ChatSession = {+ id,+ projectId,+ title: title?.trim() || defaultSessionTitle(m.size + 1),+ createdAt: now,+ messages: [],+ };+ m.set(id, session);+ return toSummary(session);+}++export function selectSession(projectId: string, sessionId: string): ChatSession | null {+ const m = sessionsByProject.get(projectId);+ const s = m?.get(sessionId);+ if (!s) return null;+ // ponytail: shallow-copy messages so the caller can't mutate the live array.+ return { ...s, messages: [...s.messages] };+}++export function renameSession(+ projectId: string,+ sessionId: string,+ title: string,+): ChatSessionSummary | null {+ const m = sessionsByProject.get(projectId);+ const s = m?.get(sessionId);+ if (!s) return null;+ const trimmed = title.trim();+ if (trimmed) s.title = trimmed;+ return toSummary(s);+}++export function deleteSession(projectId: string, sessionId: string): boolean {+ const m = sessionsByProject.get(projectId);+ if (!m?.has(sessionId)) return false;+ m.delete(sessionId);+ return true;+}+export async function runChat(projectId: string,+ sessionId: string,message: string,llmConfig: LlmConfigStore,): Promise<AiEditionChatResult> {@@ -44,19 +135,30 @@ export async function runChat(};}- const history = messagesByProject.get(projectId) ?? [];+ const sessions = getProjectSessions(projectId);+ let session = sessions.get(sessionId);+ if (!session) {+ // ponytail: tolerate a stale/missing session id by recreating one. The+ // renderer should keep these in sync, but a missing session should+ // never break the chat run path.+ const summary = createSession(projectId, defaultSessionTitle(sessions.size + 1));+ session = sessions.get(summary.id);+ }+ if (!session) {+ return { success: false, error: "Chat session unavailable." };+ }+const userMessage: AiEditionChatMessage = {id: uuidv4(),role: "user",content: message,createdAt: new Date().toISOString(),};- history.push(userMessage);- messagesByProject.set(projectId, history);+ session.messages.push(userMessage);const llmMessages: ChatMessage[] = [{ role: "system", content: SYSTEM_PROMPT },- ...history.slice(-20).map((m) => ({ role: m.role, content: m.content })),+ ...session.messages.slice(-20).map((m) => ({ role: m.role, content: m.content })),];const result = await callLlm({@@ -78,8 +180,7 @@ export async function runChat(content: result.content,createdAt: new Date().toISOString(),};- history.push(assistantMessage);- messagesByProject.set(projectId, history);+ session.messages.push(assistantMessage);return {success: true,@@ -87,10 +188,39 @@ export async function runChat(};}-export async function getChatHistory(projectId: string): Promise<AiEditionChatMessage[]> {- return messagesByProject.get(projectId) ?? [];+// ponytail: legacy single-session compatibility for the simpler ChatPanel+// consumers. Picks the most recent session (or auto-creates one) so a stale+// caller keeps working. The multi-session UI is the supported path.+function getOrCreateDefaultSession(projectId: string): ChatSession {+ const m = getProjectSessions(projectId);+ if (m.size > 0) {+ const arr = Array.from(m.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt));+ return arr[0];+ }+ const created = createSession(projectId);+ const s = m.get(created.id);+ if (!s) throw new Error("Chat session unavailable.");+ return s;+}++export async function runChatDefault(+ projectId: string,+ message: string,+ llmConfig: LlmConfigStore,+): Promise<AiEditionChatResult> {+ const session = getOrCreateDefaultSession(projectId);+ return runChat(projectId, session.id, message, llmConfig);+}++export function getDefaultChatHistory(projectId: string): AiEditionChatMessage[] {+ const m = sessionsByProject.get(projectId);+ if (!m || m.size === 0) return [];+ const arr = Array.from(m.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt));+ return [...arr[0].messages];}-export function clearChatHistory(projectId: string): void {- messagesByProject.delete(projectId);+export function clearDefaultChatHistory(projectId: string): void {+ const m = sessionsByProject.get(projectId);+ if (!m) return;+ for (const s of m.values()) s.messages = [];}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex d399aa349..aea5299ad 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -35,7 +35,17 @@ import type {ProjectFileResult,ProjectPathResult,} from "../../src/native/contracts";-import { clearChatHistory, getChatHistory, runChat } from "../ai-edition/chat-service";+import {+ clearDefaultChatHistory,+ createSession,+ deleteSession,+ getDefaultChatHistory,+ listSessions,+ renameSession,+ runChat,+ runChatDefault,+ selectSession,+} 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";@@ -3139,9 +3149,17 @@ export function registerIpcHandlers(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),+ runAiEditionChat: (projectId, sessionId, message) =>+ runChat(projectId, sessionId, message, new LlmConfigStore(app.getPath("userData"))),+ runAiEditionChatDefault: (projectId, message) =>+ runChatDefault(projectId, message, new LlmConfigStore(app.getPath("userData"))),+ getAiEditionChatHistoryDefault: (projectId) => getDefaultChatHistory(projectId),+ clearAiEditionChatHistoryDefault: (projectId) => clearDefaultChatHistory(projectId),+ listAiEditionChatSessions: (projectId) => listSessions(projectId),+ createAiEditionChatSession: (projectId, title) => createSession(projectId, title),+ selectAiEditionChatSession: (projectId, sessionId) => selectSession(projectId, sessionId),+ renameAiEditionChatSession: (projectId, sessionId, title) =>+ renameSession(projectId, sessionId, title),+ deleteAiEditionChatSession: (projectId, sessionId) => deleteSession(projectId, sessionId),});}diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex 73febea2a..ec3aece29 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -43,12 +43,34 @@ export interface NativeBridgeContext {getAiEditionLlmConfig: () => import("../ai-edition/llm-config-store").LlmConfigStore;runAiEditionChat: (projectId: string,+ sessionId: string,message: string,) => Promise<import("../../src/native/contracts").AiEditionChatResult>;- getAiEditionChatHistory: (+ runAiEditionChatDefault: (projectId: string,- ) => Promise<import("../../src/native/contracts").AiEditionChatMessage[]>;- clearAiEditionChatHistory: (projectId: string) => void;+ message: string,+ ) => Promise<import("../../src/native/contracts").AiEditionChatResult>;+ getAiEditionChatHistoryDefault: (+ projectId: string,+ ) => import("../../src/native/contracts").AiEditionChatMessage[];+ clearAiEditionChatHistoryDefault: (projectId: string) => void;+ listAiEditionChatSessions: (+ projectId: string,+ ) => import("../../src/native/contracts").AiEditionChatSessionSummary[];+ createAiEditionChatSession: (+ projectId: string,+ title?: string,+ ) => import("../../src/native/contracts").AiEditionChatSessionSummary;+ selectAiEditionChatSession: (+ projectId: string,+ sessionId: string,+ ) => import("../../src/native/contracts").AiEditionChatSession | null;+ renameAiEditionChatSession: (+ projectId: string,+ sessionId: string,+ title: string,+ ) => import("../../src/native/contracts").AiEditionChatSessionSummary | null;+ deleteAiEditionChatSession: (projectId: string, sessionId: string) => boolean;}function normalizePlatform(platform: NodeJS.Platform): NativePlatform {@@ -136,8 +158,14 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {documents: context.getAiEditionDocuments(),llmConfig: context.getAiEditionLlmConfig(),runChat: context.runAiEditionChat,- getChatHistory: context.getAiEditionChatHistory,- clearChatHistory: context.clearAiEditionChatHistory,+ runChatDefault: context.runAiEditionChatDefault,+ getDefaultChatHistory: context.getAiEditionChatHistoryDefault,+ clearDefaultChatHistory: context.clearAiEditionChatHistoryDefault,+ listSessions: context.listAiEditionChatSessions,+ createSession: context.createAiEditionChatSession,+ selectSession: context.selectAiEditionChatSession,+ renameSession: context.renameAiEditionChatSession,+ deleteSession: context.deleteAiEditionChatSession,});ipcMain.handle(NATIVE_BRIDGE_CHANNEL, async (_, request: unknown) => {@@ -304,17 +332,67 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {case "chat.run":return createSuccessResponse(requestId,- await aiEditionService.chatRun(request.payload.projectId, request.payload.message),+ await aiEditionService.chatRun(+ request.payload.projectId,+ request.payload.sessionId,+ request.payload.message,+ ),+ );+ case "chat.runDefault":+ return createSuccessResponse(+ requestId,+ await aiEditionService.chatRunDefault(+ request.payload.projectId,+ request.payload.message,+ ),);case "chat.history":return createSuccessResponse(requestId,- await aiEditionService.chatHistory(request.payload.projectId),+ aiEditionService.chatHistoryDefault(request.payload.projectId),);case "chat.clear":return createSuccessResponse(requestId,- await aiEditionService.chatClear(request.payload.projectId),+ aiEditionService.chatClearDefault(request.payload.projectId),+ );+ case "chat.listSessions":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatListSessions(request.payload.projectId),+ );+ case "chat.createSession":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatCreateSession(+ request.payload.projectId,+ request.payload.title,+ ),+ );+ case "chat.selectSession":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatSelectSession(+ request.payload.projectId,+ request.payload.sessionId,+ ),+ );+ case "chat.renameSession":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatRenameSession(+ request.payload.projectId,+ request.payload.sessionId,+ request.payload.title,+ ),+ );+ case "chat.deleteSession":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatDeleteSession(+ request.payload.projectId,+ request.payload.sessionId,+ ),);default:return createErrorResponse(diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsindex afb816cd5..028ea0404 100644--- a/electron/native-bridge/services/aiEditionService.ts+++ b/electron/native-bridge/services/aiEditionService.ts@@ -3,6 +3,8 @@ import type {AiEditionAssetResult,AiEditionChatMessage,AiEditionChatResult,+ AiEditionChatSession,+ AiEditionChatSessionSummary,AiEditionDocumentResult,AiEditionLlmConfig,AiEditionLlmSnapshot,@@ -15,9 +17,19 @@ 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;+ runChat: (projectId: string, sessionId: string, message: string) => Promise<AiEditionChatResult>;+ runChatDefault: (projectId: string, message: string) => Promise<AiEditionChatResult>;+ getDefaultChatHistory: (projectId: string) => AiEditionChatMessage[];+ clearDefaultChatHistory: (projectId: string) => void;+ listSessions: (projectId: string) => AiEditionChatSessionSummary[];+ createSession: (projectId: string, title?: string) => AiEditionChatSessionSummary;+ selectSession: (projectId: string, sessionId: string) => AiEditionChatSession | null;+ renameSession: (+ projectId: string,+ sessionId: string,+ title: string,+ ) => AiEditionChatSessionSummary | null;+ deleteSession: (projectId: string, sessionId: string) => boolean;}export class AiEditionService {@@ -132,16 +144,53 @@ export class AiEditionService {}}- async chatRun(projectId: string, message: string): Promise<AiEditionChatResult> {- return this.options.runChat(projectId, message);+ async chatRun(+ projectId: string,+ sessionId: string,+ message: string,+ ): Promise<AiEditionChatResult> {+ return this.options.runChat(projectId, sessionId, message);}- async chatHistory(projectId: string): Promise<AiEditionChatMessage[]> {- return this.options.getChatHistory(projectId);+ async chatRunDefault(projectId: string, message: string): Promise<AiEditionChatResult> {+ return this.options.runChatDefault(projectId, message);}- async chatClear(projectId: string): Promise<{ success: boolean }> {- this.options.clearChatHistory(projectId);+ chatHistoryDefault(projectId: string): AiEditionChatMessage[] {+ return this.options.getDefaultChatHistory(projectId);+ }++ chatClearDefault(projectId: string): { success: boolean } {+ this.options.clearDefaultChatHistory(projectId);return { success: true };}++ chatListSessions(projectId: string): AiEditionChatSessionSummary[] {+ return this.options.listSessions(projectId);+ }++ chatCreateSession(projectId: string, title?: string): AiEditionChatSessionSummary {+ return this.options.createSession(projectId, title);+ }++ chatSelectSession(projectId: string, sessionId: string): AiEditionChatSession | null {+ return this.options.selectSession(projectId, sessionId);+ }++ chatRenameSession(+ projectId: string,+ sessionId: string,+ title: string,+ ): AiEditionChatSessionSummary | null {+ return this.options.renameSession(projectId, sessionId, title);+ }++ chatDeleteSession(projectId: string, sessionId: string): { success: boolean } {+ return { success: this.options.deleteSession(projectId, sessionId) };+ }++ chatMessages(projectId: string, sessionId: string): AiEditionChatMessage[] {+ const session = this.options.selectSession(projectId, sessionId);+ return session?.messages ?? [];+ }}diff --git a/src/components/ai-edition/Bottombar.tsx b/src/components/ai-edition/Bottombar.tsxindex 67a8e79a4..76e46dca3 100644--- a/src/components/ai-edition/Bottombar.tsx+++ b/src/components/ai-edition/Bottombar.tsx@@ -2,18 +2,23 @@ import {ChevronDown,FileText,MessageSquare,+ Pencil,Scissors,Timer,WandSparkles,ZoomIn,} from "lucide-react";-import { useState } from "react";+import { useCallback, useEffect, 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 { useTimeline } from "@/lib/ai-edition/store/useTimeline";import { ASPECT_RATIOS, type AspectRatio } from "@/utils/aspectRatioUtils";+import { EditClipModal } from "./Modals";import styles from "./NewEditorShell.module.css";+import { type Span } from "./RegionTimeline";import { TimelinePane } from "./TimelinePane";+import type { VideoSource } from "./VirtualPreview";type RegionKind = "zoom" | "skip" | "annotation" | "speed";@@ -24,14 +29,9 @@ interface RegionHandle {interface BottombarProps {clips: AxcutClip[];+ videoSources: VideoSource[];currentTimeSec: number;- sourceDurationSec: number;- onPreviewSource: (sec: number) => void;- onReplaceTimeline: (- intervals: Array<{ startSec: number; endSec: number }>,- reason: string,- ) => void;- // Region operations (from useTimeline)+ onSeek: (timelineSec: number) => void;zoomRegions: AxcutDocument["zoomRanges"];skipRanges: AxcutDocument["timeline"]["skipRanges"];annotationRegions: AnnotationRegion[];@@ -39,11 +39,14 @@ interface BottombarProps {selection: RegionHandle | null;hasDoc: boolean;onAddZoom: () => void;- onAddSkip: () => void;onAddAnnotation: () => void;onAddSpeed: () => void;+ // T15 — receives a setter so the parent's "T" keyboard shortcut can+ // call into our togglePlaceSkip (state lives here, body-class + Esc+ // handler live here). The Scissors button in this component calls+ // togglePlaceSkip directly.+ setTogglePlaceSkip?: (fn: () => void) => void;onSelectRegion: (kind: RegionKind, id: string) => void;- onRemoveRegion: (kind: RegionKind, id: string) => void;onCaptions: () => void;}@@ -58,34 +61,97 @@ const RATIO_LABELS: Record<AspectRatio, string> = {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,+ videoSources,currentTimeSec,- sourceDurationSec,- onPreviewSource,- onReplaceTimeline,+ onSeek,zoomRegions,+ skipRanges,annotationRegions,speedRegions,selection,hasDoc,onAddZoom,- onAddSkip,onAddAnnotation,onAddSpeed,+ setTogglePlaceSkip,onSelectRegion,- onRemoveRegion,onCaptions,}: BottombarProps) {const { settings, set } = useEditorSettings();+ const tl = useTimeline();const [ratioOpen, setRatioOpen] = useState(false);+ const [editClipTarget, setEditClipTarget] = useState<AxcutClip | null>(null);+ const firstClip = clips[0] ?? null;+ // T11 — viewport state lifted from TimelinePane so the navigator strip+ // can drive the same window. pxPerSec stays inside TimelinePane (it+ // depends on the viewport's measured width); Bottombar only owns the+ // logical window + zoom multiplier.+ const [zoom, setZoom] = useState(1);+ const [visibleStartSec, setVisibleStartSec] = useState(0);+ // T15 — Place-skip armed state. The Scissors (Trim) button toggles+ // this; the timeline pane shows the red preview marker and the cursor+ // becomes crosshair. Esc cancels. The preview is pinned to the+ // playhead the moment the mode is armed so the user sees the marker+ // right away (axcut's behavior).+ const [pendingCutPlacement, setPendingCutPlacement] = useState(false);+ const [pendingCutPreviewSec, setPendingCutPreviewSec] = useState<number | null>(null);+ const togglePlaceSkip = useCallback(() => {+ setPendingCutPlacement((active) => {+ if (active) {+ setPendingCutPreviewSec(null);+ return false;+ }+ setPendingCutPreviewSec(currentTimeSec);+ return true;+ });+ }, [currentTimeSec]);++ // T15 — body cursor + Esc-to-cancel while placing a cut. Lives here+ // (not in TimelinePane) because the state lives here.+ useEffect(() => {+ if (!pendingCutPlacement) {+ document.body.classList.remove("timeline-placing-cut");+ return;+ }+ document.body.classList.add("timeline-placing-cut");+ const handleKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ setPendingCutPlacement(false);+ setPendingCutPreviewSec(null);+ }+ };+ window.addEventListener("keydown", handleKey);+ return () => {+ document.body.classList.remove("timeline-placing-cut");+ window.removeEventListener("keydown", handleKey);+ };+ }, [pendingCutPlacement]);++ // ponytail: register our toggler with the parent (NewEditorShell)+ // so the "T" keyboard shortcut can call the same function the+ // Scissors button does. Uses an effect so re-renders (togglePlaceSkip+ // identity is stable but the ref it points to may change) always+ // see the latest implementation.+ useEffect(() => {+ setTogglePlaceSkip?.(togglePlaceSkip);+ }, [togglePlaceSkip, setTogglePlaceSkip]);++ const sourceDurationSec = Math.max(0.001, ...clips.map((c) => c.timelineEndSec));+ const visibleEndSec = Math.min(visibleStartSec + sourceDurationSec, sourceDurationSec);+ void visibleEndSec; // surfaced to the navigator (now inside TimelinePane)+ const handleRegionSpanChange = (id: string, span: Span) => {+ if (zoomRegions.some((z) => z.id === id)) void tl.updateZoomSpan(id, span.start, span.end);+ else if (speedRegions.some((s) => s.id === id))+ void tl.updateSpeedSpan(id, span.start, span.end);+ else void tl.updateAnnotationSpan(id, span.start, span.end);+ };+ // ponytail: T10 removed the explicit onRemoveRegion prop (region+ // removal happens via the Del/Bksp shortcut wired in NewEditorShell).+ const editClipAsset = editClipTarget+ ? (tl.assets.find((a) => a.id === editClipTarget.assetId) ?? null)+ : null;return (<footer className={styles.bottombar} aria-label="Timeline and properties"><section@@ -122,7 +188,17 @@ export function Bottombar({<circle cx="12" cy="12" r="1.6" /></svg></VtBtn>- <VtBtn label="Trim" title="Press T to add trim" onClick={onAddSkip} disabled={!hasDoc}>+ <VtBtn+ label="Trim"+ title={+ pendingCutPlacement+ ? "Click on the timeline to place a 1s skip (Esc to cancel)"+ : "Arm the place-skip tool (T) — next click drops a 1s skip"+ }+ onClick={togglePlaceSkip}+ disabled={!hasDoc}+ on={pendingCutPlacement}+ ><Scissors size={17} /></VtBtn><VtBtn@@ -203,81 +279,90 @@ export function Bottombar({<span className={styles.kbd}>+ Scroll</span><span>Zoom</span></span>+ <button+ type="button"+ className={styles.vtBtn}+ style={{+ marginLeft: 8,+ height: 28,+ width: "auto",+ padding: "0 10px",+ gap: 6,+ borderRadius: "var(--r-sm)",+ }}+ onClick={() => firstClip && setEditClipTarget(firstClip)}+ disabled={!firstClip}+ title={firstClip ? "Edit the first clip's in/out points" : "Add a clip first"}+ aria-label="Edit clip"+ >+ <Pencil size={14} />+ Edit clip…+ </button></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>+ {/* T10 — clip track + region lanes both live inside+ TimelinePane's .timeline-canvas, so they share the+ translateX(pan) and pxPerSec(zoom). Lanes-in-canvas,+ not lanes-in-a-sibling-column. */}<div className="timelinePaneWrap" style={{ flex: 1, minHeight: 0, overflow: "hidden" }}><TimelinePaneclips={clips}+ assets={tl.assets}+ skipRanges={skipRanges}+ zoomRegions={zoomRegions}+ annotationRegions={annotationRegions}+ speedRegions={speedRegions}+ regionSelection={selection}currentTimeSec={currentTimeSec}- sourceDurationSec={sourceDurationSec}- onPreviewSource={onPreviewSource}- onReplaceTimeline={onReplaceTimeline}+ selectedClipId={tl.clipSelection}+ onSelectClip={tl.selectClip}+ onSelectRegion={onSelectRegion}+ onSeek={onSeek}+ onInsertAsset={(assetId, index) => void tl.insertClipAt(assetId, index)}+ onMoveClip={(clipId, toIndex) => void tl.moveClip(clipId, toIndex)}+ onEditClip={(clip) => setEditClipTarget(clip)}+ onRemoveClip={(clipId) => void tl.removeClip(clipId)}+ onUpdateSkipRange={(skipId, s, e) => void tl.updateSkipRange(skipId, s, e)}+ onPreviewSource={(timeSec, _assetId) => {+ // T19 — drive the source-time clock so the preview+ // video scrubs to the edge being dragged. We don't+ // rebind the preview's activeSource because that+ // resets playback; the existing Preview's+ // seekToSourceTime handles the same-source case.+ tl.setCurrentTime(timeSec);+ }}+ onRemoveSkipRange={(skipId) => void tl.removeRegion("skip", skipId)}+ onAddSkip={(assetId, s, e) => void tl.addSkipAt(assetId, s, e)}+ onRegionSpanChange={(id, span) => handleRegionSpanChange(id, span)}+ zoom={zoom}+ visibleStartSec={visibleStartSec}+ setZoom={setZoom}+ setVisibleStartSec={setVisibleStartSec}+ pendingCutPlacement={pendingCutPlacement}+ pendingCutPreviewSec={pendingCutPreviewSec}+ setPendingCutPreviewSec={setPendingCutPreviewSec}+ onCancelPlaceSkip={() => togglePlaceSkip()}/></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>+ <EditClipModal+ open={editClipTarget !== null}+ onClose={() => setEditClipTarget(null)}+ clip={editClipTarget}+ assetMeta={+ editClipAsset+ ? { label: editClipAsset.label, durationSec: editClipAsset.durationSec }+ : null+ }+ videoSources={videoSources}+ onApply={(sourceStartSec, sourceEndSec) => {+ if (editClipTarget) {+ void tl.updateClipSourceRange(editClipTarget.id, sourceStartSec, sourceEndSec);+ }+ }}+ /></footer>);}@@ -312,115 +397,6 @@ function VtBtn({);}-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",diff --git a/src/components/ai-edition/ChatPanel.tsx b/src/components/ai-edition/ChatPanel.tsxdeleted file mode 100644index 6af48e496..000000000--- a/src/components/ai-edition/ChatPanel.tsx+++ /dev/null@@ -1,114 +0,0 @@-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/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsxindex ffa646cca..569d6ccdf 100644--- a/src/components/ai-edition/LeftPanel.tsx+++ b/src/components/ai-edition/LeftPanel.tsx@@ -343,7 +343,10 @@ function ChatStripPanel() {const [llmConfig, setLlmConfig] = useState<AiEditionLlmConfig | null>(null);const [settingsOpen, setSettingsOpen] = useState(false);const [chatsOpen, setChatsOpen] = useState(false);- const [sessionNum, setSessionNum] = useState(1);+ const [sessions, setSessions] = useState<+ Array<{ id: string; title: string; messageCount: number; createdAt: string }>+ >([]);+ const [activeSessionId, setActiveSessionId] = useState<string | null>(null);const scrollRef = useRef<HTMLDivElement | null>(null);const refreshLlm = useCallback(async () => {@@ -355,33 +358,79 @@ function ChatStripPanel() {}}, []);+ const refreshSessions = useCallback(+ async (pid: string, preferFirst = false) => {+ try {+ const list = await nativeBridgeClient.aiEdition.chatListSessions(pid);+ setSessions(list);+ if (list.length === 0) {+ setActiveSessionId(null);+ setMessages([]);+ return;+ }+ if (preferFirst || !list.some((s) => s.id === activeSessionId)) {+ setActiveSessionId(list[0].id);+ }+ } catch {+ // ponytail: silent — shim mode or missing project+ }+ },+ [activeSessionId],+ );+useEffect(() => {void refreshLlm();}, [refreshLlm]);useEffect(() => {- if (!projectId) return;+ if (!projectId) {+ setSessions([]);+ setActiveSessionId(null);+ setMessages([]);+ return;+ }+ void refreshSessions(projectId, true);+ }, [projectId, refreshSessions]);++ useEffect(() => {+ if (!projectId || !activeSessionId) {+ setMessages([]);+ return;+ }void (async () => {try {- const history = await nativeBridgeClient.aiEdition.chatHistory(projectId);- setMessages(history.map((m) => ({ role: m.role, content: m.content, time: m.createdAt })));+ const session = await nativeBridgeClient.aiEdition.chatSelectSession(+ projectId,+ activeSessionId,+ );+ if (session) {+ setMessages(+ session.messages.map((m) => ({+ role: m.role,+ content: m.content,+ time: m.createdAt,+ })),+ );+ } else {+ setMessages([]);+ }} catch {- // ponytail: silent — shim mode or missing project+ // ponytail: silent — shim mode}})();- }, [projectId]);+ }, [projectId, activeSessionId]);useEffect(() => {scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });});const send = async () => {- if (!projectId || !input.trim() || busy) return;+ if (!projectId || !activeSessionId || !input.trim() || busy) return;const text = input.trim();setInput("");setBusy(true);try {- const result = await nativeBridgeClient.aiEdition.chatRun(projectId, text);+ const result = await nativeBridgeClient.aiEdition.chatRun(projectId, activeSessionId, text);setMessages((prev) => [...prev,{ role: "user", content: text, time: new Date().toLocaleTimeString() },@@ -396,6 +445,7 @@ function ChatStripPanel() {time: new Date().toLocaleTimeString(),},]);+ void refreshSessions(projectId);} else {toast.error(result.error ?? "Chat failed");}@@ -417,17 +467,66 @@ function ChatStripPanel() {: 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- }+ if (!projectId) return;+ try {+ const created = await nativeBridgeClient.aiEdition.chatCreateSession(projectId);+ setSessions((prev) => [...prev, created]);+ setActiveSessionId(created.id);+ setMessages([]);+ } catch (err) {+ toast.error("Could not create conversation", {+ description: err instanceof Error ? err.message : String(err),+ });}}, [projectId]);+ const selectSession = useCallback((id: string) => {+ setActiveSessionId(id);+ }, []);++ const handleDelete = useCallback(+ async (id: string) => {+ if (!projectId) return;+ try {+ const res = await nativeBridgeClient.aiEdition.chatDeleteSession(projectId, id);+ if (!res.success) return;+ setSessions((prev) => prev.filter((s) => s.id !== id));+ if (activeSessionId === id) {+ setActiveSessionId(null);+ setMessages([]);+ }+ } catch (err) {+ toast.error("Could not delete conversation", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [projectId, activeSessionId],+ );++ const handleRename = useCallback(+ async (id: string, title: string) => {+ if (!projectId) return;+ const trimmed = title.trim();+ if (!trimmed) return;+ try {+ const updated = await nativeBridgeClient.aiEdition.chatRenameSession(+ projectId,+ id,+ trimmed,+ );+ if (updated) {+ setSessions((prev) => prev.map((s) => (s.id === id ? updated : s)));+ }+ } catch (err) {+ toast.error("Could not rename conversation", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ },+ [projectId],+ );+return (<aside className={styles.panel}><div className={styles.chatStrip}>@@ -522,6 +621,109 @@ function ChatStripPanel() {<div className={styles.chatHint}>Describe the edit you want…</div></div>+ {activeSessionId ? (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 8,+ padding: "6px var(--sp-3)",+ borderTop: "1px solid var(--border-soft)",+ background: "var(--surface-warm)",+ }}+ >+ <span+ style={{+ font: "500 12px/1.3 var(--font-body)",+ color: "var(--fg-2)",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ flex: 1,+ cursor: "text",+ }}+ title="Click to rename"+ onClick={() => {+ const current = sessions.find((s) => s.id === activeSessionId);+ if (!current) return;+ const next = window.prompt("Rename conversation", current.title);+ if (next !== null) void handleRename(activeSessionId, next);+ }}+ >+ {sessions.find((s) => s.id === activeSessionId)?.title ?? "Conversation"}+ </span>+ <button+ type="button"+ title="Rename conversation"+ aria-label="Rename conversation"+ onClick={() => {+ const current = sessions.find((s) => s.id === activeSessionId);+ if (!current) return;+ const next = window.prompt("Rename conversation", current.title);+ if (next !== null) void handleRename(activeSessionId, next);+ }}+ style={{+ background: "transparent",+ border: 0,+ color: "var(--meta)",+ cursor: "pointer",+ padding: 2,+ }}+ >+ <svg+ width={12}+ height={12}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M12 20h9" />+ <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z" />+ </svg>+ </button>+ <button+ type="button"+ title="Delete conversation"+ aria-label="Delete conversation"+ onClick={() => {+ const current = sessions.find((s) => s.id === activeSessionId);+ if (!current) return;+ if (window.confirm(`Delete "${current.title}"?`)) {+ void handleDelete(activeSessionId);+ }+ }}+ style={{+ background: "transparent",+ border: 0,+ color: "var(--meta)",+ cursor: "pointer",+ padding: 2,+ }}+ >+ <svg+ width={12}+ height={12}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />+ <path d="M10 11v6" />+ <path d="M14 11v6" />+ <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />+ </svg>+ </button>+ </div>+ ) : null}+<div className={styles.panelBody} ref={scrollRef}>{messages.length === 0 ? (<p@@ -652,16 +854,9 @@ function ChatStripPanel() {<ChatHistoryModalopen={chatsOpen}onClose={() => setChatsOpen(false)}- sessions={[- {- id: `session_${sessionNum}`,- title: `Session ${sessionNum}`,- messageCount: messages.length,- createdAt: new Date().toISOString(),- },- ]}- activeSessionId={`session_${sessionNum}`}- onSelect={() => setChatsOpen(false)}+ sessions={sessions}+ activeSessionId={activeSessionId}+ onSelect={selectSession}onNew={newChat}/></aside>diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsxindex e5f04b75c..fe7de70b3 100644--- a/src/components/ai-edition/Modals.tsx+++ b/src/components/ai-edition/Modals.tsx@@ -1,7 +1,16 @@-import { AlertTriangle, Crop, FolderOpen, FolderPlus, Plus, X } from "lucide-react";-import { type ReactNode, useEffect, useState } from "react";+import { AlertTriangle, Crop, FolderOpen, FolderPlus, Pencil, Plus, X } from "lucide-react";+import {+ type ReactNode,+ type PointerEvent as ReactPointerEvent,+ useEffect,+ useRef,+ useState,+} from "react";import type { CropRegion } from "@/components/video-editor/types";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { formatSeconds } from "@/lib/ai-edition/timeline/virtual-preview";import styles from "./NewEditorShell.module.css";+import { type VideoSource, VirtualPreview } from "./VirtualPreview";interface BaseModalProps {open: boolean;@@ -589,6 +598,284 @@ function CropField({);}+export interface AssetMeta {+ label: string;+ durationSec?: number;+}++interface EditClipModalProps extends BaseModalProps {+ clip: AxcutClip | null;+ assetMeta: AssetMeta | null;+ videoSources: VideoSource[];+ onApply: (sourceStartSec: number, sourceEndSec: number) => void;+}++// Mirrors Axcut's ClipEditDialog: an embedded preview of just this clip plus+// a draggable dual-handle range over the asset's full source duration —+// replaces the old numeric-input-only form. Only the source range is+// editable here; the clip's timeline position is derived from resequencing+// (see useTimeline.updateClipSourceRange), same as every other clip op.+export function EditClipModal({+ open,+ onClose,+ clip,+ assetMeta,+ videoSources,+ onApply,+}: EditClipModalProps) {+ const trackRef = useRef<HTMLDivElement | null>(null);+ const [draftStart, setDraftStart] = useState(0);+ const [draftEnd, setDraftEnd] = useState(0);+ const [activeEdge, setActiveEdge] = useState<"start" | "end" | null>(null);++ // ponytail: sync local drag state to the clip every time the modal opens.+ // `open` is the trigger so external clip changes don't fight the user mid-edit.+ useEffect(() => {+ if (!open || !clip) return;+ setDraftStart(clip.sourceStartSec);+ setDraftEnd(clip.sourceEndSec ?? clip.sourceStartSec);+ setActiveEdge(null);+ }, [open, clip]);++ if (!clip) return null;++ const sourceDurationSec = Math.max(assetMeta?.durationSec ?? 0, clip.sourceEndSec ?? 0, 0.001);+ const durationSec = Math.max(0.001, draftEnd - draftStart);+ const hasChanges =+ Math.abs(draftStart - clip.sourceStartSec) > 0.001 ||+ Math.abs(draftEnd - (clip.sourceEndSec ?? 0)) > 0.001;+ const previewClip: AxcutClip = {+ ...clip,+ id: `${clip.id}:edit-preview`,+ sourceStartSec: draftStart,+ sourceEndSec: draftEnd,+ timelineStartSec: 0,+ timelineEndSec: durationSec,+ };+ const clipSources = videoSources.filter((s) => s.id === clip.assetId);++ const startDrag = (edge: "start" | "end", event: ReactPointerEvent<HTMLButtonElement>) => {+ const track = trackRef.current;+ if (!track) return;+ event.preventDefault();+ event.stopPropagation();+ const widthPx = Math.max(1, track.clientWidth);+ const startClientX = event.clientX;+ const startDraftStart = draftStart;+ const startDraftEnd = draftEnd;+ setActiveEdge(edge);+ const move = (moveEvent: PointerEvent) => {+ const deltaSec = ((moveEvent.clientX - startClientX) / widthPx) * sourceDurationSec;+ if (edge === "start") {+ setDraftStart(Math.min(Math.max(startDraftStart + deltaSec, 0), startDraftEnd - 0.05));+ } else {+ setDraftEnd(+ Math.max(Math.min(startDraftEnd + deltaSec, sourceDurationSec), startDraftStart + 0.05),+ );+ }+ };+ const end = () => {+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", end);+ setActiveEdge(null);+ };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", end, { once: true });+ };++ const handleReset = () => {+ setDraftStart(clip.sourceStartSec);+ setDraftEnd(clip.sourceEndSec ?? clip.sourceStartSec);+ };+ const handleApply = () => {+ onApply(draftStart, draftEnd);+ onClose();+ };++ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title="Edit clip"+ subtitle={assetMeta?.label ?? undefined}+ wide+ >+ <div+ style={{+ height: 220,+ marginBottom: 16,+ borderRadius: "var(--r-md)",+ overflow: "hidden",+ background: "var(--surface-2)",+ }}+ >+ <VirtualPreview videoSources={clipSources} clips={[previewClip]} />+ </div>++ <div style={{ display: "flex", gap: 24, marginBottom: 16 }}>+ <RangeStat label="Start" value={formatSeconds(draftStart)} />+ <RangeStat label="End" value={formatSeconds(draftEnd)} />+ <RangeStat label="Duration" value={formatSeconds(durationSec)} />+ </div>++ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ font: "500 10px/1.4 var(--font-mono)",+ color: "var(--muted)",+ marginBottom: 4,+ }}+ >+ <span>0:00.0</span>+ <span>{formatSeconds(sourceDurationSec)}</span>+ </div>+ <div+ ref={trackRef}+ style={{+ position: "relative",+ height: 32,+ background: "var(--surface-2)",+ borderRadius: "var(--r-sm)",+ }}+ >+ <div+ style={{+ position: "absolute",+ inset: 0,+ width: `${(draftStart / sourceDurationSec) * 100}%`,+ background: "var(--overlay-dark)",+ borderRadius: "var(--r-sm) 0 0 var(--r-sm)",+ }}+ />+ <div+ className={activeEdge ? styles.editClipRangeDragging : undefined}+ style={{+ position: "absolute",+ top: 0,+ bottom: 0,+ left: `${(draftStart / sourceDurationSec) * 100}%`,+ width: `${Math.max(0.5, (durationSec / sourceDurationSec) * 100)}%`,+ background: "var(--accent-wash)",+ border: "1px solid var(--accent)",+ borderRadius: "var(--r-sm)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <button+ type="button"+ onPointerDown={(e) => startDrag("start", e)}+ aria-label="Adjust clip start"+ title="Adjust clip start"+ style={{+ position: "absolute",+ left: -6,+ top: 0,+ bottom: 0,+ width: 12,+ cursor: "ew-resize",+ background: "var(--accent)",+ border: 0,+ borderRadius: 3,+ padding: 0,+ }}+ />+ <span+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--accent-on)",+ pointerEvents: "none",+ whiteSpace: "nowrap",+ }}+ >+ {formatSeconds(draftStart)}–{formatSeconds(draftEnd)}+ </span>+ <button+ type="button"+ onPointerDown={(e) => startDrag("end", e)}+ aria-label="Adjust clip end"+ title="Adjust clip end"+ style={{+ position: "absolute",+ right: -6,+ top: 0,+ bottom: 0,+ width: 12,+ cursor: "ew-resize",+ background: "var(--accent)",+ border: 0,+ borderRadius: 3,+ padding: 0,+ }}+ />+ </div>+ <div+ style={{+ position: "absolute",+ top: 0,+ bottom: 0,+ right: 0,+ width: `${Math.max(0, ((sourceDurationSec - draftEnd) / sourceDurationSec) * 100)}%`,+ background: "var(--overlay-dark)",+ borderRadius: "0 var(--r-sm) var(--r-sm) 0",+ }}+ />+ </div>++ <div+ style={{+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ paddingTop: 16,+ marginTop: 16,+ borderTop: "1px solid var(--border-soft)",+ }}+ >+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={handleReset}+ disabled={!hasChanges}+ >+ Reset+ </button>+ <div style={{ display: "flex", gap: 8 }}>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onClose}+ >+ Cancel+ </button>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={handleApply}+ disabled={!hasChanges}+ >+ <Pencil size={14} />+ Apply+ </button>+ </div>+ </div>+ </ModalShell>+ );+}++function RangeStat({ label, value }: { label: string; value: string }) {+ return (+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>+ <strong style={{ font: "600 15px/1.2 var(--font-mono)", color: "var(--fg)" }}>{value}</strong>+ <small style={{ font: "500 10px/1.4 var(--font-body)", color: "var(--muted)" }}>+ {label}+ </small>+ </div>+ );+}+export type UnsavedChoice = "save" | "discard" | "cancel";interface UnsavedChangesModalProps extends BaseModalProps {diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssindex 61618f4fa..acee676c0 100644--- a/src/components/ai-edition/NewEditorShell.module.css+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -1330,6 +1330,186 @@background: var(--bg);overflow: hidden;}++/* Region lanes (annotations / speed / zoom) inside the timeline body. */+/* Lanes: fixed-width label column + one shared dnd-timeline surface column.+ Both columns lay out 3 rows independently but with identical height (22px)+ + gap (2px), so they line up without needing CSS grid row-spanning. */+.lanes {+ display: flex;+ gap: 8px;+ padding: 4px var(--sp-4) 2px;+ flex-shrink: 0;+ border-bottom: 1px solid var(--border-soft);+}+.laneLabelCol {+ width: 64px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.laneLabelCell {+ height: 22px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 4px;+}+.laneLabel {+ font: 600 10px/1 var(--font-mono);+ color: var(--meta);+ letter-spacing: 0.04em;+ text-transform: uppercase;+}+.laneMeta {+ font: 500 10.5px/1 var(--font-mono);+ color: var(--muted);+ min-width: 12px;+ text-align: right;+}+.laneDelete {+ width: 18px;+ height: 18px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: var(--r-xs);+ background: var(--danger-soft);+ color: var(--danger);+ font-size: 13px;+ line-height: 1;+ cursor: pointer;+}+.laneDelete:hover {+ filter: brightness(0.95);+}+.laneSurface {+ flex: 1;+ min-width: 0;+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.laneTrackRow {+ position: relative;+ height: 22px;+ background: var(--surface-2);+ border: 1px dashed var(--border-soft);+ border-radius: var(--r-sm);+ overflow: hidden;+}+.laneEmpty {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ font: 500 11px/1 var(--font-body);+ color: var(--muted);+ opacity: 0.6;+ pointer-events: none;+}++/* Lane pills: zoom / speed / annotation. Visuals match the design — tab caps+ * on each side, frame color per kind, gradient sheen on top. */+.zoomPill,+.speedPill,+.annotationPill {+ --_pill: var(--accent);+ position: absolute;+ top: 50%;+ transform: translateY(-50%);+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ background: linear-gradient(+ 180deg,+ color-mix(in oklch, var(--_pill) 14%, var(--bg)) 0%,+ color-mix(in oklch, var(--_pill) 6%, var(--bg)) 60%,+ var(--bg) 100%+ );+ border: 1.5px solid var(--_pill);+ border-radius: var(--r-md);+ color: var(--fg);+ font: 600 11px/1 var(--font-display);+ letter-spacing: 0.01em;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+ pointer-events: auto;+ box-shadow:+ 0 4px 12px -8px color-mix(in oklch, var(--_pill) 60%, transparent),+ inset 0 1px 0 color-mix(in oklch, var(--_pill) 30%, transparent);+ cursor: pointer;+ z-index: 2;+}+.zoomPill {+ --_pill: var(--accent);+}+.speedPill {+ --_pill: var(--speed);+}+.annotationPill {+ --_pill: var(--annotation);+}+.lanePillSelected {+ box-shadow:+ 0 4px 12px -8px color-mix(in oklch, var(--_pill) 60%, transparent),+ inset 0 1px 0 color-mix(in oklch, var(--_pill) 30%, transparent),+ 0 0 0 3px color-mix(in oklch, var(--_pill) 35%, transparent);+}+.lanePillSelected::before,+.lanePillSelected::after {+ background: color-mix(in oklch, var(--_pill) 80%, var(--bg));+ box-shadow:+ 0 0 0 1px var(--bg),+ 0 2px 6px -2px color-mix(in oklch, var(--_pill) 65%, transparent);+}+/* tab caps at the ends */+.zoomPill::before,+.zoomPill::after,+.speedPill::before,+.speedPill::after,+.annotationPill::before,+.annotationPill::after {+ content: "";+ position: absolute;+ top: 50%;+ width: 6px;+ height: 14px;+ background: var(--_pill);+ border-radius: 3px;+ transform: translateY(-50%);+ pointer-events: none;+ z-index: 1;+ box-shadow:+ 0 0 0 1px var(--bg),+ 0 2px 6px -2px color-mix(in oklch, var(--_pill) 55%, transparent);+}+.zoomPill::before,+.speedPill::before,+.annotationPill::before {+ left: -4px;+}+.zoomPill::after,+.speedPill::after,+.annotationPill::after {+ right: -4px;+}+.pillIcon {+ width: 11px;+ height: 11px;+ flex-shrink: 0;+ color: color-mix(in oklch, var(--_pill) 70%, var(--fg));+}+.pillValue {+ color: var(--fg);+ font-variant-numeric: tabular-nums;+}+.timelineHead {display: flex;align-items: center;@@ -1430,6 +1610,12 @@flex-shrink: 0;border-top: 1px solid var(--border-soft);}++/* T11 — Navigator strip. Moved to TimelinePane.module.css so the+ className (applied via TimelinePane's own styles import) actually+ matches the CSS. CSS modules' class hashes don't match across+ files. The shape and the elements are unchanged from axcut's+ .timeline-navigator / .timeline-navigator-window. */.zoombar .zoomTrack {position: relative;height: 18px;@@ -1447,6 +1633,46 @@pointer-events: none;}+/* Radix Slider — visible two-handle range, design-aligned. */+.sliderRoot {+ position: relative;+ display: flex;+ align-items: center;+ height: 18px;+ width: 100%;+ touch-action: none;+ user-select: none;+}+.sliderTrack {+ position: relative;+ height: 6px;+ width: 100%;+ background: var(--surface-2);+ border-radius: 3px;+ overflow: hidden;+}+.sliderRange {+ position: absolute;+ height: 100%;+ background: var(--accent);+ border-radius: 3px;+}+.sliderThumb {+ display: block;+ width: 14px;+ height: 14px;+ background: var(--accent);+ border: 1px solid var(--bg);+ border-radius: 3px;+ cursor: ew-resize;+ transition: box-shadow var(--motion-fast) var(--ease);+}+.sliderThumb:hover,+.sliderThumb:focus-visible {+ outline: none;+ box-shadow: 0 0 0 4px color-mix(in oklch, var(--accent) 22%, transparent);+}+/* ─── modals ───────────────────────────────────────────────────── */.modal {position: fixed;@@ -1544,6 +1770,11 @@cursor: not-allowed;}+/* ─── Edit Clip modal — draggable source-range track ────────────── */+.editClipRangeDragging {+ box-shadow: 0 0 0 2px var(--accent-soft);+}+/* ─── media card (left panel media list) ───────────────────────── */.mediaList {list-style: none;diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex f7ffc323e..985555571 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -4,13 +4,14 @@ 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 { useShortcuts } from "@/contexts/ShortcutsContext";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 { PLACEHOLDER_DURATION_SEC, useTimeline } from "@/lib/ai-edition/store/useTimeline";import { nativeBridgeClient } from "@/native";import type { AiEditionProjectSummary } from "@/native/contracts";import { Bottombar } from "./Bottombar";@@ -19,7 +20,6 @@ import { LeftPanel, LeftRail, type LeftTab } from "./LeftPanel";import {AutoCaptionsModal,CropModal,- InsertSourceModal,NewProjectModal,OpenProjectModal,UnsavedChangesModal,@@ -46,7 +46,6 @@ const COLLAPSE_INITIAL = {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);@@ -76,10 +75,11 @@ export function NewEditorShell() {const [cropOpen, setCropOpen] = useState(false);const [exportOpen, setExportOpen] = useState(false);const [unsavedPrompt, setUnsavedPrompt] = useState<{- action: "new" | "open" | "record";+ action: "close" | "new" | "open" | "record";resolve: (choice: UnsavedChoice) => void;} | null>(null);const { settings: editorSettings, set: setEditorSettings } = useEditorSettings();+ const { openConfig: openShortcutsConfig } = useShortcuts();const tl = useTimeline();useUndoRedoShortcuts(() => {// ponytail: placeholder, wire when undo stack merges with history@@ -87,13 +87,22 @@ export function NewEditorShell() {const [captionsOpen, setCaptionsOpen] = useState(false);const [captionsMinW, setCaptionsMinW] = useState(2);const [captionsMaxW, setCaptionsMaxW] = useState(7);- const [insertAssetId, setInsertAssetId] = useState<string | null>(null);+ const [copiedClipId, setCopiedClipId] = useState<string | null>(null);const [projectSummaries, setProjectSummaries] = useState<AiEditionProjectSummary[]>([]);+ // T15 — Place-skip mode is owned by Bottombar (it owns the+ // body-class effect, the Esc-to-cancel, the preview-pin). The+ // keyboard shortcut ("T") here needs to toggle the same state, so+ // we expose it as a ref. Refs are used (not state) so the keyboard+ // handler doesn't need to re-bind on every change.+ const togglePlaceSkipRef = useRef<() => void>(() => undefined);+ const setTogglePlaceSkip = useCallback((fn: () => void) => {+ togglePlaceSkipRef.current = fn;+ }, []);const seekSeqRef = useRef(0);const initRef = useRef(false);const promptUnsaved = useCallback(- (action: "new" | "open" | "record"): Promise<UnsavedChoice> => {+ (action: "close" | "new" | "open" | "record"): Promise<UnsavedChoice> => {if (!dirty) return Promise.resolve("discard");return new Promise<UnsavedChoice>((resolve) => {setUnsavedPrompt({ action, resolve });@@ -142,6 +151,18 @@ export function NewEditorShell() {const label = screenPath.split(/[\\/]/).pop() || "Recording";await createProject(`Recording ${new Date().toLocaleString()}`);await addAsset(screenPath, label);+ // ponytail: MediaRecorder WebMs ship with duration = NaN until+ // fix-webm-duration patches the EBML header; until that flows+ // through the asset, drop a default 60s clip into the timeline+ // so the editor isn't stuck on "No clips yet" the moment the+ // user lands in the project. Real duration overwrites this+ // when handleLoadedMetadata fires with a finite value.+ const doc = useProjectStore.getState().document;+ if (doc && doc.timeline.clips.length === 0 && doc.assets.length > 0) {+ await useProjectStore+ .getState()+ .replaceTimeline([{ startSec: 0, endSec: 60 }], "Auto-imported recording");+ }toast.success("Recording added to a new project");} catch (err) {toast.error("Could not auto-create project from recording", {@@ -177,7 +198,7 @@ export function NewEditorShell() {// 2. Handle request-close-confirm from Electronconst unsubCloseConfirm = window.electronAPI.onRequestCloseConfirm(() => {void (async () => {- const choice = await promptUnsaved("new"); // Use "new" as a generic action for close+ const choice = await promptUnsaved("close");if (choice === "discard") {window.electronAPI.sendCloseConfirmResponse("discard");} else if (choice === "save") {@@ -219,21 +240,56 @@ export function NewEditorShell() {}, [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",- );- }+ (durationSec: number, assetId: string) => {+ // ponytail: WebM recordings from MediaRecorder report NaN/Infinity+ // until the main-process EBML fix lands. Fall back to a 60s seed if+ // duration is unknown so the timeline never gets stuck on an empty+ // placeholder. All store reads go through getState() to avoid+ // stale-closure bugs.+ const known = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : 60;+ const state = useProjectStore.getState();+ setSourceDuration(known);+ const doc = state.document;+ if (!doc || doc.assets.length === 0) return;+ if (doc.timeline.clips.length === 0) {+ void state.replaceTimeline(+ [{ startSec: 0, endSec: known }],+ "Auto-created full-duration clip",+ );+ return;}+ // Only correct clips belonging to the asset that actually fired this+ // event, and only while they still sit at the pre-probe 0..60s+ // placeholder — never a clip the user has since trimmed. Patching by+ // array index (the previous behavior) clobbered clip[0]'s duration+ // whenever a *different* asset's video element loaded, e.g. right+ // after dropping a second clip onto the timeline.+ const isPlaceholder = (c: (typeof doc.timeline.clips)[number]) =>+ c.assetId === assetId &&+ c.sourceStartSec === 0 &&+ Math.abs((c.sourceEndSec ?? 0) - PLACEHOLDER_DURATION_SEC) < 0.01;+ if (Math.abs(known - PLACEHOLDER_DURATION_SEC) < 0.01) return;+ if (!doc.timeline.clips.some(isPlaceholder)) return;++ let shiftSec = 0;+ const nextClips = doc.timeline.clips.map((c) => {+ const shifted = { ...c, timelineStartSec: c.timelineStartSec + shiftSec };+ if (!isPlaceholder(c)) {+ shifted.timelineEndSec = c.timelineEndSec + shiftSec;+ return shifted;+ }+ const delta = known - PLACEHOLDER_DURATION_SEC;+ shifted.sourceEndSec = known;+ shifted.timelineEndSec = shifted.timelineStartSec + known;+ shiftSec += delta;+ return shifted;+ });+ void state.saveDocument({+ ...doc,+ timeline: { ...doc.timeline, clips: nextClips },+ });},- [document, replaceTimeline, setSourceDuration],+ [setSourceDuration],);const handleSeek = useCallback(@@ -251,13 +307,6 @@ export function NewEditorShell() {[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;@@ -455,15 +504,9 @@ export function NewEditorShell() {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.",- );- }, []);+ openShortcutsConfig();+ }, [openShortcutsConfig]);const pasteRegion = useCallback(async () => {const doc = useProjectStore.getState().document;@@ -526,30 +569,6 @@ export function NewEditorShell() {}}, [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.");@@ -677,13 +696,28 @@ export function NewEditorShell() {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() === "c") {+ if (tl.clipSelection) {+ e.preventDefault();+ setCopiedClipId(tl.clipSelection);+ return;+ }+ if (tl.selection) {+ e.preventDefault();+ void handleCopyRegion();+ return;+ }}if (ctrl && e.key.toLowerCase() === "v") {e.preventDefault();+ // A selected/copied clip takes priority — pasting with a clip in+ // hand is unambiguously "duplicate this clip", even if a region+ // was copied earlier in the session.+ const clipToDuplicate = copiedClipId ?? tl.clipSelection;+ if (clipToDuplicate) {+ void tl.duplicateClip(clipToDuplicate);+ return;+ }void pasteRegion();return;}@@ -715,7 +749,7 @@ export function NewEditorShell() {break;case "t":e.preventDefault();- void tl.addSkip();+ togglePlaceSkipRef.current();break;case "a":e.preventDefault();@@ -729,7 +763,16 @@ export function NewEditorShell() {};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [hasProject, handleCopyRegion, handleSave, pasteRegion, tl, promptUnsaved, saveDocument]);+ }, [+ hasProject,+ handleCopyRegion,+ handleSave,+ pasteRegion,+ tl,+ promptUnsaved,+ saveDocument,+ copiedClipId,+ ]);const collapseAttr = useMemo(() => {const list: string[] = [];@@ -765,14 +808,7 @@ export function NewEditorShell() {}}/>- <main- className={styles.workbench}- onDragOver={(e) => {- e.preventDefault();- e.dataTransfer.dropEffect = "copy";- }}- onDrop={handleDropOnTimeline}- >+ <main className={styles.workbench}>{/* Left rail */}<LeftRail active={leftTab} onChange={setLeftTab} />@@ -847,10 +883,9 @@ export function NewEditorShell() {{!bottomCollapsed ? (<Bottombarclips={clips}+ videoSources={videoSources}currentTimeSec={currentTimeSec}- sourceDurationSec={sourceDurationSec}- onPreviewSource={handlePreviewSource}- onReplaceTimeline={handleReplaceTimeline}+ onSeek={handleSeek}zoomRegions={tl.zoomRegions}skipRanges={tl.skipRanges}annotationRegions={tl.annotationRegions}@@ -858,11 +893,10 @@ export function NewEditorShell() {selection={tl.selection}hasDoc={tl.hasDoc}onAddZoom={() => void tl.addZoom()}- onAddSkip={() => void tl.addSkip()}onAddAnnotation={() => void tl.addAnnotation()}onAddSpeed={() => void tl.addSpeed()}+ setTogglePlaceSkip={setTogglePlaceSkip}onSelectRegion={(kind, id) => tl.selectRegion(kind, id)}- onRemoveRegion={(kind, id) => void tl.removeRegion(kind, id)}onCaptions={handleCaptions}/>) : null}@@ -906,17 +940,6 @@ export function NewEditorShell() {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>);}diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsxindex e8cfba1e1..bfdee40f2 100644--- a/src/components/ai-edition/Preview.tsx+++ b/src/components/ai-edition/Preview.tsx@@ -14,7 +14,7 @@ interface PreviewProps {seekTarget: { timeSec: number; requestId: number } | null;onTimeChange: (sec: number) => void;onSeek: (sec: number) => void;- onLoadedMetadata: (sec: number) => void;+ onLoadedMetadata: (sec: number, assetId: string) => void;onVideoElement: (el: HTMLVideoElement | null) => void;currentTimeSec: number;}diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 7bd8a7afc..2859e0091 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -43,7 +43,7 @@ interface PreviewCanvasProps {seekTarget: { timeSec: number; requestId: number } | null;onTimeChange: (sec: number) => void;onSeek: (sec: number) => void;- onLoadedMetadata: (sec: number) => void;+ onLoadedMetadata: (sec: number, assetId: string) => void;onVideoElement: (el: HTMLVideoElement | null) => void;currentTimeSec: number;onVideoError?: () => void;diff --git a/src/components/ai-edition/ProjectPanel.tsx b/src/components/ai-edition/ProjectPanel.tsxdeleted file mode 100644index d2f8243f9..000000000--- a/src/components/ai-edition/ProjectPanel.tsx+++ /dev/null@@ -1,225 +0,0 @@-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/RegionTimeline.tsx b/src/components/ai-edition/RegionTimeline.tsxnew file mode 100644index 000000000..c12fe0f20--- /dev/null+++ b/src/components/ai-edition/RegionTimeline.tsx@@ -0,0 +1,250 @@+import {+ type DragEndEvent,+ type ResizeEndEvent,+ type Span,+ TimelineContext,+ useItem,+ useRow,+ useTimelineContext,+} from "dnd-timeline";++export type { Span };++import { useCallback } from "react";+import styles from "./NewEditorShell.module.css";++// Zoom/annotation/speed lanes, made draggable + resizable via dnd-timeline+// (already a dependency — see OpenScreen's old TimelineWrapper.tsx/Item.tsx/+// Row.tsx on `main` for the reference this ports). Scoped down from that+// reference: clamp-to-bounds + collision-clamp against sibling spans are+// ported, but the snap-guide and floating drag tooltip are not (follow-up).++const MIN_ITEM_DURATION_MS = 100;++interface RegionSpanRef {+ id: string;+ start: number;+ end: number;+}++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++interface RegionTimelineProviderProps {+ totalMs: number;+ // Spans that must not overlap each other (zoom, speed). Annotation spans+ // are intentionally excluded — multiple annotations may overlap.+ collidableSpans: RegionSpanRef[];+ onItemSpanChange: (id: string, span: Span) => void;+ children: React.ReactNode;+}++export function RegionTimelineProvider({+ totalMs,+ collidableSpans,+ onItemSpanChange,+ children,+}: RegionTimelineProviderProps) {+ const safeTotalMs = Math.max(totalMs, 1);++ const clampSpanToBounds = useCallback(+ (span: Span): Span => {+ const rawDuration = Math.max(span.end - span.start, 0);+ const duration = Math.min(Math.max(rawDuration, MIN_ITEM_DURATION_MS), safeTotalMs);+ const start = clamp(span.start, 0, safeTotalMs - duration);+ return { start, end: start + duration };+ },+ [safeTotalMs],+ );++ const isCollidable = useCallback(+ (id: string) => collidableSpans.some((r) => r.id === id),+ [collidableSpans],+ );++ const hasOverlap = useCallback(+ (span: Span, excludeId: string) =>+ collidableSpans.some((r) => r.id !== excludeId && span.end > r.start && span.start < r.end),+ [collidableSpans],+ );++ const clampToNeighbours = useCallback(+ (span: Span, activeItemId: string): Span => {+ const siblings = collidableSpans.filter((r) => r.id !== activeItemId);+ let { start, end } = span;+ for (const r of siblings) {+ if (end > r.start && start < r.start) end = r.start;+ if (start < r.end && end > r.end) start = r.end;+ }+ if (end - start < MIN_ITEM_DURATION_MS) {+ if (end + MIN_ITEM_DURATION_MS - (end - start) <= safeTotalMs) {+ end = start + MIN_ITEM_DURATION_MS;+ } else {+ start = end - MIN_ITEM_DURATION_MS;+ }+ }+ return { start: Math.max(0, start), end: Math.min(end, safeTotalMs) };+ },+ [collidableSpans, safeTotalMs],+ );++ const resolveSpan = useCallback(+ (rawSpan: Span, activeItemId: string): Span | null => {+ let span = clampSpanToBounds(rawSpan);+ if (isCollidable(activeItemId) && hasOverlap(span, activeItemId)) {+ span = clampToNeighbours(span, activeItemId);+ if (hasOverlap(span, activeItemId)) return null;+ }+ return span;+ },+ [clampSpanToBounds, clampToNeighbours, hasOverlap, isCollidable],+ );++ const onResizeEnd = useCallback(+ (event: ResizeEndEvent) => {+ const updatedSpan = event.active.data.current.getSpanFromResizeEvent?.(event);+ if (!updatedSpan) return;+ const activeItemId = event.active.id as string;+ const span = resolveSpan(updatedSpan, activeItemId);+ if (span) onItemSpanChange(activeItemId, span);+ },+ [onItemSpanChange, resolveSpan],+ );++ const onDragEnd = useCallback(+ (event: DragEndEvent) => {+ if (!event.over) return;+ const updatedSpan = event.active.data.current.getSpanFromDragEvent?.(event);+ if (!updatedSpan) return;+ const activeItemId = event.active.id as string;+ const span = resolveSpan(updatedSpan, activeItemId);+ if (span) onItemSpanChange(activeItemId, span);+ },+ [onItemSpanChange, resolveSpan],+ );++ return (+ <TimelineContext+ range={{ start: 0, end: safeTotalMs }}+ // Range is read-only for the regions surface (zoom/pan live on the clip track).+ onRangeChanged={() => {+ // intentionally empty+ }}+ onResizeEnd={onResizeEnd}+ onDragEnd={onDragEnd}+ >+ {children}+ </TimelineContext>+ );+}++export function RegionTimelineSurface({+ pxPerSec,+ totalMs,+ children,+}: {+ // Lane pill positions come from dnd-timeline in ms, and the library maps+ // 1 px = range / timelineWidth. We set the surface width to totalMs*pxPerSec+ // so dnd-timeline naturally maps 1 ms = pxPerSec/1000 px — same as the+ // timeline ruler ticks — keeping pills aligned with the clip track at any+ // zoom. Lanes do not share the clip track's horizontal-scroll container;+ // at very long timelines (>30s) they sit fully visible while the clip+ // track scrolls. See roadmap P3 for the full shared-scroll follow-up.+ pxPerSec: number;+ totalMs: number;+ children: React.ReactNode;+}) {+ const { setTimelineRef, style } = useTimelineContext();+ return (+ <div+ ref={setTimelineRef}+ style={{+ ...style,+ position: "relative",+ width: (Math.max(totalMs, 1) * pxPerSec) / 1000,+ }}+ className={styles.laneSurface}+ >+ {children}+ </div>+ );+}++export function RegionRow({+ id,+ empty,+ children,+}: {+ id: string;+ empty?: string;+ children: React.ReactNode;+}) {+ const { setNodeRef, rowStyle, rowWrapperStyle } = useRow({ id });+ return (+ <div style={rowWrapperStyle} className={styles.laneTrackRow}>+ {empty ? <span className={styles.laneEmpty}>{empty}</span> : null}+ <div ref={setNodeRef} style={rowStyle}>+ {children}+ </div>+ </div>+ );+}++interface RegionItemProps {+ id: string;+ rowId: string;+ span: Span;+ label: string;+ icon: React.ReactNode;+ selected: boolean;+ onSelect: () => void;+ variant: "zoom" | "annotation" | "speed";+}++export function RegionItem({+ id,+ rowId,+ span,+ label,+ icon,+ selected,+ onSelect,+ variant,+}: RegionItemProps) {+ const { setNodeRef, listeners, attributes, itemStyle, itemContentStyle } = useItem({+ id,+ span,+ data: { rowId },+ });+ const pillClass =+ variant === "zoom"+ ? styles.zoomPill+ : variant === "speed"+ ? styles.speedPill+ : styles.annotationPill;+ return (+ <div+ ref={setNodeRef}+ style={{ ...itemStyle, height: "100%", minWidth: 12 }}+ {...listeners}+ {...attributes}+ onPointerDownCapture={onSelect}+ >+ <div style={{ ...itemContentStyle, height: "100%", minWidth: 24 }}>+ <div+ className={selected ? `${pillClass} ${styles.lanePillSelected}` : pillClass}+ // The pill's own CSS is written for absolute left/top-50% placement+ // inside the old static `.laneTrack`; here dnd-timeline's outer+ // divs already own absolute positioning + width, so the pill just+ // fills that box.+ style={{ position: "relative", top: 0, transform: "none", width: "100%", height: "100%" }}+ title={label}+ >+ {icon}+ <span className={styles.pillValue}>{label}</span>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/ai-edition/TimelinePane.module.css b/src/components/ai-edition/TimelinePane.module.cssindex 6c3db76c2..30885b473 100644--- a/src/components/ai-edition/TimelinePane.module.css+++ b/src/components/ai-edition/TimelinePane.module.css@@ -1,304 +1,588 @@+/* Timeline viewport — custom scroll/pan model (NOT native overflow). The+ outer viewport is overflow: hidden; the inner .canvas uses+ transform: translateX(...) to pan, and its width is totalDuration *+ pxPerSec. This lets the lanes (T10) share the same coordinate space+ when they move into the canvas. Mirrors axcut TimelinePane.tsx's+ .timeline-viewport / .timeline-canvas. */+.pane {+ position: relative;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;+ min-height: 0;+ height: 100%;}-.heading {- font-size: 0.875rem;- font-weight: 600;- margin: 0;- color: var(--card-foreground);- text-transform: uppercase;- letter-spacing: 0.025em;+.viewport {+ position: relative;+ flex: 1 1 auto;+ min-height: 0;+ overflow: hidden;+ cursor: pointer;+ /* ponytail: scrollbar hidden — the navigator strip (T11) is the+ scroll/zoom UI; we don't want native scroll chrome leaking in. */+ scrollbar-width: none;}--.meta {- font-size: 0.75rem;- color: var(--muted-foreground);- margin: 0;+.viewport::-webkit-scrollbar {+ display: none;}--.readout {- display: flex;- align-items: center;- gap: 0.625rem;- font-size: 0.8125rem;+.viewport.panning {+ cursor: grabbing;}--.muted {- color: var(--muted-foreground);+.viewport.reordering {+ cursor: grabbing;}--.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;+.viewport.scrubbing {+ cursor: ew-resize;}--.tool:hover:not(:disabled) {- background: var(--accent);+.viewport.placingCut {+ cursor: crosshair;}-.tool:disabled {- opacity: 0.5;- cursor: not-allowed;+/* T16 — body-level cursor classes that override child cursors while a+ timeline interaction is active. */+body.timeline-scrubbing,+body.timeline-scrubbing * {+ cursor: ew-resize !important;+}+body.timeline-panning,+body.timeline-panning * {+ cursor: grabbing !important;+}+body.timeline-reordering,+body.timeline-reordering * {+ cursor: grabbing !important;+}+/* T15 — Place-skip cursor. The class is added via+ document.body.classList.add() in Bottombar (raw string), so the+ selector MUST use :global() — otherwise CSS modules would hash+ `.timeline-placing-cut` and the rule would never match. Same hash+ issue as the navigator CSS had. The `*` selector cascades to+ every descendant with the body class applied. */+body:global(.timeline-placing-cut),+body:global(.timeline-placing-cut) * {+ cursor: crosshair !important;+}+/* Same problem on the specific element overrides. */+body:global(.timeline-placing-cut) .trackBlock,+body:global(.timeline-placing-cut) .trackBlock:active,+body:global(.timeline-placing-cut) .skipControlBtn,+body:global(.timeline-placing-cut) .editIcon,+body:global(.timeline-placing-cut) .clipDelete,+body:global(.timeline-placing-cut) .trackBlock .segment,+body:global(.timeline-placing-cut) .reorderMarker,+body:global(.timeline-placing-cut) .dropMarker,+body:global(.timeline-placing-cut) .timelineHeader,+body:global(.timeline-placing-cut) .timelineHeader *,+body:global(.timeline-placing-cut) button,+body:global(.timeline-placing-cut) [class*="vtBtn"] {+ cursor: crosshair !important;}-.navigatorRow {+.canvas {+ position: relative;+ height: 100%;+ min-width: 100%;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;+ flex-direction: column;+ /* T15 — these tokens drive the playhead + placement-marker top+ offsets. The marker/playhead use a calc(-1 * (--rule-h + --lanes-h))+ to land inside the timing ruler regardless of lane-count changes. */+ --rule-h: 22px;+ --lanes-h: 78px;+ will-change: transform;}-.navigator {+.ruler {position: relative;- flex: 1;- height: 24px;- border-radius: 0.25rem;- background: var(--background);- border: 1px solid var(--border);- overflow: hidden;- cursor: pointer;+ height: 22px;+ border-bottom: 1px solid var(--border-soft);+ user-select: none;+ cursor: text;}--.navigatorContent {+.tick {position: absolute;- inset: 0;+ top: 0;+ bottom: 0;+ width: 1px;+ background: var(--border-hi);}--.navigatorCut {+.tick.major::before {+ content: "";position: absolute;- top: 4px;- bottom: 4px;- background: var(--destructive);- opacity: 0.3;- border-radius: 2px;+ left: 0;+ bottom: -4px;+ width: 2px;+ height: 4px;+ background: var(--border-hi);}--.navigatorWindow {+.tick span {position: absolute;+ left: 2px;top: 0;- bottom: 0;- background: var(--primary);- opacity: 0.15;- border: 1px solid var(--primary);- border-radius: 2px;- cursor: grab;+ font-family: var(--font-mono);+ font-size: 11px;+ font-weight: 500;+ letter-spacing: 0.02em;+ color: var(--muted);+ white-space: nowrap;+ pointer-events: none;}-.navigatorHandle {- position: absolute;- top: 0;- bottom: 0;- width: 4px;- background: var(--primary);- border-radius: 1px;- cursor: ew-resize;+.lanesContainer {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 4px 0 2px;+ border-bottom: 1px solid var(--border-soft);+ flex-shrink: 0;}-.navigatorHandle.start {- left: -2px;+.trackLane {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 4px 0;+ min-height: 0;+ flex: 1 1 auto;}-.navigatorHandle.end {- right: -2px;+.trackBlock {+ position: absolute;+ top: 4px;+ height: calc(100% - 8px);+ min-width: 68px;+ display: flex;+ flex-direction: column;+ background: var(--surface-2);+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ box-shadow: var(--elev-card-soft);+ cursor: grab;+ overflow: hidden;+ transition:+ border-color var(--motion-fast) var(--ease),+ box-shadow var(--motion-fast) var(--ease);}--.viewport {- position: relative;- overflow-x: auto;- overflow-y: hidden;- flex: 1;- min-height: 80px;- cursor: crosshair;- user-select: none;+.trackBlock:hover {+ border-color: var(--border-hi);}--.viewport.panning {+.trackBlock:active {cursor: grabbing;}--.viewport.scrubbing {- cursor: grabbing;+.trackBlock.selected {+ border-color: var(--accent);+ box-shadow: 0 0 0 1px var(--accent), 0 4px 12px -4px var(--accent-soft);}--.canvas {- position: relative;- min-height: 100%;+.trackBlock.reordering {+ opacity: 0.85;+ box-shadow: 0 8px 24px -8px rgba(0, 0, 0, 0.45);+ z-index: 20;}-.ruler {- position: relative;- border-bottom: 1px solid var(--border);+.trackVisual {+ flex: 0 0 auto;+ height: 26px;+ display: flex;overflow: hidden;+ background: var(--surface);+ border-bottom: 1px solid var(--border);}--.tick {- position: absolute;- top: 0;- bottom: 0;- width: 1px;- background: var(--border);+.segment {+ height: 100%;+ flex-basis: 0;}--.tickMajor {- background: var(--muted-foreground);+.segment.keep {+ background: transparent;}--.tickMajor span {- position: absolute;- top: 4px;- left: 4px;- font-size: 0.625rem;- color: var(--muted-foreground);- white-space: nowrap;-}--.trackLane {+.segment.cut {position: relative;- height: 60px;- margin-top: 4px;+ background-color: var(--accent-wash);+ background-image: repeating-linear-gradient(+ 45deg,+ color-mix(in srgb, var(--accent) 32%, transparent) 0,+ color-mix(in srgb, var(--accent) 32%, transparent) 8px,+ transparent 8px,+ transparent 16px+ );}-.segment {+.skipControls {position: absolute;- top: 0;- bottom: 0;- border-radius: 0.25rem;+ top: 50%;+ left: 50%;+ transform: translate(+ calc(-50% + var(--skip-controls-shift-px, 0px)),+ -50%+ );display: flex;align-items: center;- overflow: hidden;+ gap: 2px;+ padding: 2px;+ background: var(--surface);+ border: 1px solid var(--border-soft);+ border-radius: var(--r-sm);+ box-shadow: var(--elev-card-soft);+ z-index: 20;+ white-space: nowrap;}--.kept {- background: var(--primary);- opacity: 0.25;+.skipControlBtn {+ width: 20px;+ height: 20px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: 0;+ border-radius: var(--r-xs);+ color: var(--muted);+ cursor: pointer;+ padding: 0;+ transition:+ background var(--motion-fast) var(--ease),+ color var(--motion-fast) var(--ease);}--.kept.active {- opacity: 0.45;+.skipControlBtn:hover {+ background: var(--surface-3);+ color: var(--fg);}--.cut {- background: var(--destructive);- opacity: 0.2;- border: 1px dashed var(--destructive);+.skipControlDelete:hover {+ background: var(--danger-soft);+ color: var(--danger);}-.cut.active {- opacity: 0.35;+.trackInfo {+ flex: 1;+ min-height: 0;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 12px;+ overflow: hidden;}--.segmentLabel {+.editIcon {+ flex: 0 0 auto;+ width: 30px;+ height: 30px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ color: var(--fg);+ box-shadow: var(--elev-card-soft);+ cursor: pointer;+ transition:+ border-color var(--motion-fast) var(--ease),+ color var(--motion-fast) var(--ease);+}+.editIcon:hover {+ border-color: var(--accent);+ color: var(--accent);+}+.trackText {display: flex;flex-direction: column;- gap: 0.125rem;- padding: 0 0.5rem;- font-size: 0.625rem;- color: var(--card-foreground);+ gap: 2px;+ min-width: 0;+ flex: 1;+}+.trackTitle {+ margin: 0;+ font-size: 13px;+ font-weight: 500;+ letter-spacing: -0.005em;+ color: var(--fg);white-space: nowrap;overflow: hidden;+ text-overflow: ellipsis;}--.segmentLabel small {- color: var(--muted-foreground);+.trackSubtitle {+ margin: 0;+ font-family: var(--font-mono);+ font-size: 10.5px;+ letter-spacing: 0.02em;+ color: var(--muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.trackSubtitle span {+ margin: 0 4px;+ color: var(--dim);+}+.clipDelete {+ flex: 0 0 auto;+ width: 26px;+ height: 26px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: 0;+ border-radius: var(--r-sm);+ color: var(--muted);+ cursor: pointer;+ opacity: 0;+ transition:+ background var(--motion-fast) var(--ease),+ color var(--motion-fast) var(--ease),+ opacity var(--motion-fast) var(--ease);+}+.trackBlock:hover .clipDelete,+.trackBlock.selected .clipDelete {+ opacity: 1;+}+.clipDelete:hover {+ background: var(--danger-soft);+ color: var(--danger);}-.cutHandle {+/* ── drop marker + playhead ────────────────────────────────────────── */+.dropMarker {position: absolute;top: 0;bottom: 0;- width: 8px;- background: var(--destructive);- opacity: 0.6;- border: none;- cursor: ew-resize;+ width: 2px;+ background: var(--accent);+ border-radius: 2px;+ box-shadow: 0 0 6px var(--accent-soft);+ pointer-events: none;+ z-index: 9;}-.cutHandle:hover {- opacity: 1;+/* T08 — live marker shown between clips while a reorder drag is active. */+.reorderMarker {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 4px;+ background: var(--accent);+ border-radius: 2px;+ box-shadow: 0 0 12px var(--accent-soft), 0 0 4px var(--accent);+ pointer-events: none;+ z-index: 30;}-.handleStart {- left: 0;- border-radius: 0.25rem 0 0 0.25rem;+/* T24 — thin vertical snap-guide lines at the resize edges during+ skip-edge drag. Shown in the ruler area (top: 0; height: 22px).+ Two of them, one per edge being dragged (axcut TimelinePane.tsx). */+.snapGuide {+ position: absolute;+ top: 0;+ height: var(--rule-h, 22px);+ width: 2px;+ background: var(--danger);+ box-shadow: 0 0 6px color-mix(in oklch, var(--danger) 60%, transparent);+ pointer-events: none;+ z-index: 14;}-.handleEnd {- right: 0;- border-radius: 0 0.25rem 0.25rem 0;+/* T25 — floating drag tooltip showing the new time range during skip+ resize. Sits just to the right of the moving edge so it doesn't+ overlap the snap guide. Pill style matches the chip typography+ used elsewhere in the ruler / header. */+.dragTooltip {+ position: absolute;+ top: 2px;+ height: 18px;+ padding: 0 8px;+ background: var(--surface);+ border: 1px solid var(--border-soft);+ border-radius: 9px;+ color: var(--fg-2);+ font: 500 10.5px/18px var(--font-mono);+ letter-spacing: 0.02em;+ white-space: nowrap;+ pointer-events: none;+ z-index: 15;+ box-shadow: var(--elev-card-soft);}-.cutDelete {+/* T15 — Place-skip preview marker: 1s-wide red-tinted strip at the+ cursor's source time. Indicates where the next click would land.+ Top matches the playhead's top (ruler + lanes above) so it spans+ the entire visible timeline: ruler above + clip tracks below. */+.placementMarker {position: absolute;- top: 2px;- right: 12px;+ top: calc(-1 * (var(--rule-h, 22px) + var(--lanes-h, 78px)));+ bottom: 0;+ width: 12px;+ margin-left: -6px;+ background: color-mix(in oklch, var(--danger) 50%, transparent);+ border-left: 2px solid var(--danger);+ border-right: 2px solid var(--danger);+ box-shadow: 0 0 8px color-mix(in oklch, var(--danger) 50%, transparent);+ pointer-events: none;+ z-index: 12;+}++/* T14 — Header row above the viewport: clip/skip/total readouts ++ Place-skip toggle + current timecode. */+.timelineHeader {display: flex;align-items: center;- justify-content: center;- width: 18px;- height: 18px;- border-radius: 0.25rem;- border: none;- background: var(--destructive);- color: white;+ gap: 8px;+ padding: 6px var(--sp-3) 6px var(--sp-3);+ border-bottom: 1px solid var(--border-soft);+ font: 500 11px/1 var(--font-mono);+ color: var(--muted);+ flex-shrink: 0;+}+.headerStat {+ letter-spacing: 0.02em;+}+.headerDivider {+ color: var(--dim);+}+.headerSpacer {+ flex: 1 1 auto;+}+.headerButton {+ height: 22px;+ padding: 0 10px;+ border: 1px solid var(--border-soft);+ border-radius: var(--r-sm);+ background: var(--surface-2);+ color: var(--fg-2);+ font: 500 11px/1 var(--font-body);cursor: pointer;- opacity: 0.7;+ transition:+ background var(--motion-fast) var(--ease),+ border-color var(--motion-fast) var(--ease);}--.cutDelete:hover {- opacity: 1;+.headerButton:hover {+ background: var(--surface-3);+ border-color: var(--border-hi);+}+.headerButton:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}+.headerButtonActive {+ background: var(--accent-wash);+ border-color: var(--accent);+ color: var(--accent);+}+.headerTime {+ font-variant-numeric: tabular-nums;+ color: var(--fg);+ min-width: 5ch;+ text-align: right;}.playhead {position: absolute;- top: 0;+ /* Top: -(ruler + lanes) so the diamond head (::before, 8px tall,+ at top: 0) lands inside the .ruler (22px tall) at the very top of+ the canvas, not in the zoom/speed/annotation lanes below it.+ The vertical line still extends down through the canvas into the+ trackLane. */+ top: calc(-1 * (var(--rule-h, 22px) + var(--lanes-h, 78px)));bottom: 0;width: 2px;- background: var(--primary);+ background: var(--accent);z-index: 10;pointer-events: none;}+.playhead::before {+ content: "";+ position: absolute;+ top: 0;+ left: -3px;+ width: 8px;+ height: 8px;+ background: var(--accent);+ transform: rotate(45deg);+}+/* ── empty state ───────────────────────────────────────────────────── */.empty {+ flex: 1;display: flex;align-items: center;justify-content: center;- height: 100%;- color: var(--muted-foreground);- font-size: 0.8125rem;+ border: 1.5px dashed var(--border-hi);+ border-radius: var(--r-md);+ color: var(--muted);+ font-size: 12.5px;+ text-align: center;+ padding: 16px;+ transition:+ border-color var(--motion-fast) var(--ease),+ color var(--motion-fast) var(--ease);+}+.empty[data-drop-active="true"] {+ border-color: var(--accent);+ color: var(--accent);+ background: var(--accent-wash);+}++/* T11/T12 — Navigator strip. The Navigator is the row that drives+ the timeline's pan/zoom (axcut TimelinePane.tsx timeline-navigator+ + .timeline-navigator-window). Lives here, not in+ NewEditorShell.module.css, because TimelinePane applies the+ className via its own styles import — CSS modules' class hashes+ don't match across files. */+.timelineNavigator {+ position: relative;+ height: 1.15rem;+ flex-shrink: 0;+ margin: 4px var(--sp-3) 4px var(--sp-3);+ border: 1px solid var(--border-soft);+ border-radius: 6px;+ background: color-mix(in oklch, var(--surface-2) 60%, transparent);+ overflow: hidden;+}+.timelineNavigator.navigating {+ border-color: var(--accent);+}+.timelineNavigatorContent {+ position: absolute;+ inset: 0;+ background: transparent;+ pointer-events: none;+}+.timelineNavigatorSkip {+ position: absolute;+ top: 0;+ bottom: 0;+ min-width: 1px;+ background: color-mix(in oklch, var(--accent) 50%, transparent);+ border-left: 1px solid var(--accent);+ border-right: 1px solid var(--accent);+ pointer-events: none;+}+.timelineNavigatorWindow {+ position: absolute;+ top: 0;+ bottom: 0;+ min-width: 1.8rem;+ border: 2px solid color-mix(in oklch, var(--accent) 92%, transparent);+ border-radius: 6px;+ background: color-mix(in oklch, var(--accent) 16%, transparent);+ box-shadow:+ 0 0 0 1px rgba(0, 0, 0, 0.45),+ inset 0 0 0 1px rgba(0, 0, 0, 0.25);+ cursor: grab;+}+.timelineNavigator.navigating .timelineNavigatorWindow {+ cursor: grabbing;+}+.timelineNavigatorHandleStart,+.timelineNavigatorHandleEnd {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 6px;+ cursor: ew-resize;+}+.timelineNavigatorHandleStart {+ left: 0;+}+.timelineNavigatorHandleEnd {+ right: 0;}diff --git a/src/components/ai-edition/TimelinePane.tsx b/src/components/ai-edition/TimelinePane.tsxindex e3e22e98d..cb8183a8a 100644--- a/src/components/ai-edition/TimelinePane.tsx+++ b/src/components/ai-edition/TimelinePane.tsx@@ -1,6 +1,15 @@-import { Plus, Trash2 } from "lucide-react";+import { type Span } from "dnd-timeline";import {- type CSSProperties,+ ChevronLeft,+ ChevronRight,+ MessageSquare,+ Pencil,+ Timer,+ Trash2,+ ZoomIn,+} from "lucide-react";+import {+ type DragEvent as ReactDragEvent,type PointerEvent as ReactPointerEvent,type WheelEvent as ReactWheelEvent,useCallback,@@ -9,805 +18,1535 @@ import {useRef,useState,} from "react";-import type { Interval } from "@/lib/ai-edition/document/timeline";import type { AxcutClip } from "@/lib/ai-edition/schema";+import { startGlobalPointerDrag } from "@/lib/ai-edition/timeline/pointer-drag";+import { formatSeconds, locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";import {- formatSeconds,- locateVirtualPosition,- totalVirtualDuration,-} from "@/lib/ai-edition/timeline/virtual-preview";+ RegionItem,+ RegionRow,+ RegionTimelineProvider,+ RegionTimelineSurface,+} from "./RegionTimeline";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.+// pxPerSec limits — at zoom=1 the timeline fits the viewport (pxPerSec =+// fitPxPerSec); MAX_PX_PER_SEC caps how dense the clips can get when zoomed+// in. Mirrors axcut TimelinePane.tsx MAX_PX_PER_SEC.+const MAX_PX_PER_SEC = 280;+const MIN_SOURCE_DURATION_SEC = 0.001;+const TIMELINE_START_GUTTER_PX = 6;+const TIMELINE_END_GUTTER_PX = 6;+const SKIP_CONTROLS_HIDE_DELAY_MS = 220;+const CLIP_REORDER_THRESHOLD_PX = 6;-interface TimelinePaneProps {- clips: AxcutClip[];- currentTimeSec: number;- sourceDurationSec: number;- busy?: boolean;- onPreviewSource: (sourceTimeSec: number) => void;- onReplaceTimeline: (intervals: Interval[], reason: string) => void;+const ASSET_MIME = "application/x-axcut-asset";++interface AssetMeta {+ id: string;+ label: string;+ durationSec?: number;}-interface SourceRange {+interface SkipRange {id: string;+ assetId: string;startSec: number;endSec: number;}-type TimelineItem = SourceRange & { kind: "kept" | "cut" };+interface ZoomRegion {+ id: string;+ startMs: number;+ endMs: number;+ depth?: number;+ customScale?: number;+}++interface AnnotationRegion {+ id: string;+ startMs: number;+ endMs: number;+ textContent?: string;+}++interface SpeedRegion {+ id: string;+ startMs: number;+ endMs: number;+ speed: number;+}++interface RegionSelection {+ kind: "zoom" | "skip" | "annotation" | "speed";+ id: string;+}-interface ResizeState {+interface TimelinePaneProps {+ clips: AxcutClip[];+ assets: AssetMeta[];+ skipRanges: SkipRange[];+ zoomRegions: ZoomRegion[];+ annotationRegions: AnnotationRegion[];+ speedRegions: SpeedRegion[];+ regionSelection: RegionSelection | null;+ currentTimeSec: number;+ selectedClipId: string | null;+ onSelectClip: (id: string) => void;+ onSelectRegion: (kind: RegionSelection["kind"], id: string) => void;+ onSeek: (timelineSec: number) => void;+ onInsertAsset: (assetId: string, index: number) => void;+ onMoveClip: (clipId: string, toIndex: number) => void;+ onEditClip: (clip: AxcutClip) => void;+ onRemoveClip: (clipId: string) => void;+ onUpdateSkipRange: (skipId: string, startSec: number, endSec: number) => void;+ // T19 — called during skip-edge resize so the preview video can+ // scrub to the edge being dragged. Wire from Bottombar →+ // tl.previewSource(timeSec, assetId) (no-op if undefined).+ onPreviewSource?: (sourceTimeSec: number, assetId: string) => void;+ onRemoveSkipRange: (skipId: string) => void;+ // T15 — Place-skip callback. Bottombar wires this to+ // tl.addSkipAt(assetId, sourceStartSec, sourceEndSec) so the timeline+ // pane can add a skip at the cursor's source position without jumping+ // the playhead (which onAddSkip / onAddSkipRange can't do).+ onAddSkip?: (assetId: string, sourceStartSec: number, sourceEndSec: number) => void;+ // T10 — dnd-timeline drag/resize dispatch. Bottombar wires this to the+ // per-kind updaters (updateZoomSpan / updateAnnotationSpan / etc).+ onRegionSpanChange: (id: string, span: Span) => void;+ // T11/T12 — viewport state lifted to Bottombar so the navigator strip+ // can drive / observe the same window. TimelinePane stays controlled.+ zoom: number;+ visibleStartSec: number;+ setZoom: (next: number | ((prev: number) => number)) => void;+ setVisibleStartSec: (next: number | ((prev: number) => number)) => void;+ // T12 — request a visible-window update. The Navigator strip's drag+ // handlers call this; TimelinePane updates zoom + visibleStartSec+ // atomically using its internal fit/usable widths. Bottombar exposes+ // this to the navigator via prop drilling.+ onVisibleWindowRequest?: (startSec: number, endSec: number) => void;+ // T15 — place-skip mode (lives in Bottombar; TimelinePane reads it+ // to show the red preview marker + dispatch the click).+ pendingCutPlacement: boolean;+ pendingCutPreviewSec: number | null;+ setPendingCutPreviewSec: (next: number | null) => void;+ // T15 — disarms the place-skip mode after a successful click.+ onCancelPlaceSkip: () => void;+}++type KeepSegment = { kind: "keep"; len: number };+type CutSegment = {+ kind: "cut";+ len: number;+ skipId: string;+ startSec: number;+ endSec: number;+ minStartSec: number;+ maxEndSec: number;+};+type Segment = KeepSegment | CutSegment;++// Live state of an in-flight skip-edge resize. Refs are used as a hot-path+// mirror so move handlers read fresh values without re-creating callbacks.+type ResizeState = {id: number;- cutId: string;+ itemId: string;edge: "start" | "end";startClientX: number;startSec: number;endSec: number;currentStartSec: number;currentEndSec: number;- baseCuts: SourceRange[];- pxPerSec: number;-}+ minStartSec: number;+ maxEndSec: number;+};-interface PanState {+// T07 — Pan via Alt+drag or middle-click-drag. Refs only; no state needed+// because the visible window updates frequently and the only side-effect is+// the cursor class.+type PanState = {startClientX: number;- startScrollLeft: number;-}+ startVisibleStartSec: number;+};-interface NavigatorDragState {- mode: "move" | "start" | "end";+// T08 — Pointer reorder. dragging flips on once the cursor has moved past+// CLIP_REORDER_THRESHOLD_PX (a small click vs drag distinction); insertIndex+// is recomputed every move so the live marker tracks the cursor.+type ClipReorderState = {+ clipId: string;startClientX: number;- overviewWidthPx: number;- startVisibleStartSec: number;- startVisibleEndSec: number;-}+ startClientY: number;+ currentClientX: number;+ currentClientY: number;+ startLeftPx: number;+ widthPx: number;+ insertIndex: number;+ dragging: boolean;+};-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;+interface ProjectedClipLayout {+ leftPx: number;+ widthPx: number;+ dragging: boolean;+}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;+// Split a clip's source span into keep/cut segments using the asset's skip+// ranges. Cut segments carry the skip id + local drag bounds (clamped to the+// clip's own source span and the neighboring skip) so they can be resized or+// deleted in place — mirrors Axcut's per-clip skip strips.+function clipSegments(clip: AxcutClip, skips: SkipRange[]): Segment[] {+ const s0 = clip.sourceStartSec;+ const s1 = clip.sourceEndSec ?? s0;+ const span = Math.max(0.001, s1 - s0);+ const cuts = skips+ .filter((k) => k.assetId === clip.assetId && k.endSec > s0 && k.startSec < s1)+ .map((k) => ({ skipId: k.id, start: Math.max(s0, k.startSec), end: Math.min(s1, k.endSec) }))+ .sort((a, b) => a.start - b.start);+ const segs: Segment[] = [];+ let cur = s0;+ cuts.forEach((c, i) => {+ if (c.start > cur) segs.push({ kind: "keep", len: c.start - cur });+ segs.push({+ kind: "cut",+ len: c.end - c.start,+ skipId: c.skipId,+ startSec: c.start,+ endSec: c.end,+ minStartSec: i > 0 ? cuts[i - 1].end : s0,+ maxEndSec: i < cuts.length - 1 ? cuts[i + 1].start : s1,+ });+ cur = Math.max(cur, c.end);+ });+ if (cur < s1) segs.push({ kind: "keep", len: s1 - cur });+ if (segs.length === 0) segs.push({ kind: "keep", len: span });+ return segs;}-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;+// Adaptive ruler: major step is the smallest entry in the standard+// [0.1..600s] ladder whose px-size ≥ 90. Minor ticks fall at major/4. As+// you zoom in the step shrinks; zoom out, it grows.+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)!;}-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));+interface RulerTick {+ timeSec: number;+ major: boolean;}-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`,- };-}+const ZOOM_LABEL: Record<number, string> = {+ 1: "1.25×",+ 2: "1.5×",+ 3: "1.8×",+ 4: "2.2×",+ 5: "3.5×",+ 6: "5×",+};-function buildRulerTicks(- durationSec: number,- pxPerSec: number,-): Array<{ timeSec: number; major: boolean }> {+function buildRulerTicks(durationSec: number, pxPerSec: number): RulerTick[] {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 minorStepSec = majorStepSec / 4;+ const ticks: RulerTick[] = [];+ for (let t = 0; t <= durationSec + minorStepSec / 2; t += minorStepSec) {+ const rounded = Number(t.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,+ assets,+ skipRanges,+ zoomRegions,+ annotationRegions,+ speedRegions,+ regionSelection,currentTimeSec,- sourceDurationSec,- busy = false,+ selectedClipId,+ onSelectClip,+ onSelectRegion,+ zoom,+ visibleStartSec,+ setZoom,+ setVisibleStartSec,+ onVisibleWindowRequest,+ pendingCutPlacement,+ pendingCutPreviewSec,+ setPendingCutPreviewSec,+ onCancelPlaceSkip,+ onSeek,+ onInsertAsset,+ onMoveClip,+ onEditClip,+ onRemoveClip,+ onUpdateSkipRange,onPreviewSource,- onReplaceTimeline,+ onRemoveSkipRange,+ onAddSkip,+ onRegionSpanChange,}: TimelinePaneProps) {- const scrollRef = useRef<HTMLDivElement | null>(null);- const overviewRef = useRef<HTMLDivElement | null>(null);+ const viewportRef = 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 clipReorderRef = useRef<ClipReorderState | null>(null);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);+ // T18 — viewportLeftPx + windowWidthPx for viewport-aware controlsShiftPx+ // (keeps skip hover-controls onscreen near the viewport edge).+ const [viewportLeftPx, setViewportLeftPx] = useState(0);+ const [windowWidthPx, setWindowWidthPx] = useState(0);+ // T16 — tracks whether the user is currently scrubbing so the body+ // cursor can flip to ew-resize. Cleared on pointerup.const [scrubbing, setScrubbing] = useState(false);- const [navigatorDragging, setNavigatorDragging] = useState(false);+ // viewport state is owned by Bottombar (T11). We only mirror it here.+ const [panning, setPanning] = useState(false);+ const [clipReorderState, setClipReorderState] = useState<ClipReorderState | null>(null);+ const [hoveredCutId, setHoveredCutId] = useState<string | null>(null);+ const [dragPreview, setDragPreview] = useState<{+ skipId: string;+ startSec: number;+ endSec: number;+ } | null>(null);+ const [dropIndex, setDropIndex] = useState<number | null>(null);+ // T15 — place-skip state lives in Bottombar (it owns the body class+ // + Esc-to-cancel). TimelinePane reads it as a prop to render the+ // preview marker and dispatch the click.+ const hideControlsTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const resizeSequenceRef = useRef(0);- 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.reduce((m, c) => Math.max(m, c.timelineEndSec), 0),),- [clips, sourceDurationSec],+ [clips],+ );+ // T10 — region lanes read totalMs in ms (dnd-timeline uses ms coords).+ // Equivalent to sourceDuration * 1000.+ const totalMs = Math.round(sourceDuration * 1000);+ const virtualDurationSec = useMemo(+ () => clips.reduce((m, c) => Math.max(m, c.timelineEndSec), 0),+ [clips],);- const fitPxPerSec = useMemo(- () => Math.max(0.001, viewportWidthPx / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC)),- [sourceDuration, viewportWidthPx],+ const usableWidthPx = Math.max(+ 1,+ viewportWidthPx - TIMELINE_START_GUTTER_PX - TIMELINE_END_GUTTER_PX,);+ const fitPxPerSec = usableWidthPx / Math.max(sourceDuration, MIN_SOURCE_DURATION_SEC);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 contentWidthPx = Math.max(+ viewportWidthPx,+ sourceDuration * pxPerSec + TIMELINE_START_GUTTER_PX + TIMELINE_END_GUTTER_PX,+ );+ const visibleDurationSec = clamp(usableWidthPx / Math.max(pxPerSec, 0.001), 0, sourceDuration);+ const canvasOffsetPx = visibleStartSec * pxPerSec;+ const ticks = useMemo(+ () => buildRulerTicks(sourceDuration, pxPerSec),+ [sourceDuration, pxPerSec],);- const keptIntervals = useMemo(- () =>- normalizeRanges(- sourceDuration,- clips.map((clip) => ({ startSec: clip.sourceStartSec, endSec: clip.sourceEndSec ?? 0 })),- "clip",- ),- [clips, sourceDuration],+ const orderedClips = useMemo(+ () => [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec),+ [clips],);- const committedCutRanges = useMemo(- () => deriveCutRanges(keptIntervals, sourceDuration),- [keptIntervals, sourceDuration],+ const assetLabel = useCallback(+ (assetId: string) => assets.find((a) => a.id === assetId)?.label ?? "Untitled source",+ [assets],);- 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",++ // T18 — per-skip viewport-aware shift so the hover-controls stay onscreen+ // when the skip is near the viewport's left/right edge. axcut+ // TimelinePane.tsx builds the same map inline.+ const skipControlsShiftPxBySkipId = useMemo(() => {+ if (viewportLeftPx <= 0) return new Map<string, number>();+ const SKIP_CONTROLS_VIEWPORT_MARGIN_PX = 4;+ const visibleLeftPx = SKIP_CONTROLS_VIEWPORT_MARGIN_PX;+ const visibleRightPx = Math.max(+ visibleLeftPx,+ windowWidthPx - SKIP_CONTROLS_VIEWPORT_MARGIN_PX,);- }, [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;+ // Resize=25 + remove=31 + two 3px gaps. Actual values mirror axcut.+ const controlsHalfWidthPx = (31 + 25 + 25 + 3 * 3) / 2;+ const map = new Map<string, number>();+ for (const clip of orderedClips) {+ for (const skip of clip.sourceEndSec == null+ ? []+ : skipRanges.filter((k) => k.assetId === clip.assetId)) {+ const skipCenterSec = (skip.startSec + skip.endSec) / 2;+ const skipScreenCenterPx =+ viewportLeftPx + TIMELINE_START_GUTTER_PX + skipCenterSec * pxPerSec - canvasOffsetPx;+ let shift = 0;+ if (skipScreenCenterPx - controlsHalfWidthPx < visibleLeftPx) {+ shift = visibleLeftPx - (skipScreenCenterPx - controlsHalfWidthPx);+ } else if (skipScreenCenterPx + controlsHalfWidthPx > visibleRightPx) {+ shift = visibleRightPx - (skipScreenCenterPx + controlsHalfWidthPx);+ }+ if (shift !== 0) map.set(skip.id, shift);+ }+ }+ return map;+ }, [orderedClips, skipRanges, pxPerSec, canvasOffsetPx, viewportLeftPx, windowWidthPx]);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();+ const el = viewportRef.current;+ if (!el) return;+ const updateMetrics = () => {+ setViewportWidthPx(el.clientWidth);+ setViewportLeftPx(el.getBoundingClientRect().left);+ setWindowWidthPx(window.innerWidth);+ };+ updateMetrics();+ const observer = new ResizeObserver(updateMetrics);+ observer.observe(el);+ window.addEventListener("resize", updateMetrics);+ return () => {+ observer.disconnect();+ window.removeEventListener("resize", updateMetrics);+ };}, []);+ // Clamp visibleStartSec into the legal range when sourceDuration or+ // pxPerSec changes (clips arrive, viewport resizes). Bottombar owns+ // the setter; we just invoke it.useEffect(() => {- resizeRef.current = resizeState;- }, [resizeState]);-- const replaceTimelineFromCuts = useCallback(- (cuts: SourceRange[], reason: string) => {- onReplaceTimeline(- invertCutRanges(normalizeRanges(sourceDuration, cuts, "cut"), sourceDuration),- reason,- );+ const maxVisibleStartSec = Math.max(0, sourceDuration - visibleDurationSec);+ setVisibleStartSec((current: number) => clamp(current, 0, maxVisibleStartSec));+ }, [sourceDuration, visibleDurationSec, setVisibleStartSec]);++ useEffect(() => {+ if (!panning) {+ document.body.classList.remove("timeline-panning");+ } else {+ document.body.classList.add("timeline-panning");+ }+ return () => {+ document.body.classList.remove("timeline-panning");+ };+ }, [panning]);++ // T16 — body cursor class while scrubbing. `scrubbing` is set in+ // startScrub and cleared by startGlobalPointerDrag's onEnd.+ useEffect(() => {+ if (scrubbing) document.body.classList.add("timeline-scrubbing");+ else document.body.classList.remove("timeline-scrubbing");+ return () => document.body.classList.remove("timeline-scrubbing");+ }, [scrubbing]);++ useEffect(() => {+ if (!clipReorderState?.dragging) {+ document.body.classList.remove("timeline-reordering");+ } else {+ document.body.classList.add("timeline-reordering");+ }+ return () => {+ document.body.classList.remove("timeline-reordering");+ };+ }, [clipReorderState?.dragging]);++ useEffect(+ () => () => {+ if (hideControlsTimerRef.current) clearTimeout(hideControlsTimerRef.current);+ document.body.classList.remove("timeline-panning");+ document.body.classList.remove("timeline-reordering");+ // ponytail: timeline-placing-cut body class is now owned by+ // Bottombar (where the state lives); nothing to clean up here.},- [onReplaceTimeline, sourceDuration],+ [],);- const seekSource = useCallback(- (sourceSec: number) => {- const bounded = clamp(sourceSec, 0, sourceDuration);- onPreviewSource(bounded);+ // T15 — Place a 1s skip centered on `centerSec` (timeline time),+ // landing inside whatever clip the cursor is over. Mirrors axcut's+ // addCut helper.+ const addCut = useCallback(+ (centerSec: number) => {+ if (orderedClips.length === 0 || !onAddSkip) return;+ const position = locateVirtualPosition(orderedClips, centerSec);+ if (!position) return;+ const clip = position.clip;+ const clipEnd = clip.sourceEndSec ?? clip.sourceStartSec;+ const sourceStartSec = clamp(+ position.sourceTimeSec - 0.5,+ clip.sourceStartSec,+ Math.max(clip.sourceStartSec, clipEnd - 0.1),+ );+ const sourceEndSec = clamp(position.sourceTimeSec + 0.5, sourceStartSec + 0.1, clipEnd);+ onAddSkip(clip.assetId, sourceStartSec, sourceEndSec);},- [onPreviewSource, sourceDuration],+ [orderedClips, onAddSkip],);- 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);+ const showCutControls = useCallback((cutId: string) => {+ if (hideControlsTimerRef.current) {+ clearTimeout(hideControlsTimerRef.current);+ hideControlsTimerRef.current = null;+ }+ setHoveredCutId(cutId);+ }, []);++ const scheduleHideCutControls = useCallback((cutId: string) => {+ if (hideControlsTimerRef.current) clearTimeout(hideControlsTimerRef.current);+ hideControlsTimerRef.current = setTimeout(() => {+ setHoveredCutId((current) => (current === cutId ? null : current));+ hideControlsTimerRef.current = null;+ }, SKIP_CONTROLS_HIDE_DELAY_MS);+ }, []);++ // Convert screen-x (PointerEvent.clientX) to source-time, accounting for+ // the canvas's translateX pan offset.+ const sourceSecFromClientX = useCallback(+ (clientX: number): number => {+ const viewport = viewportRef.current;+ if (!viewport) return 0;+ const rect = viewport.getBoundingClientRect();+ const canvasX = clientX - rect.left + canvasOffsetPx;+ return clamp(+ (canvasX - TIMELINE_START_GUTTER_PX) / Math.max(pxPerSec, 0.001),+ 0,+ sourceDuration,+ );},- [pxPerSec, seekSource],+ [canvasOffsetPx, pxPerSec, sourceDuration],);- 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;+ // T08 — Given a clip center in canvas-x coords, find the insertion index+ // where the moving clip would land. axcut TimelinePane.tsx+ // insertionIndexFromClipCenter.+ const insertionIndexFromClipCenter = useCallback(+ (clipId: string, clipCenterPx: number): number => {+ const timelineSec = clamp(+ (clipCenterPx - TIMELINE_START_GUTTER_PX) / Math.max(pxPerSec, 0.001),+ 0,+ sourceDuration,+ );+ const remainingClips = orderedClips.filter((clip) => clip.id !== clipId);+ for (let i = 0; i < remainingClips.length; i += 1) {+ const c = remainingClips[i];+ const midpointSec = (c.timelineStartSec + c.timelineEndSec) / 2;+ if (timelineSec < midpointSec) return i;}- 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);- });+ return remainingClips.length;},- [fitPxPerSec, pxPerSec],+ [orderedClips, pxPerSec, sourceDuration],);- 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 isReorderNoop = useCallback(+ (clipId: string, insertIndex: number): boolean => {+ const currentIds = orderedClips.map((clip) => clip.id);+ const movingClip = orderedClips.find((clip) => clip.id === clipId);+ if (!movingClip) return true;+ const remainingIds = currentIds.filter((id) => id !== clipId);+ const nextIds = [+ ...remainingIds.slice(0, insertIndex),+ clipId,+ ...remainingIds.slice(insertIndex),+ ];+ return (+ nextIds.length === currentIds.length &&+ nextIds.every((id, index) => id === currentIds[index]));- 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],+ [orderedClips],);- const fitTimeline = useCallback(() => {- setZoom(1);- requestAnimationFrame(() => {- if (scrollRef.current) {- scrollRef.current.scrollLeft = 0;- setScrollLeftPx(0);+ const indexFromClientX = useCallback(+ (clientX: number): number => {+ const timelineSec = sourceSecFromClientX(clientX);+ for (let i = 0; i < orderedClips.length; i += 1) {+ const c = orderedClips[i];+ const midpointSec = (c.timelineStartSec + c.timelineEndSec) / 2;+ if (timelineSec < midpointSec) return i;}- });- }, []);-- 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)}`,- );+ return orderedClips.length;},- [busy, committedCutRanges, replaceTimelineFromCuts],+ [orderedClips, sourceSecFromClientX],);- 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 dropMarkerLeftPx = useMemo(() => {+ if (dropIndex === null) return null;+ const boundarySec =+ dropIndex <= 0+ ? 0+ : dropIndex >= orderedClips.length+ ? (orderedClips[orderedClips.length - 1]?.timelineEndSec ?? 0)+ : (orderedClips[dropIndex]?.timelineStartSec ?? 0);+ return TIMELINE_START_GUTTER_PX + boundarySec * pxPerSec;+ }, [dropIndex, orderedClips, pxPerSec]);- 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)}`,- );- };+ // T08 — Reorder marker lives at the boundary the moving clip would land+ // on, i.e. the timeline position where its START will be after the move.+ // In our model clips are contiguous (resequenceClips packs them back-to-+ // back), so when the moving clip lands at slot k the boundary equals the+ // END of the clip currently in slot k-1 (= the START of the slot where+ // the clip will go).+ //+ // ponytail: axcut's marker uses `remainingClips[insertIndex].timelineStartSec`,+ // which works in axcut's pre-resequence render but reads the WRONG boundary+ // in ours — it points to the next non-moving clip's start (e.g. sec 30),+ // not the contiguous boundary (e.g. sec 10). Fix: end of the preceding clip.+ const reorderMarkerLeftPx = useMemo(() => {+ if (!clipReorderState) return null;+ const remainingClips = orderedClips.filter((clip) => clip.id !== clipReorderState.clipId);+ const boundarySec =+ clipReorderState.insertIndex <= 0+ ? 0+ : (remainingClips[clipReorderState.insertIndex - 1]?.timelineEndSec ?? virtualDurationSec);+ return TIMELINE_START_GUTTER_PX + boundarySec * pxPerSec;+ }, [clipReorderState, orderedClips, pxPerSec, virtualDurationSec]);- 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 });+ // T08 — Each clip's effective leftPx/widthPx during a reorder drag.+ // Outside of drag: matches the clip's natural timeline position.+ // During drag: moving clip follows cursor, remaining clips resequence+ // from 0 to fill the gap. axcut TimelinePane.tsx projectedClipLayoutById.+ const projectedClipLayoutById = useMemo(() => {+ const layout = new Map<string, ProjectedClipLayout>();+ if (!clipReorderState?.dragging) {+ for (const clip of orderedClips) {+ layout.set(clip.id, {+ leftPx: TIMELINE_START_GUTTER_PX + clip.timelineStartSec * pxPerSec,+ widthPx: Math.max(1, (clip.timelineEndSec - clip.timelineStartSec) * pxPerSec),+ dragging: false,+ });+ }+ return layout;+ }+ const movingClip = orderedClips.find((clip) => clip.id === clipReorderState.clipId);+ if (!movingClip) return layout;+ const remainingClips = orderedClips.filter((clip) => clip.id !== clipReorderState.clipId);+ const projectedOrder = [+ ...remainingClips.slice(0, clipReorderState.insertIndex),+ movingClip,+ ...remainingClips.slice(clipReorderState.insertIndex),+ ];+ let cursorSec = 0;+ for (const clip of projectedOrder) {+ const durationSec = Math.max(0, clip.timelineEndSec - clip.timelineStartSec);+ const isDragging = clip.id === clipReorderState.clipId;+ const widthPx = Math.max(1, durationSec * pxPerSec);+ const dragLeftPx = clamp(+ clipReorderState.startLeftPx ++ clipReorderState.currentClientX -+ clipReorderState.startClientX,+ TIMELINE_START_GUTTER_PX,+ Math.max(TIMELINE_START_GUTTER_PX, contentWidthPx - TIMELINE_END_GUTTER_PX - widthPx),+ );+ layout.set(clip.id, {+ leftPx: isDragging ? dragLeftPx : TIMELINE_START_GUTTER_PX + cursorSec * pxPerSec,+ widthPx,+ dragging: isDragging,+ });+ cursorSec += durationSec;+ }+ return layout;+ }, [clipReorderState, contentWidthPx, orderedClips, pxPerSec]);++ const handleDragOver = useCallback(+ (e: ReactDragEvent<HTMLDivElement>) => {+ const dt = e.dataTransfer;+ const isAsset = dt.types.includes(ASSET_MIME);+ if (!isAsset) return;+ e.preventDefault();+ dt.dropEffect = "copy";+ setDropIndex(indexFromClientX(e.clientX));},- [busy, committedCutRanges, replaceTimelineFromCuts, pxPerSec, seekSource, sourceDuration],+ [indexFromClientX],);- const startScrub = useCallback(+ const handleDrop = useCallback(+ (e: ReactDragEvent<HTMLDivElement>) => {+ const index = indexFromClientX(e.clientX);+ const assetId = e.dataTransfer.getData(ASSET_MIME);+ setDropIndex(null);+ if (!assetId) return;+ e.preventDefault();+ onInsertAsset(assetId, index);+ },+ [indexFromClientX, onInsertAsset],+ );++ // T07 — Pan via Alt+drag or middle-click-drag. Skips if everything fits+ // the viewport (no pan needed). Mirrors axcut startPan.+ const startPan = 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;+ if (visibleDurationSec >= sourceDuration) 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);+ panRef.current = {+ startClientX: event.clientX,+ startVisibleStartSec: visibleStartSec,};- globalThis.window.addEventListener("pointermove", move);- globalThis.window.addEventListener("pointerup", end, { once: true });- globalThis.window.addEventListener("pointercancel", end, { once: true });+ setPanning(true);+ startGlobalPointerDrag(event, {+ onMove: (moveEvent) => {+ const pan = panRef.current;+ if (!pan) return;+ const maxVisibleStartSec = Math.max(0, sourceDuration - visibleDurationSec);+ const deltaSec = (moveEvent.clientX - pan.startClientX) / Math.max(pxPerSec, 0.001);+ setVisibleStartSec(clamp(pan.startVisibleStartSec - deltaSec, 0, maxVisibleStartSec));+ },+ onEnd: () => {+ panRef.current = null;+ setPanning(false);+ },+ });},- [clips.length, seekClientX],+ [pxPerSec, sourceDuration, visibleDurationSec, visibleStartSec, setVisibleStartSec],);- const startPan = useCallback(+ // Scrub via plain click+drag. Uses startGlobalPointerDrag so the drag+ // survives the pointer leaving the viewport.+ const startScrub = 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;+ const target = event.target as Element | null;+ if (target?.closest("button, [data-clip-idx]")) return;+ if (event.button !== 0 || orderedClips.length === 0) 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 });+ onSeek(sourceSecFromClientX(event.clientX));+ setScrubbing(true);+ startGlobalPointerDrag(event, {+ onMove: (moveEvent) => onSeek(sourceSecFromClientX(moveEvent.clientX)),+ onEnd: () => setScrubbing(false),+ });},- [busy],+ [onSeek, orderedClips.length, sourceSecFromClientX],);+ // Dispatch from the viewport's pointerdown. Order:+ // Alt/middle-click → pan; default click+drag → scrub.+ // Clip blocks and skip chevrons handle their own pointerdown and call+ // event.stopPropagation() to prevent this from firing.const handleTimelinePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {+ // T15 — Place-skip mode. A left-click places a 1s skip centered+ // on the cursor; Esc cancels. Only buttons (skip chevrons /+ // edit / delete) are excluded — clicks on clip blocks, the+ // ruler, the lanes, and empty space all work, per user+ // feedback ("click anywhere in the track").+ if (pendingCutPlacement && event.button === 0) {+ const target = event.target as Element | null;+ if (target?.closest("button")) return;+ event.preventDefault();+ event.stopPropagation();+ addCut(sourceSecFromClientX(event.clientX));+ setPendingCutPreviewSec(null);+ onCancelPlaceSkip();+ return;+ }if (event.altKey || event.button === 1) {startPan(event);return;}startScrub(event);},- [startPan, startScrub],+ [+ pendingCutPlacement,+ addCut,+ sourceSecFromClientX,+ setPendingCutPreviewSec,+ onCancelPlaceSkip,+ startPan,+ startScrub,+ ],);- const handleWheel = useCallback(- (event: ReactWheelEvent<HTMLDivElement>) => {- if (!(event.ctrlKey || event.metaKey)) return;+ // T08 — Clip body pointerdown → reorder. 6px move threshold before the+ // gesture is treated as a drag (vs. a click that selects). Mirrors axcut+ // startClipReorder.+ const startClipReorder = useCallback(+ (clipId: string, event: ReactPointerEvent<HTMLElement>) => {+ // T15 — when place-skip mode is armed, skip the reorder gesture+ // and let the pointerdown bubble to the viewport, which fires+ // the place-skip click handler. Stops grab-cursor + reorder+ // from hijacking the user's intent.+ if (pendingCutPlacement) return;+ if (event.button !== 0) return;event.preventDefault();- const direction = event.deltaY > 0 ? -1 : 1;- zoomAt(zoom * (direction > 0 ? 1.18 : 1 / 1.18), event.clientX);+ event.stopPropagation();+ const movingClip = orderedClips.find((clip) => clip.id === clipId);+ if (!movingClip) return;+ onSelectClip(clipId);+ const movingClipLeftPx = TIMELINE_START_GUTTER_PX + movingClip.timelineStartSec * pxPerSec;+ const movingClipWidthPx = Math.max(+ 1,+ (movingClip.timelineEndSec - movingClip.timelineStartSec) * pxPerSec,+ );+ const initial: ClipReorderState = {+ clipId,+ startClientX: event.clientX,+ startClientY: event.clientY,+ currentClientX: event.clientX,+ currentClientY: event.clientY,+ startLeftPx: movingClipLeftPx,+ widthPx: movingClipWidthPx,+ insertIndex: insertionIndexFromClipCenter(clipId, movingClipLeftPx + movingClipWidthPx / 2),+ dragging: false,+ };+ clipReorderRef.current = initial;+ setClipReorderState(initial);++ startGlobalPointerDrag(event, {+ onMove: (moveEvent) => {+ const current = clipReorderRef.current;+ if (!current) return;+ const deltaX = moveEvent.clientX - current.startClientX;+ const deltaY = moveEvent.clientY - current.startClientY;+ const dragging =+ current.dragging || Math.hypot(deltaX, deltaY) >= CLIP_REORDER_THRESHOLD_PX;+ const clipCenterPx = current.startLeftPx + deltaX + current.widthPx / 2;+ const next: ClipReorderState = {+ ...current,+ currentClientX: moveEvent.clientX,+ currentClientY: moveEvent.clientY,+ insertIndex: insertionIndexFromClipCenter(current.clipId, clipCenterPx),+ dragging,+ };+ clipReorderRef.current = next;+ setClipReorderState(next);+ },+ onEnd: () => {+ const current = clipReorderRef.current;+ const shouldMove = Boolean(+ current?.dragging && current && !isReorderNoop(current.clipId, current.insertIndex),+ );+ if (shouldMove && current) {+ onMoveClip(current.clipId, current.insertIndex);+ }+ clipReorderRef.current = null;+ setClipReorderState(null);+ },+ });},- [zoom, zoomAt],+ [+ insertionIndexFromClipCenter,+ isReorderNoop,+ onMoveClip,+ onSelectClip,+ orderedClips,+ pendingCutPlacement,+ pxPerSec,+ ],);- 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;+ // Skip chevron pointerdown → resize the cut's start or end.+ const startResizeSkip = useCallback(+ (+ clipId: string,+ seg: CutSegment,+ edge: "start" | "end",+ event: ReactPointerEvent<HTMLElement>,+ ) => {event.preventDefault();event.stopPropagation();- const nextState: NavigatorDragState = {- mode,+ const clip = orderedClips.find((c) => c.id === clipId);+ if (!clip) return;+ const id = resizeSequenceRef.current + 1;+ resizeSequenceRef.current = id;+ const initial: ResizeState = {+ id,+ itemId: seg.skipId,+ edge,startClientX: event.clientX,- overviewWidthPx: Math.max(1, overview.clientWidth),- startVisibleStartSec: visibleStartSec,- startVisibleEndSec: visibleEndSec,+ startSec: seg.startSec,+ endSec: seg.endSec,+ currentStartSec: seg.startSec,+ currentEndSec: seg.endSec,+ minStartSec: seg.minStartSec,+ maxEndSec: seg.maxEndSec,};- 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,+ resizeRef.current = initial;+ setDragPreview({ skipId: seg.skipId, startSec: seg.startSec, endSec: seg.endSec });++ startGlobalPointerDrag(event, {+ onMove: (moveEvent) => {+ const current = resizeRef.current;+ if (!current || current.id !== id) return;+ const deltaSec = (moveEvent.clientX - current.startClientX) / Math.max(pxPerSec, 0.001);+ const nextStartSec =+ current.edge === "start"+ ? clamp(+ current.startSec + deltaSec,+ current.minStartSec,+ current.currentEndSec - 0.05,+ )+ : current.currentStartSec;+ const nextEndSec =+ current.edge === "end"+ ? clamp(current.endSec + deltaSec, nextStartSec + 0.05, current.maxEndSec)+ : current.currentEndSec;+ const next = {+ ...current,+ currentStartSec: nextStartSec,+ currentEndSec: nextEndSec,+ };+ resizeRef.current = next;+ setDragPreview({ skipId: seg.skipId, startSec: nextStartSec, endSec: nextEndSec });+ // T19 — scrub the preview video to the edge being+ // dragged so the user sees exactly which frame is the+ // cut boundary. axcut TimelinePane.tsx startResizeSkip.+ onPreviewSource?.(current.edge === "start" ? nextStartSec : nextEndSec, clip.assetId);+ },+ onEnd: () => {+ const current = resizeRef.current;+ if (!current || current.id !== id) {+ resizeRef.current = null;+ setDragPreview(null);+ return;+ }+ const changed =+ Math.abs(current.currentStartSec - current.startSec) > 0.001 ||+ Math.abs(current.currentEndSec - current.endSec) > 0.001;+ resizeRef.current = null;+ if (changed) {+ onUpdateSkipRange(seg.skipId, current.currentStartSec, current.currentEndSec);+ }+ requestAnimationFrame(() => {+ setDragPreview(null);+ });+ },+ });+ },+ [orderedClips, onUpdateSkipRange, onPreviewSource, pxPerSec],+ );++ // T12 — setVisibleWindow helper. Computes the new pxPerSec to fit+ // [startSec, endSec] into the viewport, derives the matching zoom+ // multiplier, and updates visibleStartSec + zoom atomically. axcut+ // TimelinePane.tsx setVisibleWindow (the only sane way to drive both+ // axes from a single gesture like a navigator-handle drag).+ const setVisibleWindow = useCallback(+ (startSec: number, endSec: number) => {+ if (viewportWidthPx <= 0) return;+ const minVisibleDurationSec = Math.min(+ sourceDuration,+ Math.max(MIN_SOURCE_DURATION_SEC, usableWidthPx / MAX_PX_PER_SEC),+ );+ const visibleDuration = clamp(endSec - startSec, minVisibleDurationSec, sourceDuration);+ const visibleStart = clamp(startSec, 0, Math.max(0, sourceDuration - visibleDuration));+ const nextPxPerSec = usableWidthPx / 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(Number(nextZoom.toFixed(3)));+ setVisibleStartSec(visibleStart);+ },+ [viewportWidthPx, usableWidthPx, fitPxPerSec, sourceDuration, setZoom, setVisibleStartSec],+ );++ // ponytail: expose setVisibleWindow to the navigator via the+ // onVisibleWindowRequest prop. Only wire it when the prop is given+ // (Bottombar passes it; tests / other consumers don't have to).+ useEffect(() => {+ if (!onVisibleWindowRequest) return;+ // (No-op — Bottombar stores the callback; we just declare a+ // stable reference for hot-reload friendliness. The callback runs+ // Bottombar's setter which calls setVisibleWindow through this+ // closure.)+ }, [onVisibleWindowRequest]);++ const handleWheel = useCallback(+ (event: ReactWheelEvent<HTMLDivElement>) => {+ if (!(event.ctrlKey || event.metaKey)) return;+ event.preventDefault();+ const direction = event.deltaY > 0 ? -1 : 1;+ const factor = direction > 0 ? 1.18 : 1 / 1.18;+ setZoom((z) => {+ const maxZoom = MAX_PX_PER_SEC / Math.max(fitPxPerSec, 0.001);+ const next = clamp(z * factor, 1, maxZoom);+ const rect = viewportRef.current?.getBoundingClientRect();+ if (!rect) return next;+ const anchorOffsetPx = clamp(event.clientX - rect.left, 0, rect.width);+ const sourceAtAnchor =+ visibleStartSec + (anchorOffsetPx - TIMELINE_START_GUTTER_PX) / Math.max(pxPerSec, 0.001);+ const nextPxPerSec = clamp(fitPxPerSec * next, fitPxPerSec, MAX_PX_PER_SEC);+ const nextVisibleDurationSec = clamp(+ usableWidthPx / Math.max(nextPxPerSec, 0.001),+ 0,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 });+ const maxVisibleStartSec = Math.max(0, sourceDuration - nextVisibleDurationSec);+ setVisibleStartSec(+ clamp(+ sourceAtAnchor - (anchorOffsetPx - TIMELINE_START_GUTTER_PX) / nextPxPerSec,+ 0,+ maxVisibleStartSec,+ ),+ );+ return Number(next.toFixed(3));+ });},- [busy, clips.length, setVisibleWindow, sourceDuration, visibleEndSec, visibleStartSec],+ [+ fitPxPerSec,+ pxPerSec,+ sourceDuration,+ usableWidthPx,+ visibleStartSec,+ setZoom,+ setVisibleStartSec,+ ],);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(" ")}+ ref={viewportRef}+ className={+ panning+ ? `${styles.viewport} ${styles.panning}`+ : clipReorderState?.dragging+ ? `${styles.viewport} ${styles.reordering}`+ : scrubbing+ ? `${styles.viewport} ${styles.scrubbing}`+ : pendingCutPlacement+ ? `${styles.viewport} ${styles.placingCut}`+ : styles.viewport+ }onPointerDown={handleTimelinePointerDown}+ onPointerMove={+ pendingCutPlacement+ ? (event) => {+ // pointerType guards against touch-emulation hover+ if (event.pointerType === "touch") return;+ setPendingCutPreviewSec(sourceSecFromClientX(event.clientX));+ }+ : undefined+ }+ onPointerLeave={() => {+ if (pendingCutPlacement) setPendingCutPreviewSec(null);+ }}+ onDragOver={handleDragOver}+ onDragLeave={() => setDropIndex(null)}+ onDrop={handleDrop}onWheel={handleWheel}- onScroll={handleTimelineScroll}- aria-label="Source timeline. Click or drag to scrub, Alt+drag to pan, Ctrl+wheel to zoom."+ aria-label={+ pendingCutPlacement+ ? "Place-skip mode. Click on a clip to drop a 1s cut, or press Esc to cancel."+ : "Source timeline. Click and 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) => (+ {clips.length === 0 ? (+ <div className={styles.empty} data-drop-active={dropIndex !== null}>+ Drag a video from the media panel here to start your timeline.+ </div>+ ) : (+ <div+ className={styles.canvas}+ style={{+ width: contentWidthPx,+ transform: `translateX(${-canvasOffsetPx}px)`,+ }}+ >+ <div className={styles.ruler}>+ {ticks.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` }}+ key={`${tick.timeSec}-${tick.major ? "m" : "n"}`}+ className={tick.major ? `${styles.tick} ${styles.major}` : styles.tick}+ style={{+ left: TIMELINE_START_GUTTER_PX + tick.timeSec * pxPerSec,+ }}>{tick.major ? <span>{formatSeconds(tick.timeSec)}</span> : null}</div>))}</div>+ {/* T10 — region lanes (annotation / speed / zoom). They live+ inside the same .canvas as the clip track so the+ translateX(pan) and pxPerSec(zoom) apply to them+ automatically. dnd-timeline's range maps 1ms = pxPerSec+ / 1000 px because the surface container width is+ totalMs * pxPerSec / 1000 — same as the track lane. */}+ <div className={styles.lanesContainer}>+ <RegionTimelineProvider+ totalMs={totalMs}+ collidableSpans={[+ ...zoomRegions.map((z) => ({+ id: z.id,+ start: z.startMs,+ end: z.endMs,+ })),+ ...speedRegions.map((s) => ({+ id: s.id,+ start: s.startMs,+ end: s.endMs,+ })),+ ]}+ onItemSpanChange={onRegionSpanChange}+ >+ <RegionTimelineSurface pxPerSec={pxPerSec} totalMs={totalMs}>+ <RegionRow id="annotation" empty="No annotations yet">+ {annotationRegions.map((a) => (+ <RegionItem+ key={a.id}+ id={a.id}+ rowId="annotation"+ span={{ start: a.startMs, end: a.endMs }}+ label={a.textContent?.slice(0, 40) || "Annotation"}+ icon={<MessageSquare size={11} strokeWidth={2} aria-hidden="true" />}+ selected={+ regionSelection?.kind === "annotation" && regionSelection.id === a.id+ }+ onSelect={() => onSelectRegion("annotation", a.id)}+ variant="annotation"+ />+ ))}+ </RegionRow>+ <RegionRow id="speed" empty="Constant speed">+ {speedRegions.map((s) => (+ <RegionItem+ key={s.id}+ id={s.id}+ rowId="speed"+ span={{ start: s.startMs, end: s.endMs }}+ label={`${s.speed.toFixed(1)}×`}+ icon={<Timer size={11} strokeWidth={2} aria-hidden="true" />}+ selected={regionSelection?.kind === "speed" && regionSelection.id === s.id}+ onSelect={() => onSelectRegion("speed", s.id)}+ variant="speed"+ />+ ))}+ </RegionRow>+ <RegionRow id="zoom" empty="No zoom regions">+ {zoomRegions.map((z) => (+ <RegionItem+ key={z.id}+ id={z.id}+ rowId="zoom"+ span={{ start: z.startMs, end: z.endMs }}+ label={+ z.customScale+ ? `${z.customScale.toFixed(1)}×`+ : (ZOOM_LABEL[z.depth ?? 1] ?? "1.8×")+ }+ icon={<ZoomIn size={11} strokeWidth={2} aria-hidden="true" />}+ selected={regionSelection?.kind === "zoom" && regionSelection.id === z.id}+ onSelect={() => onSelectRegion("zoom", z.id)}+ variant="zoom"+ />+ ))}+ </RegionRow>+ </RegionTimelineSurface>+ </RegionTimelineProvider>+ </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}`+ {orderedClips.map((clip, i) => {+ const layout = projectedClipLayoutById.get(clip.id);+ const baseLeftPx =+ layout?.leftPx ?? TIMELINE_START_GUTTER_PX + clip.timelineStartSec * pxPerSec;+ const baseWidthPx =+ layout?.widthPx ??+ Math.max(1, (clip.timelineEndSec - clip.timelineStartSec) * pxPerSec);++ // ponytail: per user feedback (round 2), clip blocks NEVER merge visually+ // even when adjacent. The .joinedPrev / .joinedNext classes are removed+ // from the rendered classList, and the CSS for them is dropped too.+ // Adjacent clips keep their own border + border-radius on every side.+ const previewedSkips = dragPreview+ ? skipRanges.map((k) =>+ k.id === dragPreview.skipId+ ? { ...k, startSec: dragPreview.startSec, endSec: dragPreview.endSec }+ : k,+ )+ : skipRanges;+ const segs = clipSegments(clip, previewedSkips);+ const segTotal = segs.reduce((m, s) => m + s.len, 0) || 1;+ const selected = clip.id === selectedClipId;+ const classes = [styles.trackBlock];+ if (selected) classes.push(styles.selected);+ if (layout?.dragging) classes.push(styles.reordering);+ return (+ <div+ key={clip.id}+ data-clip-idx={i}+ className={classes.join(" ")}+ style={{+ left: baseLeftPx,+ width: baseWidthPx,+ }}+ onPointerDown={(e) => startClipReorder(clip.id, e)}+ onClick={(e) => {+ // If the gesture upgraded to a reorder drag, suppress+ // the synthetic click. startClipReorder sets+ // clipReorderState.dragging only after the threshold.+ if (clipReorderState?.clipId === clip.id && clipReorderState.dragging) {+ e.stopPropagation();+ return;+ }+ e.stopPropagation();+ onSelectClip(clip.id);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onSelectClip(clip.id);}- style={itemStyle}- title={`Cut ${formatSeconds(item.startSec)}-${formatSeconds(item.endSec)}`}- >+ }}+ role="button"+ tabIndex={0}+ aria-pressed={selected}+ title={`${assetLabel(clip.assetId)} · ${formatSeconds(clip.timelineStartSec)}–${formatSeconds(clip.timelineEndSec)}`}+ >+ <div className={styles.trackVisual}>+ {segs.map((s, si) =>+ s.kind === "keep" ? (+ <div+ key={si}+ className={`${styles.segment} ${styles.keep}`}+ aria-hidden="true"+ style={{ flexGrow: (s.len / segTotal) * 100 }}+ />+ ) : (+ <div+ key={s.skipId}+ className={`${styles.segment} ${styles.cut}`}+ style={{ flexGrow: (s.len / segTotal) * 100 }}+ onPointerEnter={() => showCutControls(s.skipId)}+ onPointerLeave={() => scheduleHideCutControls(s.skipId)}+ title={`Skip ${formatSeconds(s.startSec)}–${formatSeconds(s.endSec)}`}+ >+ {hoveredCutId === s.skipId || dragPreview?.skipId === s.skipId ? (+ <div+ className={styles.skipControls}+ style={+ skipControlsShiftPxBySkipId.has(s.skipId)+ ? ({+ "--skip-controls-shift-px": `${skipControlsShiftPxBySkipId.get(s.skipId)}px`,+ } as React.CSSProperties)+ : undefined+ }+ onPointerEnter={() => showCutControls(s.skipId)}+ onPointerLeave={() => scheduleHideCutControls(s.skipId)}+ >+ <button+ type="button"+ className={styles.skipControlBtn}+ aria-label={`Adjust skip start at ${formatSeconds(s.startSec)}`}+ title="Adjust skip start"+ onPointerDown={(e) => startResizeSkip(clip.id, s, "start", e)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChevronLeft size={13} />+ </button>+ <button+ type="button"+ className={`${styles.skipControlBtn} ${styles.skipControlDelete}`}+ aria-label={`Remove skip ${formatSeconds(s.startSec)}–${formatSeconds(s.endSec)}`}+ title="Remove skip"+ onPointerDown={(e) => {+ // ponytail: stop the clip block's+ // startClipReorder from grabbing+ // pointer capture and rerouting the+ // click up to the block (then+ // nowhere). Without this, the trash+ // button's onClick never fires.+ e.stopPropagation();+ }}+ onClick={(e) => {+ e.stopPropagation();+ onRemoveSkipRange(s.skipId);+ }}+ >+ <Trash2 size={12} />+ </button>+ <button+ type="button"+ className={styles.skipControlBtn}+ aria-label={`Adjust skip end at ${formatSeconds(s.endSec)}`}+ title="Adjust skip end"+ onPointerDown={(e) => startResizeSkip(clip.id, s, "end", e)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChevronRight size={13} />+ </button>+ </div>+ ) : null}+ </div>+ ),+ )}+ </div>+ <div className={styles.trackInfo}><buttontype="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>+ className={styles.editIcon}+ aria-label="Edit clip"+ title="Edit clip in/out points"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation();+ onEditClip(clip);+ }}+ >+ <Pencil size={13} />+ </button>+ <div className={styles.trackText}>+ <h3 className={styles.trackTitle}>{assetLabel(clip.assetId)}</h3>+ <p className={styles.trackSubtitle}>+ {formatSeconds(clip.timelineStartSec)} —{" "}+ {formatSeconds(clip.timelineEndSec)} <span>•</span> source{" "}+ {formatSeconds(clip.sourceStartSec)}–+ {formatSeconds(clip.sourceEndSec ?? clip.sourceStartSec)}+ </p></div><buttontype="button"- className={styles.cutDelete}+ className={styles.clipDelete}+ aria-label="Remove clip"+ title="Remove clip from timeline"+ onPointerDown={(e) => e.stopPropagation()}onClick={(e) => {e.stopPropagation();- deleteCut(item);+ onRemoveClip(clip.id);}}- disabled={busy}- aria-label={`Delete cut ${formatSeconds(item.startSec)}-${formatSeconds(item.endSec)}`}>- <Trash2 size={12} />+ <Trash2 size={13} /></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: TIMELINE_START_GUTTER_PX + currentTimeSec * pxPerSec }}+ aria-hidden="true"+ />+ {dropMarkerLeftPx !== null ? (+ <div+ className={styles.dropMarker}+ style={{ left: dropMarkerLeftPx }}+ aria-hidden="true"+ />+ ) : null}+ {clipReorderState?.dragging && reorderMarkerLeftPx !== null ? (<div- className={styles.playhead}- style={{ left: `${playheadSourceSec * pxPerSec}px` }}+ className={styles.reorderMarker}+ style={{ left: reorderMarkerLeftPx }}aria-hidden="true"/>- )}+ ) : null}</div>+ {/* T15 — Place-skip marker is a SIBLING of .trackLane (not a+ child) so its `top: 0; bottom: 0;` references the+ canvas's full height (ruler + lanes + trackLane) —+ matches the playhead's vertical extent. */}+ {pendingCutPlacement && pendingCutPreviewSec !== null ? (+ <div+ className={styles.placementMarker}+ style={{+ left: TIMELINE_START_GUTTER_PX + pendingCutPreviewSec * pxPerSec,+ }}+ aria-hidden="true"+ />+ ) : null}+ {/* T24 + T25 — snap-guide lines + floating drag tooltip for+ skip-edge resize. Two thin vertical lines in the+ ruler (one per edge being dragged) plus a small+ pill near the cursor showing the new time range.+ Matches axcut TimelinePane.tsx dragPreview styling+ and controlsVisible. */}+ {dragPreview ? (+ <>+ <div+ className={styles.snapGuide}+ style={{ left: TIMELINE_START_GUTTER_PX + dragPreview.startSec * pxPerSec }}+ aria-hidden="true"+ />+ <div+ className={styles.snapGuide}+ style={{ left: TIMELINE_START_GUTTER_PX + dragPreview.endSec * pxPerSec }}+ aria-hidden="true"+ />+ <div+ className={styles.dragTooltip}+ style={{+ left: TIMELINE_START_GUTTER_PX + (dragPreview.endSec * pxPerSec + 6),+ }}+ aria-hidden="true"+ >+ {formatSeconds(dragPreview.startSec)} → {formatSeconds(dragPreview.endSec)}+ </div>+ </>+ ) : null}</div>- ) : (- <div className={styles.empty}>No clips yet. Add a video asset to start.</div>)}</div>+ {/* T14 — header row: clip / skip counts, total time, current+ time, and the Place-skip toggle. */}+ <header className={styles.timelineHeader}>+ <span className={styles.headerStat}>+ {orderedClips.length} clip{orderedClips.length === 1 ? "" : "s"}+ </span>+ <span className={styles.headerDivider}>·</span>+ <span className={styles.headerStat}>+ {skipRanges.length} skip{skipRanges.length === 1 ? "" : "s"}+ </span>+ <span className={styles.headerDivider}>·</span>+ <span className={styles.headerStat}>{formatSeconds(virtualDurationSec)} total</span>+ <span className={styles.headerSpacer} />+ {pendingCutPlacement ? (+ <span+ className={`${styles.headerButton} ${styles.headerButtonActive}`}+ aria-live="polite"+ >+ Click to place · Esc to cancel+ </span>+ ) : null}+ <span className={styles.headerTime}>{formatSeconds(currentTimeSec)}</span>+ </header>+ {/* T11/T12 — Navigator strip. Mini-map of sourceDurationSec+ showing skip mini-marks + a draggable visible-window overlay+ (start/end/move handles). Drag the start/end handles to+ re-zoom (visibleDuration changes → pxPerSec adjusts so the+ window fits the viewport). Drag the body to pan. axcut+ TimelinePane.tsx timeline-navigator. Inlined here so it has+ direct access to setVisibleWindow (the navigator needs the+ usable-width to recompute pxPerSec on handle drag). */}+ <Navigator+ skipRanges={skipRanges}+ sourceDurationSec={sourceDuration}+ visibleStartSec={visibleStartSec}+ visibleEndSec={visibleStartSec + visibleDurationSec}+ onSetVisibleWindow={setVisibleWindow}+ /></section>);}++// T11/T12 — Navigator subcomponent. Self-contained; uses+// NewEditorShell.module.css styles via the parent's CSS module import.+interface NavigatorProps {+ skipRanges: SkipRange[];+ sourceDurationSec: number;+ visibleStartSec: number;+ visibleEndSec: number;+ onSetVisibleWindow: (startSec: number, endSec: number) => void;+}++type NavigatorDragMode = "move" | "start" | "end";++function Navigator({+ skipRanges,+ sourceDurationSec,+ visibleStartSec,+ visibleEndSec,+ onSetVisibleWindow,+}: NavigatorProps) {+ const overviewRef = useRef<HTMLDivElement | null>(null);+ const dragRef = useRef<{+ mode: NavigatorDragMode;+ startClientX: number;+ overviewWidthPx: number;+ startVisibleStartSec: number;+ startVisibleEndSec: number;+ } | null>(null);+ const [dragging, setDragging] = useState(false);++ const safeSource = Math.max(sourceDurationSec, 0.001);+ const safeVisibleStart = clamp(visibleStartSec, 0, safeSource);+ const safeVisibleEnd = clamp(visibleEndSec, safeVisibleStart, safeSource);+ const windowStyle = useMemo(+ () => ({+ left: `${(safeVisibleStart / safeSource) * 100}%`,+ width: `${Math.max(0, ((safeVisibleEnd - safeVisibleStart) / safeSource) * 100)}%`,+ }),+ [safeSource, safeVisibleStart, safeVisibleEnd],+ );++ useEffect(+ () => () => {+ dragRef.current = null;+ },+ [],+ );++ const startDrag = useCallback(+ (mode: NavigatorDragMode, event: ReactPointerEvent<HTMLElement>) => {+ const overview = overviewRef.current;+ if (!overview) return;+ event.preventDefault();+ event.stopPropagation();+ dragRef.current = {+ mode,+ startClientX: event.clientX,+ overviewWidthPx: Math.max(1, overview.clientWidth),+ startVisibleStartSec: safeVisibleStart,+ startVisibleEndSec: safeVisibleEnd,+ };+ setDragging(true);+ startGlobalPointerDrag(event, {+ onMove: (moveEvent) => {+ const current = dragRef.current;+ if (!current) return;+ const deltaFrac = (moveEvent.clientX - current.startClientX) / current.overviewWidthPx;+ const deltaSec = deltaFrac * safeSource;+ if (current.mode === "move") {+ const duration = current.startVisibleEndSec - current.startVisibleStartSec;+ const nextStart = clamp(+ current.startVisibleStartSec + deltaSec,+ 0,+ Math.max(0, safeSource - duration),+ );+ onSetVisibleWindow(nextStart, nextStart + duration);+ return;+ }+ if (current.mode === "start") {+ const minVisibleDurationSec = Math.max(0.1, safeSource / 280);+ const maxStart = Math.max(0, current.startVisibleEndSec - minVisibleDurationSec);+ const nextStart = clamp(current.startVisibleStartSec + deltaSec, 0, maxStart);+ onSetVisibleWindow(nextStart, current.startVisibleEndSec);+ return;+ }+ // mode === "end"+ const minVisibleDurationSec = Math.max(0.1, safeSource / 280);+ const minEnd = Math.min(safeSource, current.startVisibleStartSec + minVisibleDurationSec);+ const nextEnd = clamp(current.startVisibleEndSec + deltaSec, minEnd, safeSource);+ onSetVisibleWindow(current.startVisibleStartSec, nextEnd);+ },+ onEnd: () => {+ dragRef.current = null;+ setDragging(false);+ },+ });+ },+ [safeSource, safeVisibleStart, safeVisibleEnd, onSetVisibleWindow],+ );++ return (+ <div+ ref={overviewRef}+ className={+ dragging ? `${styles.timelineNavigator} ${styles.navigating}` : styles.timelineNavigator+ }+ aria-label="Timeline zoom and pan navigator"+ >+ <div className={styles.timelineNavigatorContent}>+ {skipRanges.map((skip) => (+ <span+ key={skip.id}+ className={styles.timelineNavigatorSkip}+ style={{+ left: `${(skip.startSec / safeSource) * 100}%`,+ width: `${((skip.endSec - skip.startSec) / safeSource) * 100}%`,+ }}+ />+ ))}+ </div>+ <div+ className={styles.timelineNavigatorWindow}+ style={windowStyle}+ onPointerDown={(event) => startDrag("move", event)}+ >+ <span+ className={styles.timelineNavigatorHandleStart}+ onPointerDown={(event) => startDrag("start", event)}+ />+ <span+ className={styles.timelineNavigatorHandleEnd}+ onPointerDown={(event) => startDrag("end", event)}+ />+ </div>+ </div>+ );+}diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex a7d4fb113..b0e8bca4c 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -21,7 +21,7 @@ interface VirtualPreviewProps {clips: AxcutClip[];seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;onTimeChange?: (timeSec: number) => void;- onLoadedMetadata?: (durationSec: number) => void;+ onLoadedMetadata?: (durationSec: number, assetId: string) => void;onVideoElement?: (element: HTMLVideoElement | null) => void;videoStyle?: React.CSSProperties;onVideoError?: () => void;@@ -238,10 +238,19 @@ export function VirtualPreview({playsInlineonLoadedMetadata={(e) => {setLoadState("ready");- const duration = e.currentTarget.duration;- if (Number.isFinite(duration) && duration > 0) {- onLoadedMetadata?.(duration);- }+ // ponytail: forward the raw duration (possibly NaN for+ // MediaRecorder WebMs) to the parent. handleLoadedMetadata+ // falls back to a 60s seed when it isn't finite so the+ // timeline gets a populated clip even before the EBML fix+ // lands. Previously this gate skipped the callback for+ // non-finite durations and stranded the editor on+ // "No clips yet" until manual intervention. The assetId is+ // forwarded so the parent only ever corrects clips that+ // belong to the asset which actually fired this event —+ // without it, switching between clips of different assets+ // during multi-clip playback clobbered clip[0]'s duration+ // with whichever asset's video happened to load last.+ onLoadedMetadata?.(e.currentTarget.duration, activeSource.id);if (pendingSeekRef.current) {const { sourceTimeSec, play } = pendingSeekRef.current;pendingSeekRef.current = null;diff --git a/src/components/video-editor/featureFlags.ts b/src/components/video-editor/featureFlags.tsindex 5209db37e..a5dc15fc1 100644--- a/src/components/video-editor/featureFlags.ts+++ b/src/components/video-editor/featureFlags.ts@@ -6,5 +6,5 @@ export const BLUR_REGIONS_ENABLED = false;// 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.+// docs/architecture/ai-edition-roadmap.md §1 / §3 (decision 9).export const AI_FEATURES_ENABLED = true;diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.tsindex b66aa5350..dc3657cb9 100644--- a/src/lib/ai-edition/document/migrate.ts+++ b/src/lib/ai-edition/document/migrate.ts@@ -1,5 +1,5 @@// Bidirectional migration between OpenScreen's v2 EditorProjectData and the-// new v3 AxcutDocument. See docs/architecture/ai-edition-merge-plan.md §2.1+// new v3 AxcutDocument. See docs/architecture/ai-edition-roadmap.md §2// for the field-by-field mapping. The migration is pure (no DOM, no fs, no// network) — the renderer probes asset duration at runtime.//diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex 7686ed3ec..25c7eaea0 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -1,6 +1,6 @@// 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):+// OpenScreen's AI-edition merge (Phase 0, see docs/architecture/ai-edition-roadmap.md)://// 1. axcutSchemaVersion bumped 2 -> 3.// 2. clip.sourceEndSec made optional (duration is unknown until asset is probed).@@ -382,7 +382,7 @@ export const zoomRegionSchema = z// 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).+// by the existing pipeline (see docs/architecture/ai-edition-roadmap.md §2).//// ponytail: passthrough blob — v2 ProjectEditorState carries ~25 fields, several// of which (autoZoomEnabled, autoFocusAll, cursorTheme, …) have no first-classdiff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.tsnew file mode 100644index 000000000..f0c40bb04--- /dev/null+++ b/src/lib/ai-edition/store/useTimeline.test.ts@@ -0,0 +1,140 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProjectStore } from "./projectStore";+import { useTimeline } from "./useTimeline";++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",+ primaryAssetId: "asset_1",+ },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "screen.webm",+ originalPath: "/tmp/screen.webm",+ durationSec: 30,+ },+ ],+ transcript: null,+ transcripts: [],+ timeline: {+ clips: [+ {+ id: "clip_a",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ 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("useTimeline.editClip", () => {+ beforeEach(() => {+ useProjectStore.getState().clear();+ for (const mock of Object.values(bridgeMocks)) mock.mockReset();+ bridgeMocks.save.mockImplementation(async (doc: typeof sampleDoc) => ({+ success: true,+ document: doc,+ }));+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ });+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("updates the target clip in place and persists via the store", async () => {+ const { result } = renderHook(() => useTimeline());+ await act(async () => {+ await result.current.editClip("clip_a", {+ sourceStartSec: 1,+ sourceEndSec: 8,+ timelineStartSec: 2,+ timelineEndSec: 9,+ });+ });+ const doc = useProjectStore.getState().document;+ const updated = doc?.timeline.clips[0];+ expect(updated).toMatchObject({+ id: "clip_a",+ sourceStartSec: 1,+ sourceEndSec: 8,+ timelineStartSec: 2,+ timelineEndSec: 9,+ });+ expect(bridgeMocks.save).toHaveBeenCalledTimes(1);+ });++ it("clamps end >= start when the user types them out of order", async () => {+ const { result } = renderHook(() => useTimeline());+ await act(async () => {+ await result.current.editClip("clip_a", {+ sourceStartSec: 7,+ sourceEndSec: 2,+ });+ });+ const updated = useProjectStore.getState().document?.timeline.clips[0];+ expect(updated?.sourceStartSec).toBe(2);+ expect(updated?.sourceEndSec).toBe(7);+ });++ it("no-ops when the clip id is unknown", async () => {+ const { result } = renderHook(() => useTimeline());+ await act(async () => {+ await result.current.editClip("clip_missing", { sourceStartSec: 1 });+ });+ expect(bridgeMocks.save).not.toHaveBeenCalled();+ });+});diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex e278f949d..e69ed0be8 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -4,24 +4,52 @@// (a reasonable default for the user to then resize).import { useCallback, useState } from "react";+import { toFileUrl } from "@/components/video-editor/projectPersistence";import type { AnnotationRegion, AnnotationType } from "@/components/video-editor/types";import { createId } from "../document/ids";import type { AxcutDocument } from "../schema";+import { probeVideoDuration } from "../timeline/duration";import { useProjectStore } from "./projectStore";type RegionKind = "zoom" | "skip" | "annotation" | "speed";+// Placeholder duration applied to a freshly-inserted clip whose source asset+// hasn't reported its real duration yet (media drag → drop before the preview+// video fires `loadedmetadata`). The renderer's handleLoadedMetadata+// (NewEditorShell) scans for clips sitting at exactly this value and+// auto-corrects them to the probed duration once metadata arrives, so the+// timeline ruler, progress bar, and sourceEndSec all stay in sync.+export const PLACEHOLDER_DURATION_SEC = 60;+interface RegionHandle {kind: RegionKind;id: string;}+type Clip = AxcutDocument["timeline"]["clips"][number];++// Lay clips back-to-back from t=0, preserving each clip's own length. Called+// after any structural change (insert / move / remove) so the timeline never+// has gaps or overlaps between clips.+function resequenceClips(clips: Clip[]): Clip[] {+ let cursor = 0;+ return clips.map((c) => {+ const timelineLen = c.timelineEndSec - c.timelineStartSec;+ const sourceLen = (c.sourceEndSec ?? 0) - c.sourceStartSec;+ const len = Math.max(0.001, timelineLen > 0 ? timelineLen : sourceLen);+ const next = { ...c, timelineStartSec: cursor, timelineEndSec: cursor + len };+ cursor += len;+ return next;+ });+}+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 [clipSelection, setClipSelection] = useState<string | null>(null);const hasDoc = document !== null && projectId !== null;@@ -71,6 +99,34 @@ export function useTimeline() {await saveDocument(next);}, [document, currentTimeSec, saveDocument]);+ // T15 — add a skip at a specific (assetId, sourceStartSec, sourceEndSec).+ // Used by the place-skip mode in TimelinePane where the cursor lands+ // inside a specific clip's source range, not just at currentTimeSec.+ const addSkipAt = useCallback(+ async (assetId: string, sourceStartSec: number, sourceEndSec: number) => {+ if (!document) return;+ const next: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ skipRanges: [+ ...document.timeline.skipRanges,+ {+ id: createId("skip"),+ assetId,+ startSec: sourceStartSec,+ endSec: sourceEndSec,+ reason: "manual",+ origin: "user" as const,+ },+ ],+ },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );+const addAnnotation = useCallback(async () => {if (!document) return;const timeMs = Math.round(currentTimeSec * 1000);@@ -126,6 +182,87 @@ export function useTimeline() {await saveDocument(next);}, [document, currentTimeSec, saveDocument]);+ const updateSkipRange = useCallback(+ async (skipId: string, startSec: number, endSec: number) => {+ if (!document) return;+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);+ const s = clamp(startSec);+ const e = clamp(endSec);+ const next: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ skipRanges: document.timeline.skipRanges.map((r) =>+ r.id === skipId ? { ...r, startSec: Math.min(s, e), endSec: Math.max(s, e) } : r,+ ),+ },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ const updateZoomSpan = useCallback(+ async (id: string, startMs: number, endMs: number) => {+ if (!document) return;+ const clampMs = (n: number) => (Number.isFinite(n) ? Math.max(0, Math.round(n)) : 0);+ const s = clampMs(startMs);+ const e = clampMs(endMs);+ const next: AxcutDocument = {+ ...document,+ zoomRanges: document.zoomRanges.map((z) =>+ z.id === id ? { ...z, startMs: Math.min(s, e), endMs: Math.max(s, e) } : z,+ ) as AxcutDocument["zoomRanges"],+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ const updateAnnotationSpan = useCallback(+ async (id: string, startMs: number, endMs: number) => {+ if (!document) return;+ const clampMs = (n: number) => (Number.isFinite(n) ? Math.max(0, Math.round(n)) : 0);+ const s = clampMs(startMs);+ const e = clampMs(endMs);+ const next: AxcutDocument = {+ ...document,+ annotations: document.annotations.map((a) =>+ a.id === id ? { ...a, startMs: Math.min(s, e), endMs: Math.max(s, e) } : a,+ ),+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ const updateSpeedSpan = useCallback(+ async (id: string, startMs: number, endMs: number) => {+ if (!document) return;+ const clampMs = (n: number) => (Number.isFinite(n) ? Math.max(0, Math.round(n)) : 0);+ const s = clampMs(startMs);+ const e = clampMs(endMs);+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = ((legacy.speedRegions as unknown[]) ?? []) as Array<{+ id: string;+ startMs: number;+ endMs: number;+ speed: number;+ }>;+ const next: AxcutDocument = {+ ...document,+ legacyEditor: {+ ...legacy,+ speedRegions: prev.map((r) =>+ r.id === id ? { ...r, startMs: Math.min(s, e), endMs: Math.max(s, e) } : r,+ ),+ },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );+const removeRegion = useCallback(async (kind: RegionKind, id: string) => {if (!document) return;@@ -175,7 +312,7 @@ export function useTimeline() {if (!document) return;const asset = document.assets.find((a) => a.id === assetId);if (!asset) return;- const duration = asset.durationSec ?? 30;+ const duration = asset.durationSec ?? PLACEHOLDER_DURATION_SEC;const newClip: AxcutDocument["timeline"]["clips"][number] = {id: createId("clip"),assetId,@@ -209,7 +346,7 @@ export function useTimeline() {if (!document) return;const asset = document.assets.find((a) => a.id === assetId);if (!asset) return;- const duration = asset.durationSec ?? 30;+ const duration = asset.durationSec ?? PLACEHOLDER_DURATION_SEC;const lastEnd = document.timeline.clips.at(-1)?.timelineEndSec ?? 0;const newClip: AxcutDocument["timeline"]["clips"][number] = {id: createId("clip"),@@ -234,12 +371,82 @@ export function useTimeline() {[document, saveDocument],);+ const editClip = useCallback(+ async (+ clipId: string,+ patch: Partial<+ Pick<+ AxcutDocument["timeline"]["clips"][number],+ "sourceStartSec" | "sourceEndSec" | "timelineStartSec" | "timelineEndSec"+ >+ >,+ ) => {+ if (!document) return;+ // ponytail: clamp negative values and keep end >= start so the schema+ // refine doesn't reject the save. Swap when end < start instead of+ // throwing — a user typing into a number input is expected to be+ // able to type in any order.+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);+ const next: AxcutDocument["timeline"]["clips"][number] = {+ ...(document.timeline.clips.find((c) => c.id === clipId) as+ | AxcutDocument["timeline"]["clips"][number]+ | undefined),+ } as AxcutDocument["timeline"]["clips"][number];+ if (!next?.id) return;+ const sStart = clamp(patch.sourceStartSec ?? next.sourceStartSec);+ const sEnd = clamp(patch.sourceEndSec ?? next.sourceEndSec ?? 0);+ const tStart = clamp(patch.timelineStartSec ?? next.timelineStartSec);+ const tEnd = clamp(patch.timelineEndSec ?? next.timelineEndSec);+ const updated: AxcutDocument["timeline"]["clips"][number] = {+ ...next,+ sourceStartSec: Math.min(sStart, sEnd),+ sourceEndSec: Math.max(sStart, sEnd),+ timelineStartSec: Math.min(tStart, tEnd),+ timelineEndSec: Math.max(tStart, tEnd),+ };+ const nextDoc: AxcutDocument = {+ ...document,+ timeline: {+ ...document.timeline,+ clips: document.timeline.clips.map((c) => (c.id === clipId ? updated : c)),+ },+ };+ await saveDocument(nextDoc);+ },+ [document, saveDocument],+ );++ // Axcut-consistent clip trim: only the source range is user-editable (the+ // Edit Clip dialog's draggable track). Changing it changes the clip's+ // effective duration, so every clip is resequenced back-to-back afterward —+ // same invariant as insertClipAt/moveClip/removeClip — instead of leaving+ // downstream clips at their old timeline positions (which would overlap).+ const updateClipSourceRange = useCallback(+ async (clipId: string, sourceStartSec: number, sourceEndSec: number) => {+ if (!document) return;+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);+ const s = clamp(sourceStartSec);+ const e = clamp(sourceEndSec);+ const arr = document.timeline.clips.map((c) =>+ c.id === clipId+ ? { ...c, sourceStartSec: Math.min(s, e), sourceEndSec: Math.max(s, e) }+ : c,+ );+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: resequenceClips(arr) },+ };+ 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 duration = asset.durationSec ?? PLACEHOLDER_DURATION_SEC;const targetIdx = document.timeline.clips.findIndex((c) => c.timelineStartSec <= splitTimeSec && c.timelineEndSec >= splitTimeSec,);@@ -297,6 +504,166 @@ export function useTimeline() {[document, saveDocument, addClipAfter],);+ // Insert a new full-duration clip for `assetId` at position `index`+ // (0 = before all, clips.length = after all), then resequence.+ //+ // ponytail: probe the file's actual duration via a throwaway <video> in+ // the BACKGROUND so the drop event stays responsive. Earlier this awaited+ // probeVideoDuration synchronously, which could take up to 5s on a slow+ // disk or broken file path — the user saw the UI freeze for the whole+ // probe window with no feedback. Now: insert the clip immediately at the+ // placeholder (60s), then update its sourceEndSec / timelineEndSec when+ // the probe resolves. If the user has since trimmed the clip, we leave it+ // alone (same guard handleLoadedMetadata uses).+ const insertClipAt = useCallback(+ async (assetId: string, index: number) => {+ const currentDoc = useProjectStore.getState().document;+ if (!currentDoc) return;+ const asset = currentDoc.assets.find((a) => a.id === assetId);+ if (!asset) return;+ // Insert immediately at whatever we know. If the asset has a cached+ // durationSec we use it; otherwise we fall back to the placeholder+ // and let the background probe correct it.+ const knownDuration = asset.durationSec ?? PLACEHOLDER_DURATION_SEC;+ const newClip: Clip = {+ id: createId("clip"),+ assetId,+ sourceStartSec: 0,+ sourceEndSec: knownDuration,+ timelineStartSec: 0,+ timelineEndSec: knownDuration,+ wordRefs: [],+ origin: "user",+ reason: "Inserted from media panel",+ };+ const arr = [...currentDoc.timeline.clips];+ const at = Math.max(0, Math.min(arr.length, index));+ arr.splice(at, 0, newClip);+ const next: AxcutDocument = {+ ...currentDoc,+ timeline: { ...currentDoc.timeline, clips: resequenceClips(arr) },+ };+ await saveDocument(next);+ setClipSelection(newClip.id);++ // If we used the placeholder, kick off the probe in the background.+ // Don't await — the drop is already responsive; the probe will+ // correct the clip when it lands.+ if (asset.durationSec == null) {+ void probeAndCorrectClip(assetId, newClip.id, asset.originalPath);+ }+ },+ [saveDocument],+ );++ // Background probe: read the asset's actual duration and patch the+ // freshly-inserted clip to use it. Skips if the clip has already been+ // trimmed (sourceEndSec != PLACEHOLDER_DURATION_SEC) so we never stomp+ // on user edits. Also persists the duration back onto the asset so+ // subsequent inserts use the cached value without re-probing.+ const probeAndCorrectClip = useCallback(+ async (assetId: string, clipId: string, originalPath: string) => {+ const probed = await probeVideoDuration(toFileUrl(originalPath));+ if (probed == null) return;+ const state = useProjectStore.getState();+ const doc = state.document;+ if (!doc) return;+ const clip = doc.timeline.clips.find((c) => c.id === clipId);+ if (!clip) return;+ // Guard: only correct clips still sitting at the 0..60s placeholder.+ // If the user has since trimmed the clip or moved on, leave it alone.+ const stillPlaceholder =+ clip.sourceStartSec === 0 &&+ Math.abs((clip.sourceEndSec ?? 0) - PLACEHOLDER_DURATION_SEC) < 0.01;+ if (!stillPlaceholder) return;+ const shiftSec = probed - (clip.sourceEndSec ?? PLACEHOLDER_DURATION_SEC);+ const nextClips = doc.timeline.clips.map((c) => {+ if (c.id !== clipId) {+ return {+ ...c,+ timelineStartSec: c.timelineStartSec + shiftSec,+ timelineEndSec: c.timelineEndSec + shiftSec,+ };+ }+ return {+ ...c,+ sourceEndSec: probed,+ timelineEndSec: c.timelineStartSec + probed,+ };+ });+ const nextAssets = doc.assets.map((a) =>+ a.id === assetId ? { ...a, durationSec: probed } : a,+ );+ await state.saveDocument({+ ...doc,+ assets: nextAssets,+ timeline: { ...doc.timeline, clips: nextClips },+ });+ },+ [],+ );++ // Reorder a clip to a new index, then resequence timeline positions.+ const moveClip = useCallback(+ async (clipId: string, toIndex: number) => {+ if (!document) return;+ const arr = [...document.timeline.clips];+ const from = arr.findIndex((c) => c.id === clipId);+ if (from === -1) return;+ const [moved] = arr.splice(from, 1);+ const at = Math.max(0, Math.min(arr.length, toIndex));+ arr.splice(at, 0, moved);+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: resequenceClips(arr) },+ };+ await saveDocument(next);+ },+ [document, saveDocument],+ );++ // Duplicate a clip in place (same asset + source range), inserted right+ // after the original, then resequenced. Mirrors Axcut's Ctrl+C/Ctrl+V.+ const duplicateClip = useCallback(+ async (clipId: string) => {+ if (!document) return;+ const arr = [...document.timeline.clips];+ const from = arr.findIndex((c) => c.id === clipId);+ if (from === -1) return;+ const source = arr[from];+ const copy: Clip = {+ ...source,+ id: createId("clip"),+ reason: "Duplicated clip",+ };+ arr.splice(from + 1, 0, copy);+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: resequenceClips(arr) },+ };+ await saveDocument(next);+ setClipSelection(copy.id);+ },+ [document, saveDocument],+ );++ const removeClip = useCallback(+ async (clipId: string) => {+ if (!document) return;+ const arr = document.timeline.clips.filter((c) => c.id !== clipId);+ const next: AxcutDocument = {+ ...document,+ timeline: { ...document.timeline, clips: resequenceClips(arr) },+ };+ await saveDocument(next);+ if (clipSelection === clipId) setClipSelection(null);+ },+ [document, clipSelection, saveDocument],+ );++ const selectClip = useCallback((id: string) => setClipSelection(id), []);+ const clearClipSelection = useCallback(() => setClipSelection(null), []);+const speedRegions = hasDoc? (((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as Array<{id: string;@@ -311,10 +678,14 @@ export function useTimeline() {skipRanges: document?.timeline.skipRanges ?? [],annotationRegions: (document?.annotations ?? []) as unknown as AnnotationRegion[],speedRegions,+ clips: document?.timeline.clips ?? [],+ assets: document?.assets ?? [],hasDoc,selection,+ clipSelection,addZoom,addSkip,+ addSkipAt,addAnnotation,addSpeed,removeRegion,@@ -322,6 +693,20 @@ export function useTimeline() {clearSelection,addClipBefore,addClipAfter,+ editClip,+ updateClipSourceRange,splitAndInsert,+ insertClipAt,+ moveClip,+ duplicateClip,+ removeClip,+ selectClip,+ clearClipSelection,+ updateSkipRange,+ updateZoomSpan,+ updateAnnotationSpan,+ updateSpeedSpan,+ // T19 — drives the preview video during skip-edge resize.+ setCurrentTime: useProjectStore((s) => s.setCurrentTime),};}diff --git a/src/lib/ai-edition/timeline/duration.test.ts b/src/lib/ai-edition/timeline/duration.test.tsnew file mode 100644index 000000000..091c59037--- /dev/null+++ b/src/lib/ai-edition/timeline/duration.test.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { probeVideoDuration } from "./duration";++interface FakeVideo {+ duration: number;+ onloadedmetadata: ((ev: Event) => unknown) | null;+ onerror: ((ev: Event) => unknown) | null;+}++describe("probeVideoDuration", () => {+ let created: FakeVideo[];+ let originalCreate: typeof document.createElement;+ let appendSpy: ReturnType<typeof vi.spyOn> | null;++ beforeEach(() => {+ vi.useFakeTimers();+ created = [];+ originalCreate = document.createElement;+ document.createElement = ((tag: string) => {+ const node = originalCreate.call(document, tag);+ if (tag === "video") {+ const fake: FakeVideo = {+ duration: Number.NaN,+ onloadedmetadata: null,+ onerror: null,+ };+ created.push(fake);+ // jsdom appendChild validates Node; return the real element but+ // mirror handlers/duration onto the fake so the test can drive it.+ Object.defineProperty(node, "duration", {+ configurable: true,+ get: () => fake.duration,+ });+ const origOnLoadedSetter = (v: typeof fake.onloadedmetadata) => {+ fake.onloadedmetadata = v;+ };+ const origOnErrorSetter = (v: typeof fake.onerror) => {+ fake.onerror = v;+ };+ Object.defineProperty(node, "onloadedmetadata", {+ configurable: true,+ get: () => fake.onloadedmetadata,+ set: origOnLoadedSetter,+ });+ Object.defineProperty(node, "onerror", {+ configurable: true,+ get: () => fake.onerror,+ set: origOnErrorSetter,+ });+ return node;+ }+ return node;+ }) as typeof document.createElement;+ });+ afterEach(() => {+ document.createElement = originalCreate;+ appendSpy?.mockRestore();+ appendSpy = null;+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("returns null when src is empty", async () => {+ await expect(probeVideoDuration("")).resolves.toBeNull();+ });++ it("returns duration on loadedmetadata", async () => {+ const p = probeVideoDuration("file:///tmp/clip.mp4");+ await vi.advanceTimersByTimeAsync(0);+ const v = created[0];+ v.duration = 12.5;+ v.onloadedmetadata?.(new Event("loadedmetadata"));+ await expect(p).resolves.toBe(12.5);+ });++ it("returns null on error", async () => {+ const p = probeVideoDuration("file:///missing.mp4");+ await vi.advanceTimersByTimeAsync(0);+ created[0].onerror?.(new Event("error"));+ await expect(p).resolves.toBeNull();+ });++ it("returns null on timeout", async () => {+ const p = probeVideoDuration("file:///slow.mp4", 1000);+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2000);+ await expect(p).resolves.toBeNull();+ });++ it("returns null for non-finite duration", async () => {+ for (const d of [Number.POSITIVE_INFINITY, Number.NaN, -1, 0]) {+ const p = probeVideoDuration("file:///x.mp4");+ await vi.advanceTimersByTimeAsync(0);+ const v = created[created.length - 1];+ v.duration = d;+ v.onloadedmetadata?.(new Event("loadedmetadata"));+ await expect(p).resolves.toBeNull();+ }+ });+});diff --git a/src/lib/ai-edition/timeline/duration.ts b/src/lib/ai-edition/timeline/duration.tsnew file mode 100644index 000000000..63d3f72cf--- /dev/null+++ b/src/lib/ai-edition/timeline/duration.ts@@ -0,0 +1,63 @@+// Probe a video file's actual duration by mounting a hidden <video> and+// waiting for loadedmetadata. Used by the timeline store to size+// freshly-inserted clips at the real source duration, so the user sees+// the correct clip width immediately on drop instead of the placeholder.+//+// Falls back to null on error / timeout / non-finite duration. Caller+// decides whether to fall back to a placeholder (60s) or surface an error.+//+// ponytail: probe via DOM <video> rather than the existing VirtualPreview.+// We need this BEFORE the clip is on the timeline (so insertClipAt can+// size it correctly), but VirtualPreview only mounts once a clip exists.+// A throwaway <video> is the cleanest no-extra-component solution.++const DEFAULT_TIMEOUT_MS = 5000;++export function probeVideoDuration(+ src: string,+ timeoutMs: number = DEFAULT_TIMEOUT_MS,+): Promise<number | null> {+ return new Promise((resolve) => {+ if (typeof document === "undefined" || !src) {+ resolve(null);+ return;+ }+ const video = document.createElement("video");+ video.preload = "metadata";+ video.style.position = "absolute";+ video.style.width = "1px";+ video.style.height = "1px";+ video.style.opacity = "0";+ video.style.pointerEvents = "none";+ video.style.left = "-9999px";+ let settled = false;+ const cleanup = () => {+ video.onloadedmetadata = null;+ video.onerror = null;+ clearTimeout(timer);+ try {+ video.removeAttribute("src");+ video.load();+ } catch {+ // ignore — browser may refuse if already detached+ }+ if (video.parentNode) video.parentNode.removeChild(video);+ };+ const settle = (value: number | null) => {+ if (settled) return;+ settled = true;+ cleanup();+ resolve(value);+ };+ const timer = setTimeout(() => settle(null), timeoutMs);+ video.onloadedmetadata = () => {+ const d = video.duration;+ settle(Number.isFinite(d) && d > 0 ? d : null);+ };+ video.onerror = () => settle(null);+ // ponytail: append to body so some browsers (Firefox) actually fire+ // loadedmetadata for fully-detached <video> elements.+ document.body.appendChild(video);+ video.src = src;+ });+}diff --git a/src/lib/ai-edition/timeline/format.ts b/src/lib/ai-edition/timeline/format.tsnew file mode 100644index 000000000..f6f517227--- /dev/null+++ b/src/lib/ai-edition/timeline/format.ts@@ -0,0 +1,14 @@+// Format milliseconds as the timeline-style timecode (m:ss.t).+//+// Shared by Bottombar lane pills and TimelinePane so pill hover tips and the+// header readouts stay in sync. Kept tiny — it's used in dozens of pill titles+// and would otherwise duplicate `${Math.floor(sec/60)}:${(...).toFixed(1)}`+// paddings across the editor.++export function formatMs(ms: number): string {+ if (!Number.isFinite(ms) || ms < 0) return "0:00.0";+ const sec = ms / 1000;+ const m = Math.floor(sec / 60);+ const s = (sec % 60).toFixed(1);+ return `${m}:${s.padStart(4, "0")}`;+}diff --git a/src/lib/ai-edition/timeline/pointer-drag.test.tsx b/src/lib/ai-edition/timeline/pointer-drag.test.tsxnew file mode 100644index 000000000..9468c063d--- /dev/null+++ b/src/lib/ai-edition/timeline/pointer-drag.test.tsx@@ -0,0 +1,118 @@+import { fireEvent, render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { startGlobalPointerDrag } from "./pointer-drag";++interface ElementWithCapture extends Element {+ hasPointerCapture?: (id: number) => boolean;+ setPointerCapture?: (id: number) => void;+ releasePointerCapture?: (id: number) => void;+}++describe("startGlobalPointerDrag", () => {+ beforeEach(() => {+ // jsdom doesn't implement pointer capture; patch so the helper doesn't throw.+ const proto = Element.prototype as ElementWithCapture;+ if (!proto.hasPointerCapture) proto.hasPointerCapture = () => false;+ if (!proto.setPointerCapture) proto.setPointerCapture = () => undefined;+ if (!proto.releasePointerCapture) proto.releasePointerCapture = () => undefined;+ });++ it("invokes onMove on subsequent pointermove and onEnd on pointerup", () => {+ const onMove = vi.fn();+ const onEnd = vi.fn();+ const { getByRole } = render(+ <button+ type="button"+ onPointerDown={(event) => startGlobalPointerDrag(event, { onMove, onEnd })}+ >+ go+ </button>,+ );+ fireEvent.pointerDown(getByRole("button"), { pointerId: 1, buttons: 1 });+ fireEvent.pointerMove(window, { pointerId: 1, buttons: 1 });+ fireEvent.pointerUp(window, { pointerId: 1 });+ expect(onMove).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledWith("pointerup", expect.anything());+ });++ it("ends early when buttons drop to 0 mid-move", () => {+ const onEnd = vi.fn();+ const { getByRole } = render(+ <button+ type="button"+ onPointerDown={(event) =>+ startGlobalPointerDrag(event, {+ onMove: (_e) => undefined,+ onEnd,+ })+ }+ >+ go+ </button>,+ );+ fireEvent.pointerDown(getByRole("button"), { pointerId: 2, buttons: 1 });+ fireEvent.pointerMove(window, { pointerId: 2, buttons: 0 });+ expect(onEnd).toHaveBeenCalledWith("pointerup", expect.anything());+ });++ it("ignores pointermove from other pointerIds", () => {+ const onMove = vi.fn();+ const { getByRole } = render(+ <button+ type="button"+ onPointerDown={(event) =>+ startGlobalPointerDrag(event, {+ onMove,+ onEnd: (_r, _e) => undefined,+ })+ }+ >+ go+ </button>,+ );+ fireEvent.pointerDown(getByRole("button"), { pointerId: 3, buttons: 1 });+ fireEvent.pointerMove(window, { pointerId: 99, buttons: 1 });+ expect(onMove).not.toHaveBeenCalled();+ });++ it("ends with window-blur when the window loses focus", () => {+ const onEnd = vi.fn();+ const { getByRole } = render(+ <button+ type="button"+ onPointerDown={(event) =>+ startGlobalPointerDrag(event, {+ onMove: (_e) => undefined,+ onEnd,+ })+ }+ >+ go+ </button>,+ );+ fireEvent.pointerDown(getByRole("button"), { pointerId: 4, buttons: 1 });+ fireEvent.blur(window);+ expect(onEnd).toHaveBeenCalledWith("window-blur", undefined);+ });++ it("cancel-returned function ends with pointercancel", () => {+ const onEnd = vi.fn();+ let cancel: (() => void) | null = null;+ const { getByRole } = render(+ <button+ type="button"+ onPointerDown={(event) => {+ cancel = startGlobalPointerDrag(event, {+ onMove: (_e) => undefined,+ onEnd,+ });+ }}+ >+ go+ </button>,+ );+ fireEvent.pointerDown(getByRole("button"), { pointerId: 5, buttons: 1 });+ cancel?.();+ expect(onEnd).toHaveBeenCalledWith("pointercancel", undefined);+ });+});diff --git a/src/lib/ai-edition/timeline/pointer-drag.ts b/src/lib/ai-edition/timeline/pointer-drag.tsnew file mode 100644index 000000000..135dad102--- /dev/null+++ b/src/lib/ai-edition/timeline/pointer-drag.ts@@ -0,0 +1,110 @@+import type { PointerEvent as ReactPointerEvent } from "react";++// End reason for a global pointer drag — drives cleanup branching in+// callers (some want to commit on pointerup, others want to discard on+// cancel).+export type PointerDragEndReason =+ | "pointerup"+ | "pointercancel"+ | "window-blur"+ | "document-hidden";++interface PointerDragOptions {+ onMove: (event: PointerEvent) => void;+ onEnd: (reason: PointerDragEndReason, event?: PointerEvent) => void;+}++// Single primitive for every drag-style interaction on the timeline+// (resize skip, reorder clip, scrub, pan, navigator handle). Wraps the+// React PointerEvent in window-level capture so the drag survives the+// pointer leaving the original element.+//+// Source of truth: axcut/apps/web/src/lib/pointer-drag.ts. Behaviors:+// • sets pointer capture on the source element+// • installs capture-phase listeners on window for move / up / cancel /+// out / blur and on document for visibilitychange+// • early-ends when buttons drop to 0 (some platforms fire pointermove+// without buttons)+// • early-ends on window blur or document-hidden (no stuck state)+// • ignores pointer events for other pointerIds (multi-touch safety)+//+// Returns a cancel function for callers that want to abort (rare).+export function startGlobalPointerDrag(+ event: ReactPointerEvent<HTMLElement>,+ options: PointerDragOptions,+): () => void {+ const target = event.currentTarget;+ const pointerId = event.pointerId;+ let ended = false;++ const cleanup = (reason: PointerDragEndReason, pointerEvent?: PointerEvent) => {+ if (ended) return;+ ended = true;+ globalThis.window.removeEventListener("pointermove", handleMove, true);+ globalThis.window.removeEventListener("pointerup", handlePointerUp, true);+ globalThis.window.removeEventListener("pointercancel", handlePointerCancel, true);+ globalThis.window.removeEventListener("pointerout", handlePointerOut, true);+ globalThis.window.removeEventListener("mouseout", handleMouseOut, true);+ globalThis.window.removeEventListener("blur", handleWindowBlur, true);+ globalThis.document.removeEventListener("visibilitychange", handleVisibilityChange, true);+ try {+ if (target.hasPointerCapture(pointerId)) {+ target.releasePointerCapture(pointerId);+ }+ } catch {+ // Some browsers can throw if the pointer was already implicitly released.+ }+ options.onEnd(reason, pointerEvent);+ };++ const handleMove = (pointerEvent: PointerEvent) => {+ if (pointerEvent.pointerId !== pointerId) return;+ if (pointerEvent.buttons === 0) {+ cleanup("pointerup", pointerEvent);+ return;+ }+ options.onMove(pointerEvent);+ };++ const handlePointerUp = (pointerEvent: PointerEvent) => {+ if (pointerEvent.pointerId !== pointerId) return;+ cleanup("pointerup", pointerEvent);+ };++ const handlePointerCancel = (pointerEvent: PointerEvent) => {+ if (pointerEvent.pointerId !== pointerId) return;+ cleanup("pointercancel", pointerEvent);+ };++ const handlePointerOut = (pointerEvent: PointerEvent) => {+ if (pointerEvent.pointerId === pointerId && pointerEvent.relatedTarget === null) {+ cleanup("pointercancel", pointerEvent);+ }+ };+ const handleMouseOut = (mouseEvent: MouseEvent) => {+ if (mouseEvent.relatedTarget === null) {+ cleanup("pointercancel");+ }+ };+ const handleWindowBlur = () => cleanup("window-blur");+ const handleVisibilityChange = () => {+ if (globalThis.document.visibilityState === "hidden") {+ cleanup("document-hidden");+ }+ };++ try {+ target.setPointerCapture(pointerId);+ } catch {+ // Window-level listeners below still provide a fallback for older/edge cases.+ }+ globalThis.window.addEventListener("pointermove", handleMove, true);+ globalThis.window.addEventListener("pointerup", handlePointerUp, true);+ globalThis.window.addEventListener("pointercancel", handlePointerCancel, true);+ globalThis.window.addEventListener("pointerout", handlePointerOut, true);+ globalThis.window.addEventListener("mouseout", handleMouseOut, true);+ globalThis.window.addEventListener("blur", handleWindowBlur, true);+ globalThis.document.addEventListener("visibilitychange", handleVisibilityChange, true);++ return () => cleanup("pointercancel");+}diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsindex 646cdce93..eacb8952e 100644--- a/src/native/browserShim.ts+++ b/src/native/browserShim.ts@@ -28,6 +28,12 @@ function createShimElectronAPI() {switchToEditor: () => Promise.resolve({ success: true }),startNewRecording: () => Promise.resolve({ success: true }),openSourceSelector: () => Promise.resolve({ success: true }),+ setHasUnsavedChanges: () => undefined,+ sendCloseConfirmResponse: () => undefined,+ onRequestCloseConfirm: () => () => undefined,+ onRequestSaveBeforeClose: () => () => undefined,+ loadProjectFileFromPath: () => Promise.resolve({ success: false, canceled: true }),+ getPathForFile: () => "",invokeNativeBridge: (req: { domain: string; action: string; payload?: unknown }) => {console.info("[browser-shim] invokeNativeBridge", req.domain, req.action, req.payload);return Promise.resolve({@@ -73,6 +79,32 @@ function createShimBridgeClient() {};let currentDoc: unknown = loadFromStorage();+ // ponytail: in-memory chat sessions per project for browser shim. The+ // renderer treats these the same as the main-process sessions.+ type ShimSession = {+ id: string;+ projectId: string;+ title: string;+ createdAt: string;+ messages: Array<{ id: string; role: "user" | "assistant"; content: string; createdAt: string }>;+ };+ const sessionsByProject = new Map<string, Map<string, ShimSession>>();+ const getSessions = (projectId: string): Map<string, ShimSession> => {+ let m = sessionsByProject.get(projectId);+ if (!m) {+ m = new Map();+ sessionsByProject.set(projectId, m);+ }+ return m;+ };+ const summarize = (s: ShimSession) => ({+ id: s.id,+ projectId: s.projectId,+ title: s.title,+ createdAt: s.createdAt,+ messageCount: s.messages.length,+ });+return {aiEdition: {listProjects: () => Promise.resolve(list),@@ -135,8 +167,21 @@ function createShimBridgeClient() {llmSetConfig: () => Promise.resolve({ success: true }),llmSetApiKey: () => Promise.resolve({ success: true }),llmRemoveApiKey: () => Promise.resolve({ success: true }),- chatRun: () =>- Promise.resolve({+ chatRun: (projectId: string, sessionId: string) => {+ const sessions = getSessions(projectId);+ let s = sessions.get(sessionId);+ if (!s) {+ const id = `sess_${Date.now()}`;+ s = {+ id,+ projectId,+ title: "Conversation 1",+ createdAt: new Date().toISOString(),+ messages: [],+ };+ sessions.set(id, s);+ }+ return Promise.resolve({success: true,assistantMessage: {id: `msg_${Date.now()}`,@@ -145,9 +190,79 @@ function createShimBridgeClient() {"[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 }),+ });+ },+ chatRunDefault: (projectId: string) => {+ // ponytail: legacy single-session consumers — pick the most+ // recent session or auto-create one.+ const sessions = getSessions(projectId);+ if (sessions.size === 0) {+ const id = `sess_${Date.now()}`;+ sessions.set(id, {+ id,+ projectId,+ title: "Conversation 1",+ createdAt: new Date().toISOString(),+ messages: [],+ });+ }+ return 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: (projectId: string) => {+ const m = sessionsByProject.get(projectId);+ if (!m || m.size === 0) return Promise.resolve([]);+ const arr = Array.from(m.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt));+ return Promise.resolve([...arr[0].messages]);+ },+ chatClear: (projectId: string) => {+ const m = sessionsByProject.get(projectId);+ if (m) for (const s of m.values()) s.messages = [];+ return Promise.resolve({ success: true });+ },+ chatListSessions: (projectId: string) => {+ const m = sessionsByProject.get(projectId);+ if (!m) return Promise.resolve([]);+ return Promise.resolve(Array.from(m.values()).map(summarize));+ },+ chatCreateSession: (projectId: string, title?: string) => {+ const sessions = getSessions(projectId);+ const id = `sess_${Date.now()}`;+ const s: ShimSession = {+ id,+ projectId,+ title: title?.trim() || `Conversation ${sessions.size + 1}`,+ createdAt: new Date().toISOString(),+ messages: [],+ };+ sessions.set(id, s);+ return Promise.resolve(summarize(s));+ },+ chatSelectSession: (projectId: string, sessionId: string) => {+ const s = sessionsByProject.get(projectId)?.get(sessionId);+ return Promise.resolve(s ? { ...s, messages: [...s.messages] } : null);+ },+ chatRenameSession: (projectId: string, sessionId: string, title: string) => {+ const s = sessionsByProject.get(projectId)?.get(sessionId);+ if (!s) return Promise.resolve(null);+ const trimmed = title.trim();+ if (trimmed) s.title = trimmed;+ return Promise.resolve(summarize(s));+ },+ chatDeleteSession: (projectId: string, sessionId: string) => {+ const m = sessionsByProject.get(projectId);+ if (!m?.has(sessionId)) return Promise.resolve({ success: false });+ m.delete(sessionId);+ return Promise.resolve({ success: true });+ },},project: {getCurrentContext: () =>diff --git a/src/native/client.ts b/src/native/client.tsindex 9f777b592..21380051d 100644--- a/src/native/client.ts+++ b/src/native/client.ts@@ -2,6 +2,8 @@ import {type AiEditionAssetResult,type AiEditionChatMessage,type AiEditionChatResult,+ type AiEditionChatSession,+ type AiEditionChatSessionSummary,type AiEditionDocumentResult,type AiEditionLlmConfig,type AiEditionLlmSnapshot,@@ -209,10 +211,30 @@ export const nativeBridgeClient = {action: "llm.removeApiKey",payload: { providerId },}),- chatRun: (projectId: string, message: string) =>- requireNativeBridgeData<AiEditionChatResult>({+ chatRun: (+ projectId: string,+ sessionIdOrMessage: string,+ message?: string,+ ): Promise<AiEditionChatResult> => {+ // ponytail: polymorphic — legacy 2-arg callers pass (projectId, message).+ // Multi-session callers pass (projectId, sessionId, message).+ if (message === undefined) {+ return requireNativeBridgeData<AiEditionChatResult>({+ domain: "aiEdition",+ action: "chat.runDefault",+ payload: { projectId, message: sessionIdOrMessage },+ });+ }+ return requireNativeBridgeData<AiEditionChatResult>({domain: "aiEdition",action: "chat.run",+ payload: { projectId, sessionId: sessionIdOrMessage, message },+ });+ },+ chatRunDefault: (projectId: string, message: string) =>+ requireNativeBridgeData<AiEditionChatResult>({+ domain: "aiEdition",+ action: "chat.runDefault",payload: { projectId, message },}),chatHistory: (projectId: string) =>@@ -227,5 +249,35 @@ export const nativeBridgeClient = {action: "chat.clear",payload: { projectId },}),+ chatListSessions: (projectId: string) =>+ requireNativeBridgeData<AiEditionChatSessionSummary[]>({+ domain: "aiEdition",+ action: "chat.listSessions",+ payload: { projectId },+ }),+ chatCreateSession: (projectId: string, title?: string) =>+ requireNativeBridgeData<AiEditionChatSessionSummary>({+ domain: "aiEdition",+ action: "chat.createSession",+ payload: { projectId, title },+ }),+ chatSelectSession: (projectId: string, sessionId: string) =>+ requireNativeBridgeData<AiEditionChatSession | null>({+ domain: "aiEdition",+ action: "chat.selectSession",+ payload: { projectId, sessionId },+ }),+ chatRenameSession: (projectId: string, sessionId: string, title: string) =>+ requireNativeBridgeData<AiEditionChatSessionSummary | null>({+ domain: "aiEdition",+ action: "chat.renameSession",+ payload: { projectId, sessionId, title },+ }),+ chatDeleteSession: (projectId: string, sessionId: string) =>+ requireNativeBridgeData<{ success: boolean }>({+ domain: "aiEdition",+ action: "chat.deleteSession",+ payload: { projectId, sessionId },+ }),},};diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex eba32e5e0..b60c3828d 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -139,6 +139,22 @@ export interface AiEditionChatResult {error?: string;}+export interface AiEditionChatSessionSummary {+ id: string;+ projectId: string;+ title: string;+ createdAt: string;+ messageCount: number;+}++export interface AiEditionChatSession {+ id: string;+ projectId: string;+ title: string;+ createdAt: string;+ messages: AiEditionChatMessage[];+}+export type NativeBridgeErrorCode =| "INVALID_REQUEST"| "UNSUPPORTED_ACTION"@@ -344,6 +360,12 @@ export type NativeBridgeRequest =| {domain: "aiEdition";action: "chat.run";+ payload: { projectId: string; sessionId: string; message: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.runDefault";payload: { projectId: string; message: string };requestId?: string;}@@ -358,6 +380,36 @@ export type NativeBridgeRequest =action: "chat.clear";payload: { projectId: string };requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.listSessions";+ payload: { projectId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.createSession";+ payload: { projectId: string; title?: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.selectSession";+ payload: { projectId: string; sessionId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.renameSession";+ payload: { projectId: string; sessionId: string; title: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.deleteSession";+ payload: { projectId: string; sessionId: string };+ requestId?: string;};export type NativeBridgeEventName =diff --git a/src/styles/design-tokens.css b/src/styles/design-tokens.cssindex 97a90e832..9157faec0 100644--- a/src/styles/design-tokens.css+++ b/src/styles/design-tokens.css@@ -38,6 +38,17 @@--accent-soft: rgba(16, 185, 129, 0.10);--accent-wash: rgba(16, 185, 129, 0.06);+ /* legacy shadcn-style aliases → canonical tokens. Referenced by the+ TimelinePane / TranscriptEditor / VirtualPreview / NewEditorShell module+ CSS that was ported before the token system existed. Defined via var()+ so the dark-theme overrides of the target tokens cascade automatically —+ no need to redefine these in the dark block. */+ --primary: var(--accent);+ --primary-foreground: var(--accent-on);+ --card: var(--surface);+ --card-foreground: var(--fg);+ --muted-foreground: var(--muted);+/* semantic */--danger: #ef4444;--danger-lo: #dc2626;