Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(agent): agent tool runtime, with inspector and export polish

Etienne Lescot98b87de0b124
diff --git a/docs/architecture/ai-edition-roadmap.md b/docs/architecture/ai-edition-roadmap.md
index f96a4e25f..9f90145fe 100644
--- a/docs/architecture/ai-edition-roadmap.md
+++ b/docs/architecture/ai-edition-roadmap.md
@@ -1,7 +1,7 @@
# 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`
+Last updated: 2026-07-02 · 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
@@ -58,9 +58,9 @@ electron/ai-edition/ document-service · chat-service · llm-call · llm-c
---
-## 4. Current status (2026-07-01)
+## 4. Current status (2026-07-02)
-Build health: **`tsc --noEmit` clean · 402 tests pass (50 files)** · lint clean bar pre-existing locale UTF-8.
+Build health: **`tsc --noEmit` clean · 434 tests pass (55 files)** · lint clean.
| Area | State |
|---|---|
@@ -69,10 +69,10 @@ Build health: **`tsc --noEmit` clean · 402 tests pass (50 files)** · lint clea
| **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 6.1/6.2** chat-service + IPC + LeftPanel chat + ProviderSettings (8 providers) | ✅ done (P1 agent runtime, tool loop, checkpoints, undo added in `55372df`) |
| **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 |
+| **Phase 9** i18n (`useScopedT` across components, 13 locales), undo/redo (Cmd+Z/⇧Z, works), region clipboard, EmptyState, keyboard shortcuts | partial — i18n sweep (P3.5) still open |
**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).
@@ -115,15 +115,6 @@ The new editor's timeline follows **axcut's custom viewport model**, not the des
| 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` |
@@ -145,24 +136,51 @@ The new editor's timeline follows **axcut's custom viewport model**, not the des
**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`.
+### P1 — functional plumbing (the heart of "AI editor")
+
+| # | Task | File / line anchor | Status | Commit |
+|---|------|--------------------|--------|--------|
+| P1.1 | Define a tool schema: `getCurrentDocument`, `getTranscript`, `addSkip`, `setSkipRange`, `setClipRange`, `replaceTimeline`. JSON-schema per tool, fed to the model as `tools[]`. Lives in `electron/ai-edition/agent-tools.ts` (new). | `chat-service.ts:65-78` (current SYSTEM_PROMPT) | ✅ done | `55372df` |
+| P1.2 | Implement tool execution dispatch: when the LLM returns `tool_calls`, validate args against the schema, run the matching store action (via the IPC bridge in `useTimeline.ts`), and return a JSON result to the model. | `electron/ai-edition/chat-service.ts:130-200` (the `runChat` function) | ✅ done | `55372df` |
+| P1.3 | Save a checkpoint to `chat-service.ts` (or new `agent-runtime.ts`) **before** running each tool — current `replace_timeline` style. The user can roll back. | `chat-service.ts` (no checkpoint layer) | ✅ done | `55372df` |
+| P1.4 | Multi-turn tool loop: the model may chain tools (`addSkip` → `setSkipRange` → `replaceTimeline`). Max iterations cap (e.g. 8). Surface intermediate "I'm trimming silences…" toasts. | `chat-service.ts:150-200` | ✅ done | `55372df` |
+| P1.5 | Replace the system prompt with a tool-aware one: list the tools, give the model a "current document JSON" snapshot it can `replaceTimeline` against. | `chat-service.ts:18-22` (current SYSTEM_PROMPT) | ✅ done | `55372df` |
+| P1.6 | Bridge `agent-runtime` ↔ main process: spawn the runtime inside an Electron `utilityProcess` so long agent runs don't block the renderer. The IPC entry point `ai-edition.runAgent(chatId, message)` returns when done. | new `electron/ai-edition/agent-runtime-main.ts` + `src/native/contracts.ts` | ✅ done | `55372df` |
+| P1.7 | In the chat panel, show a compact "applied: trimmed 0:02.1–0:02.4" line per tool call so the user sees what the model did. | `src/components/ai-edition/LeftPanel.tsx` (chat history block) | ✅ done | `55372df` |
+| P1.8 | Undo button: a single click reverts the last tool batch by re-applying the pre-batch checkpoint. | `chat-service.ts` (no undo yet) | ✅ done | `55372df` |
+| **P2.1** | **Chat persistence (Phase 8 remainder).** Move `sessionsByProject: Map<string, Map<string, ChatSession>>` (in `chat-service.ts:14`) into `better-sqlite3` under `~/.config/openscreen/chat.db`. Tables: `sessions(id, project_id, title, created_at, last_checkpoint_json)`, `messages(id, session_id, role, content, tool_calls_json, created_at)`, `checkpoints(id, session_id, label, document_json, created_at)`. | `electron/ai-edition/chat-service.ts:14` + new `electron/ai-edition/database.ts` | ❌ | — |
+| **P2.2** | **OAuth device-flow + PAT auth (Phase 7 remainder).** Replace the `authKind === "oauth-device"` stub at `llm-call.ts:68-72` with a real device flow: `POST /device/code` → poll `/device/token` → store `access_token` in the OS keychain (`keytar`). Wire `ProviderSettings.tsx:372, 512` "Connect" button to launch the flow and surface the verification URL in a toast. PAT: read from env (`OPENAI_PAT`, `ANTHROPIC_PAT`) at startup. | `llm-call.ts:68-72` + `ProviderSettings.tsx:372, 512` | ❌ | — |
+| **P2.3** | **Provider-registry expand.** Add `google` (gemini-1.5-pro via OAuth) and `github-copilot` (device flow) to `provider-registry.ts:PROVIDER_DEFINITIONS`. | `electron/ai-edition/provider-registry.ts` | ❌ | — |
+| **P2.4** | **Streaming responses.** `runChat` returns a single buffered string today (`chat-service.ts`). Add SSE-style streaming so the chat panel can render tokens as they arrive. | `chat-service.ts` (no stream) | ❌ | — |
+| **P2.5** | **Tool-call permission gate.** Before running a write tool (`setSkipRange`, `replaceTimeline`, etc.), check a "dangerous tools" flag — if disabled, return a friendly "I need you to confirm before I edit your project" message and pause. The user can toggle it in `ProviderSettings.tsx`. | new permission check in `chat-service.ts:runChat` | ❌ | — |
### 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.
+
+| # | Task | File / line anchor | Status | Commit |
+|---|------|--------------------|--------|--------|
+| **F2.1** | **Auto-zoom "wand" suggestions.** Add a `suggestZoomRegions` store action that scans `transcript.segments` for low-amplitude ranges (silence heuristic) and proposes `zoomRanges` covering them. Wire to the disabled "Magic" button in `Bottombar.tsx:160-162` (currently `disabled` with no `onClick`). | new helper in `src/lib/ai-edition/store/zoomSuggestions.ts` + `Bottombar.tsx:160-162` | ✅ done | `58feb34` |
+| **F2.2** | **Region inspector — annotation options.** Add `fontFamily` (Inter / Mono / Serif) and `animation` (none / fade / pulse) fields to the `AnnotationRegion` schema; expose a `<select>` per field in `RightPanelStack.tsx`. | `RightPanelStack.tsx` annotation inspector panel + `lib/ai-edition/schema/index.ts` (`annotationSchema`) | ✅ done | `58feb34` |
+| **F2.3** | **Region inspector — figure/blur advanced.** Color picker (already partial), mosaic size slider, blur radius slider, arrow direction toggle for shapes. | `RightPanelStack.tsx` figure/blur subpanel | ✅ done | `58feb34` |
+| **F2.4** | **Advanced export options.** Expose `fps` (24/30/60) and `codec` (h264/h265/vp9) selects in `ExportDialog.tsx` next to the quality preset. Pipe to the existing exporter options object. | `ExportDialog.tsx` form + `src/lib/ai-edition/documentExporter.ts` (consumer) | ✅ done | `58feb34` |
+| **F2.5** | **Round-trip export test.** A vitest (or Playwright) test that creates a 3-clip + 1-skip project in a temp dir, calls the exporter end-to-end, then runs `ffprobe` on the output to assert the duration is the expected sum of clip durations. Marked `test:e2e` so it only runs in CI. | new `src/lib/ai-edition/documentExporter.e2e.test.ts` | ❌ | — |
+| **F2.6** | **Region drag snap-guide + floating tooltip.** axcut has both during region resize. Already shipped on the clip timeline (T24/T25). Port to `RegionTimeline.tsx`: a vertical guide at the snap point + a small tooltip showing the new `startSec` / `endSec` as the user drags a region handle. | `RegionTimeline.tsx` (region handle drag logic) | ✅ done | `01d6b46` |
+| **F2.7** | **Multi-select region operations.** Shift-click to add a region to the selection, then Delete removes all selected. Currently single-region-only. | `RegionTimeline.tsx` selection state + `useTimeline.removeRegion` | ✅ done | `01d6b46` |
+| **F2.8** | **Region clipboard (cut/copy/paste).** Cut removes + remembers, copy remembers, paste inserts at playhead. Currently only `regionClipboard.ts` exists with the storage layer but no UI wiring. | `regionClipboard.ts` (exists) + new shortcut handler in `NewEditorShell.tsx` | ✅ done | `01d6b46` |
### 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`).
+
+| # | Task | File / line anchor | Status | Commit |
+|---|------|--------------------|--------|--------|
+| **P3.1** | **Asset file size.** Add `sizeBytes: z.number().int().nonnegative().optional()` to `assetSchema` in `lib/ai-edition/schema/index.ts`. In `electron/ai-edition/document-service.ts` `addAsset()`, call `fs.stat(input.path).then(s => s.size)` (or sync) and store on the new asset. Renderer `LeftPanel.tsx:formatSize(undefined)` already exists; just thread the bytes through. | `lib/ai-edition/schema/index.ts:assetSchema` + `document-service.ts:addAsset` + `LeftPanel.tsx:formatSize` | ✅ done | `76d78db` |
+| **P3.2** | **Camera-sidecar toast on failure.** In `NewEditorShell.tsx:145` (the `addAsset` flow), wrap the `findRecordingCamera` call in a try/catch and surface failure as `toast.error("No camera file found next to <recording>")`. | `NewEditorShell.tsx:145` + `projectStore.ts:154` | ✅ done | `76d78db` |
+| **P3.3** | **RightPanes header Help buttons.** The `HelpCircle` button at `RightPanes.tsx:48-54` is rendered but `onClick` is a no-op. Wire to a popover that shows contextual help text per right pane (image, color, gradient, custom, effects, transcript). | `RightPanes.tsx:48-54` | ✅ done | `76d78db` |
+| **P3.4** | **Pixel nits.** (a) `RightPanelStack.tsx:296` — annotation color default `#ffffff` → `var(--annotation)`. (b) `.transport .rec[aria-pressed]` hardcoded `#ffffff` → `var(--danger)`. (c) Modal backdrop `rgba(22,23,29,.55)` → `var(--overlay-dark)` (define the var if missing). | `RightPanelStack.tsx`, `NewEditorShell.module.css` (.transport .rec), `design-tokens.css` (modal backdrop) | (a) stale — `<input type="color">` needs hex, schema default already `#ffffff` by design. (b) stale — selector doesn't exist in current code. (c) ✅ done. | `76d78db` (c) |
+| **P3.5** | **i18n sweep.** `ai-edition/*` still has hardcoded English: chat panel strings (`LeftPanel.tsx`), Header readouts in `TimelinePane.tsx` ("2 clips · 2 skips · 0:09.5 total"), modal titles in `Modals.tsx`, `ProviderSettings.tsx` labels, error toasts. Add a new `src/i18n/locales/en/ai-edition.json` namespace + 12 other locales + a smoke test in `src/i18n/__tests__/`. | `LeftPanel.tsx`, `TimelinePane.tsx`, `Modals.tsx`, `ProviderSettings.tsx` | ❌ | — |
+| **P3.6** | **Region drag visual polish (F2.6 in P2).** Tracked under P2 row F2.6. |
+| **P3.7** | **Timeline ruler hover scrub.** Hover the ruler with the mouse, click to seek to that time. Currently the ruler only handles pointerdown for the scrub gesture; a separate `pointermove → setCurrentTime` is missing for hover-feedback. | `TimelinePane.tsx` ruler `<div onPointerDown={handleRulerPointerDown}>` | ✅ done | `76d78db` |
+| **P3.8** | **Track-lane empty state for "no clips".** When `clips.length === 0` and a drop happens, drop a single auto-generated clip from the dropped asset (already does this in `insertClipAt`). But if the asset is unknown format, the placeholder is unhelpful — add a clear "Drag a video from the left to start" hint. Already exists at `TimelinePane.tsx:907-911` ("Drag a video from the media panel here to start your timeline."). Verify the message survives the i18n sweep (P3.5). | `TimelinePane.tsx:907-911` | pending P3.5 — message is in place, awaiting i18n wrap | — |
+| **P3.9** | **NPM-side CSS for the bottombar.** Confirm `Bottombar.module.css` exists or move the bottombar-specific CSS out of `NewEditorShell.module.css`. Currently scattered. | `NewEditorShell.module.css` vs new `Bottombar.module.css` | ❌ | — |
+| **P3.10** | **Stable drag handle ordering.** `RegionTimeline.tsx` — the row handles (.left / .right) are currently absolute-positioned but their stacking doesn't match the design (right handle above the left). Add explicit `z-index: 1` on `.right` to keep it on top. | `RegionTimeline.tsx` | moot — dnd-timeline owns handles now, no `.left`/`.right` CSS in current code | — |
### Deferred / known limitations
- **Long-recording scrub lag (>30 min)** — proxy MP4 dropped by decision 6; revival = per-asset "Generate proxy" button.
diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts
new file mode 100644
index 000000000..b25f49738
--- /dev/null
+++ b/electron/ai-edition/agent-tools.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from "vitest";
+import {
+ type AxcutDocument,
+ createEmptyDocument,
+ documentSchema,
+} from "../../src/lib/ai-edition/schema";
+import { AGENT_TOOL_SPECS, executeAgentTool, isMutatingTool } from "./agent-tools";
+
+function fixtureDocument(): AxcutDocument {
+ const base = createEmptyDocument({ title: "Test", projectId: "proj_1" });
+ return documentSchema.parse({
+ ...base,
+ project: { ...base.project, primaryAssetId: "asset_1" },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "Recording",
+ originalPath: "C:/videos/rec.mp4",
+ durationSec: 60,
+ },
+ ],
+ transcripts: [
+ {
+ assetId: "asset_1",
+ language: "en",
+ segments: [
+ { id: "seg_1", kind: "speech", startSec: 0, endSec: 5, text: "Hello", wordIds: [] },
+ { id: "seg_2", kind: "silence", startSec: 5, endSec: 8, text: "", wordIds: [] },
+ ],
+ words: [],
+ },
+ ],
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 30,
+ timelineStartSec: 0,
+ timelineEndSec: 30,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ {
+ id: "clip_2",
+ assetId: "asset_1",
+ sourceStartSec: 30,
+ sourceEndSec: 60,
+ timelineStartSec: 30,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ skipRanges: [
+ {
+ id: "skip_1",
+ assetId: "asset_1",
+ startSec: 10,
+ endSec: 12,
+ reason: "",
+ origin: "user",
+ },
+ ],
+ },
+ });
+}
+
+describe("agent-tools specs", () => {
+ it("declares the six roadmap tools with mutation flags", () => {
+ const names = AGENT_TOOL_SPECS.map((t) => t.name);
+ expect(names).toEqual([
+ "getCurrentDocument",
+ "getTranscript",
+ "addSkip",
+ "setSkipRange",
+ "setClipRange",
+ "replaceTimeline",
+ ]);
+ expect(isMutatingTool("getTranscript")).toBe(false);
+ expect(isMutatingTool("replaceTimeline")).toBe(true);
+ expect(isMutatingTool("nope")).toBe(false);
+ });
+});
+
+describe("executeAgentTool", () => {
+ it("getCurrentDocument returns a compact snapshot with ids and times", () => {
+ const result = executeAgentTool(fixtureDocument(), "getCurrentDocument", "");
+ expect(result.ok).toBe(true);
+ const snapshot = JSON.parse(result.resultJson);
+ expect(snapshot.primaryAssetId).toBe("asset_1");
+ expect(snapshot.clips.map((c: { id: string }) => c.id)).toEqual(["clip_1", "clip_2"]);
+ expect(snapshot.skipRanges[0].id).toBe("skip_1");
+ expect(snapshot.hasTranscript).toBe(true);
+ expect(result.document).toBeUndefined();
+ });
+
+ it("getTranscript returns segments for the primary asset by default", () => {
+ const result = executeAgentTool(fixtureDocument(), "getTranscript", "{}");
+ expect(result.ok).toBe(true);
+ const payload = JSON.parse(result.resultJson);
+ expect(payload.assetId).toBe("asset_1");
+ expect(payload.segments).toHaveLength(2);
+ expect(payload.segments[1].kind).toBe("silence");
+ });
+
+ it("getTranscript fails cleanly when no transcript exists", () => {
+ const doc = { ...fixtureDocument(), transcripts: [], transcript: null };
+ const result = executeAgentTool(doc, "getTranscript", "{}");
+ expect(result.ok).toBe(false);
+ expect(JSON.parse(result.resultJson).error).toMatch(/No transcript/);
+ });
+
+ it("addSkip appends an agent-origin skip range and normalizes reversed bounds", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addSkip",
+ JSON.stringify({ startSec: 22, endSec: 20, reason: "silence" }),
+ );
+ expect(result.ok).toBe(true);
+ expect(result.document).toBeDefined();
+ const added = result.document?.timeline.skipRanges.at(-1);
+ expect(added?.startSec).toBe(20);
+ expect(added?.endSec).toBe(22);
+ expect(added?.origin).toBe("agent");
+ expect(result.summary).toMatch(/added skip 0:20\.0 – 0:22\.0/);
+ });
+
+ it("addSkip rejects unknown assets", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addSkip",
+ JSON.stringify({ startSec: 0, endSec: 1, assetId: "asset_missing" }),
+ );
+ expect(result.ok).toBe(false);
+ expect(result.document).toBeUndefined();
+ });
+
+ it("setSkipRange moves an existing range and errors on unknown ids", () => {
+ const ok = executeAgentTool(
+ fixtureDocument(),
+ "setSkipRange",
+ JSON.stringify({ skipRangeId: "skip_1", startSec: 14, endSec: 18 }),
+ );
+ expect(ok.ok).toBe(true);
+ expect(ok.document?.timeline.skipRanges[0]).toMatchObject({ startSec: 14, endSec: 18 });
+
+ const missing = executeAgentTool(
+ fixtureDocument(),
+ "setSkipRange",
+ JSON.stringify({ skipRangeId: "skip_x", startSec: 0, endSec: 1 }),
+ );
+ expect(missing.ok).toBe(false);
+ });
+
+ it("setClipRange trims the clip and resequences downstream clips", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "setClipRange",
+ JSON.stringify({ clipId: "clip_1", sourceStartSec: 0, sourceEndSec: 10 }),
+ );
+ expect(result.ok).toBe(true);
+ const clips = result.document?.timeline.clips ?? [];
+ expect(clips[0]).toMatchObject({
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ // Downstream clip reflows to start where the trimmed clip now ends.
+ expect(clips[1]).toMatchObject({ timelineStartSec: 10, timelineEndSec: 40 });
+ });
+
+ it("replaceTimeline rebuilds clips and inverse skip ranges", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "replaceTimeline",
+ JSON.stringify({
+ intervals: [
+ { startSec: 0, endSec: 10 },
+ { startSec: 20, endSec: 30 },
+ ],
+ reason: "cut silences",
+ }),
+ );
+ expect(result.ok).toBe(true);
+ const timeline = result.document?.timeline;
+ expect(timeline?.clips).toHaveLength(2);
+ expect(timeline?.skipRanges.map((s) => [s.startSec, s.endSec])).toEqual([
+ [10, 20],
+ [30, 60],
+ ]);
+ expect(result.summary).toMatch(/2 intervals/);
+ });
+
+ it("rejects malformed JSON arguments and unknown tools", () => {
+ expect(executeAgentTool(fixtureDocument(), "addSkip", "{not json").ok).toBe(false);
+ expect(executeAgentTool(fixtureDocument(), "flyToTheMoon", "{}").ok).toBe(false);
+ });
+});
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
new file mode 100644
index 000000000..23d55737a
--- /dev/null
+++ b/electron/ai-edition/agent-tools.ts
@@ -0,0 +1,375 @@
+// Agent tool layer (P1.1/P1.2): the JSON-schema tool definitions fed to the
+// LLM as `tools[]`, plus the executor that validates arguments (zod) and
+// applies each tool against an AxcutDocument snapshot. Pure — no IPC, no fs.
+// The chat-service tool loop owns checkpoints and persistence; this module
+// only knows how to turn (document, toolName, argsJson) into a new document.
+//
+// Read tools return JSON the model can reason over; write tools return the
+// mutated document plus a human-readable summary line for the chat panel
+// ("applied: added skip 0:02.1 – 0:02.4").
+
+import { z } from "zod";
+import { createId } from "../../src/lib/ai-edition/document/ids";
+import { replaceTimeline, resequenceClips } from "../../src/lib/ai-edition/document/timeline";
+import type { AxcutDocument } from "../../src/lib/ai-edition/schema";
+
+export interface AgentToolSpec {
+ name: string;
+ description: string;
+ /** JSON schema for the tool arguments, sent verbatim to the provider. */
+ parameters: Record<string, unknown>;
+ /** True when the tool mutates the document (gates checkpoint + permission). */
+ mutating: boolean;
+}
+
+export interface AgentToolExecution {
+ ok: boolean;
+ /** JSON payload returned to the model as the tool result. */
+ resultJson: string;
+ /** Updated document — only set when the tool mutated it. */
+ document?: AxcutDocument;
+ /** One-line human summary for the chat panel (mutating tools only). */
+ summary?: string;
+}
+
+function formatSec(sec: number): string {
+ if (!Number.isFinite(sec) || sec < 0) return "0:00.0";
+ const m = Math.floor(sec / 60);
+ const s = (sec % 60).toFixed(1);
+ return `${m}:${s.padStart(4, "0")}`;
+}
+
+const secondsSchema = z.number().finite().nonnegative();
+
+const addSkipArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ assetId: z.string().min(1).optional(),
+ reason: z.string().default(""),
+});
+
+const setSkipRangeArgs = z.object({
+ skipRangeId: z.string().min(1),
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+});
+
+const setClipRangeArgs = z.object({
+ clipId: z.string().min(1),
+ sourceStartSec: secondsSchema,
+ sourceEndSec: secondsSchema,
+});
+
+const replaceTimelineArgs = z.object({
+ intervals: z.array(z.object({ startSec: secondsSchema, endSec: secondsSchema })).min(1),
+ reason: z.string().default(""),
+});
+
+const getTranscriptArgs = z.object({
+ assetId: z.string().min(1).optional(),
+});
+
+export const AGENT_TOOL_SPECS: AgentToolSpec[] = [
+ {
+ name: "getCurrentDocument",
+ description:
+ "Read a compact snapshot of the current project: assets (with durations), timeline clips, skip ranges, and counts of annotations/zoom ranges. Call this before editing if the snapshot in the system prompt may be stale.",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ mutating: false,
+ },
+ {
+ name: "getTranscript",
+ description:
+ "Read the transcript segments (speech and silence, with start/end seconds and text) for an asset. Omit assetId to read the primary asset's transcript.",
+ parameters: {
+ type: "object",
+ properties: {
+ assetId: { type: "string", description: "Asset id; defaults to the primary asset." },
+ },
+ additionalProperties: false,
+ },
+ mutating: false,
+ },
+ {
+ name: "addSkip",
+ description:
+ "Add a skip range (a cut — this source-time span will not be played or exported). Times are in seconds of the asset's source time.",
+ parameters: {
+ type: "object",
+ properties: {
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ assetId: { type: "string", description: "Asset id; defaults to the primary asset." },
+ reason: { type: "string", description: "Why this range is being cut." },
+ },
+ required: ["startSec", "endSec"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "setSkipRange",
+ description: "Move or resize an existing skip range by id. Times are source-time seconds.",
+ parameters: {
+ type: "object",
+ properties: {
+ skipRangeId: { type: "string" },
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ },
+ required: ["skipRangeId", "startSec", "endSec"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "setClipRange",
+ description:
+ "Trim a clip: set its source in/out points (seconds). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically.",
+ parameters: {
+ type: "object",
+ properties: {
+ clipId: { type: "string" },
+ sourceStartSec: { type: "number", minimum: 0 },
+ sourceEndSec: { type: "number", minimum: 0 },
+ },
+ required: ["clipId", "sourceStartSec", "sourceEndSec"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "replaceTimeline",
+ description:
+ "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a skip. Use for bulk edits like 'cut all silences'.",
+ parameters: {
+ type: "object",
+ properties: {
+ intervals: {
+ type: "array",
+ minItems: 1,
+ items: {
+ type: "object",
+ properties: {
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ },
+ required: ["startSec", "endSec"],
+ additionalProperties: false,
+ },
+ },
+ reason: { type: "string" },
+ },
+ required: ["intervals"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+];
+
+export function isMutatingTool(name: string): boolean {
+ return AGENT_TOOL_SPECS.find((t) => t.name === name)?.mutating ?? false;
+}
+
+// Compact projection of the document for the model: everything it needs to
+// reference ids and times, nothing it doesn't (no waveform paths, no history).
+export function documentSnapshotForModel(document: AxcutDocument): Record<string, unknown> {
+ return {
+ project: { id: document.project.id, title: document.project.title },
+ primaryAssetId: document.project.primaryAssetId ?? document.assets[0]?.id ?? null,
+ assets: document.assets.map((a) => ({
+ id: a.id,
+ label: a.label,
+ durationSec: a.durationSec ?? null,
+ })),
+ clips: document.timeline.clips.map((c) => ({
+ id: c.id,
+ assetId: c.assetId,
+ sourceStartSec: c.sourceStartSec,
+ sourceEndSec: c.sourceEndSec ?? null,
+ timelineStartSec: c.timelineStartSec,
+ timelineEndSec: c.timelineEndSec,
+ })),
+ skipRanges: document.timeline.skipRanges.map((s) => ({
+ id: s.id,
+ assetId: s.assetId,
+ startSec: s.startSec,
+ endSec: s.endSec,
+ reason: s.reason,
+ })),
+ annotationCount: document.annotations.length,
+ zoomRangeCount: document.zoomRanges.length,
+ hasTranscript: document.transcripts.length > 0 || document.transcript !== null,
+ };
+}
+
+function failure(message: string): AgentToolExecution {
+ return { ok: false, resultJson: JSON.stringify({ error: message }) };
+}
+
+export function executeAgentTool(
+ document: AxcutDocument,
+ name: string,
+ rawArgs: string,
+): AgentToolExecution {
+ let args: unknown = {};
+ if (rawArgs.trim()) {
+ try {
+ args = JSON.parse(rawArgs);
+ } catch {
+ return failure(`Tool arguments are not valid JSON: ${rawArgs.slice(0, 120)}`);
+ }
+ }
+
+ switch (name) {
+ case "getCurrentDocument": {
+ return { ok: true, resultJson: JSON.stringify(documentSnapshotForModel(document)) };
+ }
+
+ case "getTranscript": {
+ const parsed = getTranscriptArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const assetId =
+ parsed.data.assetId ?? document.project.primaryAssetId ?? document.assets[0]?.id;
+ const transcript =
+ document.transcripts.find((t) => t.assetId === assetId) ??
+ (document.transcript?.assetId === assetId ? document.transcript : null);
+ if (!transcript) {
+ return failure(`No transcript for asset ${assetId ?? "(none)"}.`);
+ }
+ // ponytail: segments only — words would blow the context for long
+ // recordings and the segment text already carries the content.
+ const segments = transcript.segments.slice(0, 800).map((s) => ({
+ id: s.id,
+ kind: s.kind,
+ startSec: s.startSec,
+ endSec: s.endSec,
+ text: s.text,
+ }));
+ return {
+ ok: true,
+ resultJson: JSON.stringify({ assetId, language: transcript.language, segments }),
+ };
+ }
+
+ case "addSkip": {
+ const parsed = addSkipArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const assetId =
+ parsed.data.assetId ?? document.project.primaryAssetId ?? document.assets[0]?.id;
+ if (!assetId) return failure("Project has no assets — nothing to skip.");
+ if (!document.assets.some((a) => a.id === assetId)) {
+ return failure(`Unknown asset: ${assetId}`);
+ }
+ const startSec = Math.min(parsed.data.startSec, parsed.data.endSec);
+ const endSec = Math.max(parsed.data.startSec, parsed.data.endSec);
+ const skip = {
+ id: createId("skip"),
+ assetId,
+ startSec,
+ endSec,
+ reason: parsed.data.reason,
+ origin: "agent" as const,
+ };
+ const next: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ skipRanges: [...document.timeline.skipRanges, skip],
+ },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ skipRangeId: skip.id, startSec, endSec }),
+ summary: `added skip ${formatSec(startSec)} – ${formatSec(endSec)}`,
+ };
+ }
+
+ case "setSkipRange": {
+ const parsed = setSkipRangeArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const { skipRangeId } = parsed.data;
+ if (!document.timeline.skipRanges.some((r) => r.id === skipRangeId)) {
+ return failure(`Unknown skip range: ${skipRangeId}`);
+ }
+ const startSec = Math.min(parsed.data.startSec, parsed.data.endSec);
+ const endSec = Math.max(parsed.data.startSec, parsed.data.endSec);
+ const next: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ skipRanges: document.timeline.skipRanges.map((r) =>
+ r.id === skipRangeId ? { ...r, startSec, endSec } : r,
+ ),
+ },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ skipRangeId, startSec, endSec }),
+ summary: `moved skip to ${formatSec(startSec)} – ${formatSec(endSec)}`,
+ };
+ }
+
+ case "setClipRange": {
+ const parsed = setClipRangeArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const { clipId } = parsed.data;
+ if (!document.timeline.clips.some((c) => c.id === clipId)) {
+ return failure(`Unknown clip: ${clipId}`);
+ }
+ const sourceStartSec = Math.min(parsed.data.sourceStartSec, parsed.data.sourceEndSec);
+ const sourceEndSec = Math.max(parsed.data.sourceStartSec, parsed.data.sourceEndSec);
+ const clips = resequenceClips(
+ document.timeline.clips.map((c) =>
+ c.id === clipId
+ ? {
+ ...c,
+ sourceStartSec,
+ sourceEndSec,
+ // ponytail: zero the timeline span so resequenceClips derives the
+ // clip length from the new source range instead of the stale one.
+ timelineStartSec: 0,
+ timelineEndSec: 0,
+ }
+ : c,
+ ),
+ );
+ const next: AxcutDocument = {
+ ...document,
+ timeline: { ...document.timeline, clips },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ clipId, sourceStartSec, sourceEndSec }),
+ summary: `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}`,
+ };
+ }
+
+ case "replaceTimeline": {
+ const parsed = replaceTimelineArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ let next: AxcutDocument;
+ try {
+ next = replaceTimeline(document, parsed.data.intervals, parsed.data.reason, "agent");
+ } catch (err) {
+ return failure(err instanceof Error ? err.message : String(err));
+ }
+ const kept = parsed.data.intervals.length;
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ clipCount: next.timeline.clips.length,
+ skipCount: next.timeline.skipRanges.length,
+ }),
+ summary: `rebuilt timeline from ${kept} interval${kept === 1 ? "" : "s"} (${next.timeline.clips.length} clips, ${next.timeline.skipRanges.length} skips)`,
+ };
+ }
+
+ default:
+ return failure(`Unknown tool: ${name}`);
+ }
+}
diff --git a/electron/ai-edition/chat-service.toolloop.test.ts b/electron/ai-edition/chat-service.toolloop.test.ts
new file mode 100644
index 000000000..b9b589c43
--- /dev/null
+++ b/electron/ai-edition/chat-service.toolloop.test.ts
@@ -0,0 +1,237 @@
+// Tool-loop behavior of runChat (P1.2–P1.5, P1.8, P2.5) with a mocked LLM.
+// The mock drives multi-turn tool chaining without network or API keys.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ type AxcutDocument,
+ createEmptyDocument,
+ documentSchema,
+} from "../../src/lib/ai-edition/schema";
+import type { CallLlmOptions, CallLlmResult } from "./llm-call";
+
+vi.mock("./llm-call", () => ({
+ callLlm: vi.fn(),
+}));
+
+import { createSession, runChat, undoLastToolBatch } from "./chat-service";
+import { callLlm } from "./llm-call";
+import type { LlmConfigStore } from "./llm-config-store";
+
+const callLlmMock = vi.mocked(callLlm);
+
+function fixtureDocument(): AxcutDocument {
+ const base = createEmptyDocument({ title: "Test", projectId: "proj_loop" });
+ return documentSchema.parse({
+ ...base,
+ project: { ...base.project, primaryAssetId: "asset_1" },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "Recording",
+ originalPath: "C:/videos/rec.mp4",
+ durationSec: 60,
+ },
+ ],
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ });
+}
+
+function stubConfig(overrides: Record<string, unknown> = {}): LlmConfigStore {
+ return {
+ getConfig: () => ({ provider: "openai", model: "gpt-4o", ...overrides }),
+ getApiKey: () => "sk-test",
+ } as unknown as LlmConfigStore;
+}
+
+beforeEach(() => {
+ callLlmMock.mockReset();
+});
+
+describe("runChat tool loop", () => {
+ it("executes tool calls, chains turns, and returns the mutated document", async () => {
+ callLlmMock
+ .mockResolvedValueOnce({
+ success: true,
+ content: "",
+ toolCalls: [
+ {
+ id: "call_1",
+ name: "addSkip",
+ arguments: JSON.stringify({ startSec: 5, endSec: 8, reason: "silence" }),
+ },
+ ],
+ })
+ .mockResolvedValueOnce({ success: true, content: "Trimmed the silence at 0:05." });
+
+ const s = createSession("proj_loop");
+ const result = await runChat(
+ "proj_loop",
+ s.id,
+ "cut the silence",
+ stubConfig(),
+ fixtureDocument(),
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.assistantMessage?.content).toBe("Trimmed the silence at 0:05.");
+ expect(result.toolCalls).toHaveLength(1);
+ expect(result.toolCalls?.[0].summary).toMatch(/added skip/);
+ const doc = documentSchema.parse(result.document);
+ expect(doc.timeline.skipRanges).toHaveLength(1);
+ expect(doc.timeline.skipRanges[0]).toMatchObject({ startSec: 5, endSec: 8, origin: "agent" });
+
+ // The second LLM call must see the tool result message.
+ const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;
+ const toolMsg = secondCall.messages.find((m) => m.role === "tool");
+ expect(toolMsg).toBeDefined();
+ expect(secondCall.tools?.map((t) => t.name)).toContain("addSkip");
+ });
+
+ it("saves a pre-batch checkpoint that undoLastToolBatch restores", async () => {
+ callLlmMock
+ .mockResolvedValueOnce({
+ success: true,
+ content: "",
+ toolCalls: [
+ {
+ id: "call_1",
+ name: "addSkip",
+ arguments: JSON.stringify({ startSec: 1, endSec: 2 }),
+ },
+ ],
+ })
+ .mockResolvedValueOnce({ success: true, content: "Done." });
+
+ const s = createSession("proj_loop_undo");
+ const original = fixtureDocument();
+ const result = await runChat("proj_loop_undo", s.id, "cut", stubConfig(), original);
+ expect(documentSchema.parse(result.document).timeline.skipRanges).toHaveLength(1);
+
+ const undo = undoLastToolBatch("proj_loop_undo", s.id);
+ expect(undo.success).toBe(true);
+ const restored = documentSchema.parse(undo.document);
+ expect(restored.timeline.skipRanges).toHaveLength(0);
+ });
+
+ it("undoLastToolBatch fails cleanly when nothing was edited", () => {
+ const s = createSession("proj_no_edits");
+ const undo = undoLastToolBatch("proj_no_edits", s.id);
+ expect(undo.success).toBe(false);
+ expect(undo.error).toMatch(/Nothing to undo/);
+ });
+
+ it("refuses write tools when allowAgentEdits is false (P2.5)", async () => {
+ callLlmMock
+ .mockResolvedValueOnce({
+ success: true,
+ content: "",
+ toolCalls: [
+ {
+ id: "call_1",
+ name: "addSkip",
+ arguments: JSON.stringify({ startSec: 1, endSec: 2 }),
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ content: "I need you to enable project edits first.",
+ });
+
+ const s = createSession("proj_gated");
+ const result = await runChat(
+ "proj_gated",
+ s.id,
+ "cut",
+ stubConfig({ allowAgentEdits: false }),
+ fixtureDocument(),
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.document).toBeUndefined();
+ expect(result.toolCalls).toBeUndefined();
+ const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;
+ const toolMsg = secondCall.messages.find((m) => m.role === "tool");
+ expect(toolMsg?.content).toMatch(/edits are disabled/i);
+ });
+
+ it("still allows read tools when edits are disabled", async () => {
+ callLlmMock
+ .mockResolvedValueOnce({
+ success: true,
+ content: "",
+ toolCalls: [{ id: "call_1", name: "getCurrentDocument", arguments: "{}" }],
+ })
+ .mockResolvedValueOnce({ success: true, content: "You have 1 clip." });
+
+ const s = createSession("proj_read_only");
+ const result = await runChat(
+ "proj_read_only",
+ s.id,
+ "what's in my project?",
+ stubConfig({ allowAgentEdits: false }),
+ fixtureDocument(),
+ );
+ expect(result.success).toBe(true);
+ const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;
+ const toolMsg = secondCall.messages.find((m) => m.role === "tool");
+ expect(toolMsg?.content).toContain("asset_1");
+ });
+
+ it("caps the loop at MAX_TOOL_ITERATIONS and reports applied edits", async () => {
+ callLlmMock.mockResolvedValue({
+ success: true,
+ content: "",
+ toolCalls: [
+ {
+ id: "call_x",
+ name: "addSkip",
+ arguments: JSON.stringify({ startSec: 1, endSec: 2 }),
+ },
+ ],
+ } satisfies CallLlmResult);
+
+ const s = createSession("proj_cap");
+ const result = await runChat("proj_cap", s.id, "loop forever", stubConfig(), fixtureDocument());
+ expect(result.success).toBe(true);
+ expect(callLlmMock).toHaveBeenCalledTimes(8);
+ expect(result.assistantMessage?.content).toMatch(/tool-call limit/);
+ expect(documentSchema.parse(result.document).timeline.skipRanges).toHaveLength(8);
+ });
+
+ it("runs text-only (no tools) when no document snapshot is provided", async () => {
+ callLlmMock.mockResolvedValueOnce({ success: true, content: "Hi!" });
+ const s = createSession("proj_text_only");
+ const result = await runChat("proj_text_only", s.id, "hello", stubConfig());
+ expect(result.success).toBe(true);
+ expect(result.document).toBeUndefined();
+ const call = callLlmMock.mock.calls[0][0] as CallLlmOptions;
+ expect(call.tools).toBeUndefined();
+ });
+
+ it("embeds the document snapshot in the system prompt (P1.5)", async () => {
+ callLlmMock.mockResolvedValueOnce({ success: true, content: "ok" });
+ const s = createSession("proj_prompt");
+ await runChat("proj_prompt", s.id, "hello", stubConfig(), fixtureDocument());
+ const call = callLlmMock.mock.calls[0][0] as CallLlmOptions;
+ const system = call.messages.find((m) => m.role === "system");
+ expect(system?.content).toContain("Current document snapshot:");
+ expect(system?.content).toContain("clip_1");
+ });
+});
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index e44dd0169..b0c70d041 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -6,18 +6,50 @@
// Phase 8 upgrades this to SQLite-backed sessions with checkpoint restore.
import { v4 as uuidv4 } from "uuid";
-import type { AiEditionChatMessage, AiEditionChatResult } from "../../src/native/contracts";
+import { type AxcutDocument, documentSchema } from "../../src/lib/ai-edition/schema";
+import type {
+ AiEditionChatMessage,
+ AiEditionChatResult,
+ AiEditionToolCallSummary,
+} from "../../src/native/contracts";
+import {
+ AGENT_TOOL_SPECS,
+ documentSnapshotForModel,
+ executeAgentTool,
+ isMutatingTool,
+} from "./agent-tools";
import { type ChatMessage, callLlm } from "./llm-call";
import type { LlmConfigStore } from "./llm-config-store";
import { PROVIDER_DEFINITIONS } from "./provider-registry";
const sessionsByProject = new Map<string, Map<string, ChatSession>>();
+// P1.3/P1.8 — pre-batch document snapshot per session, taken right before the
+// first write tool of a chat turn runs. undoLastToolBatch() re-applies it.
+const checkpointsBySession = new Map<string, { document: AxcutDocument; createdAt: string }>();
+
+// P1.4 — the model may chain tools (getTranscript → replaceTimeline → …).
+// Cap iterations so a confused model can't loop forever.
+const MAX_TOOL_ITERATIONS = 8;
+
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.";
+// P1.5 — tool-aware prompt: lists what the tools do and embeds a compact
+// document snapshot the model can edit against without a read round-trip.
+function buildToolSystemPrompt(document: AxcutDocument): string {
+ return (
+ `${SYSTEM_PROMPT}\n\n` +
+ "You can edit the project directly with tools. Times are seconds in the asset's " +
+ "source time. Read the transcript with getTranscript before cutting speech. " +
+ "Prefer addSkip/setSkipRange for local cuts and replaceTimeline for bulk re-cuts. " +
+ "After editing, tell the user in one or two sentences what you changed.\n\n" +
+ `Current document snapshot:\n${JSON.stringify(documentSnapshotForModel(document))}`
+ );
+}
+
export interface ChatSession {
id: string;
projectId: string;
@@ -108,11 +140,26 @@ export function deleteSession(projectId: string, sessionId: string): boolean {
return true;
}
+function sessionKey(projectId: string, sessionId: string): string {
+ return `${projectId}::${sessionId}`;
+}
+
+// P1.8 — return the pre-batch checkpoint document so the renderer can
+// re-apply it. The checkpoint survives the undo (re-undo is idempotent).
+export function undoLastToolBatch(projectId: string, sessionId: string): AiEditionChatResult {
+ const checkpoint = checkpointsBySession.get(sessionKey(projectId, sessionId));
+ if (!checkpoint) {
+ return { success: false, error: "Nothing to undo — the agent has not edited this project." };
+ }
+ return { success: true, document: checkpoint.document };
+}
+
export async function runChat(
projectId: string,
sessionId: string,
message: string,
llmConfig: LlmConfigStore,
+ documentInput?: unknown,
): Promise<AiEditionChatResult> {
const config = llmConfig.getConfig();
if (!config) {
@@ -148,6 +195,14 @@ export async function runChat(
return { success: false, error: "Chat session unavailable." };
}
+ // Tools only run against a valid document snapshot; a missing or invalid
+ // snapshot degrades to text-only chat instead of failing the turn.
+ let workingDocument: AxcutDocument | null = null;
+ if (documentInput !== undefined && documentInput !== null) {
+ const parsed = documentSchema.safeParse(documentInput);
+ if (parsed.success) workingDocument = parsed.data;
+ }
+
const userMessage: AiEditionChatMessage = {
id: uuidv4(),
role: "user",
@@ -156,35 +211,114 @@ export async function runChat(
};
session.messages.push(userMessage);
- const llmMessages: ChatMessage[] = [
- { role: "system", content: SYSTEM_PROMPT },
- ...session.messages.slice(-20).map((m) => ({ role: m.role, content: m.content })),
+ const systemPrompt = workingDocument ? buildToolSystemPrompt(workingDocument) : SYSTEM_PROMPT;
+ const loopMessages: ChatMessage[] = [
+ { role: "system", content: systemPrompt },
+ ...session.messages.slice(-20).map((m): ChatMessage => ({ role: m.role, content: m.content })),
];
- const result = await callLlm({
- provider: config.provider,
- model: config.model,
- apiKey: apiKey ?? "",
- baseUrl: config.baseUrl,
- reasoningEffort: config.reasoningEffort,
- messages: llmMessages,
- });
-
- if (!result.success || !result.content) {
- return { success: false, error: result.error ?? "Empty response from model." };
+ // P2.5 — write tools are gated behind the allowAgentEdits flag. Undefined
+ // means enabled (edits are checkpointed and undoable).
+ const editsAllowed = config.allowAgentEdits !== false;
+
+ const appliedToolCalls: AiEditionToolCallSummary[] = [];
+ let documentChanged = false;
+ let checkpointSaved = false;
+ let finalContent = "";
+
+ for (let iteration = 0; iteration < MAX_TOOL_ITERATIONS; iteration += 1) {
+ const result = await callLlm({
+ provider: config.provider,
+ model: config.model,
+ apiKey: apiKey ?? "",
+ baseUrl: config.baseUrl,
+ reasoningEffort: config.reasoningEffort,
+ messages: loopMessages,
+ tools: workingDocument ? AGENT_TOOL_SPECS : undefined,
+ });
+
+ if (!result.success) {
+ return { success: false, error: result.error ?? "Empty response from model." };
+ }
+
+ if (!result.toolCalls?.length) {
+ finalContent = result.content ?? "";
+ break;
+ }
+
+ loopMessages.push({
+ role: "assistant",
+ content: result.content ?? "",
+ toolCalls: result.toolCalls,
+ });
+
+ for (const call of result.toolCalls) {
+ if (!workingDocument) {
+ loopMessages.push({
+ role: "tool",
+ toolCallId: call.id,
+ content: JSON.stringify({ error: "No document available." }),
+ });
+ continue;
+ }
+ if (isMutatingTool(call.name) && !editsAllowed) {
+ loopMessages.push({
+ role: "tool",
+ toolCallId: call.id,
+ content: JSON.stringify({
+ error:
+ "Project edits are disabled in the AI settings. Ask the user to enable " +
+ "'Allow the agent to edit the project', then try again.",
+ }),
+ });
+ continue;
+ }
+ // P1.3 — checkpoint the pre-batch document before the first write.
+ if (isMutatingTool(call.name) && !checkpointSaved) {
+ checkpointsBySession.set(sessionKey(projectId, sessionId), {
+ document: workingDocument,
+ createdAt: new Date().toISOString(),
+ });
+ checkpointSaved = true;
+ }
+ const execution = executeAgentTool(workingDocument, call.name, call.arguments);
+ if (execution.ok && execution.document) {
+ workingDocument = execution.document;
+ documentChanged = true;
+ if (execution.summary) {
+ appliedToolCalls.push({ name: call.name, summary: execution.summary });
+ }
+ }
+ loopMessages.push({ role: "tool", toolCallId: call.id, content: execution.resultJson });
+ }
+
+ // The loop continues: the model sees the tool results and either chains
+ // more tools or produces the final text answer.
+ if (iteration === MAX_TOOL_ITERATIONS - 1) {
+ finalContent =
+ result.content ||
+ "I hit the tool-call limit for one message. The edits so far have been applied.";
+ }
+ }
+
+ if (!finalContent && appliedToolCalls.length === 0) {
+ return { success: false, error: "Empty response from model." };
}
const assistantMessage: AiEditionChatMessage = {
id: uuidv4(),
role: "assistant",
- content: result.content,
+ content: finalContent || "Done.",
createdAt: new Date().toISOString(),
+ toolCalls: appliedToolCalls.length ? appliedToolCalls : undefined,
};
session.messages.push(assistantMessage);
return {
success: true,
assistantMessage,
+ document: documentChanged && workingDocument ? workingDocument : undefined,
+ toolCalls: appliedToolCalls.length ? appliedToolCalls : undefined,
};
}
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index 31d842eeb..561411d23 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -174,11 +174,20 @@ export class DocumentService {
);
}
const absolutePath = path.isAbsolute(input.path) ? input.path : path.resolve(input.path);
+ // P3.1 — capture the file size at import. Non-fatal: a stat failure
+ // (network drive, permissions) just leaves sizeBytes undefined.
+ let sizeBytes: number | undefined;
+ try {
+ sizeBytes = (await fs.stat(absolutePath)).size;
+ } catch {
+ sizeBytes = undefined;
+ }
const asset: AxcutAsset = {
id: createId("asset"),
kind: "video",
label: input.label?.trim() || path.basename(absolutePath),
originalPath: absolutePath,
+ sizeBytes,
};
const next: AxcutDocument = {
...doc,
diff --git a/electron/ai-edition/llm-call.ts b/electron/ai-edition/llm-call.ts
index 2847b656a..3109a70c7 100644
--- a/electron/ai-edition/llm-call.ts
+++ b/electron/ai-edition/llm-call.ts
@@ -1,7 +1,8 @@
// Real LLM call via fetch — no LangChain dependency. Supports the
// OpenAI-compatible `/chat/completions` endpoint (OpenAI, Mistral,
-// OpenRouter, openai-compatible). Anthropic and OAuth providers stay
-// stubbed for now and return a clear "not yet implemented" error.
+// OpenRouter, openai-compatible) and Anthropic's `/v1/messages`, both with
+// tool calling (P1). OAuth providers stay stubbed and return a clear
+// "not yet implemented" error.
//
// ponytail: keep this file small and dependency-free so it works in both
// Electron and the browser-mode shim. Streaming is not supported in this
@@ -9,11 +10,24 @@
import { PROVIDER_DEFINITIONS, type ProviderDefinition } from "./provider-registry";
-export interface ChatMessage {
- role: "system" | "user" | "assistant";
- content: string;
+export interface LlmToolSpec {
+ name: string;
+ description: string;
+ parameters: Record<string, unknown>;
}
+export interface LlmToolCall {
+ id: string;
+ name: string;
+ /** Raw JSON string of the arguments, exactly as the provider returned it. */
+ arguments: string;
+}
+
+export type ChatMessage =
+ | { role: "system" | "user"; content: string }
+ | { role: "assistant"; content: string; toolCalls?: LlmToolCall[] }
+ | { role: "tool"; content: string; toolCallId: string };
+
export interface CallLlmOptions {
provider: string;
model: string;
@@ -21,11 +35,13 @@ export interface CallLlmOptions {
baseUrl?: string;
reasoningEffort?: string;
messages: ChatMessage[];
+ tools?: LlmToolSpec[];
}
export interface CallLlmResult {
success: boolean;
content?: string;
+ toolCalls?: LlmToolCall[];
error?: string;
}
@@ -56,6 +72,32 @@ function defaultBaseUrl(providerId: string): string {
}
}
+// --- OpenAI-compatible wire mapping -------------------------------------
+
+interface OpenAiToolCall {
+ id?: string;
+ type?: string;
+ function?: { name?: string; arguments?: string };
+}
+
+function toOpenAiMessage(message: ChatMessage): Record<string, unknown> {
+ if (message.role === "tool") {
+ return { role: "tool", tool_call_id: message.toolCallId, content: message.content };
+ }
+ if (message.role === "assistant" && message.toolCalls?.length) {
+ return {
+ role: "assistant",
+ content: message.content || null,
+ tool_calls: message.toolCalls.map((call) => ({
+ id: call.id,
+ type: "function",
+ function: { name: call.name, arguments: call.arguments },
+ })),
+ };
+ }
+ return { role: message.role, content: message.content };
+}
+
export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {
const def = findProvider(opts.provider);
if (!def) {
@@ -92,8 +134,18 @@ export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {
const body: Record<string, unknown> = {
model: opts.model || def.defaultModel,
- messages: opts.messages,
+ messages: opts.messages.map(toOpenAiMessage),
};
+ if (opts.tools?.length) {
+ body.tools = opts.tools.map((tool) => ({
+ type: "function",
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.parameters,
+ },
+ }));
+ }
if (def.supportsReasoningEffort && opts.reasoningEffort) {
body.reasoning_effort = REASONING_BY_PROVIDER[opts.reasoningEffort] ?? opts.reasoningEffort;
}
@@ -112,32 +164,89 @@ export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {
return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };
}
const json = (await res.json()) as {
- choices?: Array<{ message?: { content?: string } }>;
+ choices?: Array<{
+ message?: { content?: string | null; tool_calls?: OpenAiToolCall[] };
+ }>;
};
- const content = json.choices?.[0]?.message?.content;
- if (!content) {
+ const message = json.choices?.[0]?.message;
+ const toolCalls = (message?.tool_calls ?? [])
+ .filter((call) => call.function?.name)
+ .map((call, index) => ({
+ id: call.id ?? `call_${index}`,
+ name: call.function?.name ?? "",
+ arguments: call.function?.arguments ?? "{}",
+ }));
+ const content = message?.content ?? "";
+ if (!content && toolCalls.length === 0) {
return { success: false, error: "Empty response from model." };
}
- return { success: true, content };
+ return { success: true, content, toolCalls: toolCalls.length ? toolCalls : undefined };
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : String(err) };
}
}
+// --- Anthropic wire mapping ----------------------------------------------
+
+type AnthropicContentBlock =
+ | { type: "text"; text: string }
+ | { type: "tool_use"; id: string; name: string; input: unknown }
+ | { type: "tool_result"; tool_use_id: string; content: string };
+
+function toAnthropicMessages(
+ messages: ChatMessage[],
+): Array<{ role: "user" | "assistant"; content: string | AnthropicContentBlock[] }> {
+ const out: Array<{ role: "user" | "assistant"; content: string | AnthropicContentBlock[] }> = [];
+ for (const message of messages) {
+ if (message.role === "system") continue;
+ if (message.role === "tool") {
+ // Anthropic wants tool results as user-role tool_result blocks.
+ out.push({
+ role: "user",
+ content: [
+ { type: "tool_result", tool_use_id: message.toolCallId, content: message.content },
+ ],
+ });
+ continue;
+ }
+ if (message.role === "assistant" && message.toolCalls?.length) {
+ const blocks: AnthropicContentBlock[] = [];
+ if (message.content) blocks.push({ type: "text", text: message.content });
+ for (const call of message.toolCalls) {
+ let input: unknown = {};
+ try {
+ input = call.arguments ? JSON.parse(call.arguments) : {};
+ } catch {
+ input = {};
+ }
+ blocks.push({ type: "tool_use", id: call.id, name: call.name, input });
+ }
+ out.push({ role: "assistant", content: blocks });
+ continue;
+ }
+ out.push({ role: message.role, content: message.content });
+ }
+ return out;
+}
+
async function callAnthropic(opts: CallLlmOptions): Promise<CallLlmResult> {
const baseUrl = (opts.baseUrl || defaultBaseUrl("anthropic")).replace(/\/+$/, "");
const url = `${baseUrl}/messages`;
const systemMessage = opts.messages.find((m) => m.role === "system")?.content;
- const conversation = opts.messages
- .filter((m) => m.role !== "system")
- .map((m) => ({ role: m.role, content: m.content }));
const body: Record<string, unknown> = {
model: opts.model || "claude-haiku-4-5",
- max_tokens: 1024,
- messages: conversation,
+ max_tokens: 4096,
+ messages: toAnthropicMessages(opts.messages),
};
if (systemMessage) body.system = systemMessage;
+ if (opts.tools?.length) {
+ body.tools = opts.tools.map((tool) => ({
+ name: tool.name,
+ description: tool.description,
+ input_schema: tool.parameters,
+ }));
+ }
if (opts.reasoningEffort === "high") {
body.thinking = { type: "enabled", budget_tokens: 4096 };
}
@@ -157,13 +266,24 @@ async function callAnthropic(opts: CallLlmOptions): Promise<CallLlmResult> {
return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };
}
const json = (await res.json()) as {
- content?: Array<{ type: string; text?: string }>;
+ content?: Array<{ type: string; text?: string; id?: string; name?: string; input?: unknown }>;
};
- const text = json.content?.find((b) => b.type === "text")?.text;
- if (!text) {
+ const blocks = json.content ?? [];
+ const text = blocks
+ .filter((b) => b.type === "text" && b.text)
+ .map((b) => b.text)
+ .join("\n");
+ const toolCalls = blocks
+ .filter((b) => b.type === "tool_use" && b.name)
+ .map((b, index) => ({
+ id: b.id ?? `toolu_${index}`,
+ name: b.name ?? "",
+ arguments: JSON.stringify(b.input ?? {}),
+ }));
+ if (!text && toolCalls.length === 0) {
return { success: false, error: "Empty response from Anthropic." };
}
- return { success: true, content: text };
+ return { success: true, content: text, toolCalls: toolCalls.length ? toolCalls : undefined };
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : String(err) };
}
diff --git a/electron/ai-edition/llm-config-store.ts b/electron/ai-edition/llm-config-store.ts
index d7e0c50ec..287a1afed 100644
--- a/electron/ai-edition/llm-config-store.ts
+++ b/electron/ai-edition/llm-config-store.ts
@@ -15,6 +15,9 @@ export interface LlmConfig {
model: string;
baseUrl?: string;
reasoningEffort?: string;
+ /** P2.5 — when false, the agent's write tools are refused and the model is
+ * told to ask the user for confirmation. Undefined means enabled. */
+ allowAgentEdits?: boolean;
}
export interface LlmCredentials {
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index aea5299ad..dd774e3ea 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -45,6 +45,7 @@ import {
runChat,
runChatDefault,
selectSession,
+ undoLastToolBatch,
} from "../ai-edition/chat-service";
import { DocumentService } from "../ai-edition/document-service";
import { LlmConfigStore } from "../ai-edition/llm-config-store";
@@ -3149,8 +3150,9 @@ export function registerIpcHandlers(
getAiEditionDocuments: () =>
new DocumentService(path.join(app.getPath("userData"), "projects")),
getAiEditionLlmConfig: () => new LlmConfigStore(app.getPath("userData")),
- runAiEditionChat: (projectId, sessionId, message) =>
- runChat(projectId, sessionId, message, new LlmConfigStore(app.getPath("userData"))),
+ runAiEditionChat: (projectId, sessionId, message, document) =>
+ runChat(projectId, sessionId, message, new LlmConfigStore(app.getPath("userData")), document),
+ undoAiEditionToolBatch: (projectId, sessionId) => undoLastToolBatch(projectId, sessionId),
runAiEditionChatDefault: (projectId, message) =>
runChatDefault(projectId, message, new LlmConfigStore(app.getPath("userData"))),
getAiEditionChatHistoryDefault: (projectId) => getDefaultChatHistory(projectId),
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index ec3aece29..2afaac7bb 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -45,7 +45,12 @@ export interface NativeBridgeContext {
projectId: string,
sessionId: string,
message: string,
+ document?: unknown,
) => Promise<import("../../src/native/contracts").AiEditionChatResult>;
+ undoAiEditionToolBatch: (
+ projectId: string,
+ sessionId: string,
+ ) => import("../../src/native/contracts").AiEditionChatResult;
runAiEditionChatDefault: (
projectId: string,
message: string,
@@ -159,6 +164,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
llmConfig: context.getAiEditionLlmConfig(),
runChat: context.runAiEditionChat,
runChatDefault: context.runAiEditionChatDefault,
+ undoLastToolBatch: context.undoAiEditionToolBatch,
getDefaultChatHistory: context.getAiEditionChatHistoryDefault,
clearDefaultChatHistory: context.clearAiEditionChatHistoryDefault,
listSessions: context.listAiEditionChatSessions,
@@ -336,6 +342,15 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
request.payload.projectId,
request.payload.sessionId,
request.payload.message,
+ request.payload.document,
+ ),
+ );
+ case "chat.undoLastBatch":
+ return createSuccessResponse(
+ requestId,
+ aiEditionService.chatUndoLastBatch(
+ request.payload.projectId,
+ request.payload.sessionId,
),
);
case "chat.runDefault":
diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.ts
index 028ea0404..b08f6d4dd 100644
--- a/electron/native-bridge/services/aiEditionService.ts
+++ b/electron/native-bridge/services/aiEditionService.ts
@@ -17,8 +17,14 @@ import { PROVIDER_DEFINITIONS } from "../../ai-edition/provider-registry";
export interface AiEditionServiceOptions {
documents: DocumentService;
llmConfig: LlmConfigStore;
- runChat: (projectId: string, sessionId: string, message: string) => Promise<AiEditionChatResult>;
+ runChat: (
+ projectId: string,
+ sessionId: string,
+ message: string,
+ document?: unknown,
+ ) => Promise<AiEditionChatResult>;
runChatDefault: (projectId: string, message: string) => Promise<AiEditionChatResult>;
+ undoLastToolBatch: (projectId: string, sessionId: string) => AiEditionChatResult;
getDefaultChatHistory: (projectId: string) => AiEditionChatMessage[];
clearDefaultChatHistory: (projectId: string) => void;
listSessions: (projectId: string) => AiEditionChatSessionSummary[];
@@ -148,8 +154,13 @@ export class AiEditionService {
projectId: string,
sessionId: string,
message: string,
+ document?: unknown,
): Promise<AiEditionChatResult> {
- return this.options.runChat(projectId, sessionId, message);
+ return this.options.runChat(projectId, sessionId, message, document);
+ }
+
+ chatUndoLastBatch(projectId: string, sessionId: string): AiEditionChatResult {
+ return this.options.undoLastToolBatch(projectId, sessionId);
}
async chatRunDefault(projectId: string, message: string): Promise<AiEditionChatResult> {
diff --git a/src/components/ai-edition/Bottombar.tsx b/src/components/ai-edition/Bottombar.tsx
index 76e46dca3..d8e0d4640 100644
--- a/src/components/ai-edition/Bottombar.tsx
+++ b/src/components/ai-edition/Bottombar.tsx
@@ -9,10 +9,13 @@ import {
ZoomIn,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
import type { AnnotationRegion } from "@/components/video-editor/types";
import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import { useTimeline } from "@/lib/ai-edition/store/useTimeline";
+import { suggestZoomRegions } from "@/lib/ai-edition/store/zoomSuggestions";
import { ASPECT_RATIOS, type AspectRatio } from "@/utils/aspectRatioUtils";
import { EditClipModal } from "./Modals";
import styles from "./NewEditorShell.module.css";
@@ -37,6 +40,8 @@ interface BottombarProps {
annotationRegions: AnnotationRegion[];
speedRegions: Array<{ id: string; startMs: number; endMs: number; speed: number }>;
selection: RegionHandle | null;
+ // F2.7 — full shift-click selection set, for multi-select highlighting.
+ multiSelection?: RegionHandle[];
hasDoc: boolean;
onAddZoom: () => void;
onAddAnnotation: () => void;
@@ -46,7 +51,7 @@ interface BottombarProps {
// handler live here). The Scissors button in this component calls
// togglePlaceSkip directly.
setTogglePlaceSkip?: (fn: () => void) => void;
- onSelectRegion: (kind: RegionKind, id: string) => void;
+ onSelectRegion: (kind: RegionKind, id: string, additive?: boolean) => void;
onCaptions: () => void;
}
@@ -71,6 +76,7 @@ export function Bottombar({
annotationRegions,
speedRegions,
selection,
+ multiSelection,
hasDoc,
onAddZoom,
onAddAnnotation,
@@ -108,6 +114,36 @@ export function Bottombar({
});
}, [currentTimeSec]);
+ // F2.1 — Magic button: propose zoom regions over sustained speech
+ // segments and append them to the document in one save.
+ const applyZoomSuggestions = useCallback(async () => {
+ const store = useProjectStore.getState();
+ const doc = store.document;
+ if (!doc) return;
+ const suggestions = suggestZoomRegions(doc);
+ if (suggestions.length === 0) {
+ toast.info("No zoom suggestions found", {
+ description: doc.transcripts.length
+ ? "No sustained speech segments without an existing zoom."
+ : "Transcribe the recording first — suggestions come from the transcript.",
+ });
+ return;
+ }
+ try {
+ await store.saveDocument({
+ ...doc,
+ zoomRanges: [...doc.zoomRanges, ...suggestions] as AxcutDocument["zoomRanges"],
+ });
+ toast.success(
+ `Added ${suggestions.length} zoom suggestion${suggestions.length === 1 ? "" : "s"}`,
+ );
+ } catch (err) {
+ toast.error("Could not apply zoom suggestions", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }, []);
+
// T15 — body cursor + Esc-to-cancel while placing a cut. Lives here
// (not in TimelinePane) because the state lives here.
useEffect(() => {
@@ -220,7 +256,12 @@ export function Bottombar({
<VtBtn label="Captions" title="Auto captions" onClick={onCaptions} disabled={!hasDoc}>
<FileText size={17} />
</VtBtn>
- <VtBtn label="Magic" title="Auto zoom suggestions" disabled>
+ <VtBtn
+ label="Magic"
+ title="Auto zoom suggestions — propose zooms over sustained speech"
+ disabled={!hasDoc}
+ onClick={() => void applyZoomSuggestions()}
+ >
<WandSparkles size={17} />
</VtBtn>
<div style={{ position: "relative" }}>
@@ -314,6 +355,7 @@ export function Bottombar({
annotationRegions={annotationRegions}
speedRegions={speedRegions}
regionSelection={selection}
+ regionMultiSelection={multiSelection}
currentTimeSec={currentTimeSec}
selectedClipId={tl.clipSelection}
onSelectClip={tl.selectClip}
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 396511cf3..99f1e03dd 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -13,6 +13,7 @@ import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import {
type DocumentExportOptions,
+ type ExportVideoCodec,
exportAxcutDocument,
} from "@/lib/ai-edition/exporter/documentExporter";
import type { AxcutDocument } from "@/lib/ai-edition/schema";
@@ -50,6 +51,8 @@ interface ExportDialogProps {
export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
const [format, setFormat] = useState<ExportFormat>("mp4");
const [quality, setQuality] = useState<ExportQuality>("good");
+ const [fps, setFps] = useState<24 | 30 | 60>(60);
+ const [codec, setCodec] = useState<ExportVideoCodec>("h264");
const [gifFrameRate, setGifFrameRate] = useState<GifFrameRate>(15);
const [gifSize, setGifSize] = useState<GifSizePreset>("medium");
const [gifLoop, setGifLoop] = useState(true);
@@ -113,6 +116,8 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
const options: DocumentExportOptions = {
format,
quality,
+ frameRate: fps,
+ codec,
gifFrameRate,
gifLoop,
gifSizePreset: gifSize,
@@ -230,6 +235,78 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
</button>
))}
</div>
+ <div
+ style={{
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr",
+ gap: 12,
+ marginTop: 12,
+ }}
+ >
+ <div>
+ <div
+ style={{
+ font: "500 11px/1 var(--font-body)",
+ textTransform: "uppercase",
+ letterSpacing: "0.06em",
+ color: "var(--muted)",
+ marginBottom: 8,
+ }}
+ >
+ Frame rate
+ </div>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>
+ {([24, 30, 60] as const).map((r) => (
+ <button
+ type="button"
+ key={r}
+ disabled={isBusy}
+ onClick={() => setFps(r)}
+ style={segStyle(fps === r)}
+ >
+ {r}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div>
+ <div
+ style={{
+ font: "500 11px/1 var(--font-body)",
+ textTransform: "uppercase",
+ letterSpacing: "0.06em",
+ color: "var(--muted)",
+ marginBottom: 8,
+ }}
+ >
+ Codec
+ </div>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>
+ {(
+ [
+ ["h264", "H.264"],
+ ["h265", "H.265"],
+ ["vp9", "VP9"],
+ ] as Array<[ExportVideoCodec, string]>
+ ).map(([value, label]) => (
+ <button
+ type="button"
+ key={value}
+ disabled={isBusy}
+ onClick={() => setCodec(value)}
+ style={segStyle(codec === value)}
+ title={
+ value === "h264"
+ ? "Best compatibility"
+ : "May not be supported by every system encoder"
+ }
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
</section>
) : (
<section style={{ display: "flex", flexDirection: "column", gap: 12 }}>
diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsx
index 569d6ccdf..8bf155c33 100644
--- a/src/components/ai-edition/LeftPanel.tsx
+++ b/src/components/ai-edition/LeftPanel.tsx
@@ -2,10 +2,10 @@ import { Film, Loader2, MessageSquare, Plus, Search, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { AI_FEATURES_ENABLED } from "@/components/video-editor/featureFlags";
-import type { AxcutAsset } from "@/lib/ai-edition/schema";
+import { type AxcutAsset, ensureDocument } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { nativeBridgeClient } from "@/native/client";
-import type { AiEditionLlmConfig } from "@/native/contracts";
+import type { AiEditionLlmConfig, AiEditionToolCallSummary } from "@/native/contracts";
import { ChatHistoryModal, SourceTranscriptModal } from "./Modals";
import styles from "./NewEditorShell.module.css";
import { ProviderSettings } from "./ProviderSettings";
@@ -38,7 +38,6 @@ function formatTimecode(sec: number | undefined): string {
}
function formatSize(bytes: number | undefined): string {
- // ponytail: AxcutAsset has no size field yet — always em-dash.
if (!bytes || !Number.isFinite(bytes)) return "—";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
@@ -81,7 +80,7 @@ function MediaList({
{assets.map((asset, i) => {
const label = asset.label || basename(asset.originalPath);
const tc = formatTimecode(asset.durationSec);
- const size = formatSize(undefined);
+ const size = formatSize(asset.sizeBytes);
const palette = THUMB_PALETTE[i % THUMB_PALETTE.length];
const isReady = transcriptReadyIds?.has(asset.id);
const status = isReady ? "complete" : (assetStatuses?.[asset.id] ?? "idle");
@@ -333,11 +332,16 @@ export function LeftPanel({
);
}
+interface ChatDisplayMessage {
+ role: string;
+ content: string;
+ time?: string;
+ toolCalls?: AiEditionToolCallSummary[];
+}
+
function ChatStripPanel() {
const projectId = useProjectStore((s) => s.projectId);
- const [messages, setMessages] = useState<Array<{ role: string; content: string; time?: string }>>(
- [],
- );
+ const [messages, setMessages] = useState<ChatDisplayMessage[]>([]);
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const [llmConfig, setLlmConfig] = useState<AiEditionLlmConfig | null>(null);
@@ -409,6 +413,7 @@ function ChatStripPanel() {
role: m.role,
content: m.content,
time: m.createdAt,
+ toolCalls: m.toolCalls,
})),
);
} else {
@@ -424,25 +429,53 @@ function ChatStripPanel() {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
});
+ // Apply a document returned by the agent (tool batch or undo). setDocument
+ // pushes the previous doc to the local undo stack (Cmd+Z also works), then
+ // saveDocument persists it to disk.
+ const applyAgentDocument = useCallback(async (doc: unknown) => {
+ const parsed = ensureDocument(doc);
+ const store = useProjectStore.getState();
+ store.setDocument(parsed);
+ await store.saveDocument(parsed);
+ }, []);
+
const send = async () => {
if (!projectId || !activeSessionId || !input.trim() || busy) return;
const text = input.trim();
setInput("");
setBusy(true);
try {
- const result = await nativeBridgeClient.aiEdition.chatRun(projectId, activeSessionId, text);
+ // Send the current document snapshot so the agent can run edit tools
+ // against it (P1). Falls back to text-only chat when no doc is open.
+ const documentSnapshot = useProjectStore.getState().document ?? undefined;
+ const result = await nativeBridgeClient.aiEdition.chatRun(
+ projectId,
+ activeSessionId,
+ text,
+ documentSnapshot,
+ );
setMessages((prev) => [
...prev,
{ role: "user", content: text, time: new Date().toLocaleTimeString() },
]);
const assistant = result.assistantMessage;
if (result.success && assistant) {
+ if (result.document) {
+ try {
+ await applyAgentDocument(result.document);
+ } catch (err) {
+ toast.error("Could not apply the agent's edits", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
setMessages((prev) => [
...prev,
{
role: "assistant",
content: assistant.content,
time: new Date().toLocaleTimeString(),
+ toolCalls: assistant.toolCalls,
},
]);
void refreshSessions(projectId);
@@ -458,6 +491,28 @@ function ChatStripPanel() {
}
};
+ // P1.8 — one click reverts the last tool batch by re-applying the
+ // pre-batch checkpoint held by the chat service.
+ const undoLastBatch = useCallback(async () => {
+ if (!projectId || !activeSessionId) return;
+ try {
+ const result = await nativeBridgeClient.aiEdition.chatUndoLastBatch(
+ projectId,
+ activeSessionId,
+ );
+ if (result.success && result.document) {
+ await applyAgentDocument(result.document);
+ toast.success("Reverted the agent's last edits");
+ } else {
+ toast.error(result.error ?? "Nothing to undo");
+ }
+ } catch (err) {
+ toast.error("Undo failed", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }, [projectId, activeSessionId, applyAgentDocument]);
+
const modelLabel = llmConfig
? `${llmConfig.provider} / ${llmConfig.model}`
: "Configure AI Model";
@@ -755,6 +810,40 @@ function ChatStripPanel() {
) : null}
</div>
<div className={styles.msgBubble}>{m.content}</div>
+ {m.toolCalls?.length ? (
+ <div style={{ marginTop: 4, display: "flex", flexDirection: "column", gap: 2 }}>
+ {m.toolCalls.map((call, j) => (
+ <div
+ key={j}
+ style={{
+ font: "500 10px/1.5 var(--font-mono)",
+ color: "var(--success)",
+ }}
+ >
+ applied: {call.summary}
+ </div>
+ ))}
+ {i === messages.length - 1 ? (
+ <button
+ type="button"
+ onClick={() => void undoLastBatch()}
+ style={{
+ alignSelf: "flex-start",
+ marginTop: 2,
+ padding: "3px 8px",
+ background: "transparent",
+ border: "1px solid var(--border-soft)",
+ borderRadius: "var(--r-md)",
+ color: "var(--fg-2)",
+ font: "500 10px var(--font-body)",
+ cursor: "pointer",
+ }}
+ >
+ Undo these edits
+ </button>
+ ) : null}
+ </div>
+ ) : null}
</div>
))}
{busy ? (
diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsx
index fe7de70b3..db8ae494f 100644
--- a/src/components/ai-edition/Modals.tsx
+++ b/src/components/ai-edition/Modals.tsx
@@ -526,7 +526,7 @@ export function CropModal({ open, onClose, initialRegion, onApply }: CropModalPr
height: `${hPct}%`,
border: "1.5px solid var(--fg)",
borderRadius: 4,
- boxShadow: "0 0 0 9999px rgba(22,23,29,0.55)",
+ boxShadow: "0 0 0 9999px var(--overlay-dark)",
cursor: "move",
}}
/>
diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.css
index acee676c0..14fe32e78 100644
--- a/src/components/ai-edition/NewEditorShell.module.css
+++ b/src/components/ai-edition/NewEditorShell.module.css
@@ -1393,6 +1393,37 @@
flex-direction: column;
gap: 2px;
}
+/* F2.6 — vertical snap-guide lines at both edges of the region being
+ dragged/resized. Spans the full lane stack (parity with T24 on the
+ clip timeline). */
+.laneSnapGuide {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 2px;
+ background: var(--danger);
+ box-shadow: 0 0 6px color-mix(in oklch, var(--danger) 60%, transparent);
+ pointer-events: none;
+ z-index: 14;
+}
+/* F2.6 — floating tooltip with the live start – end range (parity with
+ T25 on the clip timeline). */
+.laneDragTooltip {
+ position: absolute;
+ top: -20px;
+ 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);
+}
.laneTrackRow {
position: relative;
height: 22px;
@@ -1684,7 +1715,7 @@
.modalBackdrop {
position: absolute;
inset: 0;
- background: rgba(22, 23, 29, 0.55);
+ background: var(--overlay-dark);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 985555571..7a7d85c47 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -708,6 +708,15 @@ export function NewEditorShell() {
return;
}
}
+ if (ctrl && e.key.toLowerCase() === "x") {
+ // F2.8 — cut: remember the region in the clipboard, then remove it.
+ if (tl.selection && tl.selection.kind !== "skip") {
+ e.preventDefault();
+ const cut = tl.selection;
+ void handleCopyRegion().then(() => tl.removeRegion(cut.kind, cut.id));
+ return;
+ }
+ }
if (ctrl && e.key.toLowerCase() === "v") {
e.preventDefault();
// A selected/copied clip takes priority — pasting with a clip in
@@ -734,6 +743,13 @@ export function NewEditorShell() {
return;
}
if (e.key === "Delete" || e.key === "Backspace") {
+ // F2.7 — a shift-click multi-selection deletes as one batch (one
+ // undo snapshot); a single selection keeps the original path.
+ if (tl.multiSelection.length > 1) {
+ e.preventDefault();
+ void tl.removeRegions(tl.multiSelection);
+ return;
+ }
if (tl.selection) {
e.preventDefault();
void tl.removeRegion(tl.selection.kind, tl.selection.id);
@@ -891,12 +907,13 @@ export function NewEditorShell() {
annotationRegions={tl.annotationRegions}
speedRegions={tl.speedRegions}
selection={tl.selection}
+ multiSelection={tl.multiSelection}
hasDoc={tl.hasDoc}
onAddZoom={() => void tl.addZoom()}
onAddAnnotation={() => void tl.addAnnotation()}
onAddSpeed={() => void tl.addSpeed()}
setTogglePlaceSkip={setTogglePlaceSkip}
- onSelectRegion={(kind, id) => tl.selectRegion(kind, id)}
+ onSelectRegion={(kind, id, additive) => tl.selectRegion(kind, id, { additive })}
onCaptions={handleCaptions}
/>
) : null}
diff --git a/src/components/ai-edition/ProviderSettings.tsx b/src/components/ai-edition/ProviderSettings.tsx
index 4cbaa42a0..34e88d0fb 100644
--- a/src/components/ai-edition/ProviderSettings.tsx
+++ b/src/components/ai-edition/ProviderSettings.tsx
@@ -410,6 +410,34 @@ function ProviderForm({
</Field>
) : null}
+ <Field
+ label="Project edits"
+ hint="When off, the agent must ask before changing the timeline. Edits are always undoable."
+ >
+ <label
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ font: "500 12px var(--font-body)",
+ color: "var(--fg-2)",
+ cursor: "pointer",
+ }}
+ >
+ <input
+ type="checkbox"
+ checked={config?.allowAgentEdits !== false}
+ onChange={(e) =>
+ setConfig({
+ ...(config ?? { provider: def.id, model: def.defaultModel }),
+ allowAgentEdits: e.target.checked,
+ })
+ }
+ />
+ Allow the agent to edit the project
+ </label>
+ </Field>
+
<div
style={{
display: "flex",
diff --git a/src/components/ai-edition/RegionTimeline.tsx b/src/components/ai-edition/RegionTimeline.tsx
index c12fe0f20..a13447a9b 100644
--- a/src/components/ai-edition/RegionTimeline.tsx
+++ b/src/components/ai-edition/RegionTimeline.tsx
@@ -1,6 +1,8 @@
import {
type DragEndEvent,
+ type DragMoveEvent,
type ResizeEndEvent,
+ type ResizeMoveEvent,
type Span,
TimelineContext,
useItem,
@@ -10,14 +12,20 @@ import {
export type { Span };
-import { useCallback } from "react";
+import { createContext, useCallback, useContext, useState } from "react";
+import { formatMs } from "@/lib/ai-edition/timeline/format";
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).
+// Row.tsx on `main` for the reference this ports): clamp-to-bounds +
+// collision-clamp against sibling spans, plus the F2.6 snap-guide and
+// floating drag tooltip during live drag/resize (parity with the clip
+// timeline's T24/T25).
+
+// F2.6 — the span currently being dragged/resized, resolved through the same
+// clamp pipeline as the final drop. The surface renders guides + tooltip.
+const LiveSpanContext = createContext<{ id: string; span: Span } | null>(null);
const MIN_ITEM_DURATION_MS = 100;
@@ -101,8 +109,11 @@ export function RegionTimelineProvider({
[clampSpanToBounds, clampToNeighbours, hasOverlap, isCollidable],
);
+ const [liveSpan, setLiveSpan] = useState<{ id: string; span: Span } | null>(null);
+
const onResizeEnd = useCallback(
(event: ResizeEndEvent) => {
+ setLiveSpan(null);
const updatedSpan = event.active.data.current.getSpanFromResizeEvent?.(event);
if (!updatedSpan) return;
const activeItemId = event.active.id as string;
@@ -114,6 +125,7 @@ export function RegionTimelineProvider({
const onDragEnd = useCallback(
(event: DragEndEvent) => {
+ setLiveSpan(null);
if (!event.over) return;
const updatedSpan = event.active.data.current.getSpanFromDragEvent?.(event);
if (!updatedSpan) return;
@@ -124,6 +136,31 @@ export function RegionTimelineProvider({
[onItemSpanChange, resolveSpan],
);
+ // F2.6 — live feedback while the pointer is still down. The resolved span
+ // is what would be committed on release, so the guide/tooltip show the
+ // clamped values (not the raw pointer position).
+ const onResizeMove = useCallback(
+ (event: ResizeMoveEvent) => {
+ 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) setLiveSpan({ id: activeItemId, span });
+ },
+ [resolveSpan],
+ );
+
+ const onDragMove = useCallback(
+ (event: DragMoveEvent) => {
+ 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) setLiveSpan({ id: activeItemId, span });
+ },
+ [resolveSpan],
+ );
+
return (
<TimelineContext
range={{ start: 0, end: safeTotalMs }}
@@ -131,10 +168,13 @@ export function RegionTimelineProvider({
onRangeChanged={() => {
// intentionally empty
}}
+ onResizeMove={onResizeMove}
onResizeEnd={onResizeEnd}
+ onDragMove={onDragMove}
onDragEnd={onDragEnd}
+ onDragCancel={() => setLiveSpan(null)}
>
- {children}
+ <LiveSpanContext.Provider value={liveSpan}>{children}</LiveSpanContext.Provider>
</TimelineContext>
);
}
@@ -156,6 +196,8 @@ export function RegionTimelineSurface({
children: React.ReactNode;
}) {
const { setTimelineRef, style } = useTimelineContext();
+ const liveSpan = useContext(LiveSpanContext);
+ const msToPx = pxPerSec / 1000;
return (
<div
ref={setTimelineRef}
@@ -167,6 +209,15 @@ export function RegionTimelineSurface({
className={styles.laneSurface}
>
{children}
+ {liveSpan ? (
+ <>
+ <div className={styles.laneSnapGuide} style={{ left: liveSpan.span.start * msToPx }} />
+ <div className={styles.laneSnapGuide} style={{ left: liveSpan.span.end * msToPx }} />
+ <div className={styles.laneDragTooltip} style={{ left: liveSpan.span.end * msToPx + 6 }}>
+ {formatMs(liveSpan.span.start)} – {formatMs(liveSpan.span.end)}
+ </div>
+ </>
+ ) : null}
</div>
);
}
@@ -198,7 +249,8 @@ interface RegionItemProps {
label: string;
icon: React.ReactNode;
selected: boolean;
- onSelect: () => void;
+ /** F2.7 — `additive` is true on shift-click (adds to the multi-selection). */
+ onSelect: (additive: boolean) => void;
variant: "zoom" | "annotation" | "speed";
}
@@ -229,7 +281,7 @@ export function RegionItem({
style={{ ...itemStyle, height: "100%", minWidth: 12 }}
{...listeners}
{...attributes}
- onPointerDownCapture={onSelect}
+ onPointerDownCapture={(event) => onSelect(event.shiftKey)}
>
<div style={{ ...itemContentStyle, height: "100%", minWidth: 24 }}>
<div
diff --git a/src/components/ai-edition/RightPanelStack.tsx b/src/components/ai-edition/RightPanelStack.tsx
index ad37787ab..ed5384e69 100644
--- a/src/components/ai-edition/RightPanelStack.tsx
+++ b/src/components/ai-edition/RightPanelStack.tsx
@@ -186,6 +186,19 @@ function RegionInspector({
void saveDocument({ ...document, annotations: next });
}, [annot, textDraft, document, selection.id, setDocument, saveDocument]);
+ // Shared save path for the inspector's annotation controls (style, figure
+ // and blur sub-objects) — one undo snapshot per change.
+ const patchAnnotation = useCallback(
+ (patch: (a: AxcutAnnotationRegion) => AxcutAnnotationRegion) => {
+ const next = document.annotations.map((a) =>
+ a.id === selection.id ? patch(a as AxcutAnnotationRegion) : a,
+ );
+ setDocument({ ...document, annotations: next });
+ void saveDocument({ ...document, annotations: next });
+ },
+ [document, selection.id, setDocument, saveDocument],
+ );
+
return (
<div style={{ display: "grid", gridTemplateRows: "auto 1fr", minHeight: 0 }}>
<header className={styles.paneHead}>
@@ -359,6 +372,151 @@ function RegionInspector({
))}
</select>
</Field>
+ <Field label="Font family">
+ <select
+ value={annot.style?.fontFamily ?? "Inter"}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ style: { ...a.style, fontFamily: e.target.value },
+ }))
+ }
+ style={selectStyle()}
+ >
+ <option value="Inter">Inter</option>
+ <option value="JetBrains Mono">Mono</option>
+ <option value="Georgia">Serif</option>
+ </select>
+ </Field>
+ {annot.type === "figure" ? (
+ <>
+ <Field label="Arrow direction">
+ <select
+ value={annot.figureData?.arrowDirection ?? "right"}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ figureData: {
+ arrowDirection: e.target.value as NonNullable<
+ AxcutAnnotationRegion["figureData"]
+ >["arrowDirection"],
+ color: a.figureData?.color ?? "#34B27B",
+ strokeWidth: a.figureData?.strokeWidth ?? 4,
+ },
+ }))
+ }
+ style={selectStyle()}
+ >
+ {[
+ "up",
+ "down",
+ "left",
+ "right",
+ "up-right",
+ "up-left",
+ "down-right",
+ "down-left",
+ ].map((d) => (
+ <option key={d} value={d}>
+ {d}
+ </option>
+ ))}
+ </select>
+ </Field>
+ <Field label={`Stroke width — ${annot.figureData?.strokeWidth ?? 4}px`}>
+ <input
+ type="range"
+ min={1}
+ max={16}
+ step={1}
+ value={annot.figureData?.strokeWidth ?? 4}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ figureData: {
+ arrowDirection: a.figureData?.arrowDirection ?? "right",
+ color: a.figureData?.color ?? "#34B27B",
+ strokeWidth: Number(e.target.value),
+ },
+ }))
+ }
+ style={{ width: "100%" }}
+ />
+ </Field>
+ </>
+ ) : null}
+ {annot.type === "blur" ? (
+ <>
+ <Field label="Mode">
+ <select
+ value={annot.blurData?.type ?? "mosaic"}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ blurData: {
+ type: e.target.value as "blur" | "mosaic",
+ shape: a.blurData?.shape ?? "rectangle",
+ color: a.blurData?.color ?? "white",
+ intensity: a.blurData?.intensity ?? 12,
+ blockSize: a.blurData?.blockSize ?? 12,
+ },
+ }))
+ }
+ style={selectStyle()}
+ >
+ <option value="mosaic">Mosaic</option>
+ <option value="blur">Blur</option>
+ </select>
+ </Field>
+ {(annot.blurData?.type ?? "mosaic") === "blur" ? (
+ <Field label={`Blur radius — ${annot.blurData?.intensity ?? 12}px`}>
+ <input
+ type="range"
+ min={2}
+ max={40}
+ step={1}
+ value={annot.blurData?.intensity ?? 12}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ blurData: {
+ type: a.blurData?.type ?? "mosaic",
+ shape: a.blurData?.shape ?? "rectangle",
+ color: a.blurData?.color ?? "white",
+ intensity: Number(e.target.value),
+ blockSize: a.blurData?.blockSize ?? 12,
+ },
+ }))
+ }
+ style={{ width: "100%" }}
+ />
+ </Field>
+ ) : (
+ <Field label={`Mosaic size — ${annot.blurData?.blockSize ?? 12}px`}>
+ <input
+ type="range"
+ min={4}
+ max={48}
+ step={2}
+ value={annot.blurData?.blockSize ?? 12}
+ onChange={(e) =>
+ patchAnnotation((a) => ({
+ ...a,
+ blurData: {
+ type: a.blurData?.type ?? "mosaic",
+ shape: a.blurData?.shape ?? "rectangle",
+ color: a.blurData?.color ?? "white",
+ intensity: a.blurData?.intensity ?? 12,
+ blockSize: Number(e.target.value),
+ },
+ }))
+ }
+ style={{ width: "100%" }}
+ />
+ </Field>
+ )}
+ </>
+ ) : null}
</>
) : null
) : selection.kind === "skip" ? (
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 62d8a3c41..ac0637e66 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -34,13 +34,16 @@ interface PaneProps {
title: string;
icon: ReactNode;
helpLabel?: string;
+ // P3.3 — contextual help shown in a popover when the ? button is clicked.
+ helpText?: string;
children: ReactNode;
}
-function Pane({ title, icon, helpLabel, children }: PaneProps) {
+function Pane({ title, icon, helpLabel, helpText, children }: PaneProps) {
+ const [helpOpen, setHelpOpen] = useState(false);
return (
<div className={`${styles.pane} ${styles.isActive}`}>
- <header className={styles.paneHead}>
+ <header className={styles.paneHead} style={{ position: "relative" }}>
<h2>{title}</h2>
<span style={{ marginLeft: "auto", display: "inline-flex", gap: 4 }}>
<button
@@ -48,11 +51,35 @@ function Pane({ title, icon, helpLabel, children }: PaneProps) {
className={styles.iconBtn}
title={helpLabel ?? "Help"}
aria-label={helpLabel ?? "Help"}
+ aria-expanded={helpOpen}
+ onClick={() => setHelpOpen((v) => !v)}
>
<HelpCircle size={14} />
</button>
</span>
<span style={{ display: "none" }}>{icon}</span>
+ {helpOpen ? (
+ <div
+ role="note"
+ style={{
+ position: "absolute",
+ top: "calc(100% + 4px)",
+ right: 8,
+ zIndex: 60,
+ maxWidth: 240,
+ padding: "10px 12px",
+ background: "var(--surface)",
+ border: "1px solid var(--border)",
+ borderRadius: "var(--r-md)",
+ boxShadow: "var(--elev-pop)",
+ color: "var(--fg-2)",
+ font: "400 12px/1.5 var(--font-body)",
+ }}
+ onClick={() => setHelpOpen(false)}
+ >
+ {helpText ?? `Settings for ${title.toLowerCase()}.`}
+ </div>
+ ) : null}
</header>
<div className={styles.paneBody}>{children}</div>
</div>
@@ -141,7 +168,11 @@ export function BackgroundPane() {
};
return (
- <Pane title="Background" icon={<Palette size={14} />}>
+ <Pane
+ title="Background"
+ icon={<Palette size={14} />}
+ helpText="Choose what appears behind the recording: a bundled wallpaper image, a solid color, a gradient, or a custom image from disk."
+ >
<div className={styles.paneTabs} role="tablist">
<button
type="button"
@@ -366,7 +397,11 @@ export function TranscriptPane({
}) {
if (!transcript) {
return (
- <Pane title="Current transcription" icon={<FileText size={14} />}>
+ <Pane
+ title="Current transcription"
+ icon={<FileText size={14} />}
+ helpText="The transcript of the spoken words, generated on-device by Whisper. Click a word to seek; select a range to cut it from the timeline."
+ >
<div
style={{
display: "flex",
@@ -421,7 +456,11 @@ export function TranscriptPane({
export function VideoEffectsPane() {
const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
return (
- <Pane title="Video effects" icon={<Sliders size={14} />}>
+ <Pane
+ title="Video effects"
+ icon={<Sliders size={14} />}
+ helpText="Frame styling for the recording: background blur, drop shadow, motion blur, corner radius, and padding around the video."
+ >
<div className={styles.paneRow}>
<span className="label">Blur BG</span>
<Toggle
@@ -505,7 +544,11 @@ export function LayoutPane() {
// preset isn't PiP.
const isPip = settings.webcamLayoutPreset === "picture-in-picture";
return (
- <Pane title="Layout" icon={<LayoutIcon size={14} />}>
+ <Pane
+ title="Layout"
+ icon={<LayoutIcon size={14} />}
+ helpText="How the webcam is composed with the screen: picture-in-picture, vertical stack, dual frame, mask shape, size, and mirroring."
+ >
<div className={styles.sectionLabel}>Preset</div>
<div className={styles.field}>
<label>Layout</label>
@@ -632,7 +675,11 @@ const CURSOR_STYLE_LABELS: Array<{ title: string; d: string }> = [
export function CursorPane() {
const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
return (
- <Pane title="Cursor" icon={<MousePointerClick size={14} />}>
+ <Pane
+ title="Cursor"
+ icon={<MousePointerClick size={14} />}
+ helpText="Cursor rendering from the recorded telemetry: theme, size, smoothing, motion blur, and click-bounce emphasis."
+ >
<div className={styles.paneRow}>
<span className="label">Show cursor</span>
<Toggle
@@ -722,7 +769,11 @@ export function CursorPane() {
export function TimelinePaneBody() {
const { settings, set, hasDocument } = useEditorSettings();
return (
- <Pane title="Timeline" icon={<CropIcon size={14} />}>
+ <Pane
+ title="Timeline"
+ icon={<CropIcon size={14} />}
+ helpText="Timeline display options, like showing the audio waveform on the trim track."
+ >
<div className={styles.paneRow}>
<span className="label">Show audio waveform on trim track</span>
<Toggle
diff --git a/src/components/ai-edition/TimelinePane.module.css b/src/components/ai-edition/TimelinePane.module.css
index 30885b473..8b65f18b7 100644
--- a/src/components/ai-edition/TimelinePane.module.css
+++ b/src/components/ai-edition/TimelinePane.module.css
@@ -367,6 +367,19 @@ body:global(.timeline-placing-cut) [class*="vtBtn"] {
z-index: 30;
}
+/* P3.7 — hover marker in the ruler: same footprint as .snapGuide but in
+ the accent color so it reads as "preview", not "edit in progress". */
+.hoverGuide {
+ position: absolute;
+ top: 0;
+ height: var(--rule-h, 22px);
+ width: 1px;
+ background: var(--accent);
+ opacity: 0.8;
+ pointer-events: none;
+ z-index: 13;
+}
+
/* 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). */
diff --git a/src/components/ai-edition/TimelinePane.tsx b/src/components/ai-edition/TimelinePane.tsx
index cb8183a8a..fee30672a 100644
--- a/src/components/ai-edition/TimelinePane.tsx
+++ b/src/components/ai-edition/TimelinePane.tsx
@@ -89,10 +89,12 @@ interface TimelinePaneProps {
annotationRegions: AnnotationRegion[];
speedRegions: SpeedRegion[];
regionSelection: RegionSelection | null;
+ // F2.7 — full shift-click selection set, for multi-select highlighting.
+ regionMultiSelection?: RegionSelection[];
currentTimeSec: number;
selectedClipId: string | null;
onSelectClip: (id: string) => void;
- onSelectRegion: (kind: RegionSelection["kind"], id: string) => void;
+ onSelectRegion: (kind: RegionSelection["kind"], id: string, additive?: boolean) => void;
onSeek: (timelineSec: number) => void;
onInsertAsset: (assetId: string, index: number) => void;
onMoveClip: (clipId: string, toIndex: number) => void;
@@ -266,6 +268,7 @@ export function TimelinePane({
annotationRegions,
speedRegions,
regionSelection,
+ regionMultiSelection,
currentTimeSec,
selectedClipId,
onSelectClip,
@@ -302,6 +305,9 @@ export function TimelinePane({
// 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);
+ // P3.7 — source time under the cursor while hovering the timeline; drives
+ // the ruler's hover marker + time chip. Null when the pointer is outside.
+ const [hoverSec, setHoverSec] = useState<number | null>(null);
// viewport state is owned by Bottombar (T11). We only mirror it here.
const [panning, setPanning] = useState(false);
const [clipReorderState, setClipReorderState] = useState<ClipReorderState | null>(null);
@@ -990,6 +996,12 @@ export function TimelinePane({
],
);
+ // F2.7 — a region is highlighted when it's the focused selection or part
+ // of the shift-click multi-selection.
+ const isRegionSelected = (kind: RegionSelection["kind"], id: string) =>
+ (regionSelection?.kind === kind && regionSelection.id === id) ||
+ (regionMultiSelection?.some((h) => h.kind === kind && h.id === id) ?? false);
+
return (
<section className={styles.pane}>
<div
@@ -1006,17 +1018,22 @@ export function TimelinePane({
: styles.viewport
}
onPointerDown={handleTimelinePointerDown}
- onPointerMove={
- pendingCutPlacement
- ? (event) => {
- // pointerType guards against touch-emulation hover
- if (event.pointerType === "touch") return;
- setPendingCutPreviewSec(sourceSecFromClientX(event.clientX));
- }
- : undefined
- }
+ onPointerMove={(event) => {
+ // pointerType guards against touch-emulation hover
+ if (event.pointerType === "touch") return;
+ if (pendingCutPlacement) {
+ setPendingCutPreviewSec(sourceSecFromClientX(event.clientX));
+ return;
+ }
+ // P3.7 — hover feedback: a marker + time chip in the ruler
+ // under the cursor. Click to seek (startScrub handles it).
+ if (orderedClips.length > 0) {
+ setHoverSec(Math.max(0, Math.min(sourceDuration, sourceSecFromClientX(event.clientX))));
+ }
+ }}
onPointerLeave={() => {
if (pendingCutPlacement) setPendingCutPreviewSec(null);
+ setHoverSec(null);
}}
onDragOver={handleDragOver}
onDragLeave={() => setDropIndex(null)}
@@ -1052,6 +1069,20 @@ export function TimelinePane({
{tick.major ? <span>{formatSeconds(tick.timeSec)}</span> : null}
</div>
))}
+ {hoverSec !== null && !scrubbing && !panning ? (
+ <>
+ <div
+ className={styles.hoverGuide}
+ style={{ left: TIMELINE_START_GUTTER_PX + hoverSec * pxPerSec }}
+ />
+ <div
+ className={styles.dragTooltip}
+ style={{ left: TIMELINE_START_GUTTER_PX + hoverSec * pxPerSec + 6 }}
+ >
+ {formatSeconds(hoverSec)}
+ </div>
+ </>
+ ) : null}
</div>
{/* T10 — region lanes (annotation / speed / zoom). They live
inside the same .canvas as the clip track so the
@@ -1086,10 +1117,8 @@ export function TimelinePane({
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)}
+ selected={isRegionSelected("annotation", a.id)}
+ onSelect={(additive) => onSelectRegion("annotation", a.id, additive)}
variant="annotation"
/>
))}
@@ -1103,8 +1132,8 @@ export function TimelinePane({
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)}
+ selected={isRegionSelected("speed", s.id)}
+ onSelect={(additive) => onSelectRegion("speed", s.id, additive)}
variant="speed"
/>
))}
@@ -1122,8 +1151,8 @@ export function TimelinePane({
: (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)}
+ selected={isRegionSelected("zoom", z.id)}
+ onSelect={(additive) => onSelectRegion("zoom", z.id, additive)}
variant="zoom"
/>
))}
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 3ac884300..826582f79 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -95,6 +95,22 @@ function collectWordRefs(
.map((word) => word.id);
}
+// Lay clips back-to-back from t=0, preserving each clip's own length. Called
+// after any structural change (insert / move / remove / trim) so the timeline
+// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
+// the agent tool executor (main process) so both enforce the same invariant.
+export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
+ 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 subtractInterval(intervals: Interval[], cut: Interval): Interval[] {
const output: Interval[] = [];
for (const interval of intervals) {
diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.ts
index 45bf476f6..0635d1d97 100644
--- a/src/lib/ai-edition/exporter/documentExporter.ts
+++ b/src/lib/ai-edition/exporter/documentExporter.ts
@@ -32,10 +32,21 @@ import type { CursorRecordingData, CursorTelemetryPoint } from "@/native/contrac
import { primaryAssetDuration, timelineIntervals } from "../document/timeline";
import type { AxcutDocument } from "../schema";
+export type ExportVideoCodec = "h264" | "h265" | "vp9";
+
+// WebCodecs encoder strings per user-facing codec choice (F2.4). The muxer
+// derives its mp4 track family from the same string.
+const CODEC_STRINGS: Record<ExportVideoCodec, string> = {
+ h264: "avc1.640033",
+ h265: "hvc1.1.6.L120.90",
+ vp9: "vp09.00.10.08",
+};
+
export interface DocumentExportOptions {
quality: ExportQuality;
format: ExportFormat;
frameRate?: number;
+ codec?: ExportVideoCodec;
gifFrameRate?: GifFrameRate;
gifLoop?: boolean;
gifSizePreset?: GifSizePreset;
@@ -217,7 +228,7 @@ export async function exportAxcutDocument(
height: settings.height,
frameRate: options.frameRate ?? 60,
bitrate: settings.bitrate,
- codec: "avc1.640033",
+ codec: CODEC_STRINGS[options.codec ?? "h264"],
});
return exporter.export();
}
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 25c7eaea0..cdd4a75ea 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -73,6 +73,8 @@ export const assetSchema = z.object({
proxyPath: z.string().optional(),
waveformPath: z.string().optional(),
durationSec: z.number().nonnegative().optional(),
+ // P3.1 — file size captured at import time (fs.stat in document-service).
+ sizeBytes: z.number().int().nonnegative().optional(),
video: assetVideoSchema.optional(),
audio: assetAudioSchema.optional(),
});
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 7bb247ca1..9181a30c3 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -150,8 +150,16 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
await get().saveDocument(next);
document = parseDocument(next);
}
- } catch {
- // ponytail: silent — no camera, no problem.
+ } catch (err) {
+ // P3.2 — a missing sidecar is normal (success:false above), but a
+ // *failing* lookup means the recording should have had a camera
+ // and something went wrong. Surface it instead of eating it.
+ const name = addedAsset.originalPath.split(/[\\/]/).pop() ?? addedAsset.originalPath;
+ void import("sonner").then(({ toast }) =>
+ toast.error(`No camera file found next to ${name}`, {
+ description: err instanceof Error ? err.message : String(err),
+ }),
+ );
}
}
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index e69ed0be8..4d5c871fc 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -7,6 +7,7 @@ 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 { resequenceClips } from "../document/timeline";
import type { AxcutDocument } from "../schema";
import { probeVideoDuration } from "../timeline/duration";
import { useProjectStore } from "./projectStore";
@@ -28,27 +29,16 @@ interface RegionHandle {
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);
+ // F2.7 — shift-click multi-selection. `selection` stays the inspector's
+ // focused region (the last one clicked); `multiSelection` is the full set
+ // the Delete key operates on.
+ const [multiSelection, setMultiSelection] = useState<RegionHandle[]>([]);
const [clipSelection, setClipSelection] = useState<string | null>(null);
const hasDoc = document !== null && projectId !== null;
@@ -297,15 +287,68 @@ export function useTimeline() {
}
await saveDocument(next);
if (selection?.id === id) setSelection(null);
+ setMultiSelection((prev) => prev.filter((h) => h.id !== id));
},
[document, selection, saveDocument],
);
- const selectRegion = useCallback((kind: RegionKind, id: string) => {
- setSelection({ kind, id });
- }, []);
+ // F2.7 — batch removal for multi-selection: one document save (one undo
+ // snapshot) regardless of how many regions are selected.
+ const removeRegions = useCallback(
+ async (handles: RegionHandle[]) => {
+ if (!document || handles.length === 0) return;
+ const zoomIds = new Set(handles.filter((h) => h.kind === "zoom").map((h) => h.id));
+ const skipIds = new Set(handles.filter((h) => h.kind === "skip").map((h) => h.id));
+ const annotationIds = new Set(
+ handles.filter((h) => h.kind === "annotation").map((h) => h.id),
+ );
+ const speedIds = new Set(handles.filter((h) => h.kind === "speed").map((h) => h.id));
+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
+ const prevSpeed = ((legacy.speedRegions as unknown[]) ?? []).filter(
+ (s) => !speedIds.has((s as { id: string }).id),
+ );
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: document.zoomRanges.filter(
+ (z) => !zoomIds.has(z.id),
+ ) as AxcutDocument["zoomRanges"],
+ annotations: document.annotations.filter((a) => !annotationIds.has(a.id)),
+ timeline: {
+ ...document.timeline,
+ skipRanges: document.timeline.skipRanges.filter((s) => !skipIds.has(s.id)),
+ },
+ legacyEditor:
+ speedIds.size > 0 ? { ...legacy, speedRegions: prevSpeed } : document.legacyEditor,
+ };
+ await saveDocument(next);
+ setSelection(null);
+ setMultiSelection([]);
+ },
+ [document, saveDocument],
+ );
- const clearSelection = useCallback(() => setSelection(null), []);
+ const selectRegion = useCallback(
+ (kind: RegionKind, id: string, opts?: { additive?: boolean }) => {
+ const handle = { kind, id };
+ if (opts?.additive) {
+ // Shift-click toggles membership; the focused region follows the click.
+ setMultiSelection((prev) => {
+ const exists = prev.some((h) => h.kind === kind && h.id === id);
+ return exists ? prev.filter((h) => !(h.kind === kind && h.id === id)) : [...prev, handle];
+ });
+ setSelection(handle);
+ return;
+ }
+ setMultiSelection([handle]);
+ setSelection(handle);
+ },
+ [],
+ );
+
+ const clearSelection = useCallback(() => {
+ setSelection(null);
+ setMultiSelection([]);
+ }, []);
const addClipBefore = useCallback(
async (assetId: string) => {
@@ -504,6 +547,53 @@ export function useTimeline() {
[document, saveDocument, addClipAfter],
);
+ // 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 },
+ });
+ },
+ [],
+ );
+
// Insert a new full-duration clip for `assetId` at position `index`
// (0 = before all, clips.length = after all), then resequence.
//
@@ -553,54 +643,7 @@ export function useTimeline() {
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 },
- });
- },
- [],
+ [saveDocument, probeAndCorrectClip],
);
// Reorder a clip to a new index, then resequence timeline positions.
@@ -682,6 +725,7 @@ export function useTimeline() {
assets: document?.assets ?? [],
hasDoc,
selection,
+ multiSelection,
clipSelection,
addZoom,
addSkip,
@@ -689,6 +733,7 @@ export function useTimeline() {
addAnnotation,
addSpeed,
removeRegion,
+ removeRegions,
selectRegion,
clearSelection,
addClipBefore,
diff --git a/src/lib/ai-edition/store/zoomSuggestions.test.ts b/src/lib/ai-edition/store/zoomSuggestions.test.ts
new file mode 100644
index 000000000..294d2dc48
--- /dev/null
+++ b/src/lib/ai-edition/store/zoomSuggestions.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from "vitest";
+import { type AxcutDocument, createEmptyDocument, documentSchema } from "../schema";
+import { suggestZoomRegions } from "./zoomSuggestions";
+
+function fixtureDocument(overrides: Partial<AxcutDocument> = {}): AxcutDocument {
+ const base = createEmptyDocument({ title: "Test", projectId: "proj_zoom" });
+ return documentSchema.parse({
+ ...base,
+ project: { ...base.project, primaryAssetId: "asset_1" },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "Recording",
+ originalPath: "C:/videos/rec.mp4",
+ durationSec: 60,
+ },
+ ],
+ transcripts: [
+ {
+ assetId: "asset_1",
+ language: "en",
+ segments: [
+ // Long speech — should produce a suggestion.
+ { id: "seg_1", kind: "speech", startSec: 0, endSec: 10, text: "Intro…", wordIds: [] },
+ // Silence — ignored.
+ { id: "seg_2", kind: "silence", startSec: 10, endSec: 20, text: "", wordIds: [] },
+ // Too short — ignored.
+ { id: "seg_3", kind: "speech", startSec: 20, endSec: 22, text: "Uh", wordIds: [] },
+ // Long speech — second suggestion.
+ {
+ id: "seg_4",
+ kind: "speech",
+ startSec: 30,
+ endSec: 40,
+ text: "Deep dive…",
+ wordIds: [],
+ },
+ ],
+ words: [],
+ },
+ ],
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ ...overrides,
+ });
+}
+
+describe("suggestZoomRegions", () => {
+ it("proposes auto zoom regions over sustained speech segments", () => {
+ const suggestions = suggestZoomRegions(fixtureDocument());
+ expect(suggestions).toHaveLength(2);
+ expect(suggestions[0]).toMatchObject({
+ depth: 2,
+ focusMode: "auto",
+ source: "auto",
+ });
+ // Padded 0.4s inside the 0–10s segment, mapped 1:1 (single full clip).
+ expect(suggestions[0].startMs).toBe(400);
+ expect(suggestions[0].endMs).toBe(9600);
+ expect(suggestions[1].startMs).toBe(30400);
+ });
+
+ it("skips segments that overlap existing zoom ranges", () => {
+ const doc = fixtureDocument();
+ const withZoom = {
+ ...doc,
+ zoomRanges: [
+ {
+ id: "zoom_existing",
+ startMs: 0,
+ endMs: 12000,
+ depth: 3 as const,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ ] as AxcutDocument["zoomRanges"],
+ };
+ const suggestions = suggestZoomRegions(withZoom);
+ expect(suggestions).toHaveLength(1);
+ expect(suggestions[0].startMs).toBe(30400);
+ });
+
+ it("returns nothing without a transcript", () => {
+ const doc = { ...fixtureDocument(), transcripts: [], transcript: null };
+ expect(suggestZoomRegions(doc)).toEqual([]);
+ });
+
+ it("skips speech that was cut out of the timeline", () => {
+ const doc = fixtureDocument();
+ // Timeline keeps only 0–20s of source: the 30–40s speech is gone.
+ const trimmed = {
+ ...doc,
+ timeline: {
+ ...doc.timeline,
+ clips: [{ ...doc.timeline.clips[0], sourceEndSec: 20, timelineEndSec: 20 }],
+ },
+ };
+ const suggestions = suggestZoomRegions(trimmed);
+ expect(suggestions).toHaveLength(1);
+ expect(suggestions[0].startMs).toBe(400);
+ });
+});
diff --git a/src/lib/ai-edition/store/zoomSuggestions.ts b/src/lib/ai-edition/store/zoomSuggestions.ts
new file mode 100644
index 000000000..83090b098
--- /dev/null
+++ b/src/lib/ai-edition/store/zoomSuggestions.ts
@@ -0,0 +1,71 @@
+// F2.1 — auto-zoom "wand" suggestions. Scans the transcript for sustained
+// speech segments (the silence heuristic in reverse: anything the transcriber
+// didn't mark as silence is where the speaker is explaining something) and
+// proposes zoom regions covering them. Pure — the Bottombar Magic button
+// applies the result via saveDocument.
+
+import { createId } from "../document/ids";
+import type { AxcutDocument, AxcutZoomRegion } from "../schema";
+import { locateSourcePosition } from "../timeline/virtual-preview";
+
+// A speech segment must run at least this long to justify a zoom-in.
+const MIN_SPEECH_SEC = 4;
+// Don't flood the timeline — the user can re-run after accepting/deleting.
+const MAX_SUGGESTIONS = 6;
+// Trim the zoom slightly inside the segment so the zoom-in lands after the
+// speaker starts and releases before they stop.
+const EDGE_PADDING_SEC = 0.4;
+
+function overlapsExisting(
+ startMs: number,
+ endMs: number,
+ existing: Array<{ startMs: number; endMs: number }>,
+): boolean {
+ return existing.some((z) => startMs < z.endMs && endMs > z.startMs);
+}
+
+export function suggestZoomRegions(document: AxcutDocument): AxcutZoomRegion[] {
+ const primaryAssetId = document.project.primaryAssetId ?? document.assets[0]?.id;
+ if (!primaryAssetId) return [];
+ const transcript =
+ document.transcripts.find((t) => t.assetId === primaryAssetId) ??
+ (document.transcript?.assetId === primaryAssetId ? document.transcript : null);
+ if (!transcript) return [];
+
+ const clips = document.timeline.clips;
+ const suggestions: AxcutZoomRegion[] = [];
+ const occupied: Array<{ startMs: number; endMs: number }> = document.zoomRanges.map((z) => ({
+ startMs: z.startMs,
+ endMs: z.endMs,
+ }));
+
+ for (const segment of transcript.segments) {
+ if (suggestions.length >= MAX_SUGGESTIONS) break;
+ if (segment.kind !== "speech") continue;
+ if (segment.endSec - segment.startSec < MIN_SPEECH_SEC) continue;
+
+ // Map source time → timeline time through the clip layout; segments
+ // that were cut out of the timeline are skipped entirely.
+ const start = locateSourcePosition(clips, segment.startSec + EDGE_PADDING_SEC, primaryAssetId);
+ const end = locateSourcePosition(clips, segment.endSec - EDGE_PADDING_SEC, primaryAssetId);
+ if (!start || !end) continue;
+ const startMs = Math.round(start.virtualTimeSec * 1000);
+ const endMs = Math.round(end.virtualTimeSec * 1000);
+ if (endMs - startMs < (MIN_SPEECH_SEC - 2 * EDGE_PADDING_SEC) * 1000) continue;
+ if (overlapsExisting(startMs, endMs, occupied)) continue;
+
+ const region: AxcutZoomRegion = {
+ id: createId("zoom"),
+ startMs,
+ endMs,
+ depth: 2,
+ focus: { cx: 0.5, cy: 0.5 },
+ focusMode: "auto",
+ source: "auto",
+ };
+ suggestions.push(region);
+ occupied.push({ startMs, endMs });
+ }
+
+ return suggestions;
+}
diff --git a/src/lib/exporter/muxer.ts b/src/lib/exporter/muxer.ts
index d2a2a93b9..b640a806a 100644
--- a/src/lib/exporter/muxer.ts
+++ b/src/lib/exporter/muxer.ts
@@ -25,6 +25,15 @@ export class VideoMuxer {
this.audioCodec = audioCodec;
}
+ // Map the WebCodecs codec string (e.g. "avc1.640033", "hvc1.1.6.L120.90",
+ // "vp09.00.10.08") to mediabunny's codec family for the mp4 track.
+ private videoCodecFamily(): "avc" | "hevc" | "vp9" {
+ const codec = (this.config.codec ?? "").toLowerCase();
+ if (codec.startsWith("hvc1") || codec.startsWith("hev1")) return "hevc";
+ if (codec.startsWith("vp09") || codec.startsWith("vp9")) return "vp9";
+ return "avc";
+ }
+
async initialize(): Promise<void> {
this.target = new BufferTarget();
@@ -35,8 +44,9 @@ export class VideoMuxer {
target: this.target,
});
- // Codec is deduced from the chunk metadata.
- this.videoSource = new EncodedVideoPacketSource("avc");
+ // Codec details are deduced from the chunk metadata; the family must
+ // match the encoder codec (F2.4 exposes h264/h265/vp9 in the dialog).
+ this.videoSource = new EncodedVideoPacketSource(this.videoCodecFamily());
this.output.addVideoTrack(this.videoSource, {
frameRate: this.config.frameRate,
});
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index eacb8952e..fe63931dc 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -192,6 +192,11 @@ function createShimBridgeClient() {
},
});
},
+ chatUndoLastBatch: () =>
+ Promise.resolve({
+ success: false,
+ error: "[browser-shim] No agent tool batches to undo in browser mode.",
+ }),
chatRunDefault: (projectId: string) => {
// ponytail: legacy single-session consumers — pick the most
// recent session or auto-create one.
diff --git a/src/native/client.ts b/src/native/client.ts
index 21380051d..b44d39e34 100644
--- a/src/native/client.ts
+++ b/src/native/client.ts
@@ -215,9 +215,11 @@ export const nativeBridgeClient = {
projectId: string,
sessionIdOrMessage: string,
message?: string,
+ document?: unknown,
): Promise<AiEditionChatResult> => {
// ponytail: polymorphic — legacy 2-arg callers pass (projectId, message).
- // Multi-session callers pass (projectId, sessionId, message).
+ // Multi-session callers pass (projectId, sessionId, message[, document]).
+ // The document snapshot enables the agent tool loop (P1).
if (message === undefined) {
return requireNativeBridgeData<AiEditionChatResult>({
domain: "aiEdition",
@@ -228,9 +230,15 @@ export const nativeBridgeClient = {
return requireNativeBridgeData<AiEditionChatResult>({
domain: "aiEdition",
action: "chat.run",
- payload: { projectId, sessionId: sessionIdOrMessage, message },
+ payload: { projectId, sessionId: sessionIdOrMessage, message, document },
});
},
+ chatUndoLastBatch: (projectId: string, sessionId: string) =>
+ requireNativeBridgeData<AiEditionChatResult>({
+ domain: "aiEdition",
+ action: "chat.undoLastBatch",
+ payload: { projectId, sessionId },
+ }),
chatRunDefault: (projectId: string, message: string) =>
requireNativeBridgeData<AiEditionChatResult>({
domain: "aiEdition",
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index b60c3828d..8b65d99f6 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -117,6 +117,9 @@ export interface AiEditionLlmConfig {
model: string;
baseUrl?: string;
reasoningEffort?: string;
+ /** P2.5 — when false, the agent must ask before running write tools.
+ * Undefined means enabled (edits allowed, protected by checkpoints). */
+ allowAgentEdits?: boolean;
}
export interface AiEditionLlmSnapshot {
@@ -125,17 +128,27 @@ export interface AiEditionLlmSnapshot {
availableProviders: Array<{ id: string; label: string; authKind: string }>;
}
+/** One executed agent tool call, rendered as a compact "applied: …" line in
+ * the chat panel (P1.7). */
+export interface AiEditionToolCallSummary {
+ name: string;
+ summary: string;
+}
+
export interface AiEditionChatMessage {
id: string;
role: "user" | "assistant";
content: string;
createdAt: string;
+ toolCalls?: AiEditionToolCallSummary[];
}
export interface AiEditionChatResult {
success: boolean;
assistantMessage?: AiEditionChatMessage;
+ /** Updated document when the agent ran write tools during this turn. */
document?: unknown;
+ toolCalls?: AiEditionToolCallSummary[];
error?: string;
}
@@ -360,7 +373,20 @@ export type NativeBridgeRequest =
| {
domain: "aiEdition";
action: "chat.run";
- payload: { projectId: string; sessionId: string; message: string };
+ payload: {
+ projectId: string;
+ sessionId: string;
+ message: string;
+ /** Current AxcutDocument snapshot — enables the agent tool loop.
+ * When omitted the chat runs text-only (no tools). */
+ document?: unknown;
+ };
+ requestId?: string;
+ }
+ | {
+ domain: "aiEdition";
+ action: "chat.undoLastBatch";
+ payload: { projectId: string; sessionId: string };
requestId?: string;
}
| {