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(timeline): unify the trim/effect model, ventilate on reorder, and add LLM effect tools

Etienne Lescotaaaec77efffd
diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts
index 6213daa4f..e403d7a2b 100644
--- a/electron/ai-edition/agent-tools.test.ts
+++ b/electron/ai-edition/agent-tools.test.ts
@@ -1,226 +1,313 @@
-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 doc = fixtureDocument();
- // Test the rebuild path: strip user-placed clips first so the tool
- // is allowed to operate (it refuses when origin:user clips are present).
- const stripped: AxcutDocument = {
- ...doc,
- timeline: { ...doc.timeline, clips: [] },
- };
- const result = executeAgentTool(
- stripped,
- "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("replaceTimeline refuses when the timeline has user-placed clips", () => {
- const result = executeAgentTool(
- fixtureDocument(),
- "replaceTimeline",
- JSON.stringify({
- intervals: [{ startSec: 0, endSec: 30 }],
- reason: "remove silences",
- }),
- );
- expect(result.ok).toBe(false);
- const payload = JSON.parse(result.resultJson) as { error: string };
- expect(payload.error).toMatch(/user-placed clip/);
- expect(payload.error).toMatch(/addSkip/);
- });
-
- it("rejects malformed JSON arguments and unknown tools", () => {
- expect(executeAgentTool(fixtureDocument(), "addSkip", "{not json").ok).toBe(false);
- expect(executeAgentTool(fixtureDocument(), "flyToTheMoon", "{}").ok).toBe(false);
- });
-});
+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: "",
+ },
+ ],
+ trimRanges: [
+ {
+ id: "trim_1",
+ assetId: "asset_1",
+ startSec: 10,
+ endSec: 12,
+ reason: "",
+ origin: "user",
+ },
+ ],
+ },
+ });
+}
+
+describe("agent-tools specs", () => {
+ it("declares the clip/trim + effect tools with mutation flags", () => {
+ const names = AGENT_TOOL_SPECS.map((t) => t.name);
+ expect(names).toEqual([
+ "getCurrentDocument",
+ "getTranscript",
+ "addTrim",
+ "setTrim",
+ "setClipRange",
+ "replaceTimeline",
+ "addZoom",
+ "setZoom",
+ "addSpeed",
+ "setSpeed",
+ "addAnnotation",
+ "setAnnotation",
+ ]);
+ expect(isMutatingTool("getTranscript")).toBe(false);
+ expect(isMutatingTool("replaceTimeline")).toBe(true);
+ expect(isMutatingTool("addZoom")).toBe(true);
+ expect(isMutatingTool("setAnnotation")).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.trimRanges[0].id).toBe("trim_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("addTrim appends an agent-origin skip range and normalizes reversed bounds", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addTrim",
+ JSON.stringify({ startSec: 22, endSec: 20, reason: "silence" }),
+ );
+ expect(result.ok).toBe(true);
+ expect(result.document).toBeDefined();
+ const added = result.document?.timeline.trimRanges.at(-1);
+ expect(added?.startSec).toBe(20);
+ expect(added?.endSec).toBe(22);
+ expect(added?.origin).toBe("agent");
+ expect(result.summary).toMatch(/added trim 0:20\.0 – 0:22\.0/);
+ });
+
+ it("addTrim rejects unknown assets", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addTrim",
+ JSON.stringify({ startSec: 0, endSec: 1, assetId: "asset_missing" }),
+ );
+ expect(result.ok).toBe(false);
+ expect(result.document).toBeUndefined();
+ });
+
+ it("setTrim moves an existing range and errors on unknown ids", () => {
+ const ok = executeAgentTool(
+ fixtureDocument(),
+ "setTrim",
+ JSON.stringify({ trimRangeId: "trim_1", startSec: 14, endSec: 18 }),
+ );
+ expect(ok.ok).toBe(true);
+ expect(ok.document?.timeline.trimRanges[0]).toMatchObject({ startSec: 14, endSec: 18 });
+
+ const missing = executeAgentTool(
+ fixtureDocument(),
+ "setTrim",
+ JSON.stringify({ trimRangeId: "trim_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 doc = fixtureDocument();
+ // Test the rebuild path: strip user-placed clips first so the tool
+ // is allowed to operate (it refuses when origin:user clips are present).
+ const stripped: AxcutDocument = {
+ ...doc,
+ timeline: { ...doc.timeline, clips: [] },
+ };
+ const result = executeAgentTool(
+ stripped,
+ "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?.trimRanges.map((s) => [s.startSec, s.endSec])).toEqual([
+ [10, 20],
+ [30, 60],
+ ]);
+ expect(result.summary).toMatch(/2 intervals/);
+ });
+
+ it("replaceTimeline refuses when the timeline has user-placed clips", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "replaceTimeline",
+ JSON.stringify({
+ intervals: [{ startSec: 0, endSec: 30 }],
+ reason: "remove silences",
+ }),
+ );
+ expect(result.ok).toBe(false);
+ const payload = JSON.parse(result.resultJson) as { error: string };
+ expect(payload.error).toMatch(/user-placed clip/);
+ expect(payload.error).toMatch(/addTrim/);
+ });
+
+ it("rejects malformed JSON arguments and unknown tools", () => {
+ expect(executeAgentTool(fixtureDocument(), "addTrim", "{not json").ok).toBe(false);
+ expect(executeAgentTool(fixtureDocument(), "flyToTheMoon", "{}").ok).toBe(false);
+ });
+
+ it("addZoom adds a schema-valid zoom in virtual-ms and normalizes bounds", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addZoom",
+ JSON.stringify({ startSec: 12, endSec: 8, depth: 4, focus: { cx: 0.3, cy: 0.7 } }),
+ );
+ expect(result.ok).toBe(true);
+ const zoom = result.document?.zoomRanges.at(-1);
+ expect(zoom).toMatchObject({
+ startMs: 8000,
+ endMs: 12000,
+ depth: 4,
+ focus: { cx: 0.3, cy: 0.7 },
+ });
+ // The produced document must round-trip through the schema.
+ expect(() => documentSchema.parse(result.document)).not.toThrow();
+ });
+
+ it("setZoom patches only the fields passed", () => {
+ const withZoom = executeAgentTool(
+ fixtureDocument(),
+ "addZoom",
+ JSON.stringify({ startSec: 2, endSec: 4 }),
+ ).document as AxcutDocument;
+ const id = withZoom.zoomRanges[0].id;
+ const result = executeAgentTool(withZoom, "setZoom", JSON.stringify({ zoomId: id, depth: 6 }));
+ expect(result.ok).toBe(true);
+ expect(result.document?.zoomRanges[0]).toMatchObject({ startMs: 2000, endMs: 4000, depth: 6 });
+ expect(executeAgentTool(withZoom, "setZoom", JSON.stringify({ zoomId: "nope" })).ok).toBe(
+ false,
+ );
+ });
+
+ it("addSpeed writes a legacyEditor speed region the snapshot exposes", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addSpeed",
+ JSON.stringify({ startSec: 5, endSec: 9, speed: 2 }),
+ );
+ expect(result.ok).toBe(true);
+ const legacy = result.document?.legacyEditor as Record<string, unknown>;
+ const regions = legacy.speedRegions as Array<{ startMs: number; endMs: number; speed: number }>;
+ expect(regions.at(-1)).toMatchObject({ startMs: 5000, endMs: 9000, speed: 2 });
+ expect(() => documentSchema.parse(result.document)).not.toThrow();
+ });
+
+ it("addAnnotation adds a schema-valid text annotation", () => {
+ const result = executeAgentTool(
+ fixtureDocument(),
+ "addAnnotation",
+ JSON.stringify({ startSec: 1, endSec: 3, text: "Look here", x: 20, y: 80 }),
+ );
+ expect(result.ok).toBe(true);
+ const ann = result.document?.annotations.at(-1);
+ expect(ann).toMatchObject({
+ startMs: 1000,
+ endMs: 3000,
+ type: "text",
+ textContent: "Look here",
+ position: { x: 20, y: 80 },
+ });
+ expect(() => documentSchema.parse(result.document)).not.toThrow();
+ });
+
+ it("snapshot exposes clips/trims/effects as virtual-time groups with a time-base note", () => {
+ const withEffects = executeAgentTool(
+ fixtureDocument(),
+ "addZoom",
+ JSON.stringify({ startSec: 3, endSec: 6, depth: 2 }),
+ ).document as AxcutDocument;
+ const snapshot = JSON.parse(executeAgentTool(withEffects, "getCurrentDocument", "").resultJson);
+ expect(snapshot.timeBaseNote).toMatch(/virtual/);
+ expect(snapshot.zoomRanges[0]).toMatchObject({ startSec: 3, endSec: 6, depth: 2 });
+ expect(snapshot.trimRanges[0].id).toBe("trim_1");
+ // counts-only fields are gone in favour of the labelled effect lists.
+ expect(snapshot.zoomRangeCount).toBeUndefined();
+ expect(snapshot.annotationCount).toBeUndefined();
+ });
+});
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
index 14f745605..523803428 100644
--- a/electron/ai-edition/agent-tools.ts
+++ b/electron/ai-edition/agent-tools.ts
@@ -1,389 +1,830 @@
-// 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);
- const userPlaced = document.timeline.clips.filter((c) => c.origin === "user");
- if (userPlaced.length > 0) {
- return {
- ok: false,
- resultJson: JSON.stringify({
- error: `Refused: ${userPlaced.length} user-placed clip(s) would be discarded. ` +
- `For 'remove silences' / 'cut pauses' use addSkip (one call per silent range), ` +
- `which preserves the placed clips and adds the cuts. ` +
- `For 'trim this clip' use setClipRange. ` +
- `Only call replaceTimeline when the user explicitly asks to rebuild the timeline from scratch ` +
- `(after they have already cleared their placed clips).`,
- }),
- };
- }
- 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}`);
- }
-}
+// 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 trim 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")}`;
+}
+
+function toMs(sec: number): number {
+ return Math.max(0, Math.round(sec * 1000));
+}
+
+// For the effect set* tools: keep the stored span unless the caller passes new
+// edges, and normalise so start ≤ end. Input seconds are virtual-timeline time.
+function resolveSpanMs(
+ existing: { startMs: number; endMs: number },
+ startSec: number | undefined,
+ endSec: number | undefined,
+): { startMs: number; endMs: number } {
+ if (startSec === undefined && endSec === undefined) {
+ return { startMs: existing.startMs, endMs: existing.endMs };
+ }
+ const s = startSec ?? existing.startMs / 1000;
+ const e = endSec ?? existing.endMs / 1000;
+ return { startMs: toMs(Math.min(s, e)), endMs: toMs(Math.max(s, e)) };
+}
+
+const secondsSchema = z.number().finite().nonnegative();
+
+const addTrimArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ assetId: z.string().min(1).optional(),
+ reason: z.string().default(""),
+});
+
+const setTrimArgs = z.object({
+ trimRangeId: 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(),
+});
+
+// Effects (zoom / speed / annotation) are authored in *virtual* (edited-
+// timeline) seconds — the position on the ruler the user sees — unlike clips
+// and trims, which are source-time. The executor converts to the stored ms.
+const depthSchema = z.number().int().min(1).max(6);
+const focusSchema = z.object({ cx: z.number().min(0).max(1), cy: z.number().min(0).max(1) });
+
+const addZoomArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ depth: depthSchema.default(3),
+ focus: focusSchema.default({ cx: 0.5, cy: 0.5 }),
+});
+
+const setZoomArgs = z.object({
+ zoomId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ depth: depthSchema.optional(),
+ focus: focusSchema.optional(),
+});
+
+const addSpeedArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ speed: z.number().positive().default(1.5),
+});
+
+const setSpeedArgs = z.object({
+ speedId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ speed: z.number().positive().optional(),
+});
+
+const addAnnotationArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ text: z.string().default(""),
+ x: z.number().min(0).max(100).default(50),
+ y: z.number().min(0).max(100).default(50),
+});
+
+const setAnnotationArgs = z.object({
+ annotationId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ text: z.string().optional(),
+});
+
+export const AGENT_TOOL_SPECS: AgentToolSpec[] = [
+ {
+ name: "getCurrentDocument",
+ description:
+ "Read a compact snapshot of the current project: assets (with durations), timeline clips and trim ranges (source-time), and the zoom / speed / annotation effects (virtual, edited-timeline time). 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: "addTrim",
+ description:
+ "Add a trim range: a cut of a span *inside* a clip that removes it from both playback and export without splitting the clip (a long clip with a big trim is cleaner than two clips). Times are seconds of the asset's source time. For shortening a clip's head/tail use setClipRange instead.",
+ 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: "setTrim",
+ description: "Move or resize an existing trim range by id. Times are source-time seconds.",
+ parameters: {
+ type: "object",
+ properties: {
+ trimRangeId: { type: "string" },
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ },
+ required: ["trimRangeId", "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 trim. 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,
+ },
+ {
+ name: "addZoom",
+ description:
+ "Add a zoom-in effect over a span of the *edited timeline* (virtual seconds, as seen on the ruler — not source time). depth 1–6 maps to 1.0×–3.5× (default 3 ≈ 2.0×). focus is the zoom centre in 0–1 fractions of the frame (default centre). Use for 'zoom in on …' and the smart-zoom pass.",
+ parameters: {
+ type: "object",
+ properties: {
+ startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },
+ endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },
+ depth: {
+ type: "integer",
+ minimum: 1,
+ maximum: 6,
+ description: "Zoom level 1–6 (default 3).",
+ },
+ focus: {
+ type: "object",
+ description: "Zoom centre, fractions of the frame (default {cx:0.5,cy:0.5}).",
+ properties: {
+ cx: { type: "number", minimum: 0, maximum: 1 },
+ cy: { type: "number", minimum: 0, maximum: 1 },
+ },
+ required: ["cx", "cy"],
+ additionalProperties: false,
+ },
+ },
+ required: ["startSec", "endSec"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "setZoom",
+ description:
+ "Move, resize, or restyle an existing zoom by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",
+ parameters: {
+ type: "object",
+ properties: {
+ zoomId: { type: "string" },
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ depth: { type: "integer", minimum: 1, maximum: 6 },
+ focus: {
+ type: "object",
+ properties: {
+ cx: { type: "number", minimum: 0, maximum: 1 },
+ cy: { type: "number", minimum: 0, maximum: 1 },
+ },
+ required: ["cx", "cy"],
+ additionalProperties: false,
+ },
+ },
+ required: ["zoomId"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "addSpeed",
+ description:
+ "Add a speed-change region over a span of the *edited timeline* (virtual seconds). speed > 1 fast-forwards, < 1 slows down (default 1.5×). Use to speed through slow stretches without cutting them.",
+ parameters: {
+ type: "object",
+ properties: {
+ startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },
+ endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },
+ speed: {
+ type: "number",
+ exclusiveMinimum: 0,
+ description: "Playback multiplier (default 1.5).",
+ },
+ },
+ required: ["startSec", "endSec"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "setSpeed",
+ description:
+ "Move, resize, or change the multiplier of an existing speed region by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",
+ parameters: {
+ type: "object",
+ properties: {
+ speedId: { type: "string" },
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ speed: { type: "number", exclusiveMinimum: 0 },
+ },
+ required: ["speedId"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "addAnnotation",
+ description:
+ "Add a text annotation over a span of the *edited timeline* (virtual seconds). Position x/y are percentages of the frame (0–100, default centre). Use for callouts and labels.",
+ parameters: {
+ type: "object",
+ properties: {
+ startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },
+ endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },
+ text: { type: "string", description: "The annotation text." },
+ x: {
+ type: "number",
+ minimum: 0,
+ maximum: 100,
+ description: "Horizontal position % (default 50).",
+ },
+ y: {
+ type: "number",
+ minimum: 0,
+ maximum: 100,
+ description: "Vertical position % (default 50).",
+ },
+ },
+ required: ["startSec", "endSec", "text"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+ {
+ name: "setAnnotation",
+ description:
+ "Move, resize, or edit the text of an existing annotation by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",
+ parameters: {
+ type: "object",
+ properties: {
+ annotationId: { type: "string" },
+ startSec: { type: "number", minimum: 0 },
+ endSec: { type: "number", minimum: 0 },
+ text: { type: "string" },
+ },
+ required: ["annotationId"],
+ additionalProperties: false,
+ },
+ mutating: true,
+ },
+];
+
+export function isMutatingTool(name: string): boolean {
+ return AGENT_TOOL_SPECS.find((t) => t.name === name)?.mutating ?? false;
+}
+
+function roundSec(ms: number): number {
+ return Math.round(ms) / 1000;
+}
+
+// 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).
+//
+// Three clearly-separated groups, each with its OWN time-base spelled out so the
+// model never has to guess:
+// • clips — arranged segments; source-time in/out + their timeline position.
+// • trims — source-time cuts inside a clip (do not split the clip).
+// • effects — zoom / speed / annotation, in *virtual* (edited-timeline)
+// seconds, i.e. positions on the ruler after clips + trims are applied.
+export function documentSnapshotForModel(document: AxcutDocument): Record<string, unknown> {
+ const legacy = document.legacyEditor as Record<string, unknown> | null;
+ const speedRegions =
+ (legacy?.speedRegions as
+ | Array<{ id: string; startMs: number; endMs: number; speed: number }>
+ | undefined) ?? [];
+ return {
+ timeBaseNote:
+ "clips and trims are in source-time seconds; zooms, speedRegions and annotations are in virtual (edited-timeline) seconds.",
+ 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,
+ })),
+ trimRanges: document.timeline.trimRanges.map((s) => ({
+ id: s.id,
+ assetId: s.assetId,
+ startSec: s.startSec,
+ endSec: s.endSec,
+ reason: s.reason,
+ })),
+ zoomRanges: document.zoomRanges.map((z) => ({
+ id: z.id,
+ startSec: roundSec(z.startMs),
+ endSec: roundSec(z.endMs),
+ depth: z.depth,
+ focus: z.focus,
+ })),
+ speedRegions: speedRegions.map((s) => ({
+ id: s.id,
+ startSec: roundSec(s.startMs),
+ endSec: roundSec(s.endMs),
+ speed: s.speed,
+ })),
+ annotations: document.annotations.map((a) => ({
+ id: a.id,
+ startSec: roundSec(a.startMs),
+ endSec: roundSec(a.endMs),
+ type: a.type,
+ text: a.textContent ?? a.content ?? "",
+ })),
+ 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 "addTrim": {
+ const parsed = addTrimArgs.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 trim.");
+ 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 trim = {
+ id: createId("trim"),
+ assetId,
+ startSec,
+ endSec,
+ reason: parsed.data.reason,
+ origin: "agent" as const,
+ };
+ const next: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ trimRanges: [...document.timeline.trimRanges, trim],
+ },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ trimRangeId: trim.id, startSec, endSec }),
+ summary: `added trim ${formatSec(startSec)} – ${formatSec(endSec)}`,
+ };
+ }
+
+ case "setTrim": {
+ const parsed = setTrimArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const { trimRangeId } = parsed.data;
+ if (!document.timeline.trimRanges.some((r) => r.id === trimRangeId)) {
+ return failure(`Unknown trim range: ${trimRangeId}`);
+ }
+ 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,
+ trimRanges: document.timeline.trimRanges.map((r) =>
+ r.id === trimRangeId ? { ...r, startSec, endSec } : r,
+ ),
+ },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ trimRangeId, startSec, endSec }),
+ summary: `moved trim 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);
+ const userPlaced = document.timeline.clips.filter((c) => c.origin === "user");
+ if (userPlaced.length > 0) {
+ return {
+ ok: false,
+ resultJson: JSON.stringify({
+ error:
+ `Refused: ${userPlaced.length} user-placed clip(s) would be discarded. ` +
+ `For 'remove silences' / 'cut pauses' use addTrim (one call per silent range), ` +
+ `which preserves the placed clips and adds the cuts. ` +
+ `For 'trim this clip' use setClipRange. ` +
+ `Only call replaceTimeline when the user explicitly asks to rebuild the timeline from scratch ` +
+ `(after they have already cleared their placed clips).`,
+ }),
+ };
+ }
+ 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,
+ trimCount: next.timeline.trimRanges.length,
+ }),
+ summary: `rebuilt timeline from ${kept} interval${kept === 1 ? "" : "s"} (${next.timeline.clips.length} clips, ${next.timeline.trimRanges.length} trims)`,
+ };
+ }
+
+ case "addZoom": {
+ const parsed = addZoomArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const startMs = toMs(Math.min(parsed.data.startSec, parsed.data.endSec));
+ const endMs = toMs(Math.max(parsed.data.startSec, parsed.data.endSec));
+ const zoom = {
+ id: createId("zoom"),
+ startMs,
+ endMs,
+ depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6,
+ focus: parsed.data.focus,
+ focusMode: "manual" as const,
+ source: "manual" as const,
+ };
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: [...document.zoomRanges, zoom] as AxcutDocument["zoomRanges"],
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ zoomId: zoom.id,
+ startSec: startMs / 1000,
+ endSec: endMs / 1000,
+ depth: zoom.depth,
+ }),
+ summary: `added zoom ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,
+ };
+ }
+
+ case "setZoom": {
+ const parsed = setZoomArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const { zoomId } = parsed.data;
+ const existing = document.zoomRanges.find((z) => z.id === zoomId);
+ if (!existing) return failure(`Unknown zoom: ${zoomId}`);
+ const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: document.zoomRanges.map((z) =>
+ z.id === zoomId
+ ? {
+ ...z,
+ startMs,
+ endMs,
+ ...(parsed.data.depth !== undefined
+ ? { depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6 }
+ : {}),
+ ...(parsed.data.focus ? { focus: parsed.data.focus } : {}),
+ }
+ : z,
+ ) as AxcutDocument["zoomRanges"],
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({ zoomId, startSec: startMs / 1000, endSec: endMs / 1000 }),
+ summary: `updated zoom ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,
+ };
+ }
+
+ case "addSpeed": {
+ const parsed = addSpeedArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const startMs = toMs(Math.min(parsed.data.startSec, parsed.data.endSec));
+ const endMs = toMs(Math.max(parsed.data.startSec, parsed.data.endSec));
+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
+ const prev = (legacy.speedRegions as unknown[] | undefined) ?? [];
+ const region = { id: createId("speed"), startMs, endMs, speed: parsed.data.speed };
+ const next: AxcutDocument = {
+ ...document,
+ legacyEditor: { ...legacy, speedRegions: [...prev, region] },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ speedId: region.id,
+ startSec: startMs / 1000,
+ endSec: endMs / 1000,
+ speed: region.speed,
+ }),
+ summary: `added ${parsed.data.speed}× speed ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,
+ };
+ }
+
+ case "setSpeed": {
+ const parsed = setSpeedArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
+ const prev =
+ (legacy.speedRegions as
+ | Array<{ id: string; startMs: number; endMs: number; speed: number }>
+ | undefined) ?? [];
+ const existing = prev.find((s) => s.id === parsed.data.speedId);
+ if (!existing) return failure(`Unknown speed region: ${parsed.data.speedId}`);
+ const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
+ const speed = parsed.data.speed ?? existing.speed;
+ const next: AxcutDocument = {
+ ...document,
+ legacyEditor: {
+ ...legacy,
+ speedRegions: prev.map((s) =>
+ s.id === parsed.data.speedId ? { ...s, startMs, endMs, speed } : s,
+ ),
+ },
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ speedId: parsed.data.speedId,
+ startSec: startMs / 1000,
+ endSec: endMs / 1000,
+ speed,
+ }),
+ summary: `updated speed to ${speed}×`,
+ };
+ }
+
+ case "addAnnotation": {
+ const parsed = addAnnotationArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const startMs = toMs(Math.min(parsed.data.startSec, parsed.data.endSec));
+ const endMs = toMs(Math.max(parsed.data.startSec, parsed.data.endSec));
+ const ann = {
+ id: createId("ann"),
+ startMs,
+ endMs,
+ type: "text" as const,
+ content: parsed.data.text,
+ textContent: parsed.data.text,
+ position: { x: parsed.data.x, y: parsed.data.y },
+ size: { width: 30, height: 20 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold" as const,
+ fontStyle: "normal" as const,
+ textDecoration: "none" as const,
+ textAlign: "center" as const,
+ },
+ zIndex: document.annotations.length + 1,
+ };
+ const next: AxcutDocument = {
+ ...document,
+ annotations: [...document.annotations, ann] as AxcutDocument["annotations"],
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ annotationId: ann.id,
+ startSec: startMs / 1000,
+ endSec: endMs / 1000,
+ }),
+ summary: `added annotation "${parsed.data.text.slice(0, 24)}"`,
+ };
+ }
+
+ case "setAnnotation": {
+ const parsed = setAnnotationArgs.safeParse(args);
+ if (!parsed.success) return failure(parsed.error.message);
+ const { annotationId } = parsed.data;
+ const existing = document.annotations.find((a) => a.id === annotationId);
+ if (!existing) return failure(`Unknown annotation: ${annotationId}`);
+ const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
+ const next: AxcutDocument = {
+ ...document,
+ annotations: document.annotations.map((a) =>
+ a.id === annotationId
+ ? {
+ ...a,
+ startMs,
+ endMs,
+ ...(parsed.data.text !== undefined
+ ? { content: parsed.data.text, textContent: parsed.data.text }
+ : {}),
+ }
+ : a,
+ ),
+ };
+ return {
+ ok: true,
+ document: next,
+ resultJson: JSON.stringify({
+ annotationId,
+ startSec: startMs / 1000,
+ endSec: endMs / 1000,
+ }),
+ summary: `updated annotation ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,
+ };
+ }
+
+ default:
+ return failure(`Unknown tool: ${name}`);
+ }
+}
diff --git a/electron/ai-edition/chat-compaction.test.ts b/electron/ai-edition/chat-compaction.test.ts
index f058472c6..63a61f379 100644
--- a/electron/ai-edition/chat-compaction.test.ts
+++ b/electron/ai-edition/chat-compaction.test.ts
@@ -34,7 +34,7 @@ describe("estimateHistoryTokens", () => {
role: "assistant",
content: "done",
createdAt: "2026-01-01T00:00:00.000Z",
- toolCalls: [{ name: "addSkip", summary: "skip 5-8s" }],
+ toolCalls: [{ name: "addTrim", summary: "skip 5-8s" }],
},
]);
// tool adds roughly: 16 + 4-chars-per-token of name+summary
@@ -110,9 +110,9 @@ describe("buildCompactionPrompt", () => {
role: "assistant",
content: "applied",
createdAt: "2026-01-01T00:00:00.000Z",
- toolCalls: [{ name: "addSkip", summary: "5-8s" }],
+ toolCalls: [{ name: "addTrim", summary: "5-8s" }],
},
]);
- expect(prompt).toContain("tools: addSkip (5-8s)");
+ expect(prompt).toContain("tools: addTrim (5-8s)");
});
});
diff --git a/electron/ai-edition/chat-service.test.ts b/electron/ai-edition/chat-service.test.ts
index 8cd118a30..c1e6f1fe6 100644
--- a/electron/ai-edition/chat-service.test.ts
+++ b/electron/ai-edition/chat-service.test.ts
@@ -169,14 +169,14 @@ describe("runTimelineOperation", () => {
const result = await runTimelineOperation(
"proj_run",
s.id,
- { type: "add_skip_range", startSec: 5, endSec: 8 },
+ { type: "add_trim_range", startSec: 5, endSec: 8 },
"Trimmed silence",
documents,
);
expect(result.success).toBe(true);
if (!result.success) return;
- expect(result.result.summary).toMatch(/added skip/);
- const saved = file.stored?.timeline.skipRanges ?? [];
+ expect(result.result.summary).toMatch(/added trim/);
+ const saved = file.stored?.timeline.trimRanges ?? [];
expect(saved.some((s) => s.startSec === 5)).toBe(true);
const session = selectSession("proj_run", s.id);
expect(session?.messages).toHaveLength(1);
diff --git a/electron/ai-edition/chat-service.toolloop.test.ts b/electron/ai-edition/chat-service.toolloop.test.ts
index 33d367f35..8b35a4669 100644
--- a/electron/ai-edition/chat-service.toolloop.test.ts
+++ b/electron/ai-edition/chat-service.toolloop.test.ts
@@ -143,8 +143,8 @@ async function streamAgent(
describe("runChat tool loop", () => {
it("executes tool calls, chains turns, and returns the mutated document", async () => {
invokeMock.mockImplementationOnce(async (args) => {
- args.sink.toolStart("addSkip", { startSec: 5, endSec: 8, reason: "silence" });
- args.sink.toolEnd("addSkip", true, "added skip 0:05.0 – 0:08.0");
+ args.sink.toolStart("addTrim", { startSec: 5, endSec: 8, reason: "silence" });
+ args.sink.toolEnd("addTrim", true, "added trim 0:05.0 – 0:08.0");
return { text: "Done.", document: args.document, mutated: true };
});
@@ -160,13 +160,13 @@ describe("runChat tool loop", () => {
expect(result.success).toBe(true);
expect(result.assistantMessage?.content).toBe("Done.");
expect(result.toolCalls).toHaveLength(1);
- expect(result.toolCalls?.[0].summary).toMatch(/added skip/);
+ expect(result.toolCalls?.[0].summary).toMatch(/added trim/);
});
it("rewinds to before the user message, restoring the document", async () => {
invokeMock.mockImplementationOnce(async (args) => {
- args.sink.toolStart("addSkip", { startSec: 1, endSec: 2 });
- args.sink.toolEnd("addSkip", true, "added skip 0:01.0 – 0:02.0");
+ args.sink.toolStart("addTrim", { startSec: 1, endSec: 2 });
+ args.sink.toolEnd("addTrim", true, "added trim 0:01.0 – 0:02.0");
return { text: "Done.", document: args.document, mutated: true };
});
@@ -195,7 +195,7 @@ describe("runChat tool loop", () => {
expect(undo.success).toBe(true);
if (!undo.success) return;
const restored = documentSchema.parse(undo.document);
- expect(restored.timeline.skipRanges).toHaveLength(0);
+ expect(restored.timeline.trimRanges).toHaveLength(0);
expect(undo.prompt).toBe("cut the silence");
});
@@ -245,8 +245,8 @@ describe("runChat tool loop", () => {
events.push({ kind: "captured", payload: args.userMessage });
args.sink.text("Hi ");
args.sink.text("there.");
- args.sink.toolStart("addSkip", { startSec: 1, endSec: 2 });
- args.sink.toolEnd("addSkip", true, "added skip 0:01.0 – 0:02.0");
+ args.sink.toolStart("addTrim", { startSec: 1, endSec: 2 });
+ args.sink.toolEnd("addTrim", true, "added trim 0:01.0 – 0:02.0");
return { text: "Done.", document: args.document, mutated: true };
});
@@ -266,11 +266,11 @@ describe("runChat tool loop", () => {
expect((fixture.events[0].payload as string) + (fixture.events[1].payload as string)).toBe(
"Hi there.",
);
- expect(fixture.events[2].payload).toMatchObject({ name: "addSkip" });
+ expect(fixture.events[2].payload).toMatchObject({ name: "addTrim" });
expect(fixture.events[3].payload).toMatchObject({
- name: "addSkip",
+ name: "addTrim",
ok: true,
- summary: expect.stringMatching(/added skip/),
+ summary: expect.stringMatching(/added trim/),
});
// ponytail: empty-result path. When the deep agent returns no text,
diff --git a/electron/ai-edition/codex-session.test.ts b/electron/ai-edition/codex-session.test.ts
index 87e877301..c8ea2b5a3 100644
--- a/electron/ai-edition/codex-session.test.ts
+++ b/electron/ai-edition/codex-session.test.ts
@@ -68,13 +68,13 @@ describe("consumeCodexStream", () => {
const stream = sseStream([
{
type: "response.output_item.added",
- item: { type: "function_call", call_id: "c1", name: "addSkip" },
+ item: { type: "function_call", call_id: "c1", name: "addTrim" },
},
{ type: "response.function_call_arguments.delta", call_id: "c1", delta: '{"a":' },
{ type: "response.function_call_arguments.delta", call_id: "c1", delta: "1}" },
{
type: "response.output_item.done",
- item: { type: "function_call", call_id: "c1", name: "addSkip" },
+ item: { type: "function_call", call_id: "c1", name: "addTrim" },
},
{ type: "response.completed", response: { id: "r42" } },
]);
@@ -115,7 +115,7 @@ describe("toCodexInput", () => {
{
role: "assistant",
content: "",
- toolCalls: [{ id: "c1", name: "addSkip", arguments: '{"a":1}' }],
+ toolCalls: [{ id: "c1", name: "addTrim", arguments: '{"a":1}' }],
},
{ role: "tool", content: '{"ok":true}', toolCallId: "c1" },
]);
@@ -123,7 +123,7 @@ describe("toCodexInput", () => {
{ role: "user", content: "cut it" },
{
role: "assistant",
- content: [{ type: "tool_call", name: "addSkip", arguments: '{"a":1}', call_id: "c1" }],
+ content: [{ type: "tool_call", name: "addTrim", arguments: '{"a":1}', call_id: "c1" }],
},
{ type: "tool_result", role: "tool", tool_call_id: "c1", content: '{"ok":true}' },
]);
diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts
index f3571485d..5a9b50416 100644
--- a/electron/ai-edition/deep-agent/service.ts
+++ b/electron/ai-edition/deep-agent/service.ts
@@ -24,15 +24,15 @@ export interface OpenScreenAgentSink {
// stays the source of truth for the UI's "applied: ..." chip.
const secondsSchema = z.number().finite().nonnegative();
-const addSkipArgs = z.object({
+const addTrimArgs = 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),
+const setTrimArgs = z.object({
+ trimRangeId: z.string().min(1),
startSec: secondsSchema,
endSec: secondsSchema,
});
@@ -55,6 +55,54 @@ const replaceTimelineArgs = z.object({
reason: z.string().default(""),
});
+// Effects (zoom / speed / annotation) — authored in virtual (edited-timeline)
+// seconds, mirroring the JSON-schema specs in agent-tools.ts.
+const depthSchema = z.number().int().min(1).max(6);
+const focusSchema = z.object({ cx: z.number().min(0).max(1), cy: z.number().min(0).max(1) });
+
+const addZoomArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ depth: depthSchema.default(3),
+ focus: focusSchema.default({ cx: 0.5, cy: 0.5 }),
+});
+
+const setZoomArgs = z.object({
+ zoomId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ depth: depthSchema.optional(),
+ focus: focusSchema.optional(),
+});
+
+const addSpeedArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ speed: z.number().positive().default(1.5),
+});
+
+const setSpeedArgs = z.object({
+ speedId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ speed: z.number().positive().optional(),
+});
+
+const addAnnotationArgs = z.object({
+ startSec: secondsSchema,
+ endSec: secondsSchema,
+ text: z.string().default(""),
+ x: z.number().min(0).max(100).default(50),
+ y: z.number().min(0).max(100).default(50),
+});
+
+const setAnnotationArgs = z.object({
+ annotationId: z.string().min(1),
+ startSec: secondsSchema.optional(),
+ endSec: secondsSchema.optional(),
+ text: z.string().optional(),
+});
+
const SYSTEM_PROMPT = [
"You are an AI video editor working inside OpenScreen. The user is editing a recording.",
"Help them cut silences, tighten pacing, add captions, and rewrite titles.",
@@ -62,25 +110,40 @@ const SYSTEM_PROMPT = [
"You can call the tools below against the live document snapshot; the runtime executes each edit and feeds the result back into the loop.",
"The AxcutDocument is the single source of truth. The timeline, the transcript editor, and the chat panel are all direct editors of the same document — when the user places a clip on the timeline, the document updates immediately, and when the timeline is empty, the document has no clips. Your edits operate on the live document, so preserve the user's placed clips.",
"",
+ "Time-bases (do not mix them up): clips and trims are in SOURCE-time seconds of an asset; zooms, speed regions and annotations are in VIRTUAL (edited-timeline) seconds — the position on the ruler after clips + trims are applied. getCurrentDocument returns both, clearly labelled.",
+ "",
"Tool-selection rules (these are non-negotiable):",
- "- 'remove silences' / 'cut pauses' / 'cut the silence' / 'kill the silence' / 'tighten pacing': call addSkip ONCE PER SILENT RANGE. Do NOT call setClipRange, do NOT call replaceTimeline. The placed clip is the canonical cut, the silence becomes a skip range inside it.",
- "- 'trim this clip to 0-30' / 'cut the end of this clip' / 'shorten this clip': call setClipRange with the new sourceStartSec/sourceEndSec.",
+ "- 'remove silences' / 'cut pauses' / 'cut the silence' / 'kill the silence' / 'tighten pacing': call addTrim ONCE PER SILENT RANGE. Do NOT call setClipRange, do NOT call replaceTimeline. The placed clip is the canonical cut, the silence becomes a trim inside it.",
+ "- 'trim this clip to 0-30' / 'cut the end of this clip' / 'shorten this clip': call setClipRange with the new sourceStartSec/sourceEndSec (this is the clip's in/out, distinct from a trim).",
+ "- 'zoom in on …' / smart zooms: call addZoom over the virtual-timeline span (depth 1–6, focus in 0–1 frame fractions). 'speed through …': addSpeed. 'add a caption/label': addAnnotation.",
"- 'replace the timeline' / 'rebuild the timeline' / 'start over with these intervals': call replaceTimeline. Only when the user explicitly asks for a full rebuild.",
- "Anything else (move a clip, resize a skip, change a clip's order, etc.) — pick the most specific tool. If the request is ambiguous, prefer the smallest edit that satisfies it.",
+ "Anything else (move a clip, resize a trim, restyle a zoom, change a clip's order, etc.) — pick the most specific tool. If the request is ambiguous, prefer the smallest edit that satisfies it.",
].join("\n");
const TOOL_DESCRIPTIONS: Record<string, string> = {
getCurrentDocument:
- "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. The AxcutDocument is the single source of truth — your edits should preserve the user's placed clips and any timeline state they have already set up.",
+ "Read a compact snapshot of the current project: assets (with durations), timeline clips and trim ranges (source-time), and the zoom / speed / annotation effects (virtual, edited-timeline time). Call this before editing if the snapshot in the system prompt may be stale. The AxcutDocument is the single source of truth — your edits should preserve the user's placed clips and any timeline state they have already set up.",
getTranscript:
"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.",
- addSkip:
- "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. This is the preferred (and for 'remove silences' requests, the only) way to handle silences; it preserves the user's placed clips and only adds a cut. Call this once per silent range.",
- setSkipRange: "Move or resize an existing skip range by id. Times are source-time seconds.",
+ addTrim:
+ "Add a trim range: a cut of a span inside a clip (this source-time span will not be played or exported) that does NOT split the clip. Times are in seconds of the asset's source time. This is the preferred (and for 'remove silences' requests, the only) way to handle silences; it preserves the user's placed clips and only adds a cut. Call this once per silent range.",
+ setTrim: "Move or resize an existing trim range by id. Times are source-time seconds.",
setClipRange:
- "Trim a clip: set its source in/out points (seconds). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Use this ONLY when the user explicitly asks to shorten or extend a user-placed clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addSkip.",
+ "Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Use this ONLY when the user explicitly asks to shorten or extend a user-placed clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim.",
replaceTimeline:
- "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a skip. DO NOT use this for 'cut silences' or 'remove pauses' — the user has likely placed clips on the timeline that you'd be discarding. Use this ONLY when the user explicitly asks you to rebuild the timeline from scratch (e.g. 'start over with the kept intervals from the transcript' or 'replace everything with these intervals').",
+ "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a trim. DO NOT use this for 'cut silences' or 'remove pauses' — the user has likely placed clips on the timeline that you'd be discarding. Use this ONLY when the user explicitly asks you to rebuild the timeline from scratch (e.g. 'start over with the kept intervals from the transcript' or 'replace everything with these intervals').",
+ addZoom:
+ "Add a zoom-in over a span of the edited timeline (virtual seconds). depth 1–6 maps to 1.0×–3.5× (default 3). focus is the zoom centre in 0–1 fractions of the frame (default centre). Use for 'zoom in on …' and the smart-zoom pass.",
+ setZoom:
+ "Move, resize, or restyle an existing zoom by id (virtual-timeline seconds). Only the fields you pass are changed.",
+ addSpeed:
+ "Add a speed-change region over a span of the edited timeline (virtual seconds). speed > 1 fast-forwards, < 1 slows down (default 1.5×). Use to speed through slow stretches without cutting them.",
+ setSpeed:
+ "Move, resize, or change the multiplier of an existing speed region by id (virtual-timeline seconds). Only the fields you pass are changed.",
+ addAnnotation:
+ "Add a text annotation over a span of the edited timeline (virtual seconds). x/y are frame percentages (0–100, default centre). Use for callouts and labels.",
+ setAnnotation:
+ "Move, resize, or edit the text of an existing annotation by id (virtual-timeline seconds). Only the fields you pass are changed.",
};
// ponytail: mutable document holder so a write-tool that updates the snapshot
@@ -89,6 +152,28 @@ const TOOL_DESCRIPTIONS: Record<string, string> = {
// each tool sees the latest mutated snapshot.
type DocumentHolder = { current: AxcutDocument };
+// One mutating document tool: run it through the shared executor, advance the
+// holder so the next tool in the turn sees the edit, and emit start/end chips.
+// (All write tools share this exact flow — factored out so adding a tool is one
+// line instead of a 20-line copy.)
+function mutatingTool<S extends z.ZodType>(
+ holder: DocumentHolder,
+ sink: OpenScreenAgentSink,
+ name: string,
+ schema: S,
+) {
+ return tool(
+ async (args: z.infer<S>) => {
+ sink.toolStart(name, args);
+ const execution = executeAgentTool(holder.current, name, JSON.stringify(args));
+ if (execution.document) holder.current = execution.document;
+ sink.toolEnd(name, execution.ok, execution.summary);
+ return execution.resultJson;
+ },
+ { name, description: TOOL_DESCRIPTIONS[name], schema },
+ );
+}
+
function buildTools(holder: DocumentHolder, sink: OpenScreenAgentSink) {
return [
tool(async () => JSON.stringify(documentSnapshotForModel(holder.current)), {
@@ -107,78 +192,16 @@ function buildTools(holder: DocumentHolder, sink: OpenScreenAgentSink) {
schema: z.object({ assetId: z.string().min(1).optional() }),
},
),
- tool(
- async (args: z.infer<typeof addSkipArgs>) => {
- sink.toolStart("addSkip", args);
- const execution = executeAgentTool(holder.current, "addSkip", JSON.stringify(args));
- if (execution.document) {
- holder.current = execution.document;
- sink.toolEnd("addSkip", execution.ok, execution.summary);
- } else {
- sink.toolEnd("addSkip", execution.ok, execution.summary);
- }
- return execution.resultJson;
- },
- {
- name: "addSkip",
- description: TOOL_DESCRIPTIONS.addSkip,
- schema: addSkipArgs,
- },
- ),
- tool(
- async (args: z.infer<typeof setSkipRangeArgs>) => {
- sink.toolStart("setSkipRange", args);
- const execution = executeAgentTool(holder.current, "setSkipRange", JSON.stringify(args));
- if (execution.document) {
- holder.current = execution.document;
- sink.toolEnd("setSkipRange", execution.ok, execution.summary);
- } else {
- sink.toolEnd("setSkipRange", execution.ok, execution.summary);
- }
- return execution.resultJson;
- },
- {
- name: "setSkipRange",
- description: TOOL_DESCRIPTIONS.setSkipRange,
- schema: setSkipRangeArgs,
- },
- ),
- tool(
- async (args: z.infer<typeof setClipRangeArgs>) => {
- sink.toolStart("setClipRange", args);
- const execution = executeAgentTool(holder.current, "setClipRange", JSON.stringify(args));
- if (execution.document) {
- holder.current = execution.document;
- sink.toolEnd("setClipRange", execution.ok, execution.summary);
- } else {
- sink.toolEnd("setClipRange", execution.ok, execution.summary);
- }
- return execution.resultJson;
- },
- {
- name: "setClipRange",
- description: TOOL_DESCRIPTIONS.setClipRange,
- schema: setClipRangeArgs,
- },
- ),
- tool(
- async (args: z.infer<typeof replaceTimelineArgs>) => {
- sink.toolStart("replaceTimeline", args);
- const execution = executeAgentTool(holder.current, "replaceTimeline", JSON.stringify(args));
- if (execution.document) {
- holder.current = execution.document;
- sink.toolEnd("replaceTimeline", execution.ok, execution.summary);
- } else {
- sink.toolEnd("replaceTimeline", execution.ok, execution.summary);
- }
- return execution.resultJson;
- },
- {
- name: "replaceTimeline",
- description: TOOL_DESCRIPTIONS.replaceTimeline,
- schema: replaceTimelineArgs,
- },
- ),
+ mutatingTool(holder, sink, "addTrim", addTrimArgs),
+ mutatingTool(holder, sink, "setTrim", setTrimArgs),
+ mutatingTool(holder, sink, "setClipRange", setClipRangeArgs),
+ mutatingTool(holder, sink, "replaceTimeline", replaceTimelineArgs),
+ mutatingTool(holder, sink, "addZoom", addZoomArgs),
+ mutatingTool(holder, sink, "setZoom", setZoomArgs),
+ mutatingTool(holder, sink, "addSpeed", addSpeedArgs),
+ mutatingTool(holder, sink, "setSpeed", setSpeedArgs),
+ mutatingTool(holder, sink, "addAnnotation", addAnnotationArgs),
+ mutatingTool(holder, sink, "setAnnotation", setAnnotationArgs),
];
}
@@ -299,12 +322,14 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
// the success-but-empty path above.
const e = err instanceof Error ? err : new Error(String(err));
const stackHead = (e.stack ?? "").split("\n").slice(0, 3).join(" | ");
- const reason = `Empty response from model (provider=${model.provider}, ` +
+ const reason =
+ `Empty response from model (provider=${model.provider}, ` +
`model=${model.model}, error=${e.name}: ${e.message}` +
(stackHead ? ` stack=${stackHead}` : "") +
- `). Last chunk: ${(chatModelChunks[chatModelChunks.length - 1]
- ? JSON.stringify(chatModelChunks[chatModelChunks.length - 1])
- : "(no on_chat_model_stream events)"
+ `). Last chunk: ${(
+ chatModelChunks[chatModelChunks.length - 1]
+ ? JSON.stringify(chatModelChunks[chatModelChunks.length - 1])
+ : "(no on_chat_model_stream events)"
).slice(0, 1024)}`;
sink.error(reason);
return {
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 3fa0dd4e1..2ba9bd368 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -119,13 +119,13 @@ describe("DocumentService", () => {
});
describe("removeAsset", () => {
- it("removes the asset and cascades clips + skipRanges", async () => {
+ it("removes the asset and cascades clips + trimRanges", async () => {
const doc = await service.createProject("P");
const withAsset = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });
const assetId = withAsset.assets[0]?.id;
expect(assetId).toBeTruthy();
- // Manually add a clip + skipRange so we can verify cascade
+ // Manually add a clip + trimRange so we can verify cascade
const docWithTimeline = await service.saveProject({
...withAsset,
timeline: {
@@ -141,9 +141,9 @@ describe("DocumentService", () => {
origin: "system",
},
],
- skipRanges: [
+ trimRanges: [
{
- id: "skip_1",
+ id: "trim_1",
assetId,
startSec: 0,
endSec: 1,
@@ -156,7 +156,7 @@ describe("DocumentService", () => {
const after = await service.removeAsset(docWithTimeline.project.id, assetId ?? "");
expect(after.assets).toHaveLength(0);
expect(after.timeline.clips).toHaveLength(0);
- expect(after.timeline.skipRanges).toHaveLength(0);
+ expect(after.timeline.trimRanges).toHaveLength(0);
expect(after.project.primaryAssetId).toBeUndefined();
});
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index 67640a39e..ac008a51f 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -218,7 +218,7 @@ export class DocumentService {
timeline: {
...doc.timeline,
clips: doc.timeline.clips.filter((c) => c.assetId !== assetId),
- skipRanges: doc.timeline.skipRanges.filter((r) => r.assetId !== assetId),
+ trimRanges: doc.timeline.trimRanges.filter((r) => r.assetId !== assetId),
},
project: {
...doc.project,
diff --git a/electron/ai-edition/llm-call.ts b/electron/ai-edition/llm-call.ts
index a1b7be901..459487d37 100644
--- a/electron/ai-edition/llm-call.ts
+++ b/electron/ai-edition/llm-call.ts
@@ -296,10 +296,7 @@ async function streamAnthropic(
cb: LlmStreamCallbacks,
): Promise<CallLlmResult> {
const def = getProviderDefinition(opts.provider) ?? getProviderDefinition("anthropic");
- const baseUrl = (opts.baseUrl || def?.baseUrl || "https://api.anthropic.com").replace(
- /\/+$/,
- "",
- );
+ const baseUrl = (opts.baseUrl || def?.baseUrl || "https://api.anthropic.com").replace(/\/+$/, "");
const systemMessage = opts.messages.find((m) => m.role === "system")?.content;
const conversation = opts.messages.filter((m) => m.role !== "system");
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index 684820b52..912f3c8ce 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -48,6 +48,13 @@ interface Window {
selectSource: (source: ProcessedDesktopSource) => Promise<ProcessedDesktopSource | null>;
getSelectedSource: () => Promise<ProcessedDesktopSource | null>;
onSelectedSourceChanged: (callback: (source: ProcessedDesktopSource) => void) => () => void;
+ getRecordingPrefs: () => Promise<import("./ipc/handlers").RecordingPrefs>;
+ setRecordingPrefs: (
+ prefs: Partial<import("./ipc/handlers").RecordingPrefs>,
+ ) => Promise<import("./ipc/handlers").RecordingPrefs>;
+ onRecordingPrefsChanged: (
+ callback: (prefs: import("./ipc/handlers").RecordingPrefs) => void,
+ ) => () => void;
onSourceSelectorClosed: (callback: () => void) => () => void;
onAiEditionChatEvent: (
callback: (event: import("../src/native/contracts").AiEditionChatEvent) => void,
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 8dd6445ef..9a7bea713 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -378,6 +378,30 @@ let lastEnumeratedSources = new Map<string, DesktopCapturerSource>();
let currentProjectPath: string | null = null;
let currentRecordingSession: RecordingSession | null = null;
+// ponytail: single source of truth for the mic/camera/system-audio/cursor
+// choices a user makes in the editor's Rec-mode stage, so the HUD window's
+// useScreenRecorder (a separate renderer, own process, own React tree) picks
+// up those choices instead of silently reverting to its own defaults when
+// startNewRecording() switches windows. Mirrors the selectedSource pattern
+// above (in-memory, broadcast on change) rather than persisting to disk —
+// this is a live session preference, not project content.
+export interface RecordingPrefs {
+ micEnabled: boolean;
+ micDeviceId: string | null;
+ camEnabled: boolean;
+ camDeviceId: string | null;
+ systemAudioEnabled: boolean;
+ cursorCaptureMode: CursorCaptureMode;
+}
+let recordingPrefs: RecordingPrefs = {
+ micEnabled: false,
+ micDeviceId: null,
+ camEnabled: false,
+ camDeviceId: null,
+ systemAudioEnabled: false,
+ cursorCaptureMode: "editable-overlay",
+};
+
// Cached source from the user's pick. Used by setDisplayMediaRequestHandler in main.ts for cursor-free capture.
export function getSelectedDesktopSource(): DesktopCapturerSource | null {
return selectedDesktopSource;
@@ -1538,6 +1562,19 @@ export function registerIpcHandlers(
return selectedSource;
});
+ ipcMain.handle("get-recording-prefs", () => {
+ return recordingPrefs;
+ });
+
+ ipcMain.handle("set-recording-prefs", (_, prefs: Partial<RecordingPrefs>) => {
+ recordingPrefs = { ...recordingPrefs, ...prefs };
+ const mainWin = getMainWindow();
+ if (mainWin && !mainWin.isDestroyed()) {
+ mainWin.webContents.send("recording-prefs-changed", recordingPrefs);
+ }
+ return recordingPrefs;
+ });
+
ipcMain.handle("request-camera-access", async () => {
if (process.platform !== "darwin") {
return { success: true, granted: true, status: "granted" };
diff --git a/electron/preload.ts b/electron/preload.ts
index a7db6b5dd..553e83619 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -5,6 +5,7 @@ import type { RecordingSession, StoreRecordedSessionInput } from "../src/lib/rec
import type { ShortcutBinding } from "../src/lib/shortcuts";
import type { AiEditionChatEvent } from "../src/native/contracts";
import { NATIVE_BRIDGE_CHANNEL, type NativeBridgeRequest } from "../src/native/contracts";
+import type { RecordingPrefs } from "./ipc/handlers";
import type {
SttStatusEvent,
SttTranscribeRequest,
@@ -62,6 +63,17 @@ contextBridge.exposeInMainWorld("electronAPI", {
getSelectedSource: () => {
return ipcRenderer.invoke("get-selected-source");
},
+ getRecordingPrefs: () => {
+ return ipcRenderer.invoke("get-recording-prefs");
+ },
+ setRecordingPrefs: (prefs: Partial<RecordingPrefs>) => {
+ return ipcRenderer.invoke("set-recording-prefs", prefs);
+ },
+ onRecordingPrefsChanged: (callback: (prefs: RecordingPrefs) => void) => {
+ const listener = (_event: unknown, prefs: RecordingPrefs) => callback(prefs);
+ ipcRenderer.on("recording-prefs-changed", listener);
+ return () => ipcRenderer.removeListener("recording-prefs-changed", listener);
+ },
onSelectedSourceChanged: (callback: (source: ProcessedDesktopSource) => void) => {
const listener = (_event: unknown, source: ProcessedDesktopSource) => callback(source);
ipcRenderer.on("selected-source-changed", listener);
diff --git a/public/os-preview-sample.mp4 b/public/os-preview-sample.mp4
new file mode 100644
index 000000000..795ccf7d0
Binary files /dev/null and b/public/os-preview-sample.mp4 differ
diff --git a/src/components/ai-edition/Bottombar.tsx b/src/components/ai-edition/Bottombar.tsx
index 0c40cb37c..434e257bf 100644
--- a/src/components/ai-edition/Bottombar.tsx
+++ b/src/components/ai-edition/Bottombar.tsx
@@ -26,7 +26,7 @@ import { TimelinePane } from "./TimelinePane";
import { TransportBar } from "./TransportBar";
import type { VideoSource } from "./VirtualPreview";
-type RegionKind = "zoom" | "skip" | "annotation" | "speed";
+type RegionKind = "zoom" | "trim" | "annotation" | "speed";
interface RegionHandle {
kind: RegionKind;
@@ -39,7 +39,7 @@ interface BottombarProps {
currentTimeSec: number;
onSeek: (timelineSec: number) => void;
zoomRegions: AxcutDocument["zoomRanges"];
- skipRanges: AxcutDocument["timeline"]["skipRanges"];
+ trimRanges: AxcutDocument["timeline"]["trimRanges"];
annotationRegions: AnnotationRegion[];
speedRegions: Array<{ id: string; startMs: number; endMs: number; speed: number }>;
selection: RegionHandle | null;
@@ -50,10 +50,10 @@ interface BottombarProps {
onAddAnnotation: () => void;
onAddSpeed: () => void;
// T15 — receives a setter so the parent's "T" keyboard shortcut can
- // call into our togglePlaceSkip (state lives here, body-class + Esc
+ // call into our togglePlaceTrim (state lives here, body-class + Esc
// handler live here). The Scissors button in this component calls
- // togglePlaceSkip directly.
- setTogglePlaceSkip?: (fn: () => void) => void;
+ // togglePlaceTrim directly.
+ setTogglePlaceTrim?: (fn: () => void) => void;
onSelectRegion: (kind: RegionKind, id: string, additive?: boolean) => void;
onCaptions: () => void;
// ponytail: the video transport now renders in this header (merged into
@@ -92,7 +92,7 @@ export function Bottombar({
currentTimeSec,
onSeek,
zoomRegions,
- skipRanges,
+ trimRanges,
annotationRegions,
speedRegions,
selection,
@@ -101,7 +101,7 @@ export function Bottombar({
onAddZoom,
onAddAnnotation,
onAddSpeed,
- setTogglePlaceSkip,
+ setTogglePlaceTrim,
onSelectRegion,
onCaptions,
playing,
@@ -147,7 +147,7 @@ export function Bottombar({
// right away (axcut's behavior).
const [pendingCutPlacement, setPendingCutPlacement] = useState(false);
const [pendingCutPreviewSec, setPendingCutPreviewSec] = useState<number | null>(null);
- const togglePlaceSkip = useCallback(() => {
+ const togglePlaceTrim = useCallback(() => {
setPendingCutPlacement((active) => {
if (active) {
setPendingCutPreviewSec(null);
@@ -211,12 +211,12 @@ export function Bottombar({
// ponytail: register our toggler with the parent (NewEditorShell)
// so the "T" keyboard shortcut can call the same function the
- // Scissors button does. Uses an effect so re-renders (togglePlaceSkip
+ // Scissors button does. Uses an effect so re-renders (togglePlaceTrim
// identity is stable but the ref it points to may change) always
// see the latest implementation.
useEffect(() => {
- setTogglePlaceSkip?.(togglePlaceSkip);
- }, [togglePlaceSkip, setTogglePlaceSkip]);
+ setTogglePlaceTrim?.(togglePlaceTrim);
+ }, [togglePlaceTrim, setTogglePlaceTrim]);
const sourceDurationSec = Math.max(0.001, ...clips.map((c) => c.timelineEndSec));
const visibleEndSec = Math.min(visibleStartSec + sourceDurationSec, sourceDurationSec);
@@ -225,15 +225,15 @@ export function Bottombar({
if (zoomRegions.some((z) => z.id === id)) void tl.updateZoomSpan(id, span.start, span.end);
else if (speedRegions.some((s) => s.id === id))
void tl.updateSpeedSpan(id, span.start, span.end);
- else if (skipRanges.some((s) => s.id === id)) {
+ else if (trimRanges.some((s) => s.id === id)) {
// ponytail: skip spans are edited in timeline (virtual) ms via the
// same lane drag/resize as zoom/speed/annotation, but persisted in
- // source-time seconds (skipRangeSchema) — map back through the
+ // source-time seconds (trimRangeSchema) — map back through the
// clip the span resolves to.
const startPos = locateVirtualPosition(clips, span.start / 1000);
const endPos = locateVirtualPosition(clips, span.end / 1000);
if (startPos && endPos) {
- void tl.updateSkipRange(id, startPos.sourceTimeSec, endPos.sourceTimeSec);
+ void tl.updateTrimRange(id, startPos.sourceTimeSec, endPos.sourceTimeSec);
}
} else void tl.updateAnnotationSpan(id, span.start, span.end);
};
@@ -300,7 +300,7 @@ export function Bottombar({
? "Click on the timeline to place a 1s skip (Esc to cancel)"
: "Arm the place-skip tool (T) — next click drops a 1s skip"
}
- onClick={togglePlaceSkip}
+ onClick={togglePlaceTrim}
disabled={!hasDoc}
on={pendingCutPlacement}
>
@@ -437,7 +437,7 @@ export function Bottombar({
<TimelinePane
clips={clips}
assets={tl.assets}
- skipRanges={skipRanges}
+ trimRanges={trimRanges}
zoomRegions={zoomRegions}
annotationRegions={annotationRegions}
speedRegions={speedRegions}
@@ -452,7 +452,7 @@ export function Bottombar({
onMoveClip={(clipId, toIndex) => void tl.moveClip(clipId, toIndex)}
onEditClip={(clip) => setEditClipTarget(clip)}
onRemoveClip={(clipId) => void tl.removeClip(clipId)}
- onAddSkip={(assetId, s, e) => void tl.addSkipAt(assetId, s, e)}
+ onAddTrim={(assetId, s, e) => void tl.addTrimAt(assetId, s, e)}
onRegionSpanChange={(id, span) => handleRegionSpanChange(id, span)}
zoom={zoom}
visibleStartSec={visibleStartSec}
@@ -461,7 +461,7 @@ export function Bottombar({
pendingCutPlacement={pendingCutPlacement}
pendingCutPreviewSec={pendingCutPreviewSec}
setPendingCutPreviewSec={setPendingCutPreviewSec}
- onCancelPlaceSkip={() => togglePlaceSkip()}
+ onCancelPlaceTrim={() => togglePlaceTrim()}
/>
</div>
</div>
diff --git a/src/components/ai-edition/CursorPreviewLayer.test.tsx b/src/components/ai-edition/CursorPreviewLayer.test.tsx
index b6edf4a22..37b08a0ef 100644
--- a/src/components/ai-edition/CursorPreviewLayer.test.tsx
+++ b/src/components/ai-edition/CursorPreviewLayer.test.tsx
@@ -99,7 +99,7 @@ const SAMPLE_DOC = {
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRegions: [],
captionRanges: [],
diff --git a/src/components/ai-edition/EditorEmptyState.test.tsx b/src/components/ai-edition/EditorEmptyState.test.tsx
index de66e22e9..2a32b72a0 100644
--- a/src/components/ai-edition/EditorEmptyState.test.tsx
+++ b/src/components/ai-edition/EditorEmptyState.test.tsx
@@ -28,7 +28,7 @@ const sampleDoc = vi.hoisted(() => ({
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRegions: [],
captionRanges: [],
diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsx
index 88ad4f7c4..535c55347 100644
--- a/src/components/ai-edition/LeftPanel.tsx
+++ b/src/components/ai-edition/LeftPanel.tsx
@@ -5,6 +5,7 @@ import { toast } from "sonner";
import { AI_FEATURES_ENABLED } from "@/components/video-editor/featureFlags";
import { type AxcutAsset, ensureDocument } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { useOptimisticTimelineOps } from "@/lib/ai-edition/store/useOptimisticTimelineOps";
import { nativeBridgeClient } from "@/native/client";
import type {
@@ -760,9 +761,9 @@ function ChatStripPanel() {
await store.saveDocument(parsed);
}, []);
- const send = async () => {
- if (!projectId || !input.trim() || busy) return;
- const text = input.trim();
+ const send = async (overrideText?: string) => {
+ const text = (overrideText ?? input).trim();
+ if (!projectId || !text || busy) return;
setInput("");
setBusy(true);
// ponytail: pre-seed the user message so the rewind ↩ button is
@@ -832,6 +833,19 @@ function ChatStripPanel() {
}
};
+ // Auto-send a prompt handed over by another part of the UI (e.g. the
+ // timeline's Auto-enhance → "Smart zooms + cuts with AI"). Routes through
+ // the normal send() so sessions/checkpoints/rewind all keep working; the
+ // message shows in the composer's history exactly as if typed.
+ const pendingPrompt = useChatPromptBus((s) => s.pending);
+ const consumePrompt = useChatPromptBus((s) => s.consume);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: send() is intentionally not a dep (recreated each render); consume() clears `pending` so this fires once per queued prompt.
+ useEffect(() => {
+ if (!pendingPrompt || !projectId || busy) return;
+ consumePrompt();
+ void send(pendingPrompt);
+ }, [pendingPrompt, projectId, busy, consumePrompt]);
+
// ponytail: per-user-message rewind. Pops a confirmation popover, then
// asks the main process to roll the session + document back to the
// snapshot taken right before the user hit Send. axcut parity.
@@ -1102,7 +1116,7 @@ function ChatStripPanel() {
projectId,
activeSessionId,
);
- const runAddSkip = useCallback(() => {
+ const runAddTrim = useCallback(() => {
const raw = window.prompt("Add skip range\nFormat: startSec-endSec (e.g. 1.2-3.4)", "5-8");
if (!raw) return;
const m = raw.match(/^\s*(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)\s*$/);
@@ -1117,7 +1131,7 @@ function ChatStripPanel() {
return;
}
const op: AxcutTimelineOperation = {
- type: "add_skip_range",
+ type: "add_trim_range",
startSec,
endSec,
};
@@ -1364,7 +1378,7 @@ function ChatStripPanel() {
title="Add skip range"
aria-label="Add skip range"
disabled={!activeSessionId || queueBusy}
- onClick={runAddSkip}
+ onClick={runAddTrim}
style={{
background: "transparent",
border: "1px solid var(--border-soft)",
@@ -1661,7 +1675,7 @@ function ChatStripPanel() {
className={styles.sendBtn}
title="Send (Enter)"
aria-label="Send"
- onClick={send}
+ onClick={() => void send()}
disabled={busy || !input.trim()}
>
<svg
diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsx
index 8766fdc30..21f7affe4 100644
--- a/src/components/ai-edition/Modals.tsx
+++ b/src/components/ai-edition/Modals.tsx
@@ -495,8 +495,14 @@ function TemplateCell({
interface CropModalProps extends BaseModalProps {
initialRegion: CropRegion;
onApply: (region: CropRegion) => void;
+ /** Primary video source to show as the real crop-preview frame. */
+ videoSources?: VideoSource[];
+ /** Seek the preview frame to this time (source-media seconds). */
+ currentTimeSec?: number;
}
+// `ratio` is width/height (matches the label directly: "16:9" → 16/9 means
+// a region 16 units wide for every 9 tall).
const CROP_RATIOS: Array<{ value: string; label: string; ratio: number | null }> = [
{ value: "free", label: "Free", ratio: null },
{ value: "16:9", label: "16:9", ratio: 16 / 9 },
@@ -509,20 +515,35 @@ const CROP_RATIOS: Array<{ value: string; label: string; ratio: number | null }>
function detectRatio(r: CropRegion): string {
const candidates = CROP_RATIOS.filter((c) => c.ratio !== null);
- const ratio = r.width === 0 ? 0 : r.height / r.width;
+ const whRatio = r.height === 0 ? 0 : r.width / r.height;
for (const c of candidates) {
if (c.ratio === null) continue;
- if (Math.abs(ratio - c.ratio) < 0.01) return c.value;
+ if (Math.abs(whRatio - c.ratio) < 0.01) return c.value;
}
return "free";
}
-export function CropModal({ open, onClose, initialRegion, onApply }: CropModalProps) {
+const MIN_PCT = 4;
+const clampPct = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
+
+type ResizeEdges = { left?: boolean; right?: boolean; top?: boolean; bottom?: boolean };
+
+export function CropModal({
+ open,
+ onClose,
+ initialRegion,
+ onApply,
+ videoSources = [],
+ currentTimeSec = 0,
+}: CropModalProps) {
const [xPct, setXPct] = useState(0);
const [yPct, setYPct] = useState(0);
const [wPct, setWPct] = useState(100);
const [hPct, setHPct] = useState(100);
const [ratio, setRatio] = useState("free");
+ const frameRef = useRef<HTMLDivElement | null>(null);
+ const videoRef = useRef<HTMLVideoElement | null>(null);
+ const activeSource = videoSources[0] ?? null;
// ponytail: sync local form state to the document region every time the
// modal opens. Doesn't run on every doc change — `open` is the trigger.
@@ -535,12 +556,27 @@ export function CropModal({ open, onClose, initialRegion, onApply }: CropModalPr
setRatio(detectRatio(initialRegion));
}, [open, initialRegion]);
+ // Show the frame at the same point the user was looking at in the editor
+ // — a still, paused frame is enough to judge the crop, no playback needed.
+ useEffect(() => {
+ if (!open) return;
+ const v = videoRef.current;
+ if (!v) return;
+ const seek = () => {
+ v.pause();
+ if (Number.isFinite(currentTimeSec)) v.currentTime = currentTimeSec;
+ };
+ if (v.readyState >= 1) seek();
+ else v.addEventListener("loadedmetadata", seek, { once: true });
+ return () => v.removeEventListener("loadedmetadata", seek);
+ }, [open, currentTimeSec]);
+
const handleRatioChange = (next: string) => {
setRatio(next);
const candidate = CROP_RATIOS.find((c) => c.value === next);
if (candidate?.ratio && wPct > 0) {
- const newH = Math.round(wPct * candidate.ratio);
- setHPct(Math.min(100, Math.max(1, newH)));
+ const newH = Math.round(wPct / candidate.ratio);
+ setHPct(clampPct(newH, MIN_PCT, 100));
}
};
@@ -555,23 +591,123 @@ export function CropModal({ open, onClose, initialRegion, onApply }: CropModalPr
onClose();
};
+ // Drag the whole region (keeps size, moves x/y).
+ const startMove = (e: ReactPointerEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const el = frameRef.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const start = { x: xPct, y: yPct, w: wPct, h: hPct };
+ const move = (ev: PointerEvent) => {
+ const dxPct = ((ev.clientX - startX) / r.width) * 100;
+ const dyPct = ((ev.clientY - startY) / r.height) * 100;
+ setXPct(Math.round(clampPct(start.x + dxPct, 0, 100 - start.w)));
+ setYPct(Math.round(clampPct(start.y + dyPct, 0, 100 - start.h)));
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ };
+
+ // Drag one of the 8 edge/corner handles to resize. When a fixed ratio is
+ // active, the opposite dimension follows to keep width/height locked.
+ const startResize = (edges: ResizeEdges) => (e: ReactPointerEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const el = frameRef.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const start = { x: xPct, y: yPct, w: wPct, h: hPct };
+ const activeRatio = CROP_RATIOS.find((c) => c.value === ratio)?.ratio ?? null;
+ const move = (ev: PointerEvent) => {
+ const dxPct = ((ev.clientX - startX) / r.width) * 100;
+ const dyPct = ((ev.clientY - startY) / r.height) * 100;
+ let { x, y, w, h } = start;
+ if (edges.left) {
+ const nx = clampPct(start.x + dxPct, 0, start.x + start.w - MIN_PCT);
+ w = start.w - (nx - start.x);
+ x = nx;
+ }
+ if (edges.right) {
+ w = clampPct(start.w + dxPct, MIN_PCT, 100 - start.x);
+ }
+ if (edges.top) {
+ const ny = clampPct(start.y + dyPct, 0, start.y + start.h - MIN_PCT);
+ h = start.h - (ny - start.y);
+ y = ny;
+ }
+ if (edges.bottom) {
+ h = clampPct(start.h + dyPct, MIN_PCT, 100 - start.y);
+ }
+ if (activeRatio) {
+ if (edges.left || edges.right) h = clampPct(w / activeRatio, MIN_PCT, 100 - y);
+ else if (edges.top || edges.bottom) w = clampPct(h * activeRatio, MIN_PCT, 100 - x);
+ }
+ setXPct(Math.round(x));
+ setYPct(Math.round(y));
+ setWPct(Math.round(w));
+ setHPct(Math.round(h));
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ };
+
+ const handleStyle = (pos: React.CSSProperties): React.CSSProperties => ({
+ position: "absolute",
+ width: 10,
+ height: 10,
+ borderRadius: 3,
+ background: "var(--fg)",
+ border: "1px solid var(--overlay-dark)",
+ ...pos,
+ });
+
return (
<ModalShell
open={open}
onClose={onClose}
title="Crop video"
- subtitle="Drag on each side to adjust the crop area"
+ subtitle="Drag the region or its handles to adjust the crop area"
>
<div
+ ref={frameRef}
style={{
position: "relative",
aspectRatio: "16 / 9",
- background: "linear-gradient(135deg, #16171d, #16171d)",
+ background: "#0a0b0e",
borderRadius: "var(--r-md)",
border: "1px solid var(--border)",
overflow: "hidden",
}}
>
+ {activeSource ? (
+ <video
+ ref={videoRef}
+ src={activeSource.src}
+ muted
+ playsInline
+ style={{
+ position: "absolute",
+ inset: 0,
+ width: "100%",
+ height: "100%",
+ objectFit: "contain",
+ background: "#000",
+ }}
+ />
+ ) : null}
<div
style={{
position: "absolute",
@@ -584,7 +720,41 @@ export function CropModal({ open, onClose, initialRegion, onApply }: CropModalPr
boxShadow: "0 0 0 9999px var(--overlay-dark)",
cursor: "move",
}}
- />
+ onPointerDown={startMove}
+ >
+ <div
+ onPointerDown={startResize({ left: true, top: true })}
+ style={handleStyle({ left: -5, top: -5, cursor: "nwse-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ right: true, top: true })}
+ style={handleStyle({ right: -5, top: -5, cursor: "nesw-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ left: true, bottom: true })}
+ style={handleStyle({ left: -5, bottom: -5, cursor: "nesw-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ right: true, bottom: true })}
+ style={handleStyle({ right: -5, bottom: -5, cursor: "nwse-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ top: true })}
+ style={handleStyle({ left: "50%", top: -5, marginLeft: -5, cursor: "ns-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ bottom: true })}
+ style={handleStyle({ left: "50%", bottom: -5, marginLeft: -5, cursor: "ns-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ left: true })}
+ style={handleStyle({ top: "50%", left: -5, marginTop: -5, cursor: "ew-resize" })}
+ />
+ <div
+ onPointerDown={startResize({ right: true })}
+ style={handleStyle({ top: "50%", right: -5, marginTop: -5, cursor: "ew-resize" })}
+ />
+ </div>
</div>
<div
style={{
diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.css
index 14fcf5747..8b017fd34 100644
--- a/src/components/ai-edition/NewEditorShell.module.css
+++ b/src/components/ai-edition/NewEditorShell.module.css
@@ -439,20 +439,20 @@
}
/* ─── preview area ─────────────────────────────────────────────── */
+/* ponytail: the stage wrapper (in NewEditorShell.tsx) already provides the
+ padding that reserves room for the floating inspector, and .stage paints the
+ scene gradient. previewWrap is a single transparent, zero-padding centering
+ layer so the wallpaper card floats on that gradient — matching the design's
+ stage-wrap (one framed card, no surface slab, no double padding). It is also
+ the positioned ancestor for the timecode/badge overlays and the box the
+ frame measures for its contain-fit. */
.previewWrap {
- display: grid;
- grid-template-rows: 1fr auto;
- background: var(--surface-1);
- min-width: 0;
- min-height: 0;
- position: relative;
-}
-.previewCanvas {
position: relative;
display: grid;
place-items: center;
- overflow: hidden;
- padding: var(--sp-5);
+ width: 100%;
+ height: 100%;
+ min-width: 0;
min-height: 0;
}
.previewFrame {
@@ -469,11 +469,16 @@
var(--scene-sky-mid) 35%,
var(--scene-foliage) 70%,
var(--scene-foliage-d) 100%);
- /* ponytail: don't make the canvas itself a rounded card — the video /
- camera apply their own border-radius for content clipping. A square
- canvas blends into the editor chrome; the wallpaper is the visible
- area, but no "frame around the canvas" effect. */
- border-radius: 0;
+ /* ponytail: the wallpaper card is a floating, rounded surface (per the v4
+ design's preview frame) — rounded corners + a layered drop shadow lift it
+ off the scene gradient. The custom background (buildFrameStyle) fills this
+ card; the video sits on top with its own padding so the wallpaper shows
+ around it. */
+ border-radius: 16px;
+ box-shadow:
+ 0 40px 90px -30px rgba(0, 0, 0, 0.75),
+ 0 12px 28px -12px rgba(0, 0, 0, 0.5),
+ inset 0 0 0 1px rgba(255, 255, 255, 0.09);
overflow: hidden;
display: grid;
place-items: center;
@@ -877,6 +882,7 @@
}
.paneBody {
overflow-y: auto;
+ overflow-x: hidden;
padding: 12px var(--sp-4);
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 43f01934a..6553d0db4 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -63,6 +63,12 @@ export function NewEditorShell() {
// column, and a floating facet inspector over the stage.
const [mode, setMode] = useState<EditorMode>("edit");
const [chatOpen, setChatOpen] = useState(true);
+ const [chatWidthPx, setChatWidthPx] = useState(
+ () => Number(localStorage.getItem("os-editor-chat-width")) || 392,
+ );
+ const [timelineHeightPx, setTimelineHeightPx] = useState(
+ () => Number(localStorage.getItem("os-editor-timeline-height")) || 308,
+ );
const [inspectorOpen, setInspectorOpen] = useState(true);
const [facet, setFacet] = useState<Facet>("effects");
const [openProjectOpen, setOpenProjectOpen] = useState(false);
@@ -260,7 +266,13 @@ export function NewEditorShell() {
if (!document) return [];
return document.assets.map((asset) => ({
id: asset.id,
- src: toFileUrl(asset.originalPath),
+ // Real Electron assets are filesystem paths and go through toFileUrl.
+ // In the browser preview an asset can already point at an http(s)/
+ // blob/data URL served by Vite; toFileUrl would mangle those into a
+ // broken file:// URL, so pass web URLs through untouched.
+ src: /^(https?|blob|data):/.test(asset.originalPath)
+ ? asset.originalPath
+ : toFileUrl(asset.originalPath),
label: asset.label,
}));
}, [document]);
@@ -491,11 +503,11 @@ export function NewEditorShell() {
// ponytail: transcript-pane → timeline skip ranges. The right pane's
// contentEditable region converts user Backspace/Delete into a new
- // skipRange (NOT a destructive word removal — the source text stays
+ // trimRange (NOT a destructive word removal — the source text stays
// intact, the word is just hidden by the skip overlay). Mirrors
- // axcut's `queueAddSkipRange` / `queueRemoveSkipRange` callbacks in
+ // axcut's `queueAddTrimRange` / `queueRemoveTrimRange` callbacks in
// apps/web/src/App.tsx.
- const handleAddSkipRange = useCallback(
+ const handleAddTrimRange = useCallback(
(assetId: string, startSec: number, endSec: number, reason: string) => {
// ponytail: read the latest document from the store, not the
// closure. The closure captures the document at render time; if
@@ -513,7 +525,7 @@ export function NewEditorShell() {
.then(() => import("@/lib/ai-edition/document/operations"))
.then(({ applyTimelineOperation }) =>
applyTimelineOperation(doc, {
- type: "add_skip_range",
+ type: "add_trim_range",
assetId,
startSec,
endSec,
@@ -530,16 +542,16 @@ export function NewEditorShell() {
[document, saveDocument],
);
- const handleRemoveSkipRange = useCallback(
- (skipId: string) => {
+ const handleRemoveTrimRange = useCallback(
+ (trimId: string) => {
const doc = useProjectStore.getState().document ?? document;
if (!doc) return;
const queued = saveQueueRef.current
.then(() => import("@/lib/ai-edition/document/operations"))
.then(({ applyTimelineOperation }) =>
applyTimelineOperation(doc, {
- type: "remove_skip_range",
- skipId,
+ type: "remove_trim_range",
+ trimId,
reason: "Restored from transcript pane.",
}),
)
@@ -715,7 +727,7 @@ export function NewEditorShell() {
);
if (region) {
copyRegion({
- kind: tl.selection.kind === "skip" ? "zoom" : tl.selection.kind,
+ kind: tl.selection.kind === "trim" ? "zoom" : tl.selection.kind,
region: region as Record<string, unknown>,
});
toast.success("Region copied");
@@ -863,7 +875,7 @@ export function NewEditorShell() {
}
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") {
+ if (tl.selection && tl.selection.kind !== "trim") {
e.preventDefault();
const cut = tl.selection;
void handleCopyRegion().then(() => tl.removeRegion(cut.kind, cut.id));
@@ -918,7 +930,7 @@ export function NewEditorShell() {
break;
case "t":
e.preventDefault();
- void tl.addSkip();
+ void tl.addTrim();
break;
case "a":
e.preventDefault();
@@ -944,19 +956,69 @@ export function NewEditorShell() {
]);
const showTimeline = mode !== "rec";
- const timelineRow = mode === "media" ? "188px" : "308px";
- const bodyColumns = mode === "edit" && chatOpen ? "392px 1fr" : "1fr";
+ const timelineRow = mode === "media" ? "188px" : `${timelineHeightPx}px`;
+ const bodyColumns = mode === "edit" && chatOpen ? `${chatWidthPx}px 1fr` : "1fr";
+
+ // Drag the chat/stage divider (col-resize) or the timeline's top edge
+ // (row-resize) to resize. Pointer-driven like V4Timeline's pill/nav/clip
+ // drags — pointerdown arms a window-level pointermove/pointerup pair, no
+ // drag library. Persisted to localStorage (a UI layout preference, not
+ // project content, so it doesn't belong in the document/useEditorSettings
+ // round-trip).
+ const startChatResize = useCallback(
+ (e: React.PointerEvent) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startWidth = chatWidthPx;
+ let latest = startWidth;
+ const move = (ev: PointerEvent) => {
+ latest = Math.min(560, Math.max(280, startWidth + (ev.clientX - startX)));
+ setChatWidthPx(latest);
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ localStorage.setItem("os-editor-chat-width", String(latest));
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ },
+ [chatWidthPx],
+ );
+
+ const startTimelineResize = useCallback(
+ (e: React.PointerEvent) => {
+ e.preventDefault();
+ const startY = e.clientY;
+ const startHeight = timelineHeightPx;
+ let latest = startHeight;
+ const move = (ev: PointerEvent) => {
+ // Dragging the handle up (negative clientY delta) enlarges the
+ // timeline, since it sits below the handle.
+ latest = Math.min(480, Math.max(160, startHeight - (ev.clientY - startY)));
+ setTimelineHeightPx(latest);
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ localStorage.setItem("os-editor-timeline-height", String(latest));
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ },
+ [timelineHeightPx],
+ );
const transcriptProps = {
clips,
transcripts: document?.transcripts ?? [],
assets: document?.assets ?? [],
- skipRanges: document?.timeline?.skipRanges ?? [],
+ trimRanges: document?.timeline?.trimRanges ?? [],
busy: isTranscribing,
currentTimeSec,
onSeek: handleSeek,
- onAddSkipRange: handleAddSkipRange,
- onRemoveSkipRange: handleRemoveSkipRange,
+ onAddTrimRange: handleAddTrimRange,
+ onRemoveTrimRange: handleRemoveTrimRange,
onTranscribe: handleTranscribe,
canTranscribe: hasAsset,
isTranscribing,
@@ -978,7 +1040,6 @@ export function NewEditorShell() {
openProject: () => setOpenProjectOpen(true),
newProject: () => setNewProjectOpen(true),
save: () => void handleSave(),
- newRecording: () => void handleNewRecording(),
export: handleExport,
openSettings: handleOpenSettings,
renameProject: handleRenameProject,
@@ -988,13 +1049,23 @@ export function NewEditorShell() {
<div className={v4.body} style={{ gridTemplateColumns: bodyColumns }}>
{mode === "edit" && chatOpen ? (
- <aside className={v4.agent} aria-label="AI editor">
- <LeftPanel
- active="chat"
- assetStatuses={assetStatuses}
- onRegenerateAsset={handleRegenerateAsset}
+ <>
+ <aside className={v4.agent} aria-label="AI editor">
+ <LeftPanel
+ active="chat"
+ assetStatuses={assetStatuses}
+ onRegenerateAsset={handleRegenerateAsset}
+ />
+ </aside>
+ <div
+ className={v4.chatResizeHandle}
+ style={{ left: chatWidthPx }}
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize chat panel"
+ onPointerDown={startChatResize}
/>
- </aside>
+ </>
) : null}
<section className={v4.stage} aria-label="Preview stage">
@@ -1004,13 +1075,13 @@ export function NewEditorShell() {
style={{
position: "absolute",
inset: 0,
- // ponytail: matches the design's stageWrapStyle
- // (`padding: 40px {inspectorOpen?'360px':'96px'} 110px 80px`)
- // — reserves room for the floating inspector on the
- // right (and transport at the bottom) so the video
- // resizes into the remaining space instead of sitting
- // underneath the panel.
- padding: `40px ${inspectorOpen ? 360 : 96}px 110px 80px`,
+ // Reserves room for the floating inspector on the right
+ // so the video resizes into the remaining space instead
+ // of sitting underneath the panel. The transport bar is
+ // a hover-reveal overlay (see .transportWrap) rather than
+ // permanent chrome, so it no longer reserves bottom space
+ // — the video is free to extend underneath it.
+ padding: `40px ${inspectorOpen ? 360 : 96}px 40px 80px`,
boxSizing: "border-box",
}}
>
@@ -1021,7 +1092,7 @@ export function NewEditorShell() {
clips={clips}
zoomRegions={tl.zoomRegions}
speedRegions={tl.speedRegions}
- skipRanges={tl.skipRanges}
+ trimRanges={tl.trimRanges}
selectedZoomRegionId={tl.selection?.kind === "zoom" ? tl.selection.id : null}
onZoomFocusChange={tl.updateZoomFocusLive}
onZoomFocusCommit={() => void tl.commitZoomFocus()}
@@ -1065,6 +1136,7 @@ export function NewEditorShell() {
<FloatingInspector
facet={facet}
open={inspectorOpen}
+ tl={tl}
onFacetChange={(f) => {
setFacet(f);
setInspectorOpen(true);
@@ -1078,7 +1150,10 @@ export function NewEditorShell() {
) : mode === "media" ? (
<MediaStage assetStatuses={assetStatuses} onRegenerateAsset={handleRegenerateAsset} />
) : (
- <RecStage onStartRecording={() => void handleNewRecording()} />
+ <RecStage
+ onStartRecording={() => void handleNewRecording()}
+ onClose={() => setMode("edit")}
+ />
)}
</section>
</div>
@@ -1087,12 +1162,22 @@ export function NewEditorShell() {
{showTimeline ? (
<div
style={{
+ position: "relative",
gridRow: 3,
minHeight: 0,
background: "var(--surface)",
borderTop: "1px solid var(--border)",
}}
>
+ {mode !== "media" ? (
+ <div
+ className={v4.timelineResizeHandle}
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label="Resize timeline"
+ onPointerDown={startTimelineResize}
+ />
+ ) : null}
<V4Timeline
tl={tl}
currentTimeSec={currentTimeSec}
@@ -1125,6 +1210,8 @@ export function NewEditorShell() {
onClose={() => setCropOpen(false)}
initialRegion={editorSettings.cropRegion}
onApply={(region: CropRegion) => void setEditorSettings({ cropRegion: region })}
+ videoSources={videoSources}
+ currentTimeSec={currentTimeSec}
/>
<UnsavedChangesModal
open={unsavedPrompt !== null}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index 34a9d0183..4e68d1ac6 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -3,7 +3,7 @@ import type { ZoomFocus } from "@/components/video-editor/types";
import type {
AxcutAnnotationRegion,
AxcutClip,
- AxcutSkipRange,
+ AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
@@ -21,7 +21,7 @@ interface PreviewProps {
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
- skipRanges?: AxcutSkipRange[];
+ trimRanges?: AxcutTrimRange[];
selectedZoomRegionId?: string | null;
onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;
onZoomFocusCommit?: () => void;
@@ -59,7 +59,7 @@ export function Preview({
clips,
zoomRegions,
speedRegions,
- skipRanges,
+ trimRanges,
selectedZoomRegionId,
onZoomFocusChange,
onZoomFocusCommit,
@@ -103,44 +103,42 @@ export function Preview({
data-current-time-sec={currentTimeSec.toFixed(3)}
data-is-playing={playing ? "true" : "false"}
>
- <div className={styles.previewCanvas}>
- {hasProject && hasAsset && !videoError ? (
- <PreviewCanvas
- videoSources={videoSources}
- clips={clips}
- zoomRegions={zoomRegions}
- speedRegions={speedRegions}
- skipRanges={skipRanges}
- selectedZoomRegionId={selectedZoomRegionId}
- onZoomFocusChange={onZoomFocusChange}
- onZoomFocusCommit={onZoomFocusCommit}
- annotationRegions={annotationRegions}
- selectedAnnotationId={selectedAnnotationId}
- onSelectAnnotation={onSelectAnnotation}
- onAnnotationPositionChange={onAnnotationPositionChange}
- onAnnotationSizeChange={onAnnotationSizeChange}
- onAnnotationBlurDataChange={onAnnotationBlurDataChange}
- onAnnotationCommit={onAnnotationCommit}
- seekTarget={seekTarget}
- onTimeChange={onTimeChange}
- onSeek={onSeek}
- onLoadedMetadata={onLoadedMetadata}
- onVideoElement={onVideoElement}
- currentTimeSec={currentTimeSec}
- onVideoError={() => setVideoError(true)}
- />
- ) : (
- <EditorEmptyState hasProject={hasProject} />
- )}
- {hasProject && hasAsset ? (
- <span className={styles.previewTimecode}>{formatTC(currentTimeSec)}</span>
- ) : null}
- {hasProject && hasAsset ? (
- <span className={styles.previewBadge}>
- {editorSettings.cursorShow ? "Cursor on" : "Cursor off"} · {aspectRatioLabel} · 60 fps
- </span>
- ) : null}
- </div>
+ {hasProject && hasAsset && !videoError ? (
+ <PreviewCanvas
+ videoSources={videoSources}
+ clips={clips}
+ zoomRegions={zoomRegions}
+ speedRegions={speedRegions}
+ trimRanges={trimRanges}
+ selectedZoomRegionId={selectedZoomRegionId}
+ onZoomFocusChange={onZoomFocusChange}
+ onZoomFocusCommit={onZoomFocusCommit}
+ annotationRegions={annotationRegions}
+ selectedAnnotationId={selectedAnnotationId}
+ onSelectAnnotation={onSelectAnnotation}
+ onAnnotationPositionChange={onAnnotationPositionChange}
+ onAnnotationSizeChange={onAnnotationSizeChange}
+ onAnnotationBlurDataChange={onAnnotationBlurDataChange}
+ onAnnotationCommit={onAnnotationCommit}
+ seekTarget={seekTarget}
+ onTimeChange={onTimeChange}
+ onSeek={onSeek}
+ onLoadedMetadata={onLoadedMetadata}
+ onVideoElement={onVideoElement}
+ currentTimeSec={currentTimeSec}
+ onVideoError={() => setVideoError(true)}
+ />
+ ) : (
+ <EditorEmptyState hasProject={hasProject} />
+ )}
+ {hasProject && hasAsset ? (
+ <span className={styles.previewTimecode}>{formatTC(currentTimeSec)}</span>
+ ) : null}
+ {hasProject && hasAsset ? (
+ <span className={styles.previewBadge}>
+ {editorSettings.cursorShow ? "Cursor on" : "Cursor off"} · {aspectRatioLabel} · 60 fps
+ </span>
+ ) : null}
</section>
);
}
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 58b930d73..c130753a6 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -32,7 +32,7 @@ import type {
import type {
AxcutAnnotationRegion,
AxcutClip,
- AxcutSkipRange,
+ AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
@@ -45,6 +45,7 @@ import {
getWebcamLayoutCssBoxShadow,
type WebcamCompositeLayout,
} from "@/lib/compositeLayout";
+import { classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
import { getAspectRatioValue } from "@/utils/aspectRatioUtils";
import { AnnotationLayer } from "./AnnotationLayer";
@@ -60,7 +61,7 @@ interface PreviewCanvasProps {
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
- skipRanges?: AxcutSkipRange[];
+ trimRanges?: AxcutTrimRange[];
selectedZoomRegionId?: string | null;
onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;
onZoomFocusCommit?: () => void;
@@ -109,12 +110,12 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
useEffect(() => {
const el = frameRef.current?.parentElement;
if (!el) return;
- // ponytail: clientWidth/clientHeight include the container's padding
- // (.previewCanvas has var(--sp-5) on all sides). Sizing the frame to
- // that full padded box, then centering it in the smaller content-box
- // grid track, pushed it past the padding edge on every axis —
- // overflow:hidden then clipped the video instead of letting it fit.
- // Subtracting the computed padding gives the actual content box.
+ // ponytail: measure the parent's content box, not its border box —
+ // clientWidth/clientHeight include any padding, and sizing the frame to
+ // the full padded box while it's centered in the smaller content area
+ // pushed it past the padding edge, where overflow:hidden clipped the
+ // video. The parent (.previewWrap) is currently zero-padding, but
+ // subtracting computed padding keeps this correct if that ever changes.
const update = () => {
const cs = getComputedStyle(el);
const paddingX = Number.parseFloat(cs.paddingLeft) + Number.parseFloat(cs.paddingRight);
@@ -353,30 +354,35 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
);
}
+// ponytail: resolve `settings.wallpaper` to an actual CSS background. Image
+// wallpapers must go through resolveImageWallpaperUrl (→ getAssetPath): in the
+// packaged Electron app the renderer loads over file://, where a bare
+// `/wallpapers/foo.jpg` points at the filesystem root and 404s, so the custom
+// background silently failed to paint (worked in the http dev server only).
+// classifyWallpaper also handles color-function (rgb/hsl/…) and every gradient
+// variant, which the old ad-hoc startsWith checks missed.
+function resolveWallpaperImageUrl(imagePath: string): string | null {
+ try {
+ return resolveImageWallpaperUrl(imagePath);
+ } catch {
+ return null;
+ }
+}
+
// Canvas: wallpaper only — no padding, no shadow.
function buildFrameStyle(
settings: ReturnType<typeof useEditorSettings>["settings"],
): React.CSSProperties {
- const wallpaper = settings.wallpaper;
- const isImageWallpaper = wallpaper.startsWith("/wallpapers/") || wallpaper.startsWith("data:");
- const isColor = wallpaper.startsWith("#");
- const isGradient =
- wallpaper.startsWith("linear-") ||
- wallpaper.startsWith("radial-") ||
- wallpaper.startsWith("conic-");
-
- if (isImageWallpaper) {
- return {
- backgroundImage: `url(${wallpaper})`,
- backgroundSize: "cover",
- backgroundPosition: "center",
- backgroundRepeat: "no-repeat",
- };
- }
- if (isColor) return { backgroundColor: wallpaper };
+ const w = classifyWallpaper(settings.wallpaper);
+ if (w.kind === "color") return { backgroundColor: w.value };
+ if (w.kind === "gradient") return { backgroundImage: w.value, backgroundSize: "cover" };
+ const url = resolveWallpaperImageUrl(w.path);
+ if (!url) return {};
return {
- backgroundImage: isGradient ? wallpaper : undefined,
+ backgroundImage: `url(${url})`,
backgroundSize: "cover",
+ backgroundPosition: "center",
+ backgroundRepeat: "no-repeat",
};
}
@@ -449,39 +455,22 @@ function buildBlurStyle(
settings: ReturnType<typeof useEditorSettings>["settings"],
): React.CSSProperties {
if (!settings.showBlur) return { display: "none" };
- const wallpaper = settings.wallpaper;
- const isImageWallpaper = wallpaper.startsWith("/wallpapers/") || wallpaper.startsWith("data:");
- const isColor = wallpaper.startsWith("#");
- const isGradient =
- wallpaper.startsWith("linear-") ||
- wallpaper.startsWith("radial-") ||
- wallpaper.startsWith("conic-");
-
- if (isImageWallpaper) {
- return {
- backgroundImage: `url(${wallpaper})`,
- backgroundSize: "cover",
- backgroundPosition: "center",
- filter: "blur(28px)",
- opacity: 1,
- };
- }
- if (isColor) {
- return {
- backgroundColor: wallpaper,
- filter: "blur(28px)",
- opacity: 1,
- };
+ const w = classifyWallpaper(settings.wallpaper);
+ if (w.kind === "color") {
+ return { backgroundColor: w.value, filter: "blur(28px)", opacity: 1 };
}
- if (isGradient) {
- return {
- background: wallpaper,
- backgroundSize: "cover",
- filter: "blur(28px)",
- opacity: 1,
- };
+ if (w.kind === "gradient") {
+ return { background: w.value, backgroundSize: "cover", filter: "blur(28px)", opacity: 1 };
}
- return { display: "none" };
+ const url = resolveWallpaperImageUrl(w.path);
+ if (!url) return { display: "none" };
+ return {
+ backgroundImage: `url(${url})`,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ filter: "blur(28px)",
+ opacity: 1,
+ };
}
function clamp(v: number, min: number, max: number): number {
diff --git a/src/components/ai-edition/RegionTimeline.tsx b/src/components/ai-edition/RegionTimeline.tsx
index 2fe63f996..e9283e101 100644
--- a/src/components/ai-edition/RegionTimeline.tsx
+++ b/src/components/ai-edition/RegionTimeline.tsx
@@ -259,7 +259,7 @@ interface RegionItemProps {
selected: boolean;
/** F2.7 — `additive` is true on shift-click (adds to the multi-selection). */
onSelect: (additive: boolean) => void;
- variant: "zoom" | "annotation" | "speed" | "skip";
+ variant: "zoom" | "annotation" | "speed" | "trim";
}
export function RegionItem({
@@ -282,8 +282,8 @@ export function RegionItem({
? styles.zoomPill
: variant === "speed"
? styles.speedPill
- : variant === "skip"
- ? styles.skipPill
+ : variant === "trim"
+ ? styles.trimPill
: styles.annotationPill;
return (
<div
diff --git a/src/components/ai-edition/RightPanelStack.tsx b/src/components/ai-edition/RightPanelStack.tsx
index 63e19440a..ebcdd2219 100644
--- a/src/components/ai-edition/RightPanelStack.tsx
+++ b/src/components/ai-edition/RightPanelStack.tsx
@@ -23,8 +23,8 @@ import type {
AxcutAsset,
AxcutClip,
AxcutDocument,
- AxcutSkipRange,
AxcutTranscript,
+ AxcutTrimRange,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import styles from "./NewEditorShell.module.css";
@@ -38,7 +38,7 @@ import {
VideoEffectsPane,
} from "./RightPanes";
-type RegionKind = "zoom" | "skip" | "annotation" | "speed";
+type RegionKind = "zoom" | "trim" | "annotation" | "speed";
interface RegionHandle {
kind: RegionKind;
@@ -52,12 +52,12 @@ interface RightPanelStackProps {
transcripts: AxcutTranscript[];
assets: AxcutAsset[];
clips: AxcutClip[];
- skipRanges: AxcutSkipRange[];
+ trimRanges: AxcutTrimRange[];
busy: boolean;
currentTimeSec: number;
onSeek: (sec: number) => void;
- onAddSkipRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
- onRemoveSkipRange: (skipId: string) => void;
+ onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onRemoveTrimRange: (trimId: string) => void;
onTranscribe: () => void;
canTranscribe: boolean;
isTranscribing: boolean;
@@ -86,12 +86,12 @@ export function RightPanelStack({
transcripts,
assets,
clips,
- skipRanges,
+ trimRanges,
busy,
currentTimeSec,
onSeek,
- onAddSkipRange,
- onRemoveSkipRange,
+ onAddTrimRange,
+ onRemoveTrimRange,
onTranscribe,
canTranscribe,
isTranscribing,
@@ -122,12 +122,12 @@ export function RightPanelStack({
transcripts={transcripts}
assets={assets}
clips={clips}
- skipRanges={skipRanges}
+ trimRanges={trimRanges}
busy={busy}
currentTimeSec={currentTimeSec}
onSeek={onSeek}
- onAddSkipRange={onAddSkipRange}
- onRemoveSkipRange={onRemoveSkipRange}
+ onAddTrimRange={onAddTrimRange}
+ onRemoveTrimRange={onRemoveTrimRange}
onTranscribe={onTranscribe}
canTranscribe={canTranscribe}
isTranscribing={isTranscribing}
@@ -609,7 +609,7 @@ function RegionInspector({
) : null}
</>
) : null
- ) : selection.kind === "skip" ? (
+ ) : selection.kind === "trim" ? (
<div
style={{ font: "500 12px var(--font-body)", color: "var(--muted)", padding: "0 4px" }}
>
@@ -715,7 +715,7 @@ function kindLabel(kind: RegionKind): string {
switch (kind) {
case "zoom":
return "Zoom region";
- case "skip":
+ case "trim":
return "Trim region";
case "annotation":
return "Annotation";
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 3edc761e7..7233fe2b4 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -33,8 +33,8 @@ import defaultCursorPreviewUrl from "@/assets/cursors/Cursor=Default.svg";
import type {
AxcutAsset,
AxcutClip,
- AxcutSkipRange,
AxcutTranscript,
+ AxcutTrimRange,
AxcutWord,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
@@ -44,7 +44,7 @@ import {
type ClipSection,
type ClipWord,
findCueWordId,
- type SkipRun,
+ type TrimRun,
} from "@/lib/ai-edition/timeline/aggregated-transcript";
import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatMs } from "@/lib/ai-edition/timeline/format";
@@ -409,14 +409,14 @@ function normaliseHex(raw: string): string | null {
// ─── Transcript ────────────────────────────────────────────────────
// Aggregated transcript view: one contentEditable region per clip on the
// timeline, in timeline order. Each word is rendered as a `<span
-// data-word-id>` inside the editable div. Words inside any `skipRange`
+// data-word-id>` inside the editable div. Words inside any `trimRange`
// for the clip's asset are styled red+strikethrough and show a bin icon
// on hover (removing the skip restores them). User actions:
//
// - Click on a word → seek (timeline.playhead)
// - Backspace / Delete → convert selection (or caret-adjacent word)
-// into a new skipRange (the document's
-// `timeline.skipRanges[]`, NOT the transcript
+// into a new trimRange (the document's
+// `timeline.trimRanges[]`, NOT the transcript
// text). The deleted word stays in the DOM as
// red text — nothing destructive.
//
@@ -425,12 +425,12 @@ export function TranscriptPane({
clips,
transcripts,
assets,
- skipRanges,
+ trimRanges,
busy,
currentTimeSec,
onSeek,
- onAddSkipRange,
- onRemoveSkipRange,
+ onAddTrimRange,
+ onRemoveTrimRange,
onTranscribe,
canTranscribe,
isTranscribing,
@@ -438,19 +438,19 @@ export function TranscriptPane({
clips: AxcutClip[];
transcripts: AxcutTranscript[];
assets: AxcutAsset[];
- skipRanges: AxcutSkipRange[];
+ trimRanges: AxcutTrimRange[];
busy: boolean;
currentTimeSec: number;
onSeek: (sec: number) => void;
- onAddSkipRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
- onRemoveSkipRange: (skipId: string) => void;
+ onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onRemoveTrimRange: (trimId: string) => void;
onTranscribe: () => void;
canTranscribe: boolean;
isTranscribing: boolean;
}) {
const sections = useMemo(
- () => buildAggregatedSections(clips, transcripts, assets, skipRanges),
- [clips, transcripts, assets, skipRanges],
+ () => buildAggregatedSections(clips, transcripts, assets, trimRanges),
+ [clips, transcripts, assets, trimRanges],
);
// ponytail: the cue position is the playback head's location in the
@@ -525,8 +525,8 @@ export function TranscriptPane({
busy={busy}
cueWordId={cueWordId}
onSeek={onSeek}
- onAddSkipRange={onAddSkipRange}
- onRemoveSkipRange={onRemoveSkipRange}
+ onAddTrimRange={onAddTrimRange}
+ onRemoveTrimRange={onRemoveTrimRange}
/>
))}
</div>
@@ -537,24 +537,24 @@ export function TranscriptPane({
// One contentEditable block per clip — header (vignette + filename +
// range) and a flowing word stream. The stream contains every transcript
// word inside the clip's source range, color-coded by whether the word
-// is inside any skipRange. Backspace/Delete adds a new skipRange via
-// onAddSkipRange; hover-bin on a skip run removes it via onRemoveSkipRange.
+// is inside any trimRange. Backspace/Delete adds a new trimRange via
+// onAddTrimRange; hover-bin on a skip run removes it via onRemoveTrimRange.
function TranscriptClipBlock({
index,
section,
busy,
cueWordId,
onSeek,
- onAddSkipRange,
- onRemoveSkipRange,
+ onAddTrimRange,
+ onRemoveTrimRange,
}: {
index: number;
section: ClipSection;
busy: boolean;
cueWordId: string | null;
onSeek: (sec: number) => void;
- onAddSkipRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
- onRemoveSkipRange: (skipId: string) => void;
+ onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onRemoveTrimRange: (trimId: string) => void;
}) {
const { clip, asset, words } = section;
const filename = asset?.label ?? clip.assetId;
@@ -605,7 +605,7 @@ function TranscriptClipBlock({
}, [cueWordId]);
// ponytail: keep the caret anchored to the next kept word after a
- // skipRange is added (so the user can keep deleting without the caret
+ // trimRange is added (so the user can keep deleting without the caret
// jumping to the start of the block).
useLayoutEffect(() => {
const wordId = pendingCaretWordIdRef.current;
@@ -623,22 +623,22 @@ function TranscriptClipBlock({
pendingCaretWordIdRef.current = keptRange[0].word.id;
const startSec = Math.min(...keptRange.map((w) => w.word.startSec));
const endSec = Math.max(...keptRange.map((w) => w.word.endSec));
- onAddSkipRange(
+ onAddTrimRange(
clip.assetId,
startSec,
endSec,
`Skip ${formatMs(startSec * 1000)}-${formatMs(endSec * 1000)} from ${clip.assetId}.`,
);
},
- [busy, clip.assetId, onAddSkipRange],
+ [busy, clip.assetId, onAddTrimRange],
);
- const removeSkipRun = useCallback(
- (run: SkipRun) => {
- if (busy || !run.skipId) return;
- onRemoveSkipRange(run.skipId);
+ const removeTrimRun = useCallback(
+ (run: TrimRun) => {
+ if (busy || !run.trimId) return;
+ onRemoveTrimRange(run.trimId);
},
- [busy, onRemoveSkipRange],
+ [busy, onRemoveTrimRange],
);
const cutNativeSelection = useCallback(
@@ -853,7 +853,7 @@ function TranscriptClipBlock({
key={cw.word.id}
cw={cw}
isCue={cw.word.id === cueWordId}
- onRestore={removeSkipRun}
+ onRestore={removeTrimRun}
/>
))}
</div>
@@ -873,7 +873,7 @@ function TranscriptWord({
}: {
cw: ClipWord;
isCue: boolean;
- onRestore: (run: SkipRun) => void;
+ onRestore: (run: TrimRun) => void;
}) {
const [hover, setHover] = useState(false);
const removed = !cw.kept;
@@ -882,7 +882,7 @@ function TranscriptWord({
data-word-id={cw.word.id}
data-start-sec={cw.word.startSec}
data-end-sec={cw.word.endSec}
- data-skip-id={cw.skipId ?? undefined}
+ data-skip-id={cw.trimId ?? undefined}
data-cue={isCue ? "true" : undefined}
style={{
display: "inline",
@@ -901,7 +901,7 @@ function TranscriptWord({
the LLM is the only place that names a word a filler (via the
filler_or_hesitation reason when generating suggestions). */}
{cw.word.text}{" "}
- {removed && hover && cw.skipId ? (
+ {removed && hover && cw.trimId ? (
<button
type="button"
contentEditable={false}
@@ -909,10 +909,10 @@ function TranscriptWord({
aria-label={`Restore "${cw.word.text}"`}
onClick={(e) => {
e.stopPropagation();
- // ponytail: build a minimal SkipRun stub — only skipId is
+ // ponytail: build a minimal TrimRun stub — only trimId is
// read by onRestore.
onRestore({
- skipId: cw.skipId ?? "",
+ trimId: cw.trimId ?? "",
assetId: "",
startWordIndex: 0,
endWordIndex: 0,
@@ -961,7 +961,7 @@ function findCollapsedDeletionWordId(
): string | null {
// ponytail: read the kept/skip state from the words array, not the
// DOM's data-skip-id. The DOM may be lagging a render behind (its
- // skipId is only set on the next React commit), so a DOM check would
+ // trimId is only set on the next React commit), so a DOM check would
// re-trim an already-trimmed word. The words array is the React state
// captured at the call site — always current.
const skippedIds = new Set(words.filter((w) => !w.kept).map((w) => w.word.id));
diff --git a/src/components/ai-edition/TimelinePane.tsx b/src/components/ai-edition/TimelinePane.tsx
index 79632e341..cad9d202d 100644
--- a/src/components/ai-edition/TimelinePane.tsx
+++ b/src/components/ai-edition/TimelinePane.tsx
@@ -42,7 +42,7 @@ interface AssetMeta {
durationSec?: number;
}
-interface SkipRange {
+interface TrimRange {
id: string;
assetId: string;
startSec: number;
@@ -72,14 +72,14 @@ interface SpeedRegion {
}
interface RegionSelection {
- kind: "zoom" | "skip" | "annotation" | "speed";
+ kind: "zoom" | "trim" | "annotation" | "speed";
id: string;
}
interface TimelinePaneProps {
clips: AxcutClip[];
assets: AssetMeta[];
- skipRanges: SkipRange[];
+ trimRanges: TrimRange[];
zoomRegions: ZoomRegion[];
annotationRegions: AnnotationRegion[];
speedRegions: SpeedRegion[];
@@ -96,10 +96,10 @@ interface TimelinePaneProps {
onEditClip: (clip: AxcutClip) => void;
onRemoveClip: (clipId: string) => void;
// T15 — Place-skip callback. Bottombar wires this to
- // tl.addSkipAt(assetId, sourceStartSec, sourceEndSec) so the timeline
+ // tl.addTrimAt(assetId, sourceStartSec, sourceEndSec) so the timeline
// pane can add a skip at the cursor's source position without jumping
- // the playhead (which onAddSkip / onAddSkipRange can't do).
- onAddSkip?: (assetId: string, sourceStartSec: number, sourceEndSec: number) => void;
+ // the playhead (which onAddTrim / onAddTrimRange can't do).
+ onAddTrim?: (assetId: string, sourceStartSec: number, sourceEndSec: number) => void;
// T10 — dnd-timeline drag/resize dispatch. Bottombar wires this to the
// per-kind updaters (updateZoomSpan / updateAnnotationSpan / etc).
onRegionSpanChange: (id: string, span: Span) => void;
@@ -120,7 +120,7 @@ interface TimelinePaneProps {
pendingCutPreviewSec: number | null;
setPendingCutPreviewSec: (next: number | null) => void;
// T15 — disarms the place-skip mode after a successful click.
- onCancelPlaceSkip: () => void;
+ onCancelPlaceTrim: () => void;
}
// T07 — Pan via Alt+drag or middle-click-drag. Refs only; no state needed
@@ -193,7 +193,7 @@ function buildRulerTicks(durationSec: number, pxPerSec: number): RulerTick[] {
export function TimelinePane({
clips,
assets,
- skipRanges,
+ trimRanges,
zoomRegions,
annotationRegions,
speedRegions,
@@ -211,13 +211,13 @@ export function TimelinePane({
pendingCutPlacement,
pendingCutPreviewSec,
setPendingCutPreviewSec,
- onCancelPlaceSkip,
+ onCancelPlaceTrim,
onSeek,
onInsertAsset,
onMoveClip,
onEditClip,
onRemoveClip,
- onAddSkip,
+ onAddTrim,
onRegionSpanChange,
}: TimelinePaneProps) {
const viewportRef = useRef<HTMLDivElement | null>(null);
@@ -284,9 +284,9 @@ export function TimelinePane({
// skip's source-time span through whichever clip it falls within to
// get a timeline(ms) span for the lane — same coordinate space the
// zoom/speed/annotation lanes already use.
- const skipRegionSpans = useMemo(() => {
+ const trimRegionSpans = useMemo(() => {
const spans: Array<{ id: string; start: number; end: number; durationSec: number }> = [];
- for (const skip of skipRanges) {
+ for (const skip of trimRanges) {
const startPos = locateSourcePosition(orderedClips, skip.startSec, skip.assetId);
const endPos = locateSourcePosition(orderedClips, skip.endSec, skip.assetId);
if (!startPos || !endPos) continue;
@@ -298,7 +298,7 @@ export function TimelinePane({
});
}
return spans;
- }, [skipRanges, orderedClips]);
+ }, [trimRanges, orderedClips]);
useEffect(() => {
const el = viewportRef.current;
@@ -369,7 +369,7 @@ export function TimelinePane({
// addCut helper.
const addCut = useCallback(
(centerSec: number) => {
- if (orderedClips.length === 0 || !onAddSkip) return;
+ if (orderedClips.length === 0 || !onAddTrim) return;
const position = locateVirtualPosition(orderedClips, centerSec);
if (!position) return;
const clip = position.clip;
@@ -380,9 +380,9 @@ export function TimelinePane({
Math.max(clip.sourceStartSec, clipEnd - 0.1),
);
const sourceEndSec = clamp(position.sourceTimeSec + 0.5, sourceStartSec + 0.1, clipEnd);
- onAddSkip(clip.assetId, sourceStartSec, sourceEndSec);
+ onAddTrim(clip.assetId, sourceStartSec, sourceEndSec);
},
- [orderedClips, onAddSkip],
+ [orderedClips, onAddTrim],
);
// Convert screen-x (PointerEvent.clientX) to source-time, accounting for
@@ -621,7 +621,7 @@ export function TimelinePane({
event.stopPropagation();
addCut(sourceSecFromClientX(event.clientX));
setPendingCutPreviewSec(null);
- onCancelPlaceSkip();
+ onCancelPlaceTrim();
return;
}
if (event.altKey || event.button === 1) {
@@ -635,7 +635,7 @@ export function TimelinePane({
addCut,
sourceSecFromClientX,
setPendingCutPreviewSec,
- onCancelPlaceSkip,
+ onCancelPlaceTrim,
startPan,
startScrub,
],
@@ -813,7 +813,7 @@ export function TimelinePane({
className={styles.pane}
data-testid="timeline-pane"
data-clip-count={orderedClips.length}
- data-skip-count={skipRanges.length}
+ data-skip-count={trimRanges.length}
data-zoom-range-count={zoomRegions.length}
data-annotation-count={annotationRegions.length}
data-current-time-sec={currentTimeSec.toFixed(3)}
@@ -923,9 +923,9 @@ export function TimelinePane({
start: s.startMs,
end: s.endMs,
})),
- ...skipRegionSpans.map((s) => ({
+ ...trimRegionSpans.map((s) => ({
id: s.id,
- rowId: "skip",
+ rowId: "trim",
start: s.start,
end: s.end,
})),
@@ -963,18 +963,18 @@ export function TimelinePane({
/>
))}
</RegionRow>
- <RegionRow id="skip" empty="No skips">
- {skipRegionSpans.map((s) => (
+ <RegionRow id="trim" empty="No skips">
+ {trimRegionSpans.map((s) => (
<RegionItem
key={s.id}
id={s.id}
- rowId="skip"
+ rowId="trim"
span={{ start: s.start, end: s.end }}
label={formatSeconds(s.durationSec)}
icon={<Scissors size={11} strokeWidth={2} aria-hidden="true" />}
- selected={isRegionSelected("skip", s.id)}
- onSelect={(additive) => onSelectRegion("skip", s.id, additive)}
- variant="skip"
+ selected={isRegionSelected("trim", s.id)}
+ onSelect={(additive) => onSelectRegion("trim", s.id, additive)}
+ variant="trim"
/>
))}
</RegionRow>
@@ -1140,7 +1140,7 @@ export function TimelinePane({
</span>
<span className={styles.headerDivider}>·</span>
<span className={styles.headerStat}>
- {skipRanges.length} skip{skipRanges.length === 1 ? "" : "s"}
+ {trimRanges.length} skip{trimRanges.length === 1 ? "" : "s"}
</span>
<span className={styles.headerDivider}>·</span>
<span className={styles.headerStat}>{formatSeconds(virtualDurationSec)} total</span>
@@ -1164,7 +1164,7 @@ export function TimelinePane({
direct access to setVisibleWindow (the navigator needs the
usable-width to recompute pxPerSec on handle drag). */}
<Navigator
- skipRanges={skipRanges}
+ trimRanges={trimRanges}
sourceDurationSec={sourceDuration}
visibleStartSec={visibleStartSec}
visibleEndSec={visibleStartSec + visibleDurationSec}
@@ -1177,7 +1177,7 @@ export function TimelinePane({
// T11/T12 — Navigator subcomponent. Self-contained; uses
// NewEditorShell.module.css styles via the parent's CSS module import.
interface NavigatorProps {
- skipRanges: SkipRange[];
+ trimRanges: TrimRange[];
sourceDurationSec: number;
visibleStartSec: number;
visibleEndSec: number;
@@ -1187,7 +1187,7 @@ interface NavigatorProps {
type NavigatorDragMode = "move" | "start" | "end";
function Navigator({
- skipRanges,
+ trimRanges,
sourceDurationSec,
visibleStartSec,
visibleEndSec,
@@ -1282,7 +1282,7 @@ function Navigator({
aria-label="Timeline zoom and pan navigator"
>
<div className={styles.timelineNavigatorContent}>
- {skipRanges.map((skip) => (
+ {trimRanges.map((skip) => (
<span
key={skip.id}
className={styles.timelineNavigatorSkip}
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 44a273d04..756d20b47 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fromFileUrl } from "@/components/video-editor/projectPersistence";
-import type { AxcutClip, AxcutSkipRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
+import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
@@ -28,7 +28,7 @@ interface VirtualPreviewProps {
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
- skipRanges?: AxcutSkipRange[];
+ trimRanges?: AxcutTrimRange[];
seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;
onTimeChange?: (timeSec: number) => void;
onLoadedMetadata?: (durationSec: number, assetId: string) => void;
@@ -48,7 +48,7 @@ export function VirtualPreview({
clips,
zoomRegions = [],
speedRegions = [],
- skipRanges = [],
+ trimRanges = [],
seekTarget,
onTimeChange,
onLoadedMetadata,
@@ -107,8 +107,8 @@ export function VirtualPreview({
virtualDurationSecRef.current = virtualDurationSec;
const speedRegionsRef = useRef(speedRegions);
speedRegionsRef.current = speedRegions;
- const skipRangesRef = useRef(skipRanges);
- skipRangesRef.current = skipRanges;
+ const trimRangesRef = useRef(trimRanges);
+ trimRangesRef.current = trimRanges;
// biome-ignore lint/correctness/useExhaustiveDependencies: re-create the rAF when the active source swaps.
useEffect(() => {
let raf = 0;
@@ -128,30 +128,30 @@ export function VirtualPreview({
clockRef.current.virtualTimeSec = virtualTimeSecRef.current;
}
const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;
- // Skip regions only skip ahead during actual playback — mirrors
+ // Trim regions only trim ahead during actual playback — mirrors
// main's videoEventHandlers.ts (findActiveTrimRegion + jump to
// endMs, gated on `!video.paused`). Scrubbing/paused seeks are
// intentionally NOT clamped: the user can navigate freely inside
- // a skip while editing; only Play/export treats it as a cut.
+ // a trim while editing; only Play/export treats it as a cut.
if (!v.paused) {
- const activeSkip = skipRangesRef.current.find(
- (skip) =>
- skip.assetId === activeSourceId &&
- v.currentTime >= skip.startSec &&
- v.currentTime < skip.endSec,
+ const activeTrim = trimRangesRef.current.find(
+ (trim) =>
+ trim.assetId === activeSourceId &&
+ v.currentTime >= trim.startSec &&
+ v.currentTime < trim.endSec,
);
- if (activeSkip) {
- if (activeSkip.endSec >= (v.duration || Infinity)) {
+ if (activeTrim) {
+ if (activeTrim.endSec >= (v.duration || Infinity)) {
v.pause();
} else {
// ponytail: seeking to exactly `endSec` can land the decoder a
// hair before it (frame/sample quantization), which still
- // satisfies `currentTime < skip.endSec` — the next tick
+ // satisfies `currentTime < trim.endSec` — the next tick
// re-seeks to the same spot, forever, so playback never
- // actually progresses past the skip (looked like a hard
+ // actually progresses past the trim (looked like a hard
// stop instead of an invisible cut). A small epsilon past
// the boundary guarantees each re-check reads past it.
- v.currentTime = activeSkip.endSec + 0.05;
+ v.currentTime = activeTrim.endSec + 0.05;
}
return;
}
@@ -209,13 +209,14 @@ export function VirtualPreview({
};
raf = window.requestAnimationFrame(tick);
return () => window.cancelAnimationFrame(raf);
- // re-create the rAF when the active source swaps
- }, [activeSource?.src]);
+ // re-create the rAF when the active source swaps (by asset id, not src —
+ // two clips can point at distinct assets that resolve to the same URL).
+ }, [activeSource?.id]);
// report the video element up; re-notify (and clear) whenever the active
// source changes so the parent doesn't keep a stale node after the keyed
// <video> is swapped for a new asset.
- const activeSourceKey = activeSource?.src ?? null;
+ const activeSourceKey = activeSource?.id ?? null;
// biome-ignore lint/correctness/useExhaustiveDependencies: re-run on source swap
useEffect(() => {
onVideoElement?.(videoRef.current);
@@ -277,7 +278,11 @@ export function VirtualPreview({
const targetIndex = videoSources.findIndex((vs) => vs.id === position.clip.assetId);
const isAssetSwitch = targetIndex >= 0 && targetIndex !== sourceIndex;
- const shouldContinuePlayback = preservePlayback && isPlaying;
+ // Read the live paused state, not the captured `isPlaying` prop: the rAF
+ // clip-end auto-advance calls a `seekToVirtualTime` closure captured when
+ // the rAF was created (before playback started), so the captured
+ // `isPlaying` is stale-false and the cross-asset resume never fired.
+ const shouldContinuePlayback = preservePlayback && !videoRef.current?.paused;
if (isAssetSwitch) {
setSourceIndex(targetIndex);
@@ -302,7 +307,7 @@ export function VirtualPreview({
void video.play().catch(() => setIsPlaying(false));
}
},
- [clips, videoSources, sourceIndex, isPlaying, updateVirtualTime],
+ [clips, videoSources, sourceIndex, updateVirtualTime],
);
const seekToSourceTime = useCallback((sourceTimeSec: number) => {
@@ -328,7 +333,11 @@ export function VirtualPreview({
{activeSource ? (
<div ref={videoFrameRef} className={styles.videoFrame}>
<video
- key={activeSource.src}
+ // Key on the asset id, not the URL: distinct assets that resolve
+ // to the same file URL must still remount the <video> on switch so
+ // onLoadedMetadata refires and the pending cross-asset seek/resume
+ // runs (otherwise playback stalls at the clip boundary).
+ key={activeSource.id}
ref={videoRef}
src={activeSource.src}
className={styles.video}
diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsx
index 783b2b168..5edb4447d 100644
--- a/src/components/ai-edition/WebcamOverlay.test.tsx
+++ b/src/components/ai-edition/WebcamOverlay.test.tsx
@@ -65,7 +65,7 @@ function makeDocument(): AxcutDocument {
timeline: {
clips: [CLIP_WITH_CAMERA, CLIP_WITHOUT_CAMERA],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx b/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
index 77f9672b9..5727f159d 100644
--- a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
+++ b/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx
@@ -23,7 +23,7 @@
import { Application, Container, Graphics, Sprite, Texture, VideoSource } from "pixi.js";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fromFileUrl } from "@/components/video-editor/projectPersistence";
-import type { AxcutClip, AxcutSkipRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
+import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
@@ -51,7 +51,7 @@ interface PreviewCompositorProps {
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
- skipRanges?: AxcutSkipRange[];
+ trimRanges?: AxcutTrimRange[];
seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;
onTimeChange?: (timeSec: number) => void;
onLoadedMetadata?: (durationSec: number, assetId: string) => void;
@@ -71,7 +71,7 @@ export function PreviewCompositor({
clips,
zoomRegions = [],
speedRegions = [],
- skipRanges = [],
+ trimRanges = [],
seekTarget,
onTimeChange,
onLoadedMetadata,
@@ -113,8 +113,8 @@ export function PreviewCompositor({
virtualDurationSecRef.current = virtualDurationSec;
const speedRegionsRef = useRef(speedRegions);
speedRegionsRef.current = speedRegions;
- const skipRangesRef = useRef(skipRanges);
- skipRangesRef.current = skipRanges;
+ const trimRangesRef = useRef(trimRanges);
+ trimRangesRef.current = trimRanges;
const updateVirtualTime = useCallback(
(nextTimeSec: number) => {
@@ -152,17 +152,17 @@ export function PreviewCompositor({
}
const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;
if (!v.paused) {
- const activeSkip = skipRangesRef.current.find(
+ const activeTrim = trimRangesRef.current.find(
(skip) =>
skip.assetId === activeSourceId &&
v.currentTime >= skip.startSec &&
v.currentTime < skip.endSec,
);
- if (activeSkip) {
- if (activeSkip.endSec >= (v.duration || Infinity)) {
+ if (activeTrim) {
+ if (activeTrim.endSec >= (v.duration || Infinity)) {
v.pause();
} else {
- v.currentTime = activeSkip.endSec + 0.05;
+ v.currentTime = activeTrim.endSec + 0.05;
}
return;
}
diff --git a/src/components/ai-edition/v4/EditorShellV4.module.css b/src/components/ai-edition/v4/EditorShellV4.module.css
index 636b13b09..6653ed798 100644
--- a/src/components/ai-edition/v4/EditorShellV4.module.css
+++ b/src/components/ai-edition/v4/EditorShellV4.module.css
@@ -185,11 +185,42 @@
/* ─── BODY ─────────────────────────────────────────────────────────── */
.body {
+ position: relative;
grid-row: 2;
display: grid;
min-height: 0;
min-width: 0;
}
+/* ─── RESIZE HANDLES (chat panel width, timeline height) ───────────── */
+.chatResizeHandle {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 8px;
+ margin-left: -4px;
+ cursor: col-resize;
+ z-index: 30;
+ background: transparent;
+ touch-action: none;
+}
+.chatResizeHandle:hover {
+ background: var(--accent-soft);
+}
+.timelineResizeHandle {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 8px;
+ margin-top: -4px;
+ cursor: row-resize;
+ z-index: 30;
+ background: transparent;
+ touch-action: none;
+}
+.timelineResizeHandle:hover {
+ background: var(--accent-soft);
+}
.agent {
display: flex;
flex-direction: column;
@@ -208,20 +239,21 @@
}
/* ─── FLOATING INSPECTOR + FACET RAIL ──────────────────────────────── */
+/* bottom used to reserve room for the (permanently visible) transport bar;
+ the transport is now a hover-reveal overlay (see .transportWrap) and no
+ longer needs reserved space, so every facet gets the same tight margin
+ down to just above the timeline — same fix as the stage padding. */
.inspectorWrap {
position: absolute;
top: 20px;
right: 20px;
- bottom: 96px;
+ bottom: 20px;
display: flex;
align-items: flex-start;
gap: 10px;
z-index: 20;
pointer-events: none;
}
-.inspectorWrap.tall {
- bottom: 16px;
-}
.inspector {
pointer-events: auto;
width: 300px;
@@ -277,6 +309,9 @@
}
/* ─── FLOATING TRANSPORT (Edit mode) ───────────────────────────────── */
+/* Hover-reveal overlay: hidden until the pointer is over the stage (or the
+ bar itself has focus, for keyboard users), so it never reserves space
+ for the video and never gets in the way of watching playback. */
.transportWrap {
position: absolute;
left: 0;
@@ -286,9 +321,17 @@
justify-content: center;
z-index: 15;
pointer-events: none;
+ opacity: 0;
+ transition: opacity var(--motion-med) var(--ease);
}
-.transport {
+.stage:hover .transportWrap,
+.transportWrap:focus-within {
+ opacity: 1;
pointer-events: auto;
+}
+.transport {
+ /* pointer-events follows .transportWrap (none while hidden, auto on
+ hover/focus-within) — no independent override here. */
display: inline-flex;
align-items: center;
gap: 8px;
@@ -638,6 +681,28 @@
background: rgba(255, 255, 255, 0.14);
margin: 0 3px;
}
+.recDragHandle {
+ display: grid;
+ grid-auto-rows: 3.5px;
+ gap: 3.5px;
+ width: 36px;
+ height: 32px;
+ place-items: center;
+ justify-content: center;
+ align-content: center;
+ cursor: grab;
+ flex-shrink: 0;
+ touch-action: none;
+}
+.recDragHandle:active {
+ cursor: grabbing;
+}
+.recDragDot {
+ width: 3.5px;
+ height: 3.5px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.3);
+}
.recMenu {
position: absolute;
bottom: 46px;
@@ -671,6 +736,146 @@
background: var(--accent-soft);
color: var(--accent);
}
+
+/* ─── REC-MODE SOURCE PICKER MODAL ──────────────────────────────────── */
+.sourceModalOverlay {
+ position: fixed;
+ inset: 0;
+ z-index: 100;
+ background: rgba(4, 5, 7, 0.6);
+ backdrop-filter: blur(3px);
+ -webkit-backdrop-filter: blur(3px);
+ display: grid;
+ place-items: center;
+ padding: 24px;
+}
+.sourceModalCard {
+ width: 660px;
+ max-width: 100%;
+ max-height: 86vh;
+ display: flex;
+ flex-direction: column;
+ background: var(--surface-1);
+ border: 1px solid var(--border-hi);
+ border-radius: 20px;
+ box-shadow: 0 40px 90px -20px rgba(0, 0, 0, 0.7), 0 8px 24px rgba(0, 0, 0, 0.5);
+ overflow: hidden;
+}
+.sourceModalTabs {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 14px;
+ border-bottom: 1px solid var(--border-soft);
+ flex-shrink: 0;
+}
+.sourceModalTab {
+ flex: 1;
+ height: 40px;
+ border-radius: 11px;
+ background: transparent;
+ border: 1px solid transparent;
+ color: var(--muted);
+ font-size: 13.5px;
+ font-weight: 500;
+ cursor: pointer;
+}
+.sourceModalTab.active {
+ background: var(--surface-3);
+ border-color: var(--border-hi);
+ color: var(--fg-emphasis);
+ font-weight: 600;
+}
+.sourceGrid {
+ overflow-y: auto;
+ padding: 18px 18px 6px;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ scrollbar-width: thin;
+ scrollbar-color: var(--border-hi) transparent;
+}
+.sourceModalEmpty {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ padding: 40px 16px;
+ color: var(--muted);
+ font-size: 12.5px;
+}
+.sourceCard {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ text-align: left;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: 14px;
+ overflow: hidden;
+ cursor: pointer;
+ padding: 0;
+ transition: border-color var(--motion-fast) var(--ease), box-shadow var(--motion-fast) var(--ease),
+ transform var(--motion-fast) var(--ease);
+}
+.sourceCard:hover {
+ border-color: var(--border-hi);
+ transform: translateY(-2px);
+}
+.sourceCard.active {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+}
+.sourceCardThumb {
+ position: relative;
+ aspect-ratio: 16 / 10.5;
+ display: grid;
+ place-items: center;
+ background: #0a0c10;
+ color: var(--muted);
+ overflow: hidden;
+}
+.sourceCardThumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.sourceCardName {
+ display: block;
+ padding: 9px 11px;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--fg-2);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.sourceModalFooter {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 10px;
+ padding: 16px 18px;
+ border-top: 1px solid var(--border-soft);
+ flex-shrink: 0;
+}
+.sourceModalCancelBtn {
+ height: 36px;
+ padding: 0 16px;
+ border-radius: 9px;
+ background: transparent;
+ border: 1px solid var(--border-hi);
+ color: var(--fg-2);
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+}
+.sourceModalCancelBtn:hover {
+ background: var(--surface-2);
+}
+
.bigRecWrap {
position: absolute;
left: 0;
@@ -748,10 +953,6 @@
background: var(--surface-3);
color: var(--fg);
}
-.tlToolBtn.on {
- background: var(--accent-wash);
- color: var(--accent);
-}
.tlHints {
margin-left: auto;
display: flex;
@@ -879,7 +1080,7 @@
border-color: var(--speed);
background: var(--speed-wash);
}
-.laneSkip {
+.laneTrim {
border-color: var(--danger);
background: var(--danger-soft);
}
@@ -916,13 +1117,29 @@
border: 1.5px solid var(--border);
background: var(--surface-1);
overflow: hidden;
- cursor: pointer;
+ cursor: grab;
box-sizing: border-box;
box-shadow: inset 0 1px 8px rgba(255, 255, 255, 0.06);
+ /* pointer-driven reorder: suppress native touch scroll + text selection */
+ touch-action: none;
+ user-select: none;
+ transition: box-shadow var(--motion-fast) var(--ease), opacity var(--motion-fast) var(--ease),
+ transform 150ms var(--ease);
}
.tlClipSel {
border-color: var(--accent);
}
+/* The clip being carried during a reorder drag — follows the pointer 1:1
+ (no transition lag) while its siblings slide out of the way with the
+ base .tlClip transform transition above. */
+.tlClipDragging {
+ cursor: grabbing;
+ opacity: 0.9;
+ z-index: 5;
+ border-color: var(--accent);
+ box-shadow: 0 10px 26px rgba(0, 0, 0, 0.5), inset 0 1px 8px rgba(255, 255, 255, 0.06);
+ transition: box-shadow var(--motion-fast) var(--ease), opacity var(--motion-fast) var(--ease);
+}
.tlWave {
position: absolute;
inset: 0;
diff --git a/src/components/ai-edition/v4/EditorTopBar.tsx b/src/components/ai-edition/v4/EditorTopBar.tsx
index d45a43072..7422d35d1 100644
--- a/src/components/ai-edition/v4/EditorTopBar.tsx
+++ b/src/components/ai-edition/v4/EditorTopBar.tsx
@@ -9,7 +9,6 @@ import {
Save,
Settings,
Sun,
- Video,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useI18n } from "@/contexts/I18nContext";
@@ -23,7 +22,6 @@ export interface TopBarActions {
openProject: () => void;
newProject: () => void;
save: () => void;
- newRecording: () => void;
export: () => void;
openSettings: () => void;
renameProject: (title: string) => void;
@@ -93,7 +91,11 @@ export function EditorTopBar({
<span className={styles.name}>OpenScreen</span>
</span>
<span className={styles.sep} aria-hidden />
- <ProjectNameField title={projectTitle} onRename={actions.renameProject} />
+ <ProjectNameField
+ title={projectTitle}
+ onRename={actions.renameProject}
+ onOpenProjects={actions.openProject}
+ />
<span className={styles.sep} aria-hidden />
<button
type="button"
@@ -171,15 +173,6 @@ export function EditorTopBar({
))}
</div>
- <button
- type="button"
- className={styles.iconBtn}
- title="New recording"
- aria-label="New recording"
- onClick={actions.newRecording}
- >
- <Video size={16} />
- </button>
<button
type="button"
className={styles.iconBtn}
@@ -216,9 +209,11 @@ export function EditorTopBar({
function ProjectNameField({
title,
onRename,
+ onOpenProjects,
}: {
title: string | null;
onRename: (title: string) => void;
+ onOpenProjects: () => void;
}) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(title ?? "");
@@ -268,17 +263,41 @@ function ProjectNameField({
}
return (
- <button
- type="button"
- className={styles.ghostBtn}
- title="Rename project"
- aria-label="Rename project"
- disabled={!title}
- onClick={() => setEditing(true)}
- >
- <span>{title ?? "No project"}</span>
- <ChevronDown size={11} style={{ color: "var(--muted)" }} />
- </button>
+ <span className={styles.ghostBtn}>
+ <button
+ type="button"
+ title="Rename project"
+ aria-label="Rename project"
+ disabled={!title}
+ onClick={() => setEditing(true)}
+ style={{
+ all: "unset",
+ cursor: title ? "pointer" : "default",
+ color: "inherit",
+ font: "inherit",
+ }}
+ >
+ {title ?? "No project"}
+ </button>
+ <button
+ type="button"
+ title="Switch project"
+ aria-label="Switch project"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenProjects();
+ }}
+ style={{
+ all: "unset",
+ display: "grid",
+ placeItems: "center",
+ cursor: "pointer",
+ padding: 2,
+ }}
+ >
+ <ChevronDown size={11} style={{ color: "var(--muted)" }} />
+ </button>
+ </span>
);
}
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 6900ceb96..02cb79ac4 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -3,13 +3,18 @@ import {
ChevronRight,
Crop as CropIcon,
FileText,
- GitFork,
Image as ImageIcon,
Layout as LayoutIcon,
MousePointer2,
+ Scissors,
SlidersHorizontal,
+ Trash2,
+ X,
+ ZoomIn,
} from "lucide-react";
import type { ComponentProps } from "react";
+import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
+import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
import {
BackgroundPane,
CursorPane,
@@ -19,13 +24,14 @@ import {
} from "../RightPanes";
import styles from "./EditorShellV4.module.css";
+type TimelineApi = ReturnType<typeof useTimeline>;
+
export type Facet =
| "background"
| "effects"
| "layout"
| "cursor"
| "captions"
- | "chapters"
| "transcript"
| "crop";
@@ -35,7 +41,6 @@ const FACETS: Array<{ id: Facet; label: string; icon: typeof ImageIcon }> = [
{ id: "layout", label: "Layout", icon: LayoutIcon },
{ id: "cursor", label: "Cursor", icon: MousePointer2 },
{ id: "captions", label: "Captions", icon: CaptionsIcon },
- { id: "chapters", label: "Chapters", icon: GitFork },
{ id: "transcript", label: "Transcript", icon: FileText },
{ id: "crop", label: "Crop", icon: CropIcon },
];
@@ -50,6 +55,11 @@ interface FloatingInspectorProps {
onCrop: () => void;
onCaptions: () => void;
transcriptProps: TranscriptProps;
+ /** Drives the selected-element settings pane (zoom/speed/annotation/trim) —
+ * takes over the inspector, forcing it open, whenever a timeline region is
+ * selected. Clicking elsewhere on the timeline clears the selection
+ * (see V4Timeline's empty-area click handler) which closes this pane. */
+ tl: TimelineApi;
}
export function FloatingInspector({
@@ -60,19 +70,25 @@ export function FloatingInspector({
onCrop,
onCaptions,
transcriptProps,
+ tl,
}: FloatingInspectorProps) {
- const isTranscript = facet === "transcript";
+ const selection = tl.selection;
+ const effectiveOpen = open || selection !== null;
return (
- <div className={`${styles.inspectorWrap}${isTranscript ? ` ${styles.tall}` : ""}`}>
- {open ? (
+ <div className={styles.inspectorWrap}>
+ {effectiveOpen ? (
<div className={styles.inspector}>
- <FacetBody
- facet={facet}
- onCrop={onCrop}
- onCaptions={onCaptions}
- onCollapse={onToggleOpen}
- transcriptProps={transcriptProps}
- />
+ {selection ? (
+ <SelectionPane tl={tl} onClose={() => tl.clearSelection()} />
+ ) : (
+ <FacetBody
+ facet={facet}
+ onCrop={onCrop}
+ onCaptions={onCaptions}
+ onCollapse={onToggleOpen}
+ transcriptProps={transcriptProps}
+ />
+ )}
</div>
) : null}
<div className={styles.facetRail}>
@@ -82,8 +98,18 @@ export function FloatingInspector({
type="button"
title={label}
aria-label={label}
- aria-pressed={open && facet === id}
+ aria-pressed={!selection && open && facet === id}
onClick={() => {
+ // Switching facets while an element is selected should show
+ // the facet, not leave the selection pane on top of it.
+ if (selection) tl.clearSelection();
+ // Crop has no useful "settings" pane of its own — jump straight
+ // to the crop modal instead of routing through FacetBody's
+ // now-removed intermediate "Open crop…" pane.
+ if (id === "crop") {
+ onCrop();
+ return;
+ }
if (facet === id && open) {
onToggleOpen();
} else {
@@ -99,6 +125,288 @@ export function FloatingInspector({
);
}
+function paneHeader(icon: React.ReactNode, title: string, onClose: () => void) {
+ return (
+ <header
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "14px 16px 12px",
+ borderBottom: "1px solid var(--border-soft)",
+ }}
+ >
+ <span style={{ display: "grid", placeItems: "center", color: "var(--muted)" }}>{icon}</span>
+ <h2
+ style={{
+ margin: 0,
+ flex: 1,
+ fontSize: 14,
+ fontWeight: 600,
+ color: "var(--fg-emphasis)",
+ letterSpacing: "-0.01em",
+ }}
+ >
+ {title}
+ </h2>
+ <button
+ type="button"
+ title="Close"
+ aria-label="Close"
+ onClick={onClose}
+ style={{
+ width: 26,
+ height: 26,
+ display: "grid",
+ placeItems: "center",
+ borderRadius: 8,
+ color: "var(--muted)",
+ background: "transparent",
+ border: 0,
+ cursor: "pointer",
+ }}
+ >
+ <X size={15} />
+ </button>
+ </header>
+ );
+}
+
+function paneRow(label: string, control: React.ReactNode) {
+ return (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 10,
+ }}
+ >
+ <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>{label}</span>
+ {control}
+ </div>
+ );
+}
+
+const ZOOM_DEPTHS = [1, 2, 3, 4, 5, 6] as const;
+const SPEED_VALUES = [0.5, 0.75, 1, 1.25, 1.5, 2, 3];
+
+function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }) {
+ const selection = tl.selection;
+ if (!selection) return null;
+
+ const deleteAndClose = () => {
+ void tl.removeRegion(selection.kind, selection.id);
+ onClose();
+ };
+
+ const bodyStyle: React.CSSProperties = {
+ padding: "16px",
+ display: "flex",
+ flexDirection: "column",
+ gap: 16,
+ };
+ const deleteBtnStyle: React.CSSProperties = {
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 7,
+ padding: "9px 14px",
+ borderRadius: 10,
+ border: "1px solid var(--danger)",
+ background: "var(--danger-soft)",
+ color: "var(--danger)",
+ font: "600 13px var(--font-display)",
+ cursor: "pointer",
+ };
+
+ if (selection.kind === "zoom") {
+ const region = tl.zoomRegions.find((z) => z.id === selection.id);
+ if (!region) return null;
+ return (
+ <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
+ {paneHeader(<ZoomIn size={15} />, "Zoom", onClose)}
+ <div style={bodyStyle}>
+ {paneRow(
+ "Zoom level",
+ <select
+ value={region.depth}
+ onChange={(e) =>
+ void tl.updateZoomDepth(region.id, Number(e.target.value) as 1 | 2 | 3 | 4 | 5 | 6)
+ }
+ style={selectStyle}
+ >
+ {ZOOM_DEPTHS.map((d) => (
+ <option key={d} value={d}>
+ {(d / 2 + 0.5).toFixed(1)}×
+ </option>
+ ))}
+ </select>,
+ )}
+ <button
+ type="button"
+ onClick={() => {
+ tl.updateZoomFocusLive(region.id, { cx: 0.5, cy: 0.5 });
+ void tl.commitZoomFocus();
+ }}
+ style={secondaryBtnStyle}
+ >
+ Reset focus point
+ </button>
+ <button type="button" onClick={deleteAndClose} style={deleteBtnStyle}>
+ <Trash2 size={14} />
+ Delete zoom
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (selection.kind === "speed") {
+ const region = tl.speedRegions.find((s) => s.id === selection.id);
+ if (!region) return null;
+ return (
+ <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
+ {paneHeader(<ZoomIn size={15} />, "Speed", onClose)}
+ <div style={bodyStyle}>
+ {paneRow(
+ "Playback speed",
+ <select
+ value={region.speed}
+ onChange={(e) => void tl.updateSpeedValue(region.id, Number(e.target.value))}
+ style={selectStyle}
+ >
+ {SPEED_VALUES.map((s) => (
+ <option key={s} value={s}>
+ {s}×
+ </option>
+ ))}
+ </select>,
+ )}
+ <button type="button" onClick={deleteAndClose} style={deleteBtnStyle}>
+ <Trash2 size={14} />
+ Delete speed region
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (selection.kind === "annotation") {
+ const region = tl.annotationRegions.find((a) => a.id === selection.id);
+ if (!region) return null;
+ const colors = ["#ffffff", "#0f172a", "#10b981", "#f59e0b", "#f43f5e", "#6366f1"];
+ return (
+ <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
+ {paneHeader(<FileText size={15} />, "Annotation", onClose)}
+ <div style={bodyStyle}>
+ <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
+ <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>Text</span>
+ <textarea
+ value={region.content ?? ""}
+ onChange={(e) => tl.updateAnnotationLive(region.id, { content: e.target.value })}
+ onBlur={() => void tl.commitAnnotationChange()}
+ rows={2}
+ style={{
+ resize: "vertical",
+ padding: "8px 10px",
+ borderRadius: 9,
+ border: "1px solid var(--border)",
+ background: "var(--surface)",
+ color: "var(--fg)",
+ font: "500 13px var(--font-display)",
+ }}
+ />
+ </div>
+ {paneRow(
+ "Color",
+ <div style={{ display: "flex", gap: 6 }}>
+ {colors.map((c) => (
+ <button
+ key={c}
+ type="button"
+ title={c}
+ aria-label={`Set color ${c}`}
+ aria-pressed={region.style?.color === c}
+ onClick={() => {
+ tl.updateAnnotationLive(region.id, {
+ style: { ...region.style, color: c },
+ });
+ void tl.commitAnnotationChange();
+ }}
+ style={{
+ width: 22,
+ height: 22,
+ borderRadius: "50%",
+ background: c,
+ border:
+ region.style?.color === c
+ ? "2px solid var(--accent)"
+ : "1px solid var(--border-hi)",
+ cursor: "pointer",
+ }}
+ />
+ ))}
+ </div>,
+ )}
+ <button type="button" onClick={deleteAndClose} style={deleteBtnStyle}>
+ <Trash2 size={14} />
+ Delete annotation
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ // trim — a trim ventilated across a clip boundary is 2+ DSL rows that render
+ // as one coalesced pill (see V4Timeline's trimPills); the inspector must
+ // resolve the clicked id back to its whole group so the shown duration and
+ // the delete button act on all of it, not just the one row that was clicked.
+ const trimGroup = coalescedTrimGroups(tl.trimRanges, tl.clips).find((g) =>
+ g.ids.includes(selection.id),
+ );
+ if (!trimGroup) return null;
+ const durationSec = Math.max(0, trimGroup.end - trimGroup.start);
+ const deleteTrimGroup = () => {
+ void tl.removeRegions(trimGroup.ids.map((id) => ({ kind: "trim" as const, id })));
+ onClose();
+ };
+ return (
+ <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
+ {paneHeader(<Scissors size={15} />, "Trim", onClose)}
+ <div style={bodyStyle}>
+ <p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--muted)" }}>
+ {durationSec.toFixed(1)}s of source media hidden from the edited timeline.
+ </p>
+ <button type="button" onClick={deleteTrimGroup} style={deleteBtnStyle}>
+ <Trash2 size={14} />
+ Restore (delete trim)
+ </button>
+ </div>
+ </div>
+ );
+}
+
+const selectStyle: React.CSSProperties = {
+ height: 32,
+ padding: "0 8px",
+ borderRadius: 8,
+ border: "1px solid var(--border)",
+ background: "var(--surface)",
+ color: "var(--fg)",
+ font: "500 12.5px var(--font-display)",
+};
+
+const secondaryBtnStyle: React.CSSProperties = {
+ padding: "9px 14px",
+ borderRadius: 10,
+ border: "1px solid var(--border-hi)",
+ background: "var(--surface-2)",
+ color: "var(--fg-2)",
+ font: "600 13px var(--font-display)",
+ cursor: "pointer",
+};
+
function FacetBody({
facet,
onCrop,
@@ -154,23 +462,17 @@ function FacetBody({
onAction={onCaptions}
/>,
);
- if (facet === "crop")
- return wrap(
- collapse,
- <SimpleFacet
- title="Crop"
- description="Reframe the recording — pick an aspect ratio and zoom into the region you want to keep."
- actionLabel="Open crop…"
- onAction={onCrop}
- />,
- );
- // chapters
+ // crop: the rail button bypasses FacetBody and opens CropModal directly
+ // (see the facet rail's onClick above) — this is a defensive fallback for
+ // the unlikely case `facet` state is ever "crop" without going through
+ // the rail.
return wrap(
collapse,
<SimpleFacet
- title="Chapters"
- description="Chapter markers help viewers jump around long recordings."
- emptyLabel="No chapters yet"
+ title="Crop"
+ description="Reframe the recording — pick an aspect ratio and zoom into the region you want to keep."
+ actionLabel="Open crop…"
+ onAction={onCrop}
/>,
);
}
diff --git a/src/components/ai-edition/v4/RecStage.tsx b/src/components/ai-edition/v4/RecStage.tsx
index 61dd0fc1a..ddf6a59c3 100644
--- a/src/components/ai-edition/v4/RecStage.tsx
+++ b/src/components/ai-edition/v4/RecStage.tsx
@@ -1,46 +1,232 @@
import {
+ AppWindow,
Camera,
CameraOff,
ChevronDown,
+ Loader2,
MicOff,
Mic as MicOn,
+ Minus,
MonitorSmartphone,
MousePointer2,
Volume2,
VolumeX,
+ X,
} from "lucide-react";
-import { useState } from "react";
+import {
+ type PointerEvent as ReactPointerEvent,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { useCameraDevices } from "@/hooks/useCameraDevices";
+import { useMicrophoneDevices } from "@/hooks/useMicrophoneDevices";
import styles from "./EditorShellV4.module.css";
-type Menu = "source" | "mic" | "camera" | null;
+type Menu = "system" | "mic" | "camera" | null;
+type Orientation = "horizontal" | "vertical";
+
+interface RecordingPrefsState {
+ micEnabled: boolean;
+ micDeviceId: string | null;
+ camEnabled: boolean;
+ camDeviceId: string | null;
+ systemAudioEnabled: boolean;
+ cursorCaptureMode: "editable-overlay" | "system";
+}
-const SCREEN_TARGETS = ["Entire Screen", "Display 2"];
-const WINDOW_TARGETS = ["OpenScreen Studio", "Figma", "Terminal", "Google Chrome"];
-const MIC_DEVICES = ["MacBook Pro Microphone", "AirPods Pro", "Blue Yeti X"];
-const CAMERA_DEVICES = ["FaceTime HD Camera", "Logitech Brio 4K"];
+const DEFAULT_PREFS: RecordingPrefsState = {
+ micEnabled: false,
+ micDeviceId: null,
+ camEnabled: false,
+ camDeviceId: null,
+ systemAudioEnabled: false,
+ cursorCaptureMode: "editable-overlay",
+};
/**
* Rec-mode stage. The real capture pipeline lives in the standalone recorder
- * HUD window (`electronAPI.startNewRecording`); this stage presents the v4
- * source/mic/camera/cursor configuration bar and hands off to the HUD when the
- * user hits record.
+ * HUD window (`electronAPI.startNewRecording`); this stage presents a real
+ * source/mic/camera/cursor configuration bar — ported from the "OpenScreen
+ * Recording Widget" design — and hands off to the HUD when the user hits
+ * record. Device lists, source selection, and capture-preference state are
+ * all read from the same single sources of truth the rest of the app uses
+ * (useMicrophoneDevices/useCameraDevices for enumeration, the main-process
+ * selected-source + recording-prefs IPC for cross-window selection) — this
+ * component holds no invented state of its own for any of that.
*/
-export function RecStage({ onStartRecording }: { onStartRecording: () => void }) {
+export function RecStage({
+ onStartRecording,
+ onClose,
+}: {
+ onStartRecording: () => void;
+ /** "Close" on the widget has nothing to close (no separate OS window in
+ * this embedded context) — the closest real equivalent is leaving Rec
+ * mode. Optional so the component still works if a caller doesn't wire it. */
+ onClose?: () => void;
+}) {
const [menu, setMenu] = useState<Menu>(null);
+ const toggleMenu = (m: Menu) => setMenu((cur) => (cur === m ? null : m));
+
+ const [orientation, setOrientation] = useState<Orientation>("horizontal");
+ const isVertical = orientation === "vertical";
+ const [collapsed, setCollapsed] = useState(false);
+
+ // Drag-to-reposition the toolbar within the frame — position is null
+ // (CSS-centered default) until the user first drags, then becomes an
+ // explicit, clamped {x,y} offset from the frame's own top-left.
+ const frameRef = useRef<HTMLDivElement | null>(null);
+ const barRef = useRef<HTMLDivElement | null>(null);
+ const [dragPos, setDragPos] = useState<{ x: number; y: number } | null>(null);
+ const startDrag = useCallback((e: ReactPointerEvent) => {
+ e.preventDefault();
+ const frame = frameRef.current;
+ const bar = barRef.current;
+ if (!frame || !bar) return;
+ const frameRect = frame.getBoundingClientRect();
+ const barRect = bar.getBoundingClientRect();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startLeft = barRect.left - frameRect.left;
+ const startTop = barRect.top - frameRect.top;
+ const move = (ev: PointerEvent) => {
+ const x = Math.min(
+ frameRect.width - barRect.width,
+ Math.max(0, startLeft + (ev.clientX - startX)),
+ );
+ const y = Math.min(
+ frameRect.height - barRect.height,
+ Math.max(0, startTop + (ev.clientY - startY)),
+ );
+ setDragPos({ x, y });
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ }, []);
+
+ const [prefs, setPrefsState] = useState<RecordingPrefsState>(DEFAULT_PREFS);
+ useEffect(() => {
+ let cancelled = false;
+ void window.electronAPI?.getRecordingPrefs?.().then((p) => {
+ if (!cancelled && p) setPrefsState(p as RecordingPrefsState);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ const updatePrefs = useCallback((patch: Partial<RecordingPrefsState>) => {
+ setPrefsState((prev) => {
+ const next = { ...prev, ...patch };
+ void window.electronAPI?.setRecordingPrefs?.(patch);
+ return next;
+ });
+ }, []);
+
+ const micDevices = useMicrophoneDevices(true);
+ const camDevices = useCameraDevices(true);
+
+ // Seed the device hooks' local "selected" state from the persisted prefs
+ // once devices are enumerated, so the dropdown reflects the last real
+ // choice instead of the hook's own "first device" default.
+ useEffect(() => {
+ if (prefs.micDeviceId && micDevices.devices.some((d) => d.deviceId === prefs.micDeviceId)) {
+ micDevices.setSelectedDeviceId(prefs.micDeviceId);
+ }
+ }, [prefs.micDeviceId, micDevices.devices, micDevices.setSelectedDeviceId]);
+ useEffect(() => {
+ if (prefs.camDeviceId && camDevices.devices.some((d) => d.deviceId === prefs.camDeviceId)) {
+ camDevices.setSelectedDeviceId(prefs.camDeviceId);
+ }
+ }, [prefs.camDeviceId, camDevices.devices, camDevices.setSelectedDeviceId]);
+
+ // ── capture source (screen/window) ──────────────────────────────
+ const [source, setSource] = useState<ProcessedDesktopSource | null>(null);
+ useEffect(() => {
+ void window.electronAPI?.getSelectedSource?.().then((s) => setSource(s ?? null));
+ }, []);
+ const [sourceModalOpen, setSourceModalOpen] = useState(false);
const [sourceTab, setSourceTab] = useState<"screen" | "window">("screen");
- const [screenTarget, setScreenTarget] = useState(SCREEN_TARGETS[0]);
- const [windowTarget, setWindowTarget] = useState(WINDOW_TARGETS[0]);
- const [speakerOn, setSpeakerOn] = useState(false);
- const [micDevice, setMicDevice] = useState<string | null>(null);
- const [cameraDevice, setCameraDevice] = useState<string | null>(null);
- const [cursorOn, setCursorOn] = useState(true);
+ const [sources, setSources] = useState<ProcessedDesktopSource[]>([]);
+ const [loadingSources, setLoadingSources] = useState(false);
+ const openSourceModal = useCallback(async () => {
+ setMenu(null);
+ setSourceModalOpen(true);
+ setLoadingSources(true);
+ try {
+ const list = await window.electronAPI?.getSources?.({
+ types: ["screen", "window"],
+ thumbnailSize: { width: 320, height: 180 },
+ fetchWindowIcons: true,
+ });
+ setSources(list ?? []);
+ } finally {
+ setLoadingSources(false);
+ }
+ }, []);
+ const chooseSource = useCallback(async (candidate: ProcessedDesktopSource) => {
+ const result = await window.electronAPI?.selectSource?.(candidate);
+ setSource(result ?? candidate);
+ setSourceModalOpen(false);
+ }, []);
+ const screenSources = sources.filter((s) => s.id.startsWith("screen:"));
+ const windowSources = sources.filter((s) => s.id.startsWith("window:"));
+ const visibleSources = sourceTab === "screen" ? screenSources : windowSources;
+
+ const cursorHighlight = prefs.cursorCaptureMode === "editable-overlay";
- const sourceLabel = sourceTab === "screen" ? screenTarget : windowTarget;
- const toggle = (m: Menu) => setMenu((cur) => (cur === m ? null : m));
+ // Popovers open beside the bar in vertical mode (there's no room below a
+ // column layout) and above it in horizontal mode — mirrors the design's
+ // V-conditional menu positioning.
+ const menuStyle = (horizontalPos: React.CSSProperties, width: number): React.CSSProperties =>
+ isVertical
+ ? { top: 0, bottom: "auto", left: "calc(100% + 8px)", width }
+ : { ...horizontalPos, width };
+
+ if (collapsed) {
+ return (
+ <div className={styles.recStage}>
+ <div className={styles.recFrame} ref={frameRef}>
+ <span
+ aria-hidden
+ style={{
+ width: 88,
+ height: 88,
+ borderRadius: "50%",
+ background: "linear-gradient(180deg,#c2c6cc 0%,#676d78 100%)",
+ }}
+ />
+ <div className={styles.recBadge}>
+ <span className={styles.recDot} aria-hidden />
+ <span>Ready to record</span>
+ </div>
+ <div className={styles.recBarWrap}>
+ <button
+ type="button"
+ className={styles.recIconBtn}
+ title="Expand recording widget"
+ aria-label="Expand recording widget"
+ onClick={() => setCollapsed(false)}
+ style={{
+ background: "rgba(20, 22, 27, 0.72)",
+ border: "1px solid rgba(255,255,255,0.12)",
+ }}
+ >
+ <span className={styles.recDot} aria-hidden />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ }
return (
<div className={styles.recStage}>
- <div className={styles.recFrame}>
+ <div className={styles.recFrame} ref={frameRef}>
<span
aria-hidden
style={{
@@ -55,8 +241,72 @@ export function RecStage({ onStartRecording }: { onStartRecording: () => void })
<span>Ready to record</span>
</div>
- <div className={styles.recBarWrap}>
- <div className={styles.recBar}>
+ <div
+ className={styles.recBarWrap}
+ style={
+ dragPos ? { left: dragPos.x, top: dragPos.y, right: "auto", bottom: "auto" } : undefined
+ }
+ >
+ <div
+ ref={barRef}
+ className={styles.recBar}
+ style={isVertical ? { flexDirection: "column" } : undefined}
+ >
+ {/* drag handle */}
+ <span
+ title="Drag to move"
+ aria-hidden="true"
+ onPointerDown={startDrag}
+ className={styles.recDragHandle}
+ style={
+ isVertical
+ ? { gridTemplateColumns: "repeat(3, 3.5px)" }
+ : { gridTemplateColumns: "repeat(2, 3.5px)" }
+ }
+ >
+ {Array.from({ length: 6 }).map((_, i) => (
+ <span key={i} className={styles.recDragDot} />
+ ))}
+ </span>
+
+ <span className={styles.recBarSep} aria-hidden />
+
+ {/* orientation toggle */}
+ <button
+ type="button"
+ className={styles.recIconBtn}
+ title={isVertical ? "Switch to horizontal layout" : "Switch to vertical layout"}
+ aria-label={isVertical ? "Switch to horizontal layout" : "Switch to vertical layout"}
+ aria-pressed={isVertical}
+ onClick={() => setOrientation(isVertical ? "horizontal" : "vertical")}
+ >
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.6"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ >
+ {isVertical ? (
+ <>
+ <rect x="3" y="7" width="18" height="10" rx="3" />
+ <path d="M12 7v10" />
+ </>
+ ) : (
+ <>
+ <rect x="7" y="3" width="10" height="18" rx="3" />
+ <path d="M7 12h10" />
+ </>
+ )}
+ </svg>
+ </button>
+
+ <span className={styles.recBarSep} aria-hidden />
+
{/* source */}
<div style={{ position: "relative" }}>
<button
@@ -64,124 +314,102 @@ export function RecStage({ onStartRecording }: { onStartRecording: () => void })
className={styles.recBarBtn}
title="Recording source"
aria-label="Recording source"
- onClick={() => toggle("source")}
+ onClick={() => void openSourceModal()}
>
<MonitorSmartphone size={15} />
- <span>{sourceLabel}</span>
- <ChevronDown size={10} style={{ opacity: 0.6 }} />
+ {isVertical ? null : <span>{source?.name ?? "Entire Screen"}</span>}
+ {isVertical ? null : <ChevronDown size={10} style={{ opacity: 0.6 }} />}
+ </button>
+ </div>
+
+ <span className={styles.recBarSep} aria-hidden />
+
+ {/* system audio */}
+ <div style={{ position: "relative" }}>
+ <button
+ type="button"
+ className={`${styles.recIconBtn}${prefs.systemAudioEnabled ? ` ${styles.on}` : ""}`}
+ title="System audio"
+ aria-label="System audio"
+ aria-pressed={prefs.systemAudioEnabled}
+ onClick={() => toggleMenu("system")}
+ >
+ {prefs.systemAudioEnabled ? <Volume2 size={15} /> : <VolumeX size={15} />}
</button>
- {menu === "source" ? (
- <div className={styles.recMenu} style={{ left: 0, width: 220 }}>
- <div
- style={{
- display: "flex",
- gap: 2,
- padding: 2,
- background: "var(--surface-3)",
- borderRadius: 8,
- marginBottom: 6,
+ {menu === "system" ? (
+ <div className={styles.recMenu} style={menuStyle({ left: 0 }, 200)}>
+ <button
+ type="button"
+ className={`${styles.recMenuRow}${prefs.systemAudioEnabled ? ` ${styles.active}` : ""}`}
+ onClick={() => {
+ updatePrefs({ systemAudioEnabled: !prefs.systemAudioEnabled });
+ setMenu(null);
}}
>
- {(["screen", "window"] as const).map((tab) => (
- <button
- key={tab}
- type="button"
- onClick={() => setSourceTab(tab)}
- style={{
- flex: 1,
- padding: "6px 8px",
- borderRadius: 6,
- border: 0,
- fontSize: 11.5,
- fontWeight: 600,
- cursor: "pointer",
- textTransform: "capitalize",
- background: sourceTab === tab ? "var(--surface-1)" : "transparent",
- color: sourceTab === tab ? "var(--fg-emphasis)" : "var(--muted)",
- }}
- >
- {tab}
- </button>
- ))}
- </div>
- {(sourceTab === "screen" ? SCREEN_TARGETS : WINDOW_TARGETS).map((name) => {
- const active =
- sourceTab === "screen" ? name === screenTarget : name === windowTarget;
- return (
- <button
- key={name}
- type="button"
- className={`${styles.recMenuRow}${active ? ` ${styles.active}` : ""}`}
- onClick={() => {
- if (sourceTab === "screen") setScreenTarget(name);
- else setWindowTarget(name);
- setMenu(null);
- }}
- >
- <MonitorSmartphone size={14} />
- {name}
- </button>
- );
- })}
+ {prefs.systemAudioEnabled ? <Volume2 size={14} /> : <VolumeX size={14} />}
+ {prefs.systemAudioEnabled ? "Mute system audio" : "Capture system audio"}
+ </button>
</div>
) : null}
</div>
- <span className={styles.recBarSep} aria-hidden />
-
- {/* speaker / system audio */}
- <button
- type="button"
- className={`${styles.recIconBtn}${speakerOn ? ` ${styles.on}` : ""}`}
- title="Toggle system audio"
- aria-label="Toggle system audio"
- aria-pressed={speakerOn}
- onClick={() => setSpeakerOn((v) => !v)}
- >
- {speakerOn ? <Volume2 size={15} /> : <VolumeX size={15} />}
- </button>
-
{/* mic */}
<div style={{ position: "relative" }}>
<button
type="button"
- className={`${styles.recIconBtn}${micDevice ? ` ${styles.on}` : ""}`}
+ className={`${styles.recIconBtn}${prefs.micEnabled ? ` ${styles.on}` : ""}`}
title="Microphone"
aria-label="Microphone"
- onClick={() => toggle("mic")}
+ aria-pressed={prefs.micEnabled}
+ onClick={() => toggleMenu("mic")}
>
- {micDevice ? <MicOn size={15} /> : <MicOff size={15} />}
+ {prefs.micEnabled ? <MicOn size={15} /> : <MicOff size={15} />}
</button>
{menu === "mic" ? (
<div
className={styles.recMenu}
- style={{ left: "50%", transform: "translateX(-50%)", width: 210 }}
+ style={menuStyle({ left: "50%", transform: "translateX(-50%)" }, 220)}
>
<button
type="button"
- className={`${styles.recMenuRow}${!micDevice ? ` ${styles.active}` : ""}`}
+ className={`${styles.recMenuRow}${!prefs.micEnabled ? ` ${styles.active}` : ""}`}
onClick={() => {
- setMicDevice(null);
+ updatePrefs({ micEnabled: false });
setMenu(null);
}}
>
<MicOff size={14} />
No microphone
</button>
- {MIC_DEVICES.map((name) => (
- <button
- key={name}
- type="button"
- className={`${styles.recMenuRow}${micDevice === name ? ` ${styles.active}` : ""}`}
- onClick={() => {
- setMicDevice(name);
- setMenu(null);
- }}
+ {micDevices.isLoading ? (
+ <div
+ className={styles.recMenuRow}
+ style={{ color: "var(--muted)", cursor: "default" }}
>
- <MicOn size={14} />
- {name}
- </button>
- ))}
+ <Loader2 size={14} className="animate-spin" />
+ Loading microphones…
+ </div>
+ ) : (
+ micDevices.devices.map((d) => (
+ <button
+ key={d.deviceId}
+ type="button"
+ className={`${styles.recMenuRow}${
+ prefs.micEnabled && prefs.micDeviceId === d.deviceId
+ ? ` ${styles.active}`
+ : ""
+ }`}
+ onClick={() => {
+ micDevices.setSelectedDeviceId(d.deviceId);
+ updatePrefs({ micEnabled: true, micDeviceId: d.deviceId });
+ setMenu(null);
+ }}
+ >
+ <MicOn size={14} />
+ {d.label}
+ </button>
+ ))
+ )}
</div>
) : null}
</div>
@@ -190,64 +418,138 @@ export function RecStage({ onStartRecording }: { onStartRecording: () => void })
<div style={{ position: "relative" }}>
<button
type="button"
- className={`${styles.recIconBtn}${cameraDevice ? ` ${styles.on}` : ""}`}
+ className={`${styles.recIconBtn}${prefs.camEnabled ? ` ${styles.on}` : ""}`}
title="Camera"
aria-label="Camera"
- onClick={() => toggle("camera")}
+ aria-pressed={prefs.camEnabled}
+ onClick={() => toggleMenu("camera")}
>
- {cameraDevice ? <Camera size={15} /> : <CameraOff size={15} />}
+ {prefs.camEnabled ? <Camera size={15} /> : <CameraOff size={15} />}
</button>
{menu === "camera" ? (
<div
className={styles.recMenu}
- style={{ left: "50%", transform: "translateX(-50%)", width: 210 }}
+ style={menuStyle({ left: "50%", transform: "translateX(-50%)" }, 220)}
>
<button
type="button"
- className={`${styles.recMenuRow}${!cameraDevice ? ` ${styles.active}` : ""}`}
+ className={`${styles.recMenuRow}${!prefs.camEnabled ? ` ${styles.active}` : ""}`}
onClick={() => {
- setCameraDevice(null);
+ updatePrefs({ camEnabled: false });
setMenu(null);
}}
>
<CameraOff size={14} />
No camera
</button>
- {CAMERA_DEVICES.map((name) => (
- <button
- key={name}
- type="button"
- className={`${styles.recMenuRow}${
- cameraDevice === name ? ` ${styles.active}` : ""
- }`}
- onClick={() => {
- setCameraDevice(name);
- setMenu(null);
- }}
+ {camDevices.isLoading ? (
+ <div
+ className={styles.recMenuRow}
+ style={{ color: "var(--muted)", cursor: "default" }}
>
- <Camera size={14} />
- {name}
- </button>
- ))}
+ <Loader2 size={14} className="animate-spin" />
+ Loading cameras…
+ </div>
+ ) : (
+ camDevices.devices.map((d) => (
+ <button
+ key={d.deviceId}
+ type="button"
+ className={`${styles.recMenuRow}${
+ prefs.camEnabled && prefs.camDeviceId === d.deviceId
+ ? ` ${styles.active}`
+ : ""
+ }`}
+ onClick={() => {
+ camDevices.setSelectedDeviceId(d.deviceId);
+ updatePrefs({ camEnabled: true, camDeviceId: d.deviceId });
+ setMenu(null);
+ }}
+ >
+ <Camera size={14} />
+ {d.label}
+ </button>
+ ))
+ )}
</div>
) : null}
</div>
- {/* cursor capture */}
+ {/* cursor highlight */}
<button
type="button"
- className={`${styles.recIconBtn}${cursorOn ? ` ${styles.on}` : ""}`}
- title="Toggle cursor capture"
- aria-label="Toggle cursor capture"
- aria-pressed={cursorOn}
- onClick={() => setCursorOn((v) => !v)}
+ className={`${styles.recIconBtn}${cursorHighlight ? ` ${styles.on}` : ""}`}
+ title={cursorHighlight ? "Hide cursor highlight" : "Show cursor highlight"}
+ aria-label="Toggle cursor highlight"
+ aria-pressed={cursorHighlight}
+ onClick={() =>
+ updatePrefs({
+ cursorCaptureMode: cursorHighlight ? "system" : "editable-overlay",
+ })
+ }
>
<MousePointer2 size={15} />
</button>
+
+ <span className={styles.recBarSep} aria-hidden />
+
+ {/* switch to the real floating recording widget — moved here from
+ the topbar's old generic "New recording" camera-icon shortcut. */}
+ <button
+ type="button"
+ className={styles.recIconBtn}
+ title="Switch to recording widget"
+ aria-label="Switch to recording widget"
+ onClick={onStartRecording}
+ >
+ <AppWindow size={15} />
+ </button>
+
+ <span className={styles.recBarSep} aria-hidden />
+
+ {/* minimize / close */}
+ <button
+ type="button"
+ className={styles.recIconBtn}
+ title="Minimize"
+ aria-label="Minimize"
+ onClick={() => setCollapsed(true)}
+ >
+ <Minus size={14} />
+ </button>
+ {onClose ? (
+ <button
+ type="button"
+ className={styles.recIconBtn}
+ title="Close"
+ aria-label="Close"
+ onClick={onClose}
+ >
+ <X size={14} />
+ </button>
+ ) : null}
</div>
</div>
</div>
+ {menu ? (
+ <div style={{ position: "fixed", inset: 0, zIndex: 20 }} onClick={() => setMenu(null)} />
+ ) : null}
+
+ {sourceModalOpen ? (
+ <SourceModal
+ loading={loadingSources}
+ tab={sourceTab}
+ onTabChange={setSourceTab}
+ screenCount={screenSources.length}
+ windowCount={windowSources.length}
+ sources={visibleSources}
+ selectedId={source?.id ?? null}
+ onSelect={(s) => void chooseSource(s)}
+ onClose={() => setSourceModalOpen(false)}
+ />
+ ) : null}
+
<div className={styles.bigRecWrap}>
<button type="button" className={styles.bigRecBtn} onClick={onStartRecording}>
<span className={styles.bigRecDot} aria-hidden />
@@ -257,3 +559,77 @@ export function RecStage({ onStartRecording }: { onStartRecording: () => void })
</div>
);
}
+
+function SourceModal({
+ loading,
+ tab,
+ onTabChange,
+ screenCount,
+ windowCount,
+ sources,
+ selectedId,
+ onSelect,
+ onClose,
+}: {
+ loading: boolean;
+ tab: "screen" | "window";
+ onTabChange: (tab: "screen" | "window") => void;
+ screenCount: number;
+ windowCount: number;
+ sources: ProcessedDesktopSource[];
+ selectedId: string | null;
+ onSelect: (source: ProcessedDesktopSource) => void;
+ onClose: () => void;
+}) {
+ return (
+ <div className={styles.sourceModalOverlay} onClick={onClose}>
+ <div className={styles.sourceModalCard} onClick={(e) => e.stopPropagation()}>
+ <div className={styles.sourceModalTabs}>
+ <button
+ type="button"
+ className={`${styles.sourceModalTab}${tab === "screen" ? ` ${styles.active}` : ""}`}
+ onClick={() => onTabChange("screen")}
+ >
+ Screens ({screenCount})
+ </button>
+ <button
+ type="button"
+ className={`${styles.sourceModalTab}${tab === "window" ? ` ${styles.active}` : ""}`}
+ onClick={() => onTabChange("window")}
+ >
+ Windows ({windowCount})
+ </button>
+ </div>
+ <div className={styles.sourceGrid}>
+ {loading ? (
+ <div className={styles.sourceModalEmpty}>
+ <Loader2 size={20} className="animate-spin" />
+ Loading sources…
+ </div>
+ ) : sources.length === 0 ? (
+ <div className={styles.sourceModalEmpty}>No {tab}s found</div>
+ ) : (
+ sources.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ className={`${styles.sourceCard}${s.id === selectedId ? ` ${styles.active}` : ""}`}
+ onClick={() => onSelect(s)}
+ >
+ <div className={styles.sourceCardThumb}>
+ {s.thumbnail ? <img src={s.thumbnail} alt="" /> : <MonitorSmartphone size={22} />}
+ </div>
+ <span className={styles.sourceCardName}>{s.name}</span>
+ </button>
+ ))
+ )}
+ </div>
+ <div className={styles.sourceModalFooter}>
+ <button type="button" className={styles.sourceModalCancelBtn} onClick={onClose}>
+ Cancel
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 7ac66c451..eba5f0aaa 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -1,12 +1,14 @@
import {
ChevronDown,
Clock,
+ Loader2,
MessageSquare,
- MousePointer2,
+ Pencil,
Scissors,
Sparkles,
SplitSquareHorizontal,
Trash2,
+ Wand2,
ZoomIn,
} from "lucide-react";
import {
@@ -17,20 +19,37 @@ import {
useRef,
useState,
} from "react";
+import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { fromFileUrl } from "@/components/video-editor/projectPersistence";
+import { createId } from "@/lib/ai-edition/document/ids";
import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
+import { ventilateSpanAcrossClips } from "@/lib/ai-edition/timeline/region-ventilation";
+import {
+ coalescedTrimGroups,
+ resolveTimelineSpanToTrim,
+ ventilateTimelineSpanToTrims,
+} from "@/lib/ai-edition/timeline/trim-mapping";
+import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";
+import { nativeBridgeClient } from "@/native/client";
import { ASPECT_RATIOS } from "@/utils/aspectRatioUtils";
import { EditClipModal } from "../Modals";
import type { VideoSource } from "../VirtualPreview";
import styles from "./EditorShellV4.module.css";
+// Well-crafted generic prompt for the AI "smart zooms + cuts" option — sent
+// straight to the chat agent via the prompt-bus.
+const AI_ENHANCE_PROMPT =
+ "Automatically enhance this recording: (1) add smart zoom-ins on the moments where the cursor dwells or interacts with the UI, each focused on the cursor's location; and (2) cut the dead time — long pauses, silences, and idle stretches where nothing happens — to keep the pacing tight and natural. Apply the edits directly to the timeline.";
+
type TimelineApi = ReturnType<typeof useTimeline>;
const ASSET_MIME = "application/x-axcut-asset";
-type ToolId = "select" | "frame" | "cut" | "comment" | "speed" | "enhance";
+type ToolId = "cut" | "comment" | "speed";
function fmt(sec: number): string {
if (!Number.isFinite(sec) || sec < 0) sec = 0;
@@ -56,31 +75,14 @@ function waveformFor(seed: number, count: number): number[] {
return bars;
}
-// Map a skip's source-time range to timeline seconds through the clip that
-// carries it (skips are stored in asset source-time, everything else on the
-// lane is timeline-time).
-function skipToTimeline(
- skip: { assetId: string; startSec: number; endSec: number },
- clips: AxcutClip[],
-): { start: number; end: number } | null {
- for (const c of clips) {
- if (c.assetId !== skip.assetId) continue;
- const srcEnd = c.sourceEndSec ?? c.sourceStartSec;
- if (skip.startSec >= c.sourceStartSec && skip.startSec <= srcEnd) {
- const map = (s: number) =>
- c.timelineStartSec + (Math.min(Math.max(s, c.sourceStartSec), srcEnd) - c.sourceStartSec);
- return { start: map(skip.startSec), end: map(skip.endSec) };
- }
- }
- return null;
-}
-
interface LanePill {
id: string;
- kind: "annotation" | "speed" | "skip" | "zoom";
+ kind: "annotation" | "speed" | "trim" | "zoom";
start: number;
end: number;
label: string;
+ /** Underlying row ids this pill represents — >1 for a coalesced trim group. */
+ sourceIds: string[];
}
export function V4Timeline({
@@ -100,23 +102,32 @@ export function V4Timeline({
}) {
const tracksRef = useRef<HTMLDivElement | null>(null);
const navRef = useRef<HTMLDivElement | null>(null);
+ const clipsRef = useRef<HTMLDivElement | null>(null);
+ // True while a clip pointer-drag actually moved the pointer past the
+ // threshold, so the click fired on pointerup selects nothing (a drag is
+ // not a select). Reset at the start of each new clip pointerdown.
+ const didClipDragRef = useRef(false);
const [nav, setNav] = useState({ start: 0, end: 1 });
const [dragOver, setDragOver] = useState(false);
- const [placingSkip, setPlacingSkip] = useState(false);
const [snapPct, setSnapPct] = useState<number | null>(null);
+ // Live clip-reorder drag: the dragged clip follows the pointer directly
+ // (pointerDeltaX, no transition) while every clip between its origin and
+ // live target slides sideways by the dragged clip's own width+gap (with
+ // a CSS transition) to open a visible gap at the drop point — a manual
+ // FLIP-style reorder rather than a static insertion line.
+ const [clipDrag, setClipDrag] = useState<{
+ id: string;
+ from: number;
+ target: number;
+ pointerDeltaX: number;
+ shiftPx: number;
+ } | null>(null);
const [editClipTarget, setEditClipTarget] = useState<AxcutClip | null>(null);
const { settings, set: setSettings } = useEditorSettings();
- // Esc cancels the arm-place-skip tool (parity with the old Bottombar).
- useEffect(() => {
- if (!placingSkip) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") setPlacingSkip(false);
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [placingSkip]);
const [aspectMenuOpen, setAspectMenuOpen] = useState(false);
+ const [autoEnhanceOpen, setAutoEnhanceOpen] = useState(false);
+ const [autoBusy, setAutoBusy] = useState(false);
const clips = tl.clips;
const total = useMemo(
@@ -131,12 +142,16 @@ export function V4Timeline({
const showLanes = variant === "edit";
// ── region lanes ────────────────────────────────────────────────
+ // zoom/speed/annotation: one pill per row, never coalesced — each carries
+ // distinct per-instance content (depth/focus, speed value, text) that two
+ // touching-but-different regions must not silently merge into one.
const annPills: LanePill[] = tl.annotationRegions.map((a) => ({
id: a.id,
kind: "annotation",
start: a.startMs / 1000,
end: a.endMs / 1000,
label: "New annotation",
+ sourceIds: [a.id],
}));
const speedPills: LanePill[] = tl.speedRegions.map((s) => ({
id: s.id,
@@ -144,6 +159,7 @@ export function V4Timeline({
start: s.startMs / 1000,
end: s.endMs / 1000,
label: `${(s as { speed?: number }).speed ?? 1.5}×`,
+ sourceIds: [s.id],
}));
const zoomPills: LanePill[] = tl.zoomRegions.map((z) => ({
id: z.id,
@@ -151,20 +167,21 @@ export function V4Timeline({
start: z.startMs / 1000,
end: z.endMs / 1000,
label: `${(((z as { depth?: number }).depth ?? 3) / 2 + 0.5).toFixed(1)}×`,
+ sourceIds: [z.id],
+ }));
+ // trims: content-free (no per-instance text/settings), so touching rows —
+ // inevitable once a trim is ventilated across a clip boundary — are
+ // coalesced into one pill. This is what makes growing a trim across a
+ // junction look like one continuously-growing pill instead of visibly
+ // splitting, aligning trims with how zoom/speed/annotation already behave.
+ const trimPills: LanePill[] = coalescedTrimGroups(tl.trimRanges, clips).map((g) => ({
+ id: g.ids[0],
+ kind: "trim",
+ start: g.start,
+ end: g.end,
+ label: fmt(g.end - g.start),
+ sourceIds: g.ids,
}));
- const skipPills: LanePill[] = tl.skipRanges
- .map((sk): LanePill | null => {
- const mapped = skipToTimeline(sk, clips);
- if (!mapped) return null;
- return {
- id: sk.id,
- kind: "skip",
- start: mapped.start,
- end: mapped.end,
- label: fmt(mapped.end - mapped.start),
- };
- })
- .filter((p): p is LanePill => p !== null);
const rulerTicks = useMemo(() => {
const out: string[] = [];
@@ -184,8 +201,34 @@ export function V4Timeline({
[setCurrentTime, total],
);
+ // Mousedown anywhere on the empty timeline (ruler, lanes background, or
+ // the playhead diamond itself) seeks immediately AND arms a scrub drag —
+ // a single pointerdown→pointermove→pointerup replaces the old
+ // click-only seek, and doubles as the playhead's drag handle since
+ // dragging from its exact position is the same math as dragging from
+ // anywhere else. Also clears any region selection, closing the
+ // selected-element settings pane (FloatingInspector) the way clicking
+ // away from a selected element is expected to.
+ const startScrub = useCallback(
+ (e: ReactPointerEvent) => {
+ if (e.button !== 0) return;
+ const target = e.target as HTMLElement;
+ if (target.closest("[data-clip-id]") || target.closest(`.${styles.lanePill}`)) return;
+ tl.clearSelection();
+ seekToClientX(e.clientX);
+ const move = (ev: PointerEvent) => seekToClientX(ev.clientX);
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ },
+ [seekToClientX, tl],
+ );
+
// Drag a lane pill to move it (mode "move", keeps duration) or resize one
- // edge (mode "l"/"r"). Zoom/speed/annotation are timeline-ms; skips map
+ // edge (mode "l"/"r"). Zoom/speed/annotation are timeline-ms; trims map
// back to source-seconds through their carrying clip.
const startPillDrag = useCallback(
(e: ReactPointerEvent, pill: LanePill, dragMode: "move" | "l" | "r") => {
@@ -197,6 +240,14 @@ export function V4Timeline({
const r = el.getBoundingClientRect();
const startX = e.clientX;
const dur = pill.end - pill.start;
+ // A trim can span several clips; it's stored as one source-time entry per
+ // covered clip. `trimOwned` are the entry ids this drag controls — seeded
+ // from every row the grabbed (possibly already-coalesced) pill represents,
+ // then grows as the span reaches into more clips (fresh ids appended).
+ // `trimOwned` only grows; ids past the current fragment count are handed
+ // to `setTrimEntries` as `dropIds` so a shrinking span deletes the entries
+ // it no longer needs.
+ const trimOwned: string[] = [...pill.sourceIds];
// Snap targets: clip boundaries + timeline ends. Within ~1% of total,
// an edge snaps and a vertical guide is shown (Bottombar parity).
const snapTargets = [
@@ -227,14 +278,24 @@ export function V4Timeline({
else if (pill.kind === "annotation")
void tl.updateAnnotationSpan(pill.id, s * 1000, en * 1000);
else {
- const clip = clips.find((c) => {
- const se = c.sourceEndSec ?? c.sourceStartSec;
- return s >= c.timelineStartSec && s <= c.timelineStartSec + (se - c.sourceStartSec);
- });
- if (clip) {
- const toSrc = (t: number) => clip.sourceStartSec + (t - clip.timelineStartSec);
- void tl.updateSkipRange(pill.id, toSrc(s), toSrc(en));
+ // Trims are stored in source-time per asset but manipulated on the
+ // timeline like every other pill. Ventilate the new span across the
+ // clips it covers (one source range per clip) — the same primitive
+ // zoom/speed/annotation use on reorder, so trims can now be grown
+ // across a clip boundary just like a zoom.
+ let ranges = ventilateTimelineSpanToTrims(s, en, clips);
+ if (ranges.length === 0) {
+ // Span sits in a gap / past the end: fall back to the nearest clip.
+ const resolved = resolveTimelineSpanToTrim(s, en, clips);
+ if (!resolved) return;
+ ranges = [resolved];
}
+ // Grow the owned-id list to cover every fragment, keeping ids stable
+ // across frames; ids past the current fragment count are dropped.
+ while (trimOwned.length < ranges.length) trimOwned.push(createId("trim"));
+ const entries = ranges.map((rng, i) => ({ id: trimOwned[i], ...rng }));
+ const dropIds = trimOwned.slice(ranges.length);
+ void tl.setTrimEntries(entries, dropIds);
}
};
const move = (ev: PointerEvent) => {
@@ -291,6 +352,40 @@ export function V4Timeline({
[nav],
);
+ // Scroll = pan, Ctrl+scroll = zoom around the cursor's timeline position.
+ // Attached as a native (non-passive) listener rather than React's onWheel:
+ // React marks wheel handlers passive by default, so e.preventDefault()
+ // there silently no-ops and the browser/OS still intercepts Ctrl+wheel as
+ // a page-zoom gesture.
+ useEffect(() => {
+ const el = tracksRef.current;
+ if (!el) return;
+ const onWheelNative = (e: WheelEvent) => {
+ e.preventDefault();
+ const r = el.getBoundingClientRect();
+ const viewportPct = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
+ if (e.ctrlKey) {
+ setNav((prev) => {
+ const width = prev.end - prev.start;
+ const cursorFrac = prev.start + viewportPct * width;
+ const zoomFactor = e.deltaY > 0 ? 1.12 : 1 / 1.12;
+ const nextWidth = Math.min(1, Math.max(0.02, width * zoomFactor));
+ const start = Math.max(0, Math.min(1 - nextWidth, cursorFrac - viewportPct * nextWidth));
+ return { start, end: start + nextWidth };
+ });
+ } else {
+ setNav((prev) => {
+ const width = prev.end - prev.start;
+ const delta = (e.deltaY / r.width) * width;
+ const start = Math.max(0, Math.min(1 - width, prev.start + delta));
+ return { start, end: start + width };
+ });
+ }
+ };
+ el.addEventListener("wheel", onWheelNative, { passive: false });
+ return () => el.removeEventListener("wheel", onWheelNative);
+ }, []);
+
// zoom/pan: the tracks canvas is widened by 1/(navEnd-navStart) and shifted.
const navSpan = Math.max(0.02, nav.end - nav.start);
const canvasStyle = {
@@ -303,84 +398,318 @@ export function V4Timeline({
? styles.laneAnnotation
: kind === "speed"
? styles.laneSpeed
- : kind === "skip"
- ? styles.laneSkip
+ : kind === "trim"
+ ? styles.laneTrim
: styles.laneZoom;
const pillIcon = (kind: LanePill["kind"]) =>
kind === "annotation" ? (
<MessageSquare size={11} />
) : kind === "speed" ? (
<Clock size={11} />
- ) : kind === "skip" ? (
+ ) : kind === "trim" ? (
<Scissors size={11} />
) : (
<ZoomIn size={11} />
);
- // Place a 1s skip at the clicked timeline position, mapped to its clip's
- // source-time (Bottombar's arm-place-skip tool).
- const placeSkipAtClientX = useCallback(
- (clientX: number) => {
- const el = tracksRef.current;
- if (!el) return;
- const r = el.getBoundingClientRect();
- const t = Math.min(1, Math.max(0, (clientX - r.left) / r.width)) * total;
- const clip = clips.find((c) => t >= c.timelineStartSec && t <= c.timelineEndSec);
- if (!clip) return;
- const src = clip.sourceStartSec + (t - clip.timelineStartSec);
- const srcEnd = clip.sourceEndSec ?? clip.sourceStartSec;
- void tl.addSkipAt(clip.assetId, src, Math.min(srcEnd, src + 1));
- setPlacingSkip(false);
+ // Drag a clip left/right to reorder it relative to its neighbours. Pointer-
+ // driven (like the lane pills), not HTML5 DnD — that's reserved for dropping
+ // a *new* asset in from the media panel. A short move threshold keeps a
+ // plain click as "select" and a stationary press as "double-click to edit".
+ // On drop we hand the target index to tl.moveClip, which delegates to the
+ // same document/timeline.ts#moveClip the agent's "move_clip" tool uses.
+ const startClipDrag = useCallback(
+ (e: ReactPointerEvent, clip: AxcutClip) => {
+ if (e.button !== 0) return;
+ // Let the delete button (and any future in-clip control) handle its
+ // own pointer events instead of starting a drag.
+ if ((e.target as HTMLElement).closest("[data-no-clip-drag]")) return;
+ if (clips.length < 2) return;
+ const container = clipsRef.current;
+ const clipEl = (e.currentTarget as HTMLElement) ?? null;
+ if (!container || !clipEl) return;
+ const startX = e.clientX;
+ const from = clips.findIndex((c) => c.id === clip.id);
+ if (from < 0) return;
+ didClipDragRef.current = false;
+ let dragging = false;
+ // Width + gap the dragged clip displaces its neighbours by — measured
+ // once at drag start (only its position changes during the drag, not
+ // its size).
+ const gapPx = 6;
+ const shiftAmount = clipEl.getBoundingClientRect().width + gapPx;
+
+ // Boundaries are captured once, before any transform is applied —
+ // re-querying live rects mid-drag would pick up the dragged clip's own
+ // translated (pointer-following) position and corrupt the math, since
+ // its rect no longer reflects its untouched flex slot.
+ const originalRects = Array.from(
+ container.querySelectorAll<HTMLElement>("[data-clip-id]"),
+ ).map((el) => el.getBoundingClientRect());
+ const boundaries =
+ originalRects.length === 0
+ ? [0]
+ : [
+ originalRects[0].left,
+ ...originalRects.slice(1).map((r, i) => (originalRects[i].right + r.left) / 2),
+ originalRects[originalRects.length - 1].right,
+ ];
+ // Nearest clip boundary to `clientX`, as an insertion index into the
+ // *full* clip array (0..n).
+ const computeInsertFull = (clientX: number) => {
+ let bi = 0;
+ let bd = Number.POSITIVE_INFINITY;
+ for (let i = 0; i < boundaries.length; i++) {
+ const d = Math.abs(boundaries[i] - clientX);
+ if (d < bd) {
+ bd = d;
+ bi = i;
+ }
+ }
+ return bi;
+ };
+ // insertFull indexes the full array; moveClip (and our own preview
+ // math) target the array with the dragged clip already removed, so
+ // shift down by one when the drop point is to the right of its origin.
+ const computeTarget = (clientX: number) => {
+ const insertFull = computeInsertFull(clientX);
+ return insertFull > from ? insertFull - 1 : insertFull;
+ };
+
+ const move = (ev: PointerEvent) => {
+ if (!dragging && Math.abs(ev.clientX - startX) < 4) return;
+ dragging = true;
+ didClipDragRef.current = true;
+ const target = computeTarget(ev.clientX);
+ setClipDrag({
+ id: clip.id,
+ from,
+ target,
+ pointerDeltaX: ev.clientX - startX,
+ shiftPx: shiftAmount,
+ });
+ };
+ const up = async (ev: PointerEvent) => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ if (dragging) {
+ const target = computeTarget(ev.clientX);
+ // Keep the slid-open preview on screen through the async save so
+ // there's no one-frame snap-back to the original order before the
+ // store's new order lands.
+ if (target !== from) await tl.moveClip(clip.id, target);
+ }
+ setClipDrag(null);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
},
- [tl, total, clips],
+ [clips, tl],
);
- const tools: Array<{ id: ToolId; label: string; icon: React.ReactNode; on?: boolean }> = [
- { id: "select", label: "Select", icon: <MousePointer2 size={15} />, on: !placingSkip },
- {
- id: "cut",
- label: "Place skip (click the timeline)",
- icon: <SplitSquareHorizontal size={15} />,
- on: placingSkip,
- },
+ const tools: Array<{ id: ToolId; label: string; icon: React.ReactNode }> = [
+ { id: "cut", label: "Add trim at playhead", icon: <SplitSquareHorizontal size={15} /> },
{ id: "comment", label: "Comment", icon: <MessageSquare size={15} /> },
{ id: "speed", label: "Speed", icon: <Clock size={15} /> },
- { id: "enhance", label: "Auto-enhance", icon: <Sparkles size={15} /> },
];
+ // Auto-enhance option 1 — the deterministic cursor-telemetry auto-zoom
+ // (ported from main; NOT AI). Reads the recorded cursor movement for the
+ // primary asset and drops zoom-ins on the dwell moments.
+ const runAutoZooms = useCallback(async () => {
+ setAutoEnhanceOpen(false);
+ const source = videoSources[0];
+ const asset = tl.assets.find((a) => a.id === source?.id) ?? tl.assets[0];
+ if (!source || !asset) {
+ toast.error("Import a recording first");
+ return;
+ }
+ setAutoBusy(true);
+ try {
+ const telemetry =
+ (await nativeBridgeClient.cursor.getTelemetry(fromFileUrl(source.src))) ?? [];
+ const suggestions = buildAutoZoomSuggestions({
+ cursorTelemetry: telemetry,
+ totalMs: (asset.durationSec ?? 0) * 1000,
+ existingRegions: tl.zoomRegions.map((z) => ({ startMs: z.startMs, endMs: z.endMs })),
+ defaultDurationMs: 2000,
+ });
+ if (suggestions.length === 0) {
+ toast.info("No auto-zoom moments found", {
+ description:
+ "This recording has no cursor movement data, or existing zooms already cover the busy moments.",
+ });
+ return;
+ }
+ const added = await tl.addZoomsBulk(suggestions);
+ toast.success(`Added ${added} automatic zoom${added === 1 ? "" : "s"}`);
+ } catch (err) {
+ toast.error("Auto-zoom failed", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ setAutoBusy(false);
+ }
+ }, [videoSources, tl]);
+
+ // Auto-enhance option 2 — hand a generic prompt to the AI agent (smart
+ // zooms + cuts) via the chat prompt-bus.
+ const runAiEnhance = useCallback(() => {
+ setAutoEnhanceOpen(false);
+ useChatPromptBus.getState().submit(AI_ENHANCE_PROMPT);
+ toast.success("Asked the AI agent to enhance this recording");
+ }, []);
+
const isPillSelected = (id: string) =>
tl.selection?.id === id || tl.multiSelection.some((m) => m.id === id);
- const renderPills = (pills: LanePill[], emptyLabel: string) => (
- <>
- {pills.length === 0 ? <span className={styles.laneEmpty}>{emptyLabel}</span> : null}
- {pills.map((p) => (
- <div
- // biome-ignore lint/a11y/useKeyWithClickEvents: pointer-driven region drag/resize
- // biome-ignore lint/a11y/noStaticElementInteractions: lane pill is a draggable region control
- key={p.id}
- role="button"
- tabIndex={0}
- className={`${styles.lanePill} ${laneOf(p.kind)}${
- isPillSelected(p.id) ? ` ${styles.lanePillSel}` : ""
- }`}
- style={{ left: `${pctOf(p.start)}%`, width: `${Math.max(1.5, pctOf(p.end - p.start))}%` }}
- onPointerDown={(e) => startPillDrag(e, p, "move")}
- title={p.label}
- >
+ // Optimistic preview: during a clip-reorder drag, slide each region pill by
+ // the same amount as the clip it sits on — mirroring the clip transforms so
+ // zoom/speed/annotation/trim pills travel with their content in real time,
+ // then land exactly where the reprojection (document/timeline.ts#moveClip)
+ // puts them on drop. Returns px shift + whether it should track immediately
+ // (the region on the dragged clip follows the pointer with no easing).
+ const regionPreviewShift = (startSec: number): { px: number; immediate: boolean } => {
+ if (!clipDrag) return { px: 0, immediate: false };
+ const idx = clips.findIndex(
+ (c) => startSec >= c.timelineStartSec && startSec < c.timelineEndSec,
+ );
+ if (idx < 0) return { px: 0, immediate: false };
+ const { from, target, pointerDeltaX, shiftPx } = clipDrag;
+ if (idx === from) return { px: pointerDeltaX, immediate: true };
+ if (target > from && idx > from && idx <= target) return { px: -shiftPx, immediate: false };
+ if (target < from && idx >= target && idx < from) return { px: shiftPx, immediate: false };
+ return { px: 0, immediate: false };
+ };
+
+ // One rendered pill box — either the whole region (normal case) or one
+ // fragment of a region being eagerly split-previewed across a clip-drag
+ // junction (see renderPills below). Fragments are inert previews (no
+ // handles/selection/content beyond the leading one) with the touching inner
+ // edge de-styled so a split pill still reads as one continuous shape.
+ const renderOnePill = (seg: {
+ pill: LanePill;
+ key: string;
+ segStart: number;
+ segEnd: number;
+ shiftPx: number;
+ immediate: boolean;
+ showContent: boolean;
+ interactive: boolean;
+ suppressLeftSeam: boolean;
+ suppressRightSeam: boolean;
+ }) => {
+ const { pill: p } = seg;
+ return (
+ <div
+ key={seg.key}
+ role={seg.interactive ? "button" : undefined}
+ tabIndex={seg.interactive ? 0 : undefined}
+ className={`${styles.lanePill} ${laneOf(p.kind)}${
+ seg.interactive && isPillSelected(p.id) ? ` ${styles.lanePillSel}` : ""
+ }`}
+ style={{
+ left: `${pctOf(seg.segStart)}%`,
+ width: `${Math.max(1.5, pctOf(seg.segEnd - seg.segStart))}%`,
+ transform: seg.shiftPx ? `translateX(${seg.shiftPx}px)` : undefined,
+ transition: !clipDrag
+ ? undefined
+ : seg.immediate
+ ? "none"
+ : "transform 150ms cubic-bezier(0.2, 0, 0, 1)",
+ ...(seg.suppressLeftSeam
+ ? { borderTopLeftRadius: 0, borderBottomLeftRadius: 0, borderLeftWidth: 0 }
+ : {}),
+ ...(seg.suppressRightSeam
+ ? { borderTopRightRadius: 0, borderBottomRightRadius: 0, borderRightWidth: 0 }
+ : {}),
+ }}
+ onPointerDown={seg.interactive ? (e) => startPillDrag(e, p, "move") : undefined}
+ title={p.label}
+ >
+ {seg.interactive ? (
<span
className={styles.lanePillHandle}
style={{ left: 0 }}
onPointerDown={(e) => startPillDrag(e, p, "l")}
/>
- {pillIcon(p.kind)}
- <span className={styles.lanePillLabel}>{p.label}</span>
+ ) : null}
+ {seg.showContent ? (
+ <>
+ {pillIcon(p.kind)}
+ <span className={styles.lanePillLabel}>{p.label}</span>
+ </>
+ ) : null}
+ {seg.interactive ? (
<span
className={styles.lanePillHandle}
style={{ right: 0 }}
onPointerDown={(e) => startPillDrag(e, p, "r")}
/>
- </div>
- ))}
+ ) : null}
+ </div>
+ );
+ };
+
+ const renderPills = (pills: LanePill[], emptyLabel: string) => (
+ <>
+ {pills.length === 0 ? <span className={styles.laneEmpty}>{emptyLabel}</span> : null}
+ {pills.flatMap((p) => {
+ // Eager split preview: the instant a clip is grabbed, a pill that
+ // straddles the dragged clip's junction shows the same per-clip
+ // split it would resolve to on drop (via moveClip's reprojection),
+ // instead of moving as one block glued to whichever clip owns its
+ // start. Only fork into fragments when they'd actually move
+ // differently — a pill unaffected by this drag stays one DOM node.
+ if (clipDrag) {
+ const frags = ventilateSpanAcrossClips(p.start, p.end, clips);
+ if (frags.length >= 2) {
+ const clipById = new Map(clips.map((c) => [c.id, c]));
+ const shifts = frags.map((f) => {
+ const c = clipById.get(f.clipId);
+ return c
+ ? regionPreviewShift(c.timelineStartSec + f.localStartSec)
+ : { px: 0, immediate: false };
+ });
+ const first = shifts[0];
+ const differ = shifts.some((s) => s.px !== first.px || s.immediate !== first.immediate);
+ if (differ) {
+ return frags.flatMap((f, i) => {
+ const c = clipById.get(f.clipId);
+ if (!c) return [];
+ return [
+ renderOnePill({
+ pill: p,
+ key: `${p.id}__f${i}`,
+ segStart: c.timelineStartSec + f.localStartSec,
+ segEnd: c.timelineStartSec + f.localEndSec,
+ shiftPx: shifts[i].px,
+ immediate: shifts[i].immediate,
+ showContent: i === 0,
+ interactive: false,
+ suppressLeftSeam: i > 0,
+ suppressRightSeam: i < frags.length - 1,
+ }),
+ ];
+ });
+ }
+ }
+ }
+ const shift = regionPreviewShift(p.start);
+ return [
+ renderOnePill({
+ pill: p,
+ key: p.id,
+ segStart: p.start,
+ segEnd: p.end,
+ shiftPx: shift.px,
+ immediate: shift.immediate,
+ showContent: true,
+ interactive: true,
+ suppressLeftSeam: false,
+ suppressRightSeam: false,
+ }),
+ ];
+ })}
</>
);
@@ -389,17 +718,63 @@ export function V4Timeline({
<div className={styles.tlToolbar}>
{showLanes ? (
<div className={styles.tlTools} role="toolbar" aria-label="Timeline tools">
+ <Popover open={autoEnhanceOpen} onOpenChange={setAutoEnhanceOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={styles.tlToolBtn}
+ title="Auto-enhance"
+ aria-label="Auto-enhance"
+ disabled={autoBusy}
+ >
+ {autoBusy ? <Loader2 className="animate-spin" size={15} /> : <Wand2 size={15} />}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ sideOffset={6}
+ animated={false}
+ className="w-auto border-0 bg-transparent p-0 shadow-none"
+ >
+ <div
+ className={styles.recMenu}
+ style={{ position: "relative", bottom: "auto", width: 244 }}
+ >
+ <button
+ type="button"
+ className={styles.recMenuRow}
+ onClick={() => void runAutoZooms()}
+ >
+ <ZoomIn size={15} style={{ flexShrink: 0 }} />
+ <span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
+ <span style={{ fontWeight: 600 }}>Automatic zooms</span>
+ <span style={{ fontSize: 11, color: "var(--muted)" }}>
+ From recorded cursor movement
+ </span>
+ </span>
+ </button>
+ <button type="button" className={styles.recMenuRow} onClick={runAiEnhance}>
+ <Sparkles size={15} style={{ flexShrink: 0 }} />
+ <span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
+ <span style={{ fontWeight: 600 }}>Smart zooms + cuts</span>
+ <span style={{ fontSize: 11, color: "var(--muted)" }}>With AI</span>
+ </span>
+ </button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ <span className={styles.tlToolSep} aria-hidden />
{tools.map((t) => (
<button
type="button"
key={t.id}
- className={`${styles.tlToolBtn}${t.on ? ` ${styles.on}` : ""}`}
+ className={styles.tlToolBtn}
title={t.label}
aria-label={t.label}
onClick={() => {
if (t.id === "speed") void tl.addSpeed();
if (t.id === "comment") void tl.addAnnotation();
- if (t.id === "cut") setPlacingSkip((v) => !v);
+ if (t.id === "cut") void tl.addTrim();
}}
>
{t.icon}
@@ -476,23 +851,21 @@ export function V4Timeline({
</div>
</div>
- <div
- ref={tracksRef}
- className={styles.tlTracks}
- style={placingSkip ? { cursor: "crosshair" } : undefined}
- // biome-ignore lint/a11y/useKeyWithClickEvents: ruler scrubbing is pointer-only
- onClick={(e) => {
- if (placingSkip) placeSkipAtClientX(e.clientX);
- else seekToClientX(e.clientX);
- }}
- >
+ <div ref={tracksRef} className={styles.tlTracks} onPointerDown={startScrub}>
<div className={styles.tlCanvas} style={canvasStyle}>
<div
aria-hidden
className={styles.tlPlayhead}
style={{ left: `${pctOf(currentTimeSec)}%` }}
>
- <span className={styles.tlPlayheadDiamond} />
+ <span
+ className={styles.tlPlayheadDiamond}
+ style={{ pointerEvents: "auto", cursor: "grab" }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ startScrub(e);
+ }}
+ />
</div>
{snapPct !== null ? (
<div aria-hidden className={styles.tlSnapGuide} style={{ left: `${snapPct}%` }} />
@@ -508,12 +881,13 @@ export function V4Timeline({
<>
<div className={styles.tlLane}>{renderPills(annPills, "No annotations yet")}</div>
<div className={styles.tlLane}>{renderPills(speedPills, "Constant speed")}</div>
- <div className={styles.tlLane}>{renderPills(skipPills, "No skips")}</div>
+ <div className={styles.tlLane}>{renderPills(trimPills, "No trims")}</div>
<div className={styles.tlLane}>{renderPills(zoomPills, "")}</div>
</>
) : null}
<div
+ ref={clipsRef}
className={`${styles.tlClips}${dragOver ? ` ${styles.tlClipsDrag}` : ""}`}
onDragOver={(e) => {
e.preventDefault();
@@ -532,21 +906,46 @@ export function V4Timeline({
const dur = c.timelineEndSec - c.timelineStartSec;
const bars = waveformFor(i + 1, Math.max(12, Math.round(dur * 0.6)));
const selected = tl.clipSelection === c.id;
+ const dragging = clipDrag?.id === c.id;
+ // Siblings between the dragged clip's origin and its live
+ // target slide sideways (via the base .tlClip transition) to
+ // open a gap at the drop point; the dragged clip itself
+ // follows the pointer directly (see .tlClipDragging's
+ // transition:none override).
+ let clipTransform: string | undefined;
+ if (dragging) {
+ clipTransform = `translateX(${clipDrag.pointerDeltaX}px)`;
+ } else if (clipDrag) {
+ const { from, target, shiftPx } = clipDrag;
+ if (target > from && i > from && i <= target)
+ clipTransform = `translateX(${-shiftPx}px)`;
+ else if (target < from && i >= target && i < from)
+ clipTransform = `translateX(${shiftPx}px)`;
+ }
return (
- // biome-ignore lint/a11y/useKeyWithClickEvents: clip selection is pointer-driven
<div
key={c.id}
- className={`${styles.tlClip}${selected ? ` ${styles.tlClipSel}` : ""}`}
- style={{ flex: `${dur} 0 0` }}
+ data-clip-id={c.id}
+ className={`${styles.tlClip}${selected ? ` ${styles.tlClipSel}` : ""}${
+ dragging ? ` ${styles.tlClipDragging}` : ""
+ }`}
+ style={{ flex: `${dur} 0 0`, transform: clipTransform }}
+ onPointerDown={(e) => startClipDrag(e, c)}
onClick={(e) => {
e.stopPropagation();
+ // A completed reorder-drag also fires a click; don't let it
+ // double as a selection.
+ if (didClipDragRef.current) {
+ didClipDragRef.current = false;
+ return;
+ }
tl.selectClip(c.id);
}}
onDoubleClick={(e) => {
e.stopPropagation();
setEditClipTarget(c);
}}
- title="Double-click to edit in/out points"
+ title="Drag to reorder · double-click to edit in/out points"
>
<div aria-hidden className={styles.tlWave}>
{bars.map((h, bi) => (
@@ -560,8 +959,16 @@ export function V4Timeline({
))}
</div>
<div className={styles.tlClipLabel}>
- <span className={styles.tlClipIcon}>
- <Scissors size={9} />
+ <span
+ className={styles.tlClipIcon}
+ data-no-clip-drag
+ title="Edit in/out points"
+ onClick={(e) => {
+ e.stopPropagation();
+ setEditClipTarget(c);
+ }}
+ >
+ <Pencil size={9} />
</span>
<span className={styles.tlClipName}>
{tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}
@@ -570,6 +977,7 @@ export function V4Timeline({
{selected ? (
<button
type="button"
+ data-no-clip-drag
className={styles.tlClipDelete}
title="Delete clip"
aria-label="Delete clip"
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index e0ca56a8b..f2be91d1d 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -110,6 +110,27 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const [systemAudioEnabled, setSystemAudioEnabled] = useState(false);
const [webcamEnabled, setWebcamEnabledState] = useState(false);
const [cursorCaptureMode, setCursorCaptureMode] = useState<CursorCaptureMode>("editable-overlay");
+
+ // Seed from the main-process recording-prefs SSOT on mount, so choices
+ // made in the editor's Rec-mode stage (a different renderer window) carry
+ // over instead of this hook silently reverting to its own hardcoded
+ // defaults every time startNewRecording() switches to the HUD window.
+ useEffect(() => {
+ let cancelled = false;
+ void window.electronAPI?.getRecordingPrefs?.().then((prefs) => {
+ if (cancelled || !prefs) return;
+ setMicrophoneEnabled(prefs.micEnabled);
+ if (prefs.micDeviceId) setMicrophoneDeviceId(prefs.micDeviceId);
+ setWebcamEnabledState(prefs.camEnabled);
+ if (prefs.camDeviceId) setWebcamDeviceId(prefs.camDeviceId);
+ setSystemAudioEnabled(prefs.systemAudioEnabled);
+ setCursorCaptureMode(prefs.cursorCaptureMode);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
const screenRecorder = useRef<RecorderHandle | null>(null);
const webcamRecorder = useRef<RecorderHandle | null>(null);
const nativeWindowsRecording = useRef<NativeWindowsRecordingHandle | null>(null);
diff --git a/src/lib/ai-edition/document/migrate.test.ts b/src/lib/ai-edition/document/migrate.test.ts
index 39f893747..9073eaa0e 100644
--- a/src/lib/ai-edition/document/migrate.test.ts
+++ b/src/lib/ai-edition/document/migrate.test.ts
@@ -57,7 +57,7 @@ describe("migrateProjectDataToAxcutDocument", () => {
expect(clip.sourceEndSec).toBeUndefined();
});
- it("converts trimRegions to skipRanges on the primary asset (1.5s cut)", () => {
+ it("converts trimRegions to trimRanges on the primary asset (1.5s cut)", () => {
const doc = migrateProjectDataToAxcutDocument(
makeV2Project({
editor: {
@@ -67,8 +67,8 @@ describe("migrateProjectDataToAxcutDocument", () => {
}),
);
- expect(doc.timeline.skipRanges).toHaveLength(1);
- const skip = doc.timeline.skipRanges[0];
+ expect(doc.timeline.trimRanges).toHaveLength(1);
+ const skip = doc.timeline.trimRanges[0];
expect(skip.assetId).toBe(doc.assets[0].id);
expect(skip.startSec).toBeCloseTo(1.0, 3);
expect(skip.endSec).toBeCloseTo(2.5, 3);
@@ -213,7 +213,7 @@ describe("migrateProjectDataToAxcutDocument", () => {
});
describe("migrateAxcutDocumentToProjectData", () => {
- it("round-trips skipRanges back to trimRegions", () => {
+ it("round-trips trimRanges back to trimRegions", () => {
const v2 = makeV2Project({
editor: {
...makeV2Project().editor,
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 3bfb37073..8386ef9ca 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -26,7 +26,7 @@ import {
type AxcutAnnotationRegion,
type AxcutDocument,
type AxcutLegacyEditor,
- type AxcutSkipRange,
+ type AxcutTrimRange,
type AxcutZoomRegion,
axcutSchemaVersion,
documentSchema,
@@ -67,7 +67,7 @@ function toLegacyMedia(input: ProjectMedia | undefined): ProjectMedia | null {
/**
* Migrate a v2 EditorProjectData into a v3 AxcutDocument. The single recording
* becomes one asset + one clip spanning the source. trimRegions become
- * skipRanges on that asset (semantically identical: both are cuts).
+ * trimRanges on that asset (semantically identical: both are cuts).
*/
export function migrateProjectDataToAxcutDocument(
input: EditorProjectData,
@@ -129,14 +129,14 @@ export function migrateProjectDataToAxcutDocument(
}
: null;
- const skipRanges: AxcutSkipRange[] = primaryAssetId
+ const trimRanges: AxcutTrimRange[] = primaryAssetId
? trimRegions
.filter((region) => region && typeof region.id === "string")
.map((region) => {
const startMs = Math.max(0, Math.min(region.startMs ?? 0, region.endMs ?? 0));
const endMs = Math.max(startMs + 1, region.endMs ?? startMs + 1);
return {
- id: createId("skip"),
+ id: createId("trim"),
assetId: primaryAssetId,
startSec: clampSec(msToSec(startMs)),
endSec: clampSec(msToSec(endMs)),
@@ -157,7 +157,7 @@ export function migrateProjectDataToAxcutDocument(
// ponytail: annotations[] and zoomRanges[] mirror editor.annotationRegions
// and editor.zoomRegions directly (same ms units) so the renderer can swap
- // them in/out without conversion. The timeline (skipRanges, speedRanges,
+ // them in/out without conversion. The timeline (trimRanges, speedRanges,
// clip) uses axcut's seconds because the new timeline ops land there.
const migratedZoomRanges: AxcutZoomRegion[] = zoomRegions
.filter((region) => region && typeof region.id === "string")
@@ -214,7 +214,7 @@ export function migrateProjectDataToAxcutDocument(
timeline: {
clips: clip ? [clip] : [],
gaps: [],
- skipRanges,
+ trimRanges,
muteRanges: [],
speedRanges,
captionRanges: [],
@@ -238,7 +238,7 @@ export function migrateProjectDataToAxcutDocument(
/**
* Migrate a v3 AxcutDocument back to a v2 EditorProjectData. Used when the
* user toggles AI-edition off after a project was opened as v3. Round-trip is
- * not perfectly lossless — skipRanges map back to trimRegions (1:1), but the
+ * not perfectly lossless — trimRanges map back to trimRegions (1:1), but the
* timeline rebuild for clip ranges is best-effort and the speed regions remain
* in the legacyEditor envelope where the migration put them.
*/
@@ -259,7 +259,7 @@ export function migrateAxcutDocumentToProjectData(input: AxcutDocument): EditorP
})
: null;
- const trimRegions: TrimRegion[] = (document.timeline?.skipRanges ?? []).map((region, index) => ({
+ const trimRegions: TrimRegion[] = (document.timeline?.trimRanges ?? []).map((region, index) => ({
id: region.id ?? `trim-${index + 1}`,
startMs: secToMs(clampSec(region.startSec ?? 0)),
endMs: secToMs(Math.max(clampSec(region.startSec ?? 0) + 0.001, clampSec(region.endSec ?? 0))),
diff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.ts
index 6d596ef6a..693521e52 100644
--- a/src/lib/ai-edition/document/operations.test.ts
+++ b/src/lib/ai-edition/document/operations.test.ts
@@ -40,16 +40,16 @@ function makeDoc(): AxcutDocument {
};
}
-describe("applyTimelineOperation.add_skip_range", () => {
+describe("applyTimelineOperation.add_trim_range", () => {
it("appends a user-origin skip and returns a one-line summary", () => {
const result = applyTimelineOperation(makeDoc(), {
- type: "add_skip_range",
+ type: "add_trim_range",
startSec: 5,
endSec: 8,
});
- expect(result.summary).toMatch(/added skip 0:05\.0.0:08\.0/);
+ expect(result.summary).toMatch(/added trim 0:05\.0.0:08\.0/);
const next = result.document;
- const skips = next.timeline.skipRanges.filter((s) => s.assetId === "asset_1");
+ const skips = next.timeline.trimRanges.filter((s) => s.assetId === "asset_1");
expect(skips).toHaveLength(1);
expect(skips[0]).toMatchObject({
startSec: 5,
@@ -61,11 +61,11 @@ describe("applyTimelineOperation.add_skip_range", () => {
it("normalises reversed bounds (end < start)", () => {
const result = applyTimelineOperation(makeDoc(), {
- type: "add_skip_range",
+ type: "add_trim_range",
startSec: 10,
endSec: 4,
});
- const skip = result.document.timeline.skipRanges.find((s) => s.assetId === "asset_1");
+ const skip = result.document.timeline.trimRanges.find((s) => s.assetId === "asset_1");
expect(skip?.startSec).toBe(4);
expect(skip?.endSec).toBe(10);
});
@@ -111,7 +111,7 @@ describe("applyTimelineOperation.replace_timeline", () => {
describe("applyTimelineOperation.restore_full_timeline", () => {
it("drops every skip and restores a single full clip", () => {
const doc = applyTimelineOperation(makeDoc(), {
- type: "add_skip_range",
+ type: "add_trim_range",
startSec: 5,
endSec: 10,
}).document;
@@ -123,7 +123,7 @@ describe("applyTimelineOperation.restore_full_timeline", () => {
.filter((c) => c.assetId === "asset_1")
.reduce((s, c) => s + (c.sourceEndSec - c.sourceStartSec), 0);
expect(totalClip).toBe(60);
- expect(restored.document.timeline.skipRanges).toHaveLength(0);
+ expect(restored.document.timeline.trimRanges).toHaveLength(0);
});
});
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
index 76cb0d5d0..bbb30c5d1 100644
--- a/src/lib/ai-edition/document/operations.ts
+++ b/src/lib/ai-edition/document/operations.ts
@@ -33,22 +33,22 @@ export type AxcutTimelineOperation =
reason?: string;
}
| {
- type: "add_skip_range";
+ type: "add_trim_range";
assetId?: string;
startSec: number;
endSec: number;
reason?: string;
}
| {
- type: "update_skip_range";
- skipId: string;
+ type: "update_trim_range";
+ trimId: string;
startSec: number;
endSec: number;
reason?: string;
}
| {
- type: "remove_skip_range";
- skipId: string;
+ type: "remove_trim_range";
+ trimId: string;
reason?: string;
}
| {
@@ -173,16 +173,16 @@ export function applyTimelineOperation(
summary: `dropped ${formatSec(op.startSec)}–${formatSec(op.endSec)}`,
};
}
- case "add_skip_range": {
+ case "add_trim_range": {
const assetId = pickAssetId(document, op.assetId);
- if (!assetId) return { document, summary: "no asset to skip" };
+ if (!assetId) return { document, summary: "no asset to trim" };
const lo = Math.max(0, Math.min(op.startSec, op.endSec));
const hi = Math.max(lo, Math.max(op.startSec, op.endSec));
- const existing = document.timeline.skipRanges.filter((s) => s.assetId === assetId);
- // ponytail: bound by the skip-range asset's duration, not the
+ const existing = document.timeline.trimRanges.filter((s) => s.assetId === assetId);
+ // ponytail: bound by the trim-range asset's duration, not the
// primary asset's. Recording projects can have a short primary
// asset (snippet) while the clip uses a long video — using
- // primaryAssetDuration here would truncate the skip range and
+ // primaryAssetDuration here would truncate the trim range and
// only trim a few words instead of the user's full selection.
const asset = document.assets.find((a) => a.id === assetId);
const duration = asset?.durationSec ?? Infinity;
@@ -194,8 +194,8 @@ export function applyTimelineOperation(
...document,
timeline: {
...document.timeline,
- skipRanges: merged.map((iv, i) => ({
- id: `skip_${i + 1}`,
+ trimRanges: merged.map((iv, i) => ({
+ id: `trim_${i + 1}`,
assetId,
startSec: iv.startSec,
endSec: iv.endSec,
@@ -207,10 +207,10 @@ export function applyTimelineOperation(
};
return {
document: next,
- summary: `added skip ${formatSec(lo)}–${formatSec(hi)}`,
+ summary: `added trim ${formatSec(lo)}–${formatSec(hi)}`,
};
}
- case "update_skip_range": {
+ case "update_trim_range": {
const lo = Math.max(0, Math.min(op.startSec, op.endSec));
const hi = Math.max(lo, Math.max(op.startSec, op.endSec));
let found = false;
@@ -218,32 +218,32 @@ export function applyTimelineOperation(
...document,
timeline: {
...document.timeline,
- skipRanges: document.timeline.skipRanges.map((s) => {
- if (s.id !== op.skipId) return s;
+ trimRanges: document.timeline.trimRanges.map((s) => {
+ if (s.id !== op.trimId) return s;
found = true;
return { ...s, startSec: lo, endSec: hi, reason: op.reason ?? s.reason };
}),
},
preview: { ...document.preview, revision: document.preview.revision + 1 },
};
- if (!found) return { document, summary: `unknown skip ${op.skipId}` };
+ if (!found) return { document, summary: `unknown trim ${op.trimId}` };
return {
document: next,
- summary: `updated skip ${op.skipId} to ${formatSec(lo)}–${formatSec(hi)}`,
+ summary: `updated trim ${op.trimId} to ${formatSec(lo)}–${formatSec(hi)}`,
};
}
- case "remove_skip_range": {
+ case "remove_trim_range": {
const next: AxcutDocument = {
...document,
timeline: {
...document.timeline,
- skipRanges: document.timeline.skipRanges.filter((s) => s.id !== op.skipId),
+ trimRanges: document.timeline.trimRanges.filter((s) => s.id !== op.trimId),
},
preview: { ...document.preview, revision: document.preview.revision + 1 },
};
return {
document: next,
- summary: `removed skip ${op.skipId}`,
+ summary: `removed trim ${op.trimId}`,
};
}
case "restore_full_timeline": {
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index 2c180d812..8decce826 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -37,7 +37,7 @@ function makeDoc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -147,7 +147,7 @@ describe("timeline pure functions", () => {
});
describe("replaceTimeline", () => {
- it("rebuilds clips and derives skipRanges from the inverse", () => {
+ it("rebuilds clips and derives trimRanges from the inverse", () => {
const doc = makeDoc();
const updated = replaceTimeline(
doc,
@@ -158,8 +158,8 @@ describe("timeline pure functions", () => {
"test cut",
);
expect(updated.timeline.clips).toHaveLength(2);
- expect(updated.timeline.skipRanges).toHaveLength(1);
- expect(updated.timeline.skipRanges[0]).toMatchObject({
+ expect(updated.timeline.trimRanges).toHaveLength(1);
+ expect(updated.timeline.trimRanges[0]).toMatchObject({
startSec: 20,
endSec: 30,
});
@@ -181,7 +181,7 @@ describe("timeline pure functions", () => {
timeline: {
clips: [],
gaps: [],
- skipRanges: [
+ trimRanges: [
{ id: "s1", assetId: "asset_1", startSec: 10, endSec: 20, origin: "user", reason: "" },
],
muteRanges: [],
@@ -195,7 +195,7 @@ describe("timeline pure functions", () => {
sourceStartSec: 0,
sourceEndSec: 60,
});
- expect(restored.timeline.skipRanges).toHaveLength(0);
+ expect(restored.timeline.trimRanges).toHaveLength(0);
});
});
@@ -220,7 +220,7 @@ describe("timeline pure functions", () => {
},
],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -295,4 +295,79 @@ describe("duplicateClip / moveClip", () => {
expect(() => duplicateClip(doc, "missing")).toThrow();
expect(() => moveClip(doc, "missing", 0)).toThrow();
});
+
+ it("carries zoom/annotation/speed regions along with the clip they sit on", () => {
+ // clip_a tl 0-10, clip_b tl 10-20. A zoom (tl 12-14), an annotation
+ // (tl 15-16) and a speed region (tl 11-13) all sit over clip_b.
+ const doc = makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({ id: "clip_a", timelineStartSec: 0, timelineEndSec: 10 }),
+ makeClip({
+ id: "clip_b",
+ sourceStartSec: 20,
+ sourceEndSec: 30,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ }),
+ ],
+ },
+ zoomRanges: [
+ { id: "z1", startMs: 12000, endMs: 14000, depth: 3, focus: { cx: 0.5, cy: 0.5 } },
+ ],
+ annotations: [
+ {
+ id: "a1",
+ startMs: 15000,
+ endMs: 16000,
+ type: "text",
+ content: "hi",
+ position: { x: 50, y: 50 },
+ size: { width: 30, height: 20 },
+ style: {
+ color: "#fff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ textAnimation: "none",
+ },
+ zIndex: 1,
+ },
+ ] as unknown as AxcutDocument["annotations"],
+ legacyEditor: { speedRegions: [{ id: "s1", startMs: 11000, endMs: 13000, speed: 1.5 }] },
+ });
+ // Move clip_b to the front → clip_b now tl 0-10 (delta -10s). Regions
+ // over clip_b shift by -10s; the zoom now sits at tl 2-4, etc.
+ const next = moveClip(doc, "clip_b", 0);
+ expect(next.timeline.clips.map((c) => c.id)).toEqual(["clip_b", "clip_a"]);
+ expect(next.zoomRanges[0]).toMatchObject({ startMs: 2000, endMs: 4000 });
+ expect(next.annotations[0]).toMatchObject({ startMs: 5000, endMs: 6000 });
+ const speed = (next.legacyEditor as { speedRegions: Array<{ startMs: number; endMs: number }> })
+ .speedRegions[0];
+ expect(speed).toMatchObject({ startMs: 1000, endMs: 3000 });
+ });
+
+ it("leaves regions over a clip that did not move untouched", () => {
+ const doc = makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({ id: "clip_a", timelineStartSec: 0, timelineEndSec: 10 }),
+ makeClip({ id: "clip_b", timelineStartSec: 10, timelineEndSec: 20 }),
+ makeClip({ id: "clip_c", timelineStartSec: 20, timelineEndSec: 30 }),
+ ],
+ },
+ zoomRanges: [{ id: "z1", startMs: 3000, endMs: 5000, depth: 3, focus: { cx: 0.5, cy: 0.5 } }],
+ });
+ // Swapping clip_b and clip_c leaves clip_a (tl 0-10) put, so a zoom over
+ // clip_a stays exactly where it was.
+ const next = moveClip(doc, "clip_c", 1);
+ expect(next.timeline.clips.map((c) => c.id)).toEqual(["clip_a", "clip_c", "clip_b"]);
+ expect(next.zoomRanges[0]).toMatchObject({ startMs: 3000, endMs: 5000 });
+ });
});
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index d85d61dda..d63c31847 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -1,9 +1,10 @@
// Ported from axcut/apps/server/src/lib/timeline.ts — pure interval math
-// for the clip/skip model. No DOM, no IPC, no side effects. The caller
+// for the clip/trim model. No DOM, no IPC, no side effects. The caller
// (store, exporter, agent) feeds an AxcutDocument and gets back intervals
// or a new document with updated clips.
import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
+import { reprojectRegionsForReorder } from "../timeline/region-ventilation";
import { createId } from "./ids";
export function byStart(a: { startSec: number }, b: { startSec: number }): number {
@@ -158,8 +159,8 @@ export function replaceTimeline(
reason,
transcript: document.transcript,
});
- const skipRanges = invertIntervals(normalized, duration).map((cut, i) => ({
- id: `skip_${i + 1}`,
+ const trimRanges = invertIntervals(normalized, duration).map((cut, i) => ({
+ id: `trim_${i + 1}`,
assetId,
startSec: cut.startSec,
endSec: cut.endSec,
@@ -171,7 +172,7 @@ export function replaceTimeline(
timeline: {
...document.timeline,
clips,
- skipRanges,
+ trimRanges,
gaps: [],
},
preview: {
@@ -205,11 +206,37 @@ export function moveClip(
const remaining = document.timeline.clips.filter((c) => c.id !== clipId);
const bounded = Math.max(0, Math.min(insertIndex, remaining.length));
const reordered = [...remaining.slice(0, bounded), movingClip, ...remaining.slice(bounded)];
+ const oldClips = document.timeline.clips;
+ const newClips = resequenceClips(reordered);
+ // Carry the user's timeline work (zoom/speed/annotation) along with the clip
+ // it sits on, so reordering clips doesn't strand regions over unrelated
+ // content. Regions are *ventilated*: a region straddling several clips is
+ // split into one piece per clip (each following its clip), and pieces that
+ // stay contiguous after the move are merged back. Trims need no shift — they
+ // follow via their source anchor.
+ const legacy = document.legacyEditor as Record<string, unknown> | null;
+ const speedRegions = legacy?.speedRegions as
+ | Array<{ id: string; startMs: number; endMs: number }>
+ | undefined;
return {
...document,
+ zoomRanges: reprojectRegionsForReorder(document.zoomRanges, oldClips, newClips, () =>
+ createId("zoom"),
+ ) as AxcutDocument["zoomRanges"],
+ annotations: reprojectRegionsForReorder(document.annotations, oldClips, newClips, () =>
+ createId("ann"),
+ ) as AxcutDocument["annotations"],
+ legacyEditor: speedRegions
+ ? {
+ ...legacy,
+ speedRegions: reprojectRegionsForReorder(speedRegions, oldClips, newClips, () =>
+ createId("speed"),
+ ),
+ }
+ : document.legacyEditor,
timeline: {
...document.timeline,
- clips: resequenceClips(reordered),
+ clips: newClips,
},
preview: {
...document.preview,
diff --git a/src/lib/ai-edition/exporter/documentExporter.test.ts b/src/lib/ai-edition/exporter/documentExporter.test.ts
new file mode 100644
index 000000000..c24f61c9f
--- /dev/null
+++ b/src/lib/ai-edition/exporter/documentExporter.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
+import { computeExportTrimRegions } from "./documentExporter";
+
+function clip(p: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
+ return {
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ ...p,
+ };
+}
+function trim(p: Partial<AxcutTrimRange> & Pick<AxcutTrimRange, "id">): AxcutTrimRange {
+ return { assetId: "a", startSec: 0, endSec: 1, origin: "user", reason: "", ...p };
+}
+
+describe("computeExportTrimRegions", () => {
+ it("cuts everything outside the kept clip ranges (clip in/out)", () => {
+ // One clip keeps source 2..8 of a 10s asset → cut 0..2 and 8..10.
+ const clips = [clip({ id: "c1", sourceStartSec: 2, sourceEndSec: 8 })];
+ expect(computeExportTrimRegions(10, clips, [], "a")).toEqual([
+ { id: "trim_1", startMs: 0, endMs: 2000 },
+ { id: "trim_2", startMs: 8000, endMs: 10000 },
+ ]);
+ });
+
+ it("also cuts a mid-clip trim (previously dropped from export)", () => {
+ // Full clip 0..10, plus a trim removing source 4..6 → export must cut it.
+ const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 10 })];
+ const trims = [trim({ id: "t1", startSec: 4, endSec: 6 })];
+ expect(computeExportTrimRegions(10, clips, trims, "a")).toEqual([
+ { id: "trim_1", startMs: 4000, endMs: 6000 },
+ ]);
+ });
+
+ it("merges overlapping clip-gap and trim cuts", () => {
+ // Clip keeps 0..8 (cut 8..10); a trim 7..9 overlaps the tail cut → merge to 7..10.
+ const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 8 })];
+ const trims = [trim({ id: "t1", startSec: 7, endSec: 9 })];
+ expect(computeExportTrimRegions(10, clips, trims, "a")).toEqual([
+ { id: "trim_1", startMs: 7000, endMs: 10000 },
+ ]);
+ });
+
+ it("ignores trims that belong to a different asset", () => {
+ const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 10 })];
+ const trims = [trim({ id: "t1", assetId: "other", startSec: 3, endSec: 5 })];
+ expect(computeExportTrimRegions(10, clips, trims, "a")).toEqual([]);
+ });
+});
diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.ts
index 48159ca6f..9813e1a10 100644
--- a/src/lib/ai-edition/exporter/documentExporter.ts
+++ b/src/lib/ai-edition/exporter/documentExporter.ts
@@ -3,9 +3,11 @@
// pipeline — the existing FrameRenderer + StreamingVideoDecoder + muxer handle
// all the rendering (annotations, zoom, blur, webcam, cursor).
//
-// ponytail: the existing exporter already accepts trimRegions (gaps in source
-// time). Clips define what to KEEP. The inverse of clips = trimRegions. We
-// also pull zoom/annotations from the document (ms units, same as legacy) and
+// ponytail: the existing exporter accepts trimRegions (removed spans in source
+// time). Two contributors are merged into them (see computeExportTrimRegions):
+// the inverse of the kept clip ranges (clip in/out) AND the DSL `trimRanges`
+// (mid-clip trims — previously dropped from the render). We also pull
+// zoom/annotations from the document (ms units, same as legacy) and
// appearance/cursor/webcam from legacyEditor (passthrough blob). The webcam
// file path lives on the primary asset's cameraTrack (P4 — per-asset, since a
// project can hold multiple recordings; export only ever handles the primary
@@ -30,8 +32,10 @@ import {
import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
import type { ExportProgress } from "@/lib/exporter/types";
import type { CursorRecordingData, CursorTelemetryPoint } from "@/native/contracts";
-import { primaryAssetDuration, timelineIntervals } from "../document/timeline";
+import { createId } from "../document/ids";
+import { type Interval, normalizeIntervals, primaryAssetDuration } from "../document/timeline";
import type { AxcutDocument } from "../schema";
+import { projectRegionsToSourceTime } from "../timeline/region-ventilation";
export type ExportVideoCodec = "h264" | "h265" | "vp9";
@@ -67,43 +71,49 @@ export interface DocumentExportOptions {
onProgress?: (progress: ExportProgress) => void;
}
-function clipsToTrimRanges(
+// The source-time spans the exporter must CUT. Two independent contributors,
+// merged so both reach the render (this is the fix for trims being silently
+// dropped from the export — the preview + aggregated transcript already applied
+// them):
+// 1. Clip in/out: everything OUTSIDE the kept clip source ranges (head/tail
+// trimming + gaps between clips).
+// 2. Trims: the DSL `trimRanges` — removals INSIDE a clip that don't split it.
+export function computeExportTrimRegions(
sourceDurationSec: number,
clips: AxcutDocument["timeline"]["clips"],
+ trimRanges: AxcutDocument["timeline"]["trimRanges"],
+ primaryAssetId: string,
): TrimRegion[] {
- const intervals = timelineIntervals({
- ...({} as AxcutDocument),
- timeline: {
- clips,
- gaps: [],
- skipRanges: [],
- muteRanges: [],
- speedRanges: [],
- captionRanges: [],
- },
- assets: [],
- project: { primaryAssetId: "" },
- } as unknown as AxcutDocument);
- const trims: TrimRegion[] = [];
+ // Kept source ranges = clip in/out points, clamped to the real source
+ // duration and merged. (Computed directly, not via timelineIntervals + a
+ // fake empty-asset document, whose primaryAssetDuration would be 0 and
+ // clamp every kept interval away.)
+ const keptIntervals = normalizeIntervals(
+ sourceDurationSec,
+ clips.map((c) => ({ startSec: c.sourceStartSec, endSec: c.sourceEndSec ?? sourceDurationSec })),
+ );
+
+ // Cuts from clip in/out = the complement of the kept intervals over [0, dur].
+ const cuts: Interval[] = [];
let cursor = 0;
- for (const interval of intervals) {
- if (interval.startSec > cursor) {
- trims.push({
- id: `trim_${trims.length + 1}`,
- startMs: Math.round(cursor * 1000),
- endMs: Math.round(interval.startSec * 1000),
- });
- }
+ for (const interval of keptIntervals) {
+ if (interval.startSec > cursor) cuts.push({ startSec: cursor, endSec: interval.startSec });
cursor = Math.max(cursor, interval.endSec);
}
- if (cursor < sourceDurationSec) {
- trims.push({
- id: `trim_${trims.length + 1}`,
- startMs: Math.round(cursor * 1000),
- endMs: Math.round(sourceDurationSec * 1000),
- });
+ if (cursor < sourceDurationSec) cuts.push({ startSec: cursor, endSec: sourceDurationSec });
+
+ // Cuts from trims (primary asset, source time).
+ for (const trim of trimRanges) {
+ if (trim.assetId === primaryAssetId)
+ cuts.push({ startSec: trim.startSec, endSec: trim.endSec });
}
- return trims;
+
+ // Merge/normalize so overlapping clip-gap + trim cuts collapse cleanly.
+ return normalizeIntervals(sourceDurationSec, cuts).map((iv, i) => ({
+ id: `trim_${i + 1}`,
+ startMs: Math.round(iv.startSec * 1000),
+ endMs: Math.round(iv.endSec * 1000),
+ }));
}
function extractLegacyField<T>(
@@ -129,10 +139,29 @@ export async function exportAxcutDocument(
const videoUrl = toFileUrl(asset.originalPath);
const sourceDurationSec = asset.durationSec ?? primaryAssetDuration(document);
- const trimRegions = clipsToTrimRanges(sourceDurationSec, document.timeline.clips);
- const zoomRegions: ZoomRegion[] = document.zoomRanges as unknown as ZoomRegion[];
- const annotationRegions: AnnotationRegion[] =
- document.annotations as unknown as AnnotationRegion[];
+ const trimRegions = computeExportTrimRegions(
+ sourceDurationSec,
+ document.timeline.clips,
+ document.timeline.trimRanges,
+ asset.id,
+ );
+ // Effects are authored in virtual (edited-timeline) time, but the export
+ // frame loop matches them against each frame's *source* time — so project
+ // them onto source ranges through the clips they cover (clip in/out + order),
+ // splitting any region that straddles a clip boundary. This is what makes a
+ // multi-clip export's zooms/annotations/speed land on the same frames as the
+ // preview. Identity single-clip projects are unchanged (source == virtual).
+ const clips = document.timeline.clips;
+ const zoomRegions = projectRegionsToSourceTime(
+ document.zoomRanges as unknown as ZoomRegion[],
+ clips,
+ () => createId("zoom"),
+ );
+ const annotationRegions = projectRegionsToSourceTime(
+ document.annotations as unknown as AnnotationRegion[],
+ clips,
+ () => createId("ann"),
+ );
const legacy = document.legacyEditor as Record<string, unknown> | null;
const wallpaper = extractLegacyField(legacy, "wallpaper", "");
@@ -154,7 +183,11 @@ export async function exportAxcutDocument(
const webcamSizePreset = extractLegacyField(legacy, "webcamSizePreset", 25);
const webcamPosition = extractLegacyField(legacy, "webcamPosition", null);
const cursorTheme = extractLegacyField(legacy, "cursorTheme", "");
- const speedRegions: SpeedRegion[] = extractLegacyField(legacy, "speedRegions", []);
+ const speedRegions: SpeedRegion[] = projectRegionsToSourceTime(
+ extractLegacyField<SpeedRegion[]>(legacy, "speedRegions", []),
+ clips,
+ () => createId("speed"),
+ );
const sourceWidth = options.sourceWidth || 1920;
const sourceHeight = options.sourceHeight || 1080;
diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.ts
index 05890af5d..31281dcf4 100644
--- a/src/lib/ai-edition/schema/index.test.ts
+++ b/src/lib/ai-edition/schema/index.test.ts
@@ -9,8 +9,8 @@ import {
ensureDocument,
legacyEditorSchema,
rangeSchema,
- skipRangeSchema,
timelineSchema,
+ trimRangeSchema,
zoomRegionSchema,
} from "./index";
@@ -33,7 +33,7 @@ describe("axcut-schema v4", () => {
expect(doc.schemaVersion).toBe(4);
expect(doc.assets).toEqual([]);
expect(doc.timeline.clips).toEqual([]);
- expect(doc.timeline.skipRanges).toEqual([]);
+ expect(doc.timeline.trimRanges).toEqual([]);
expect(doc.timeline.speedRanges).toEqual([]);
expect(doc.timeline.muteRanges).toEqual([]);
expect(doc.timeline.captionRanges).toEqual([]);
@@ -84,9 +84,9 @@ describe("axcut-schema v4", () => {
).toThrow();
});
- it("skipRangeSchema carries assetId and origin", () => {
- const skip = skipRangeSchema.parse({
- id: "skip_1",
+ it("trimRangeSchema carries assetId and origin", () => {
+ const skip = trimRangeSchema.parse({
+ id: "trim_1",
assetId: "asset_1",
startSec: 1.5,
endSec: 3.0,
@@ -101,13 +101,25 @@ describe("axcut-schema v4", () => {
expect(r.reason).toBe("");
});
- it("timelineSchema defaults skipRanges to []", () => {
+ it("timelineSchema defaults trimRanges to []", () => {
const t = timelineSchema.parse({});
- expect(t.skipRanges).toEqual([]);
+ expect(t.trimRanges).toEqual([]);
expect(t.muteRanges).toEqual([]);
expect(t.captionRanges).toEqual([]);
});
+ it("timelineSchema migrates legacy skipRanges → trimRanges", () => {
+ // Documents persisted before the skip→trim rename carry `skipRanges`.
+ const t = timelineSchema.parse({
+ skipRanges: [
+ { id: "skip_1", assetId: "a", startSec: 3, endSec: 5, reason: "", origin: "user" },
+ ],
+ });
+ expect(t.trimRanges).toEqual([
+ { id: "skip_1", assetId: "a", startSec: 3, endSec: 5, reason: "", origin: "user" },
+ ]);
+ });
+
it("annotationRegionSchema accepts OpenScreen-shape regions", () => {
const region = annotationRegionSchema.parse({
id: "ann_1",
@@ -253,9 +265,9 @@ describe("axcut-schema v4", () => {
expect(rangeSchema.parse({ startSec: 5, endSec: 5 })).toBeTruthy();
});
- it("skipRangeSchema rejects endSec < startSec", () => {
+ it("trimRangeSchema rejects endSec < startSec", () => {
expect(() =>
- skipRangeSchema.parse({
+ trimRangeSchema.parse({
id: "s1",
assetId: "a1",
startSec: 10,
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 1439042a5..a6f9ab261 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -146,9 +146,9 @@ export const rangeSchema = z
path: ["endSec"],
});
-// ponytail: skipRanges reference asset source-time (not timeline). trimRegions
+// ponytail: trimRanges reference asset source-time (not timeline). trimRegions
// in v2 are the inverse — a skip = the region inside the source we DON'T keep.
-export const skipRangeSchema = z
+export const trimRangeSchema = z
.object({
id: z.string().min(1),
assetId: z.string().min(1),
@@ -162,14 +162,28 @@ export const skipRangeSchema = z
path: ["endSec"],
});
-export const timelineSchema = z.object({
- clips: z.array(clipSchema).default([]),
- gaps: z.array(gapSchema).default([]),
- skipRanges: z.array(skipRangeSchema).default([]),
- muteRanges: z.array(rangeSchema).default([]),
- speedRanges: z.array(rangeSchema).default([]),
- captionRanges: z.array(rangeSchema).default([]),
-});
+export const timelineSchema = z.preprocess(
+ // Back-compat: the field was renamed skipRanges → trimRanges. Old persisted
+ // documents (disk + browser-shim localStorage) still carry `skipRanges`;
+ // fold it into `trimRanges` on load so trims aren't silently dropped.
+ (value) => {
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ const v = value as Record<string, unknown>;
+ if (v.skipRanges !== undefined && v.trimRanges === undefined) {
+ return { ...v, trimRanges: v.skipRanges };
+ }
+ }
+ return value;
+ },
+ z.object({
+ clips: z.array(clipSchema).default([]),
+ gaps: z.array(gapSchema).default([]),
+ trimRanges: z.array(trimRangeSchema).default([]),
+ muteRanges: z.array(rangeSchema).default([]),
+ speedRanges: z.array(rangeSchema).default([]),
+ captionRanges: z.array(rangeSchema).default([]),
+ }),
+);
export const pendingQuestionSchema = z.object({
id: z.string().min(1),
@@ -210,23 +224,23 @@ export const timelineOperationSchema = z.discriminatedUnion("type", [
endWordId: z.string().min(1),
}),
z.object({
- type: z.literal("add_skip_range"),
+ type: z.literal("add_trim_range"),
reason: z.string().default(""),
assetId: z.string().min(1),
startSec: z.number().nonnegative(),
endSec: z.number().nonnegative(),
}),
z.object({
- type: z.literal("update_skip_range"),
+ type: z.literal("update_trim_range"),
reason: z.string().default(""),
- skipRangeId: z.string().min(1),
+ trimRangeId: z.string().min(1),
startSec: z.number().nonnegative(),
endSec: z.number().nonnegative(),
}),
z.object({
- type: z.literal("remove_skip_range"),
+ type: z.literal("remove_trim_range"),
reason: z.string().default(""),
- skipRangeId: z.string().min(1),
+ trimRangeId: z.string().min(1),
}),
z.object({
type: z.literal("update_clip_range"),
@@ -427,7 +441,7 @@ const documentSchemaShape = z.object({
timeline: timelineSchema.default({
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -531,7 +545,7 @@ export type AxcutTranscript = z.infer<typeof transcriptSchema>;
export type AxcutAsset = z.infer<typeof assetSchema>;
export type AxcutClip = z.infer<typeof clipSchema>;
export type AxcutGap = z.infer<typeof gapSchema>;
-export type AxcutSkipRange = z.infer<typeof skipRangeSchema>;
+export type AxcutTrimRange = z.infer<typeof trimRangeSchema>;
export type AxcutTimeline = z.infer<typeof timelineSchema>;
export type AxcutSuggestion = z.infer<typeof suggestionSchema>;
export type AxcutAgentState = z.infer<typeof agentStateSchema>;
@@ -569,7 +583,7 @@ export function createEmptyDocument(
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.ts
index 5338d1dd6..32294a223 100644
--- a/src/lib/ai-edition/store/editorSettings.test.ts
+++ b/src/lib/ai-edition/store/editorSettings.test.ts
@@ -12,7 +12,7 @@ const baseDoc: AxcutDocument = {
schemaVersion: 3,
project: { id: "p1", title: "Test", primaryAssetId: "a1" },
assets: [{ id: "a1", kind: "video", label: "clip", originalPath: "/x.mp4" }],
- timeline: { clips: [], skipRanges: [] },
+ timeline: { clips: [], trimRanges: [] },
annotations: [],
zoomRanges: [],
transcripts: [],
diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.ts
index 57ea47c71..7503af5f5 100644
--- a/src/lib/ai-edition/store/projectStore.test.ts
+++ b/src/lib/ai-edition/store/projectStore.test.ts
@@ -45,7 +45,7 @@ const sampleDoc = {
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useChatPromptBus.ts b/src/lib/ai-edition/store/useChatPromptBus.ts
new file mode 100644
index 000000000..1f6c361eb
--- /dev/null
+++ b/src/lib/ai-edition/store/useChatPromptBus.ts
@@ -0,0 +1,22 @@
+import { create } from "zustand";
+
+// Tiny decoupled bus so non-chat UI (e.g. the timeline's Auto-enhance "AI"
+// option) can hand a prompt to the chat panel without reaching into its local
+// state. The chat composer (ChatStripPanel) subscribes, prefills + auto-sends
+// the pending prompt through its normal send() path (so sessions, checkpoints
+// and rewind all keep working), then consume()s it.
+
+interface ChatPromptBusState {
+ /** A prompt waiting to be picked up + auto-sent by the chat panel, or null. */
+ pending: string | null;
+ /** Queue a prompt for the chat panel to send. */
+ submit: (text: string) => void;
+ /** Called by the chat panel once it has taken ownership of `pending`. */
+ consume: () => void;
+}
+
+export const useChatPromptBus = create<ChatPromptBusState>((set) => ({
+ pending: null,
+ submit: (text) => set({ pending: text }),
+ consume: () => set({ pending: null }),
+}));
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index 76b1719e4..69d4f361f 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -67,7 +67,7 @@ const sampleDoc = {
},
],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 54524d53b..6d56a73ad 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -1,5 +1,5 @@
// Hook: region mutations for the new editor shell. Wraps the project store
-// with typed add/remove/select operations for zoom, skip, annotation, and
+// with typed add/remove/select operations for zoom, trim, annotation, and
// speed regions. Each add creates a 2-second region at the current playhead
// (a reasonable default for the user to then resize).
@@ -14,9 +14,11 @@ import {
} from "../document/timeline";
import type { AxcutDocument } from "../schema";
import { probeVideoDuration } from "../timeline/duration";
+import { resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
+import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
import { useProjectStore } from "./projectStore";
-type RegionKind = "zoom" | "skip" | "annotation" | "speed";
+type RegionKind = "zoom" | "trim" | "annotation" | "speed";
// Placeholder duration applied to a freshly-inserted clip whose source asset
// hasn't reported its real duration yet (media drag → drop before the preview
@@ -68,23 +70,59 @@ export function useTimeline() {
await saveDocument(next);
}, [document, currentTimeSec, saveDocument]);
- const addSkip = useCallback(async () => {
+ // Append several auto-generated zoom regions in one save (auto-enhance).
+ // Suggestions come from buildAutoZoomSuggestions, which already reserves
+ // existing zoom spans, so no extra overlap filtering is needed here.
+ // Returns the count actually added (0 when there's no doc/suggestions).
+ const addZoomsBulk = useCallback(
+ async (suggestions: AutoZoomSuggestion[]) => {
+ if (!document || suggestions.length === 0) return 0;
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: [
+ ...document.zoomRanges,
+ ...suggestions.map((s) => ({
+ id: createId("zoom"),
+ startMs: Math.round(s.span.start),
+ endMs: Math.round(s.span.end),
+ depth: 3 as const,
+ focus: { cx: s.focus.cx, cy: s.focus.cy },
+ focusMode: "auto" as const,
+ })),
+ ] as AxcutDocument["zoomRanges"],
+ };
+ await saveDocument(next);
+ return suggestions.length;
+ },
+ [document, saveDocument],
+ );
+
+ const addTrim = useCallback(async () => {
if (!document) return;
+ // Insert a 2s trim at the playhead in *timeline* time, then resolve it
+ // down to the correct clip's asset + source-time. Writing currentTimeSec
+ // straight into startSec (as before) only happened to be right for an
+ // identity single-clip project — for trimmed/reordered clips it landed
+ // the trim at the wrong source position.
+ const resolved = resolveTimelineSpanToTrim(
+ currentTimeSec,
+ currentTimeSec + 2,
+ document.timeline.clips,
+ );
const asset =
document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];
- if (!asset) return;
- const id = createId("skip");
+ if (!resolved && !asset) return;
const next: AxcutDocument = {
...document,
timeline: {
...document.timeline,
- skipRanges: [
- ...document.timeline.skipRanges,
+ trimRanges: [
+ ...document.timeline.trimRanges,
{
- id,
- assetId: asset.id,
- startSec: currentTimeSec,
- endSec: currentTimeSec + 2,
+ id: createId("trim"),
+ assetId: resolved?.assetId ?? asset!.id,
+ startSec: resolved?.sourceStartSec ?? currentTimeSec,
+ endSec: resolved?.sourceEndSec ?? currentTimeSec + 2,
reason: "manual",
origin: "user" as const,
},
@@ -94,20 +132,20 @@ export function useTimeline() {
await saveDocument(next);
}, [document, currentTimeSec, saveDocument]);
- // T15 — add a skip at a specific (assetId, sourceStartSec, sourceEndSec).
- // Used by the place-skip mode in TimelinePane where the cursor lands
+ // T15 — add a trim at a specific (assetId, sourceStartSec, sourceEndSec).
+ // Used by the place-trim mode in TimelinePane where the cursor lands
// inside a specific clip's source range, not just at currentTimeSec.
- const addSkipAt = useCallback(
+ const addTrimAt = useCallback(
async (assetId: string, sourceStartSec: number, sourceEndSec: number) => {
if (!document) return;
const next: AxcutDocument = {
...document,
timeline: {
...document.timeline,
- skipRanges: [
- ...document.timeline.skipRanges,
+ trimRanges: [
+ ...document.timeline.trimRanges,
{
- id: createId("skip"),
+ id: createId("trim"),
assetId,
startSec: sourceStartSec,
endSec: sourceEndSec,
@@ -177,8 +215,8 @@ export function useTimeline() {
await saveDocument(next);
}, [document, currentTimeSec, saveDocument]);
- const updateSkipRange = useCallback(
- async (skipId: string, startSec: number, endSec: number) => {
+ const updateTrimRange = useCallback(
+ async (trimId: string, startSec: number, endSec: number) => {
if (!document) return;
const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);
const s = clamp(startSec);
@@ -187,8 +225,8 @@ export function useTimeline() {
...document,
timeline: {
...document.timeline,
- skipRanges: document.timeline.skipRanges.map((r) =>
- r.id === skipId ? { ...r, startSec: Math.min(s, e), endSec: Math.max(s, e) } : r,
+ trimRanges: document.timeline.trimRanges.map((r) =>
+ r.id === trimId ? { ...r, startSec: Math.min(s, e), endSec: Math.max(s, e) } : r,
),
},
};
@@ -197,6 +235,74 @@ export function useTimeline() {
[document, saveDocument],
);
+ // Like updateTrimRange but also re-attaches the trim to a (possibly
+ // different) asset — needed when a trim is dragged across a clip boundary
+ // onto a clip backed by another asset. Callers resolve the timeline span to
+ // { assetId, sourceStartSec, sourceEndSec } via resolveTimelineSpanToTrim.
+ const updateTrim = useCallback(
+ async (trimId: string, next: { assetId: string; startSec: number; endSec: number }) => {
+ if (!document) return;
+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);
+ const s = clamp(next.startSec);
+ const e = clamp(next.endSec);
+ const nextDoc: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ trimRanges: document.timeline.trimRanges.map((r) =>
+ r.id === trimId
+ ? { ...r, assetId: next.assetId, startSec: Math.min(s, e), endSec: Math.max(s, e) }
+ : r,
+ ),
+ },
+ };
+ await saveDocument(nextDoc);
+ },
+ [document, saveDocument],
+ );
+
+ // Reconcile the set of trim entries "owned" by one drag with a freshly
+ // ventilated result. A trim resized across a clip boundary can't stay a
+ // single source range (source-time is per asset), so it materialises as one
+ // entry per covered clip — the caller passes explicit, stable ids (so the
+ // dragged pill keeps its identity across frames) plus `dropIds` for entries a
+ // shrinking span no longer needs. Trims not owned by this drag are untouched.
+ const setTrimEntries = useCallback(
+ async (
+ entries: Array<{
+ id: string;
+ assetId: string;
+ sourceStartSec: number;
+ sourceEndSec: number;
+ }>,
+ dropIds: string[],
+ ) => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ const managed = new Set<string>([...entries.map((e) => e.id), ...dropIds]);
+ const others = doc.timeline.trimRanges.filter((r) => !managed.has(r.id));
+ const clamp = (n: number) => (Number.isFinite(n) ? Math.max(0, n) : 0);
+ const rebuilt = entries.map((e) => {
+ const prev = doc.timeline.trimRanges.find((r) => r.id === e.id);
+ const s = clamp(e.sourceStartSec);
+ const en = clamp(e.sourceEndSec);
+ return {
+ id: e.id,
+ assetId: e.assetId,
+ startSec: Math.min(s, en),
+ endSec: Math.max(s, en),
+ reason: prev?.reason ?? "manual",
+ origin: prev?.origin ?? ("user" as const),
+ };
+ });
+ await saveDocument({
+ ...doc,
+ timeline: { ...doc.timeline, trimRanges: [...others, ...rebuilt] },
+ });
+ },
+ [saveDocument],
+ );
+
const updateZoomSpan = useCallback(
async (id: string, startMs: number, endMs: number) => {
if (!document) return;
@@ -241,6 +347,23 @@ export function useTimeline() {
await saveDocument(doc);
}, [saveDocument]);
+ // Zoom-level control for the region-settings panel (1-6, matches
+ // zoomRegionSchema's depth literal union — 1.0x..3.5x in 0.5x steps per
+ // the `depth/2 + 0.5` label formula used throughout the timeline UI).
+ const updateZoomDepth = useCallback(
+ async (id: string, depth: 1 | 2 | 3 | 4 | 5 | 6) => {
+ if (!document) return;
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: document.zoomRanges.map((z) =>
+ z.id === id ? { ...z, depth } : z,
+ ) as AxcutDocument["zoomRanges"],
+ };
+ await saveDocument(next);
+ },
+ [document, saveDocument],
+ );
+
const updateAnnotationSpan = useCallback(
async (id: string, startMs: number, endMs: number) => {
if (!document) return;
@@ -307,6 +430,28 @@ export function useTimeline() {
[document, saveDocument],
);
+ const updateSpeedValue = useCallback(
+ async (id: string, speed: number) => {
+ if (!document) return;
+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
+ const prev = ((legacy.speedRegions as unknown[]) ?? []) as Array<{
+ id: string;
+ startMs: number;
+ endMs: number;
+ speed: number;
+ }>;
+ const next: AxcutDocument = {
+ ...document,
+ legacyEditor: {
+ ...legacy,
+ speedRegions: prev.map((r) => (r.id === id ? { ...r, speed } : r)),
+ },
+ };
+ await saveDocument(next);
+ },
+ [document, saveDocument],
+ );
+
const removeRegion = useCallback(
async (kind: RegionKind, id: string) => {
if (!document) return;
@@ -316,12 +461,12 @@ export function useTimeline() {
...document,
zoomRanges: document.zoomRanges.filter((z) => z.id !== id) as AxcutDocument["zoomRanges"],
};
- } else if (kind === "skip") {
+ } else if (kind === "trim") {
next = {
...document,
timeline: {
...document.timeline,
- skipRanges: document.timeline.skipRanges.filter((s) => s.id !== id),
+ trimRanges: document.timeline.trimRanges.filter((s) => s.id !== id),
},
};
} else if (kind === "annotation") {
@@ -352,7 +497,7 @@ export function useTimeline() {
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 trimIds = new Set(handles.filter((h) => h.kind === "trim").map((h) => h.id));
const annotationIds = new Set(
handles.filter((h) => h.kind === "annotation").map((h) => h.id),
);
@@ -369,7 +514,7 @@ export function useTimeline() {
annotations: document.annotations.filter((a) => !annotationIds.has(a.id)),
timeline: {
...document.timeline,
- skipRanges: document.timeline.skipRanges.filter((s) => !skipIds.has(s.id)),
+ trimRanges: document.timeline.trimRanges.filter((s) => !trimIds.has(s.id)),
},
legacyEditor:
speedIds.size > 0 ? { ...legacy, speedRegions: prevSpeed } : document.legacyEditor,
@@ -602,7 +747,7 @@ export function useTimeline() {
);
// Background probe: read the asset's actual duration and patch the
- // freshly-inserted clip to use it. Skips if the clip has already been
+ // freshly-inserted clip to use it. Trims 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.
@@ -756,7 +901,7 @@ export function useTimeline() {
return {
zoomRegions: document?.zoomRanges ?? [],
- skipRanges: document?.timeline.skipRanges ?? [],
+ trimRanges: document?.timeline.trimRanges ?? [],
annotationRegions: (document?.annotations ?? []) as unknown as AnnotationRegion[],
speedRegions,
clips: document?.timeline.clips ?? [],
@@ -766,8 +911,9 @@ export function useTimeline() {
multiSelection,
clipSelection,
addZoom,
- addSkip,
- addSkipAt,
+ addZoomsBulk,
+ addTrim,
+ addTrimAt,
addAnnotation,
addSpeed,
removeRegion,
@@ -785,15 +931,19 @@ export function useTimeline() {
removeClip,
selectClip,
clearClipSelection,
- updateSkipRange,
+ updateTrimRange,
+ updateTrim,
+ setTrimEntries,
updateZoomSpan,
updateZoomFocusLive,
commitZoomFocus,
+ updateZoomDepth,
updateAnnotationSpan,
updateAnnotationLive,
commitAnnotationChange,
updateSpeedSpan,
- // T19 — drives the preview video during skip-edge resize.
+ updateSpeedValue,
+ // T19 — drives the preview video during trim-edge resize.
setCurrentTime: useProjectStore((s) => s.setCurrentTime),
};
}
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
index f4fc27382..261e97ca3 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import type { AxcutAsset, AxcutClip, AxcutSkipRange, AxcutTranscript } from "../schema";
+import type { AxcutAsset, AxcutClip, AxcutTranscript, AxcutTrimRange } from "../schema";
import { buildAggregatedSections, buildClipSection, findCueWordId } from "./aggregated-transcript";
function makeClip(overrides: Partial<AxcutClip> = {}): AxcutClip {
@@ -32,9 +32,9 @@ function makeTranscript(words: AxcutTranscript["words"]): AxcutTranscript {
return { assetId: "asset_1", language: "en", segments: [], words };
}
-function makeSkip(overrides: Partial<AxcutSkipRange>): AxcutSkipRange {
+function makeTrim(overrides: Partial<AxcutTrimRange>): AxcutTrimRange {
return {
- id: overrides.id ?? "skip_1",
+ id: overrides.id ?? "trim_1",
assetId: overrides.assetId ?? "asset_1",
startSec: overrides.startSec ?? 0,
endSec: overrides.endSec ?? 0,
@@ -44,7 +44,7 @@ function makeSkip(overrides: Partial<AxcutSkipRange>): AxcutSkipRange {
}
describe("buildClipSection", () => {
- it("marks every word in source range as kept when no skips exist", () => {
+ it("marks every word in source range as kept when no trims exist", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 3 });
const transcript = makeTranscript([
{ id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "hi" },
@@ -54,10 +54,10 @@ describe("buildClipSection", () => {
const section = buildClipSection(clip, transcript, makeAsset(), []);
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
- expect(section.skipRuns).toEqual([]);
+ expect(section.trimRuns).toEqual([]);
});
- it("flags words inside a skip range as removed and groups them into one SkipRun", () => {
+ it("flags words inside a trim range as removed and groups them into one TrimRun", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 5 });
const transcript = makeTranscript([
{ id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "hi" },
@@ -66,27 +66,27 @@ describe("buildClipSection", () => {
{ id: "w4", segmentId: "s1", startSec: 3, endSec: 4, text: "pause" },
{ id: "w5", segmentId: "s1", startSec: 4, endSec: 5, text: "bye" },
]);
- const skip = makeSkip({ id: "skip_a", startSec: 1, endSec: 4 });
+ const trim = makeTrim({ id: "trim_a", startSec: 1, endSec: 4 });
- const section = buildClipSection(clip, transcript, makeAsset(), [skip]);
+ const section = buildClipSection(clip, transcript, makeAsset(), [trim]);
expect(section.words.map((cw) => cw.kept)).toEqual([true, false, false, false, true]);
- expect(section.words.map((cw) => cw.skipId)).toEqual([
+ expect(section.words.map((cw) => cw.trimId)).toEqual([
null,
- "skip_a",
- "skip_a",
- "skip_a",
+ "trim_a",
+ "trim_a",
+ "trim_a",
null,
]);
- expect(section.skipRuns).toHaveLength(1);
- expect(section.skipRuns[0]).toMatchObject({
- skipId: "skip_a",
+ expect(section.trimRuns).toHaveLength(1);
+ expect(section.trimRuns[0]).toMatchObject({
+ trimId: "trim_a",
startWordIndex: 1,
endWordIndex: 3,
durationSec: 3,
});
});
- it("splits separated skip ranges into multiple SkipRuns", () => {
+ it("splits separated trim ranges into multiple TrimRuns", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 6 });
const transcript = makeTranscript([
{ id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "a" },
@@ -96,34 +96,34 @@ describe("buildClipSection", () => {
{ id: "w5", segmentId: "s1", startSec: 4, endSec: 5, text: "e" },
{ id: "w6", segmentId: "s1", startSec: 5, endSec: 6, text: "f" },
]);
- const skips = [
- makeSkip({ id: "skip_a", startSec: 1, endSec: 2 }),
- makeSkip({ id: "skip_b", startSec: 3, endSec: 4 }),
+ const trims = [
+ makeTrim({ id: "trim_a", startSec: 1, endSec: 2 }),
+ makeTrim({ id: "trim_b", startSec: 3, endSec: 4 }),
];
- const section = buildClipSection(clip, transcript, makeAsset(), skips);
- expect(section.skipRuns).toHaveLength(2);
- expect(section.skipRuns[0]).toMatchObject({
- skipId: "skip_a",
+ const section = buildClipSection(clip, transcript, makeAsset(), trims);
+ expect(section.trimRuns).toHaveLength(2);
+ expect(section.trimRuns[0]).toMatchObject({
+ trimId: "trim_a",
startWordIndex: 1,
endWordIndex: 1,
});
- expect(section.skipRuns[1]).toMatchObject({
- skipId: "skip_b",
+ expect(section.trimRuns[1]).toMatchObject({
+ trimId: "trim_b",
startWordIndex: 3,
endWordIndex: 3,
});
});
- it("does NOT apply skips from a different asset", () => {
+ it("does NOT apply trims from a different asset", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 3 });
const transcript = makeTranscript([
{ id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "hi" },
{ id: "w2", segmentId: "s1", startSec: 1, endSec: 2, text: "there" },
]);
- const skip = makeSkip({ id: "skip_x", assetId: "asset_2", startSec: 0.5, endSec: 2.5 });
+ const trim = makeTrim({ id: "trim_x", assetId: "asset_2", startSec: 0.5, endSec: 2.5 });
- const section = buildClipSection(clip, transcript, makeAsset(), [skip]);
+ const section = buildClipSection(clip, transcript, makeAsset(), [trim]);
expect(section.words.map((cw) => cw.kept)).toEqual([true, true]);
});
@@ -139,7 +139,7 @@ describe("buildClipSection", () => {
// ponytail: the LLM (not the renderer) decides what is a filler. Every
// word renders as plain text in the right pane.
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
- expect(section.words.map((cw) => cw.skipId)).toEqual([null, null, null]);
+ expect(section.words.map((cw) => cw.trimId)).toEqual([null, null, null]);
});
it("returns an empty words list when the clip has no matching transcript", () => {
@@ -147,16 +147,16 @@ describe("buildClipSection", () => {
const section = buildClipSection(clip, null, makeAsset(), []);
expect(section.words).toEqual([]);
- expect(section.skipRuns).toEqual([]);
+ expect(section.trimRuns).toEqual([]);
expect(section.transcript).toBeNull();
});
it("ignores transcript words outside the clip's source range", () => {
const clip = makeClip({ sourceStartSec: 2, sourceEndSec: 4 });
const transcript = makeTranscript([
- { id: "w_before", segmentId: "s1", startSec: 0, endSec: 1, text: "skip" },
+ { id: "w_before", segmentId: "s1", startSec: 0, endSec: 1, text: "trim" },
{ id: "w_mid", segmentId: "s1", startSec: 2.5, endSec: 3.5, text: "in" },
- { id: "w_after", segmentId: "s1", startSec: 5, endSec: 6, text: "skip" },
+ { id: "w_after", segmentId: "s1", startSec: 5, endSec: 6, text: "trim" },
]);
const section = buildClipSection(clip, transcript, makeAsset(), []);
@@ -231,9 +231,9 @@ describe("findCueWordId", () => {
words: wordTimes.map(([id, start, end]) => ({
word: { id, segmentId: "s1", startSec: start, endSec: end, text: id },
kept: true,
- skipId: null,
+ trimId: null,
})),
- skipRuns: [],
+ trimRuns: [],
};
}
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.ts b/src/lib/ai-edition/timeline/aggregated-transcript.ts
index d47e9d600..1102f3f06 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.ts
@@ -4,7 +4,7 @@
// ponytail: pure functions, no React. Mirrors axcut's
// apps/web/src/components/CurrentTranscriptView.tsx#buildClipTranscriptProjections
// + buildTranscriptRuns. Word kept/removed is decided by whether the word
-// falls inside one of the document's `timeline.skipRanges` for the same
+// falls inside one of the document's `timeline.trimRanges` for the same
// asset — not by `clip.wordRefs` (which is now only used by the timeline
// retime math, not by the right pane).
//
@@ -14,17 +14,17 @@
// names a word a filler. The transcript view shows plain text for every
// kept word; the user or the LLM decides what to mark as skipped.
-import type { AxcutAsset, AxcutClip, AxcutSkipRange, AxcutTranscript, AxcutWord } from "../schema";
+import type { AxcutAsset, AxcutClip, AxcutTranscript, AxcutTrimRange, AxcutWord } from "../schema";
/** A contiguous run of removed words inside one clip's source range. */
-export interface SkipRun {
- /** Id of the skip range this run came from (used by the bin-icon restore). */
- skipId: string;
+export interface TrimRun {
+ /** Id of the trim range this run came from (used by the bin-icon restore). */
+ trimId: string;
/** Index of the first removed word in `words`. */
startWordIndex: number;
/** Inclusive index of the last removed word in `words`. */
endWordIndex: number;
- /** Asset id the skip belongs to. */
+ /** Asset id the trim belongs to. */
assetId: string;
/** Wall-clock seconds from the first removed word's start to the last removed word's end. */
durationSec: number;
@@ -33,10 +33,10 @@ export interface SkipRun {
/** One word in the clip's source range, tagged kept / removed. */
export interface ClipWord {
word: AxcutWord;
- /** Whether the word is inside a skipRange for this clip's asset. */
+ /** Whether the word is inside a trimRange for this clip's asset. */
kept: boolean;
- /** Id of the skip range that removed this word, if any. */
- skipId: string | null;
+ /** Id of the trim range that removed this word, if any. */
+ trimId: string | null;
}
/** One clip's contribution to the aggregated flow. */
@@ -45,63 +45,63 @@ export interface ClipSection {
asset: AxcutAsset | null;
transcript: AxcutTranscript | null;
words: ClipWord[];
- skipRuns: SkipRun[];
+ trimRuns: TrimRun[];
}
function wordsInRange(transcript: AxcutTranscript, startSec: number, endSec: number): AxcutWord[] {
return transcript.words.filter((w) => w.endSec > startSec && w.startSec < endSec);
}
-/** Find the skip range covering this word's center (returns the deepest match). */
-function findCoveringSkip(word: AxcutWord, skipRanges: AxcutSkipRange[]): AxcutSkipRange | null {
+/** Find the trim range covering this word's center (returns the deepest match). */
+function findCoveringTrim(word: AxcutWord, trimRanges: AxcutTrimRange[]): AxcutTrimRange | null {
const center = (word.startSec + word.endSec) / 2;
- for (const skip of skipRanges) {
- if (center >= skip.startSec && center <= skip.endSec) return skip;
+ for (const trim of trimRanges) {
+ if (center >= trim.startSec && center <= trim.endSec) return trim;
}
return null;
}
/**
* Build one clip section. Words inside the clip's source range that fall
- * inside any skip range for the same asset are marked removed; the rest
- * are kept. Contiguous removed words from the same skip range group into
- * one `SkipRun` (for the trim-duration pill + bin-icon restore).
+ * inside any trim range for the same asset are marked removed; the rest
+ * are kept. Contiguous removed words from the same trim range group into
+ * one `TrimRun` (for the trim-duration pill + bin-icon restore).
*/
export function buildClipSection(
clip: AxcutClip,
transcript: AxcutTranscript | null,
asset: AxcutAsset | null,
- skipRanges: AxcutSkipRange[],
+ trimRanges: AxcutTrimRange[],
): ClipSection {
- const clipSkips = skipRanges.filter(
- (skip) =>
- skip.assetId === clip.assetId &&
- skip.endSec > clip.sourceStartSec &&
- skip.startSec < (clip.sourceEndSec ?? Infinity),
+ const clipTrims = trimRanges.filter(
+ (trim) =>
+ trim.assetId === clip.assetId &&
+ trim.endSec > clip.sourceStartSec &&
+ trim.startSec < (clip.sourceEndSec ?? Infinity),
);
const words = transcript
? wordsInRange(transcript, clip.sourceStartSec, clip.sourceEndSec ?? Infinity)
: [];
const tagged: ClipWord[] = words.map((word) => {
- const covering = findCoveringSkip(word, clipSkips);
+ const covering = findCoveringTrim(word, clipTrims);
return {
word,
kept: covering === null,
- skipId: covering?.id ?? null,
+ trimId: covering?.id ?? null,
};
});
- const skipRuns: SkipRun[] = [];
+ const trimRuns: TrimRun[] = [];
let runStart = -1;
let runEnd = -1;
- let runSkipId = "";
+ let runTrimId = "";
let runMinStart = 0;
let runMaxEnd = 0;
const flush = () => {
if (runStart >= 0) {
- skipRuns.push({
- skipId: runSkipId,
+ trimRuns.push({
+ trimId: runTrimId,
assetId: clip.assetId,
startWordIndex: runStart,
endWordIndex: runEnd,
@@ -110,7 +110,7 @@ export function buildClipSection(
}
runStart = -1;
runEnd = -1;
- runSkipId = "";
+ runTrimId = "";
runMinStart = 0;
runMaxEnd = 0;
};
@@ -119,21 +119,21 @@ export function buildClipSection(
flush();
return;
}
- // Split the run if the skip range id changes (overlapping skips).
- if (runStart >= 0 && cw.skipId !== runSkipId) {
+ // Split the run if the trim range id changes (overlapping trims).
+ if (runStart >= 0 && cw.trimId !== runTrimId) {
flush();
}
if (runStart < 0) {
runStart = i;
runMinStart = cw.word.startSec;
- runSkipId = cw.skipId ?? "";
+ runTrimId = cw.trimId ?? "";
}
runEnd = i;
runMaxEnd = Math.max(runMaxEnd, cw.word.endSec);
});
flush();
- return { clip, asset, transcript, words: tagged, skipRuns };
+ return { clip, asset, transcript, words: tagged, trimRuns };
}
/**
@@ -145,7 +145,7 @@ export function buildAggregatedSections(
clips: AxcutClip[],
transcripts: AxcutTranscript[],
assets: AxcutAsset[],
- skipRanges: AxcutSkipRange[],
+ trimRanges: AxcutTrimRange[],
): ClipSection[] {
const transcriptById = new Map(transcripts.map((t) => [t.assetId, t]));
const assetById = new Map(assets.map((a) => [a.id, a]));
@@ -154,7 +154,7 @@ export function buildAggregatedSections(
clip,
transcriptById.get(clip.assetId) ?? null,
assetById.get(clip.assetId) ?? null,
- skipRanges,
+ trimRanges,
),
);
}
diff --git a/src/lib/ai-edition/timeline/region-ventilation.test.ts b/src/lib/ai-edition/timeline/region-ventilation.test.ts
new file mode 100644
index 000000000..e5afc3907
--- /dev/null
+++ b/src/lib/ai-edition/timeline/region-ventilation.test.ts
@@ -0,0 +1,230 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutClip } from "../schema";
+import {
+ coalesceTouchingSpans,
+ projectRegionsToSourceTime,
+ reprojectRegionsForReorder,
+ reprojectSpanForReorder,
+ ventilateSpanAcrossClips,
+ virtualSpanToSourceSpans,
+} from "./region-ventilation";
+
+// Clips are laid contiguously on the timeline; `src` is just an identity tag on
+// the source range so reordering is observable.
+function clip(id: string, timelineStartSec: number, lenSec: number, srcStart = 0): AxcutClip {
+ return {
+ id,
+ assetId: "a",
+ sourceStartSec: srcStart,
+ sourceEndSec: srcStart + lenSec,
+ timelineStartSec,
+ timelineEndSec: timelineStartSec + lenSec,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ };
+}
+
+// A 3-clip timeline: c1 [0,10) c2 [10,20) c3 [20,30).
+const c1 = clip("c1", 0, 10);
+const c2 = clip("c2", 10, 10);
+const c3 = clip("c3", 20, 10);
+const threeClips = [c1, c2, c3];
+
+describe("ventilateSpanAcrossClips", () => {
+ it("keeps a span inside one clip as a single clip-local fragment", () => {
+ expect(ventilateSpanAcrossClips(2, 6, threeClips)).toEqual([
+ { clipId: "c1", localStartSec: 2, localEndSec: 6 },
+ ]);
+ });
+
+ it("splits a span straddling two clips into per-clip fragments", () => {
+ expect(ventilateSpanAcrossClips(8, 13, threeClips)).toEqual([
+ { clipId: "c1", localStartSec: 8, localEndSec: 10 },
+ { clipId: "c2", localStartSec: 0, localEndSec: 3 },
+ ]);
+ });
+
+ it("splits across three clips", () => {
+ expect(ventilateSpanAcrossClips(5, 25, threeClips)).toEqual([
+ { clipId: "c1", localStartSec: 5, localEndSec: 10 },
+ { clipId: "c2", localStartSec: 0, localEndSec: 10 },
+ { clipId: "c3", localStartSec: 0, localEndSec: 5 },
+ ]);
+ });
+
+ it("omits clips the span doesn't touch", () => {
+ expect(ventilateSpanAcrossClips(22, 28, threeClips)).toEqual([
+ { clipId: "c3", localStartSec: 2, localEndSec: 8 },
+ ]);
+ });
+});
+
+describe("reprojectSpanForReorder", () => {
+ it("shifts a single-clip span to the clip's new position", () => {
+ // Move c2 to the front: new layout c2 [0,10) c1 [10,20) c3 [20,30).
+ const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
+ // A zoom over c1 (2..6s) must ride c1 to its new [10,20) slot → 12..16s.
+ expect(reprojectSpanForReorder(2000, 6000, threeClips, newClips)).toEqual([
+ { startMs: 12000, endMs: 16000 },
+ ]);
+ });
+
+ it("splits a cross-clip span into two when the clips separate", () => {
+ // Zoom straddling c1 (8..10) + c2 (10..13). Move c3 between them:
+ // new layout c1 [0,10) c3 [10,20) c2 [20,30).
+ const newClips = [c1, clip("c3", 10, 10), clip("c2", 20, 10)];
+ expect(reprojectSpanForReorder(8000, 13000, threeClips, newClips)).toEqual([
+ { startMs: 8000, endMs: 10000 }, // stays on c1
+ { startMs: 20000, endMs: 23000 }, // rides c2 to its new slot
+ ]);
+ });
+
+ it("merges the pieces back when the clips stay contiguous after the move", () => {
+ // Same straddling zoom, but c1 and c2 remain adjacent (just both shifted):
+ // swap so order is c2,c1 would break adjacency — instead move c3 to front:
+ // new layout c3 [0,10) c1 [10,20) c2 [20,30). c1 then c2 still contiguous.
+ const newClips = [clip("c3", 0, 10), clip("c1", 10, 10), clip("c2", 20, 10)];
+ expect(reprojectSpanForReorder(8000, 13000, threeClips, newClips)).toEqual([
+ { startMs: 18000, endMs: 23000 },
+ ]);
+ });
+
+ it("leaves a span not sitting on any clip unchanged", () => {
+ const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
+ // 40..45s is past the end of every clip.
+ expect(reprojectSpanForReorder(40000, 45000, threeClips, newClips)).toEqual([
+ { startMs: 40000, endMs: 45000 },
+ ]);
+ });
+});
+
+describe("reprojectRegionsForReorder", () => {
+ it("keeps the id on single-piece regions and preserves extra fields", () => {
+ const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
+ const regions = [{ id: "z1", startMs: 2000, endMs: 6000, depth: 2 }];
+ expect(reprojectRegionsForReorder(regions, threeClips, newClips, () => "NEW")).toEqual([
+ { id: "z1", startMs: 12000, endMs: 16000, depth: 2 },
+ ]);
+ });
+
+ it("emits a fresh id for the extra fragment of a split region", () => {
+ const newClips = [c1, clip("c3", 10, 10), clip("c2", 20, 10)];
+ const regions = [{ id: "z1", startMs: 8000, endMs: 13000, depth: 3 }];
+ expect(reprojectRegionsForReorder(regions, threeClips, newClips, () => "z2")).toEqual([
+ { id: "z1", startMs: 8000, endMs: 10000, depth: 3 },
+ { id: "z2", startMs: 20000, endMs: 23000, depth: 3 },
+ ]);
+ });
+});
+
+describe("virtualSpanToSourceSpans (export coherence)", () => {
+ it("is a no-op for an identity single clip (source == virtual)", () => {
+ const clips = [clip("c1", 0, 10, 0)];
+ expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([{ startMs: 2000, endMs: 4000 }]);
+ });
+
+ it("shifts by clip in/out (a virtual span maps to its source range)", () => {
+ // Clip plays source 5..15 at virtual 0..10.
+ const clips = [clip("c1", 0, 10, 5)];
+ // Zoom at virtual 2..4 → source 7..9 (so the export matches the right frames
+ // instead of source 2..4, which are trimmed off the clip's head).
+ expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([{ startMs: 7000, endMs: 9000 }]);
+ });
+
+ it("splits a span across a clip boundary into two source spans", () => {
+ // c1 source 0..10 @ virtual 0..10; c2 source 20..30 @ virtual 10..20.
+ const clips = [clip("c1", 0, 10, 0), clip("c2", 10, 10, 20)];
+ // Zoom at virtual 8..12 straddles the boundary → source 8..10 and 20..22.
+ expect(virtualSpanToSourceSpans(8000, 12000, clips)).toEqual([
+ { startMs: 8000, endMs: 10000 },
+ { startMs: 20000, endMs: 22000 },
+ ]);
+ });
+
+ it("returns [] when the span sits on no clip", () => {
+ expect(virtualSpanToSourceSpans(40000, 45000, [clip("c1", 0, 10, 0)])).toEqual([]);
+ });
+});
+
+describe("projectRegionsToSourceTime (export coherence)", () => {
+ it("splits a cross-boundary zoom into two source-time regions, second with a fresh id", () => {
+ const clips = [clip("c1", 0, 10, 0), clip("c2", 10, 10, 20)];
+ const zooms = [{ id: "z1", startMs: 8000, endMs: 12000, depth: 4 }];
+ expect(projectRegionsToSourceTime(zooms, clips, () => "z2")).toEqual([
+ { id: "z1", startMs: 8000, endMs: 10000, depth: 4 },
+ { id: "z2", startMs: 20000, endMs: 22000, depth: 4 },
+ ]);
+ });
+
+ it("passes a region over no clip through unchanged", () => {
+ const clips = [clip("c1", 0, 10, 0)];
+ const zooms = [{ id: "z1", startMs: 40000, endMs: 45000, depth: 2 }];
+ expect(projectRegionsToSourceTime(zooms, clips, () => "NEW")).toEqual(zooms);
+ });
+});
+
+describe("coalesceTouchingSpans", () => {
+ it("returns [] for empty input", () => {
+ expect(coalesceTouchingSpans([])).toEqual([]);
+ });
+
+ it("passes a single span through as its own group", () => {
+ expect(coalesceTouchingSpans([{ id: "a", start: 2, end: 5 }])).toEqual([
+ { ids: ["a"], start: 2, end: 5 },
+ ]);
+ });
+
+ it("merges two spans that touch exactly (zero gap)", () => {
+ const spans = [
+ { id: "a", start: 0, end: 5 },
+ { id: "b", start: 5, end: 9 },
+ ];
+ expect(coalesceTouchingSpans(spans)).toEqual([{ ids: ["a", "b"], start: 0, end: 9 }]);
+ });
+
+ it("merges a gap just under epsilon, keeps a gap just over epsilon separate", () => {
+ const eps = 0.001;
+ const justUnder = [
+ { id: "a", start: 0, end: 5 },
+ { id: "b", start: 5 + eps * 0.5, end: 9 },
+ ];
+ expect(coalesceTouchingSpans(justUnder, eps)).toEqual([{ ids: ["a", "b"], start: 0, end: 9 }]);
+
+ const justOver = [
+ { id: "a", start: 0, end: 5 },
+ { id: "b", start: 5 + eps * 2, end: 9 },
+ ];
+ expect(coalesceTouchingSpans(justOver, eps)).toEqual([
+ { ids: ["a"], start: 0, end: 5 },
+ { ids: ["b"], start: 5 + eps * 2, end: 9 },
+ ]);
+ });
+
+ it("merges a transitive chain A-touching-B-touching-C into one group of 3, left-to-right", () => {
+ const spans = [
+ { id: "c", start: 8, end: 12 },
+ { id: "a", start: 0, end: 4 },
+ { id: "b", start: 4, end: 8 },
+ ];
+ expect(coalesceTouchingSpans(spans)).toEqual([{ ids: ["a", "b", "c"], start: 0, end: 12 }]);
+ });
+
+ it("does not shrink the group's end when a later, nested span ends earlier (Math.max regression)", () => {
+ // A=[0,10] fully contains B=[3,7]. A naive `end = next.end` would corrupt
+ // the group's end to 7, potentially detaching a real third span near 10.
+ const spans = [
+ { id: "a", start: 0, end: 10 },
+ { id: "b", start: 3, end: 7 },
+ ];
+ expect(coalesceTouchingSpans(spans)).toEqual([{ ids: ["a", "b"], start: 0, end: 10 }]);
+ });
+
+ it("sorts unsorted input before grouping", () => {
+ const spans = [
+ { id: "b", start: 5, end: 9 },
+ { id: "a", start: 0, end: 5 },
+ ];
+ expect(coalesceTouchingSpans(spans)).toEqual([{ ids: ["a", "b"], start: 0, end: 9 }]);
+ });
+});
diff --git a/src/lib/ai-edition/timeline/region-ventilation.ts b/src/lib/ai-edition/timeline/region-ventilation.ts
new file mode 100644
index 000000000..344cdb0ff
--- /dev/null
+++ b/src/lib/ai-edition/timeline/region-ventilation.ts
@@ -0,0 +1,198 @@
+// Ventilation: distribute a virtual-timeline span across the clips it covers.
+//
+// Timeline-anchored regions (zoom / speed / annotation, stored in absolute
+// virtual-timeline ms) sit "over" the clips beneath them. When clips are
+// reordered, a region must follow the *content* it was over — which means a
+// region that straddles several clips is split into one piece per clip, each
+// following its clip. Pieces that land back-to-back after the move are merged
+// so a region only actually splits when its clips separate. Pure, no DOM/IPC.
+
+import type { AxcutClip } from "../schema";
+
+export interface ClipFragment {
+ clipId: string;
+ /** Offset (seconds) from the covering clip's timelineStartSec. */
+ localStartSec: number;
+ localEndSec: number;
+}
+
+/**
+ * Decompose a virtual-timeline span into the portions that fall over each clip,
+ * expressed as clip-local offsets. Clips the span doesn't touch are omitted.
+ */
+export function ventilateSpanAcrossClips(
+ startSec: number,
+ endSec: number,
+ clips: AxcutClip[],
+): ClipFragment[] {
+ const lo = Math.min(startSec, endSec);
+ const hi = Math.max(startSec, endSec);
+ const out: ClipFragment[] = [];
+ for (const c of clips) {
+ const s = Math.max(lo, c.timelineStartSec);
+ const e = Math.min(hi, c.timelineEndSec);
+ if (e > s) {
+ out.push({
+ clipId: c.id,
+ localStartSec: s - c.timelineStartSec,
+ localEndSec: e - c.timelineStartSec,
+ });
+ }
+ }
+ return out;
+}
+
+export interface Span {
+ startMs: number;
+ endMs: number;
+}
+
+/**
+ * Re-project a virtual-ms span through a clip reorder: decompose over the OLD
+ * clip layout, re-place over the NEW layout, then merge fragments that stay
+ * contiguous. Returns ≥1 spans — more than one only when the covered clips
+ * actually separated. A span not sitting on any clip is returned unchanged.
+ */
+export function reprojectSpanForReorder(
+ startMs: number,
+ endMs: number,
+ oldClips: AxcutClip[],
+ newClips: AxcutClip[],
+): Span[] {
+ const frags = ventilateSpanAcrossClips(startMs / 1000, endMs / 1000, oldClips);
+ if (frags.length === 0) return [{ startMs, endMs }];
+ const newById = new Map(newClips.map((c) => [c.id, c]));
+ const spans = frags
+ .map((f): Span | null => {
+ const nc = newById.get(f.clipId);
+ if (!nc) return null;
+ return {
+ startMs: Math.round((nc.timelineStartSec + f.localStartSec) * 1000),
+ endMs: Math.round((nc.timelineStartSec + f.localEndSec) * 1000),
+ };
+ })
+ .filter((x): x is Span => x !== null)
+ .sort((a, b) => a.startMs - b.startMs);
+ if (spans.length === 0) return [{ startMs, endMs }];
+ const merged: Span[] = [];
+ for (const s of spans) {
+ const last = merged.at(-1);
+ // ≤1ms rounding gap counts as contiguous.
+ if (last && s.startMs - last.endMs <= 1) last.endMs = Math.max(last.endMs, s.endMs);
+ else merged.push({ ...s });
+ }
+ return merged;
+}
+
+/**
+ * Re-project a list of virtual-ms regions through a clip reorder. A region that
+ * ends up split across separated clips becomes several regions (extra copies
+ * get a fresh id from `makeId`, keeping every other field). The first fragment
+ * keeps the original id so single-piece regions are untouched identity-wise.
+ */
+export function reprojectRegionsForReorder<
+ T extends { id: string; startMs: number; endMs: number },
+>(regions: T[], oldClips: AxcutClip[], newClips: AxcutClip[], makeId: () => string): T[] {
+ const out: T[] = [];
+ for (const region of regions) {
+ const spans = reprojectSpanForReorder(region.startMs, region.endMs, oldClips, newClips);
+ spans.forEach((span, i) => {
+ out.push({
+ ...region,
+ id: i === 0 ? region.id : makeId(),
+ startMs: span.startMs,
+ endMs: span.endMs,
+ });
+ });
+ }
+ return out;
+}
+
+/**
+ * Map a virtual-ms span down to **source-ms** spans, one per covered clip.
+ * Effects (zoom / speed / annotation) are authored in virtual time, but the
+ * export frame loop matches them against each decoded frame's *source* time —
+ * so before export a virtual region is projected onto the source ranges of the
+ * clips it covers (through clip in/out + order). A region straddling two clips
+ * yields two source spans (which land at the right output frames on each side
+ * of the clip boundary). Returns [] when the span sits on no clip.
+ */
+export function virtualSpanToSourceSpans(
+ startMs: number,
+ endMs: number,
+ clips: AxcutClip[],
+): Span[] {
+ const byId = new Map(clips.map((c) => [c.id, c]));
+ return ventilateSpanAcrossClips(startMs / 1000, endMs / 1000, clips).flatMap((f) => {
+ const c = byId.get(f.clipId);
+ if (!c) return [];
+ return [
+ {
+ startMs: Math.round((c.sourceStartSec + f.localStartSec) * 1000),
+ endMs: Math.round((c.sourceStartSec + f.localEndSec) * 1000),
+ },
+ ];
+ });
+}
+
+/**
+ * Project a list of virtual-ms regions to source-ms for the export matcher
+ * (see `virtualSpanToSourceSpans`). Regions straddling clips split into one per
+ * covered clip (extra copies get a fresh id from `makeId`; the first keeps the
+ * original id). A region over no clip is passed through unchanged (best effort).
+ */
+export function projectRegionsToSourceTime<
+ T extends { id: string; startMs: number; endMs: number },
+>(regions: T[], clips: AxcutClip[], makeId: () => string): T[] {
+ const out: T[] = [];
+ for (const region of regions) {
+ const spans = virtualSpanToSourceSpans(region.startMs, region.endMs, clips);
+ if (spans.length === 0) {
+ out.push(region);
+ continue;
+ }
+ spans.forEach((span, i) => {
+ out.push({
+ ...region,
+ id: i === 0 ? region.id : makeId(),
+ startMs: span.startMs,
+ endMs: span.endMs,
+ });
+ });
+ }
+ return out;
+}
+
+export interface CoalescedSpan {
+ /** Member ids, left-to-right. */
+ ids: string[];
+ start: number;
+ end: number;
+}
+
+/**
+ * Group same-kind spans whose edges touch (within `epsilonSec`) into single
+ * spans — the "two touching elements act as one" rule for display/selection.
+ * Sorts by start first, so grouping is transitive (A touching B touching C
+ * yields one group of 3) regardless of input order. Overlapping (not just
+ * touching) spans also merge, so a nested span with a smaller end must not
+ * shrink the group's end backward — hence `Math.max`, not overwrite.
+ */
+export function coalesceTouchingSpans(
+ spans: Array<{ id: string; start: number; end: number }>,
+ epsilonSec = 0.001,
+): CoalescedSpan[] {
+ if (spans.length === 0) return [];
+ const sorted = [...spans].sort((a, b) => a.start - b.start);
+ const out: CoalescedSpan[] = [];
+ for (const s of sorted) {
+ const last = out.at(-1);
+ if (last && s.start - last.end <= epsilonSec) {
+ last.ids.push(s.id);
+ last.end = Math.max(last.end, s.end);
+ } else {
+ out.push({ ids: [s.id], start: s.start, end: s.end });
+ }
+ }
+ return out;
+}
diff --git a/src/lib/ai-edition/timeline/trim-mapping.test.ts b/src/lib/ai-edition/timeline/trim-mapping.test.ts
new file mode 100644
index 000000000..9f50fe7ca
--- /dev/null
+++ b/src/lib/ai-edition/timeline/trim-mapping.test.ts
@@ -0,0 +1,341 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
+import {
+ coalescedTrimGroups,
+ resolveTimelineSpanToTrim,
+ trimToTimelineSpan,
+ ventilateTimelineSpanToTrims,
+} from "./trim-mapping";
+
+function clip(partial: Partial<AxcutClip> & Pick<AxcutClip, "id" | "assetId">): AxcutClip {
+ return {
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ ...partial,
+ };
+}
+
+function trim(
+ partial: Partial<AxcutTrimRange> & Pick<AxcutTrimRange, "id" | "assetId">,
+): AxcutTrimRange {
+ return { startSec: 0, endSec: 1, reason: "", origin: "user", ...partial };
+}
+
+describe("trimToTimelineSpan", () => {
+ it("maps a source-time trim through an identity single clip", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 42,
+ timelineStartSec: 0,
+ timelineEndSec: 42,
+ }),
+ ];
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 5, endSec: 7 }, clips)).toEqual({
+ start: 5,
+ end: 7,
+ });
+ });
+
+ it("offsets by the carrying clip's source→timeline shift", () => {
+ // Clip plays source 16..30 at timeline 14..28.
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ // A trim at source 20..22 lives in c2 → timeline 14 + (20-16) = 18..20.
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 20, endSec: 22 }, clips)).toEqual({
+ start: 18,
+ end: 20,
+ });
+ });
+
+ it("returns null when no clip carries the trim's source region", () => {
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 40, endSec: 42 }, clips)).toBeNull();
+ expect(trimToTimelineSpan({ assetId: "b", startSec: 2, endSec: 4 }, clips)).toBeNull();
+ });
+});
+
+describe("resolveTimelineSpanToTrim", () => {
+ it("maps a timeline span back to source-time on the containing clip", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ // Timeline 18..20 falls in c2 (asset b) → source 16 + (18-14)=20 .. 22.
+ expect(resolveTimelineSpanToTrim(18, 20, clips)).toEqual({
+ assetId: "b",
+ sourceStartSec: 20,
+ sourceEndSec: 22,
+ });
+ });
+
+ it("re-attaches to whichever clip the span's start lands in", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ // Start in c1 → asset a, start in c2 → asset b.
+ expect(resolveTimelineSpanToTrim(2, 4, clips)?.assetId).toBe("a");
+ expect(resolveTimelineSpanToTrim(20, 22, clips)?.assetId).toBe("b");
+ });
+
+ it("clamps the span to the carrier clip's extent (no straddling)", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ // Span 10..20 starts in c1; end clamps to c1's end (timeline 14 → source 14).
+ expect(resolveTimelineSpanToTrim(10, 20, clips)).toEqual({
+ assetId: "a",
+ sourceStartSec: 10,
+ sourceEndSec: 14,
+ });
+ });
+
+ it("round-trips with trimToTimelineSpan", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ const resolved = resolveTimelineSpanToTrim(18, 21, clips);
+ expect(resolved).not.toBeNull();
+ if (!resolved) return;
+ const back = trimToTimelineSpan(
+ {
+ assetId: resolved.assetId,
+ startSec: resolved.sourceStartSec,
+ endSec: resolved.sourceEndSec,
+ },
+ clips,
+ );
+ expect(back).toEqual({ start: 18, end: 21 });
+ });
+
+ it("returns null with no clips", () => {
+ expect(resolveTimelineSpanToTrim(1, 2, [])).toBeNull();
+ });
+});
+
+describe("ventilateTimelineSpanToTrims", () => {
+ // c1: asset a, source 0..14 at timeline 0..14. c2: asset b, source 16..30 at
+ // timeline 14..28 (a source→timeline shift so mapping is observable).
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+
+ it("stays a single source range inside one clip (matches resolveTimelineSpanToTrim)", () => {
+ expect(ventilateTimelineSpanToTrims(2, 4, clips)).toEqual([
+ { assetId: "a", sourceStartSec: 2, sourceEndSec: 4 },
+ ]);
+ });
+
+ it("splits a span across a clip boundary into one source range per clip", () => {
+ // Timeline 10..20 covers c1 (10..14) and c2 (14..20).
+ expect(ventilateTimelineSpanToTrims(10, 20, clips)).toEqual([
+ { assetId: "a", sourceStartSec: 10, sourceEndSec: 14 },
+ // c2: source 16 + (14-14)=16 .. 16 + (20-14)=22.
+ { assetId: "b", sourceStartSec: 16, sourceEndSec: 22 },
+ ]);
+ });
+
+ it("returns [] when the span sits on no clip (caller falls back)", () => {
+ expect(ventilateTimelineSpanToTrims(40, 45, clips)).toEqual([]);
+ });
+});
+
+describe("coalescedTrimGroups", () => {
+ it("groups two ventilation-produced fragments from one cross-boundary drag", () => {
+ // c1 source [0,14) at timeline [0,14); c2 source [16,30) at timeline
+ // [14,28) — a non-contiguous source gap, so trimToTimelineSpan can
+ // unambiguously attribute each fragment to its own clip (matches the
+ // fixture ventilateTimelineSpanToTrims's own tests use for the same
+ // reason). Ventilating timeline 8..20 across these clips produces
+ // exactly these two rows (source 8..14 on c1, source 16..22 on c2),
+ // whose timeline spans touch exactly at 14.
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 14,
+ timelineStartSec: 0,
+ timelineEndSec: 14,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 16,
+ sourceEndSec: 30,
+ timelineStartSec: 14,
+ timelineEndSec: 28,
+ }),
+ ];
+ const trims = [
+ trim({ id: "t1", assetId: "a", startSec: 8, endSec: 14 }), // -> timeline 8..14
+ trim({ id: "t2", assetId: "a", startSec: 16, endSec: 22 }), // -> timeline 14..20
+ ];
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1", "t2"], start: 8, end: 20 }]);
+ });
+
+ it("groups two independently-created trims snapped to touching clip boundaries", () => {
+ // Distinct from the ventilation case: two SEPARATE trims (not from one
+ // drag), each fully inside its own clip, whose mapped timeline spans
+ // happen to touch exactly at the clip boundary (e.g. both snapped there).
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ }),
+ ];
+ const trims = [
+ trim({ id: "t1", assetId: "a", startSec: 7, endSec: 10 }), // -> timeline 7..10
+ trim({ id: "t2", assetId: "b", startSec: 0, endSec: 2 }), // -> timeline 10..12
+ ];
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1", "t2"], start: 7, end: 12 }]);
+ });
+
+ it("keeps a trim separated by a real gap in its own group", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 20,
+ timelineStartSec: 0,
+ timelineEndSec: 20,
+ }),
+ ];
+ const trims = [
+ trim({ id: "t1", assetId: "a", startSec: 2, endSec: 4 }),
+ trim({ id: "t2", assetId: "a", startSec: 10, endSec: 12 }),
+ ];
+ expect(coalescedTrimGroups(trims, clips)).toEqual([
+ { ids: ["t1"], start: 2, end: 4 },
+ { ids: ["t2"], start: 10, end: 12 },
+ ]);
+ });
+
+ it("drops a trim whose carrying clip is gone, without corrupting other groups", () => {
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ }),
+ ];
+ const trims = [
+ trim({ id: "gone", assetId: "b", startSec: 0, endSec: 2 }), // no clip carries asset b
+ trim({ id: "t1", assetId: "a", startSec: 3, endSec: 5 }),
+ ];
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1"], start: 3, end: 5 }]);
+ });
+});
diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.ts
new file mode 100644
index 000000000..c100de5ef
--- /dev/null
+++ b/src/lib/ai-edition/timeline/trim-mapping.ts
@@ -0,0 +1,149 @@
+// Timeline↔source mapping for trim ranges.
+//
+// Trims are stored in the DSL in *source-time per asset*
+// (AxcutTrimRange = { assetId, startSec, endSec }) — that's the single source
+// of truth the agent's `add_trim_range` op and the exporter read. But in the
+// editor UI the user manipulates them on the timeline ruler, in *timeline
+// (virtual) time*, exactly like zoom/speed/annotation regions. These pure
+// helpers bridge the two so the DSL stays source-time while the UI treats
+// trims as first-class timeline regions that can be dragged/resized freely
+// across the ruler and re-attach to whichever clip they land on.
+
+import type { AxcutClip, AxcutTrimRange } from "../schema";
+import {
+ type CoalescedSpan,
+ coalesceTouchingSpans,
+ ventilateSpanAcrossClips,
+} from "./region-ventilation";
+
+/** A clip's on-timeline extent in source-seconds (how much of the source it plays). */
+function clipSourceLen(clip: AxcutClip): number {
+ return (clip.sourceEndSec ?? clip.sourceStartSec) - clip.sourceStartSec;
+}
+
+/**
+ * Map a source-time trim to its span on the timeline, through the clip that
+ * carries it (matches the source range of the trim's asset). Returns null when
+ * no clip currently carries the trim's source region (e.g. the clip was trimmed
+ * away) — such a trim is simply not shown on the ruler.
+ */
+export function trimToTimelineSpan(
+ trim: Pick<AxcutTrimRange, "assetId" | "startSec" | "endSec">,
+ clips: AxcutClip[],
+): { start: number; end: number } | null {
+ for (const c of clips) {
+ if (c.assetId !== trim.assetId) continue;
+ const srcEnd = c.sourceEndSec ?? c.sourceStartSec;
+ // Anchor on the trim's start falling inside this clip's source range.
+ if (trim.startSec >= c.sourceStartSec && trim.startSec <= srcEnd) {
+ const map = (s: number) =>
+ c.timelineStartSec + (Math.min(Math.max(s, c.sourceStartSec), srcEnd) - c.sourceStartSec);
+ return { start: map(trim.startSec), end: map(trim.endSec) };
+ }
+ }
+ return null;
+}
+
+/** A source range for one clip, the shape a DSL trim entry needs. */
+export interface TrimSourceRange {
+ assetId: string;
+ sourceStartSec: number;
+ sourceEndSec: number;
+}
+
+/**
+ * Ventilate a **timeline** span into one source range per clip it covers — the
+ * cross-clip analogue of `resolveTimelineSpanToTrim`. A trim grown across a clip
+ * boundary can't be a single source range (source-time is per asset and the
+ * clips may draw from different source positions or assets), so it materialises
+ * as one entry per covered clip, exactly like a zoom straddling two clips splits
+ * on reorder. Uses the shared ventilation primitive so trims and effects share
+ * one manipulation path. Returns [] when the span touches no clip (the caller
+ * falls back to the nearest-clip single range).
+ */
+export function ventilateTimelineSpanToTrims(
+ startSec: number,
+ endSec: number,
+ clips: AxcutClip[],
+): TrimSourceRange[] {
+ const byId = new Map(clips.map((c) => [c.id, c]));
+ return ventilateSpanAcrossClips(startSec, endSec, clips).flatMap((f) => {
+ const c = byId.get(f.clipId);
+ if (!c) return [];
+ return [
+ {
+ assetId: c.assetId,
+ sourceStartSec: c.sourceStartSec + f.localStartSec,
+ sourceEndSec: c.sourceStartSec + f.localEndSec,
+ },
+ ];
+ });
+}
+
+/**
+ * Group trims whose timeline spans touch into one visual unit — trims carry no
+ * user-visible content (no text, no per-instance settings), so unlike zoom /
+ * speed / annotation, coalescing them for display and selection loses nothing.
+ * This is what lets a trim ventilated across a clip boundary (necessarily 2+
+ * DSL rows, see `ventilateTimelineSpanToTrims`) render and act as ONE pill —
+ * aligning trims with how zoom/speed/annotation already behave under direct
+ * drag (never visibly split). Trims with no mapped timeline span (their
+ * carrying clip is gone) are dropped entirely, same as `trimToTimelineSpan`
+ * callers already expect.
+ */
+export function coalescedTrimGroups(
+ trimRanges: AxcutTrimRange[],
+ clips: AxcutClip[],
+ epsilonSec?: number,
+): CoalescedSpan[] {
+ const spans = trimRanges
+ .map((t) => {
+ const mapped = trimToTimelineSpan(t, clips);
+ return mapped ? { id: t.id, start: mapped.start, end: mapped.end } : null;
+ })
+ .filter((x): x is { id: string; start: number; end: number } => x !== null);
+ return coalesceTouchingSpans(spans, epsilonSec);
+}
+
+/**
+ * Inverse mapping: given a desired **timeline** span, find the clip whose
+ * timeline extent contains the span's start, clamp the span to that clip's
+ * extent, and map both edges back to the clip's **source-time** — yielding the
+ * `assetId` + source range a DSL trim needs. This is what lets a trim be
+ * dragged anywhere on the ruler and re-attach to whichever clip it lands on,
+ * always producing a valid single-asset source range.
+ *
+ * Returns null when there are no clips at all.
+ */
+export function resolveTimelineSpanToTrim(
+ startSec: number,
+ endSec: number,
+ clips: AxcutClip[],
+): { assetId: string; sourceStartSec: number; sourceEndSec: number } | null {
+ if (clips.length === 0) return null;
+ const lo = Math.min(startSec, endSec);
+ const hi = Math.max(startSec, endSec);
+
+ // Clip whose timeline extent contains `lo`; fall back to the nearest clip so
+ // a span dropped into a gap or past the end still resolves cleanly.
+ const carrier =
+ clips.find((c) => lo >= c.timelineStartSec && lo <= c.timelineEndSec) ??
+ clips.reduce((best, c) =>
+ Math.abs(c.timelineStartSec - lo) < Math.abs(best.timelineStartSec - lo) ? c : best,
+ );
+
+ const srcLen = clipSourceLen(carrier);
+ // Clamp the timeline span to the carrier's timeline extent so it maps to a
+ // single, in-bounds source range (trims never straddle two clips in the DSL).
+ const tStart = Math.max(
+ carrier.timelineStartSec,
+ Math.min(lo, carrier.timelineStartSec + srcLen),
+ );
+ const tEnd = Math.max(tStart, Math.min(hi, carrier.timelineStartSec + srcLen));
+ const toSrc = (t: number) => carrier.sourceStartSec + (t - carrier.timelineStartSec);
+ return {
+ assetId: carrier.assetId,
+ sourceStartSec: toSrc(tStart),
+ sourceEndSec: toSrc(tEnd),
+ };
+}
diff --git a/src/lib/ai-edition/timeline/zoom-suggestions.test.ts b/src/lib/ai-edition/timeline/zoom-suggestions.test.ts
new file mode 100644
index 000000000..2c0229959
--- /dev/null
+++ b/src/lib/ai-edition/timeline/zoom-suggestions.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import type { CursorTelemetryPoint } from "@/components/video-editor/types";
+import { buildAutoZoomSuggestions, detectZoomDwellCandidates } from "./zoom-suggestions";
+
+// A dwell = many samples clustered in time at (nearly) the same position.
+function dwell(
+ centerMs: number,
+ cx: number,
+ cy: number,
+ count = 6,
+ spanMs = 900,
+): CursorTelemetryPoint[] {
+ const step = spanMs / (count - 1);
+ return Array.from({ length: count }, (_, i) => ({
+ timeMs: centerMs - spanMs / 2 + i * step,
+ cx,
+ cy,
+ }));
+}
+
+describe("detectZoomDwellCandidates", () => {
+ it("finds a dwell where the cursor sits still", () => {
+ const candidates = detectZoomDwellCandidates(dwell(1000, 0.4, 0.6));
+ expect(candidates).toHaveLength(1);
+ expect(candidates[0].focus.cx).toBeCloseTo(0.4, 5);
+ expect(candidates[0].focus.cy).toBeCloseTo(0.6, 5);
+ });
+
+ it("ignores a fast sweep across the screen (no dwell)", () => {
+ const samples: CursorTelemetryPoint[] = Array.from({ length: 10 }, (_, i) => ({
+ timeMs: i * 100,
+ cx: i / 10,
+ cy: i / 10,
+ }));
+ expect(detectZoomDwellCandidates(samples)).toHaveLength(0);
+ });
+});
+
+describe("buildAutoZoomSuggestions", () => {
+ it("returns a centered span around each accepted dwell", () => {
+ const telemetry = dwell(2000, 0.5, 0.5);
+ const suggestions = buildAutoZoomSuggestions({
+ cursorTelemetry: telemetry,
+ totalMs: 5000,
+ existingRegions: [],
+ defaultDurationMs: 2000,
+ });
+ expect(suggestions).toHaveLength(1);
+ // centred on ~2000ms with a 2000ms default → ~1000..3000
+ expect(suggestions[0].span.start).toBe(1000);
+ expect(suggestions[0].span.end).toBe(3000);
+ });
+
+ it("drops candidates overlapping an existing zoom region", () => {
+ const telemetry = dwell(2000, 0.5, 0.5);
+ const suggestions = buildAutoZoomSuggestions({
+ cursorTelemetry: telemetry,
+ totalMs: 5000,
+ existingRegions: [{ startMs: 1500, endMs: 2500 }],
+ defaultDurationMs: 2000,
+ });
+ expect(suggestions).toHaveLength(0);
+ });
+
+ it("spaces two dwells and returns both when far apart", () => {
+ const telemetry = [...dwell(1500, 0.2, 0.2), ...dwell(6000, 0.8, 0.8)];
+ const suggestions = buildAutoZoomSuggestions({
+ cursorTelemetry: telemetry,
+ totalMs: 9000,
+ existingRegions: [],
+ defaultDurationMs: 1500,
+ });
+ expect(suggestions.length).toBe(2);
+ });
+
+ it("returns nothing without telemetry", () => {
+ expect(
+ buildAutoZoomSuggestions({
+ cursorTelemetry: [],
+ totalMs: 5000,
+ existingRegions: [],
+ defaultDurationMs: 2000,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/src/lib/ai-edition/timeline/zoom-suggestions.ts b/src/lib/ai-edition/timeline/zoom-suggestions.ts
new file mode 100644
index 000000000..e1dd2a428
--- /dev/null
+++ b/src/lib/ai-edition/timeline/zoom-suggestions.ts
@@ -0,0 +1,164 @@
+// Cursor-telemetry-driven auto-zoom suggestions. Pure, no DOM/IPC.
+//
+// Ported from main's `src/components/video-editor/timeline/zoomSuggestionUtils.ts`
+// (the legacy editor's "magic wand" auto-zoom) into the ai-edition timeline
+// module. This is NOT an AI feature — it's a deterministic dwell-detector over
+// recorded cursor movement: stretches where the cursor sits still become
+// zoom-in candidates, focused on the average cursor position during the dwell.
+
+import type { CursorTelemetryPoint, ZoomFocus } from "@/components/video-editor/types";
+
+export const MIN_DWELL_DURATION_MS = 450;
+export const MAX_DWELL_DURATION_MS = 2600;
+export const DWELL_MOVE_THRESHOLD = 0.02;
+/** Minimum spacing between two accepted suggestion centres. */
+export const SUGGESTION_SPACING_MS = 1800;
+
+export interface ZoomDwellCandidate {
+ centerTimeMs: number;
+ focus: ZoomFocus;
+ strength: number;
+}
+
+function normalizeTelemetrySample(
+ sample: CursorTelemetryPoint,
+ totalMs: number,
+): CursorTelemetryPoint {
+ return {
+ timeMs: Math.max(0, Math.min(sample.timeMs, totalMs)),
+ cx: Math.max(0, Math.min(sample.cx, 1)),
+ cy: Math.max(0, Math.min(sample.cy, 1)),
+ };
+}
+
+export function normalizeCursorTelemetry(
+ telemetry: CursorTelemetryPoint[],
+ totalMs: number,
+): CursorTelemetryPoint[] {
+ return [...telemetry]
+ .filter(
+ (sample) =>
+ Number.isFinite(sample.timeMs) && Number.isFinite(sample.cx) && Number.isFinite(sample.cy),
+ )
+ .sort((a, b) => a.timeMs - b.timeMs)
+ .map((sample) => normalizeTelemetrySample(sample, totalMs));
+}
+
+export function detectZoomDwellCandidates(samples: CursorTelemetryPoint[]): ZoomDwellCandidate[] {
+ if (samples.length < 2) {
+ return [];
+ }
+
+ const dwellCandidates: ZoomDwellCandidate[] = [];
+ let runStart = 0;
+
+ const pushRunIfDwell = (startIndex: number, endIndexExclusive: number) => {
+ if (endIndexExclusive - startIndex < 2) {
+ return;
+ }
+
+ const start = samples[startIndex];
+ const end = samples[endIndexExclusive - 1];
+ const runDuration = end.timeMs - start.timeMs;
+ if (runDuration < MIN_DWELL_DURATION_MS || runDuration > MAX_DWELL_DURATION_MS) {
+ return;
+ }
+
+ const runSamples = samples.slice(startIndex, endIndexExclusive);
+ const avgCx = runSamples.reduce((sum, sample) => sum + sample.cx, 0) / runSamples.length;
+ const avgCy = runSamples.reduce((sum, sample) => sum + sample.cy, 0) / runSamples.length;
+
+ dwellCandidates.push({
+ centerTimeMs: Math.round((start.timeMs + end.timeMs) / 2),
+ focus: { cx: avgCx, cy: avgCy },
+ strength: runDuration,
+ });
+ };
+
+ for (let index = 1; index < samples.length; index += 1) {
+ const prev = samples[index - 1];
+ const curr = samples[index];
+ const distance = Math.hypot(curr.cx - prev.cx, curr.cy - prev.cy);
+
+ if (distance > DWELL_MOVE_THRESHOLD) {
+ pushRunIfDwell(runStart, index);
+ runStart = index;
+ }
+ }
+ pushRunIfDwell(runStart, samples.length);
+
+ return dwellCandidates;
+}
+
+export interface AutoZoomSuggestion {
+ span: { start: number; end: number };
+ focus: ZoomFocus;
+}
+
+/**
+ * Build non-overlapping zoom suggestions from cursor telemetry: detect dwell moments,
+ * rank by duration, space by SUGGESTION_SPACING_MS, drop any overlapping an existing
+ * region. Pure, shared by the magic-wand toggle and the on-load auto-suggest pass.
+ */
+export function buildAutoZoomSuggestions(options: {
+ cursorTelemetry: CursorTelemetryPoint[];
+ totalMs: number;
+ existingRegions: { startMs: number; endMs: number }[];
+ defaultDurationMs: number;
+}): AutoZoomSuggestion[] {
+ const { cursorTelemetry, totalMs, existingRegions, defaultDurationMs } = options;
+ if (totalMs <= 0 || cursorTelemetry.length < 2) {
+ return [];
+ }
+
+ const defaultDuration = Math.min(defaultDurationMs, totalMs);
+ if (defaultDuration <= 0) {
+ return [];
+ }
+
+ const normalizedSamples = normalizeCursorTelemetry(cursorTelemetry, totalMs);
+ if (normalizedSamples.length < 2) {
+ return [];
+ }
+
+ const dwellCandidates = detectZoomDwellCandidates(normalizedSamples);
+ if (dwellCandidates.length === 0) {
+ return [];
+ }
+
+ const reservedSpans = existingRegions
+ .map((region) => ({ start: region.startMs, end: region.endMs }))
+ .sort((a, b) => a.start - b.start);
+
+ const sortedCandidates = [...dwellCandidates].sort((a, b) => b.strength - a.strength);
+ const acceptedCenters: number[] = [];
+ const suggestions: AutoZoomSuggestion[] = [];
+
+ for (const candidate of sortedCandidates) {
+ const tooCloseToAccepted = acceptedCenters.some(
+ (center) => Math.abs(center - candidate.centerTimeMs) < SUGGESTION_SPACING_MS,
+ );
+ if (tooCloseToAccepted) {
+ continue;
+ }
+
+ const centeredStart = Math.round(candidate.centerTimeMs - defaultDuration / 2);
+ const candidateStart = Math.max(0, Math.min(centeredStart, totalMs - defaultDuration));
+ const candidateEnd = candidateStart + defaultDuration;
+ const hasOverlap = reservedSpans.some(
+ (span) => candidateEnd > span.start && candidateStart < span.end,
+ );
+ if (hasOverlap) {
+ continue;
+ }
+
+ reservedSpans.push({ start: candidateStart, end: candidateEnd });
+ acceptedCenters.push(candidate.centerTimeMs);
+ suggestions.push({
+ span: { start: candidateStart, end: candidateEnd },
+ focus: candidate.focus,
+ });
+ }
+
+ return suggestions;
+}
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index 63e187cc0..af8cfa88e 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -17,6 +17,53 @@ function isBrowserMode(): boolean {
return detectBrowserMode();
}
+// ponytail: RecStage's source picker + recording-prefs need something to talk
+// to in browser-mode preview too — real desktopCapturer isn't available in a
+// plain browser tab, so fake a couple of plausible screen/window entries
+// (no thumbnails; RecStage already falls back to an icon when thumbnail is
+// null). Prefs persist to localStorage, same pattern as the LLM config shim
+// below, so toggles survive a reload like the real main-process store would.
+type ShimDesktopSource = {
+ id: string;
+ name: string;
+ display_id: string;
+ thumbnail: string | null;
+ appIcon: string | null;
+};
+const SHIM_SOURCES: ShimDesktopSource[] = [
+ { id: "screen:0", name: "Entire Screen", display_id: "0", thumbnail: null, appIcon: null },
+ { id: "screen:1", name: "Display 2", display_id: "1", thumbnail: null, appIcon: null },
+ { id: "window:100", name: "OpenScreen", display_id: "", thumbnail: null, appIcon: null },
+ { id: "window:101", name: "Terminal", display_id: "", thumbnail: null, appIcon: null },
+];
+let shimSelectedSource: ShimDesktopSource | null = null;
+
+type ShimRecordingPrefs = {
+ micEnabled: boolean;
+ micDeviceId: string | null;
+ camEnabled: boolean;
+ camDeviceId: string | null;
+ systemAudioEnabled: boolean;
+ cursorCaptureMode: "editable-overlay" | "system";
+};
+const recordingPrefsStorageKey = "browser-shim-recording-prefs";
+let shimRecordingPrefs: ShimRecordingPrefs = {
+ micEnabled: false,
+ micDeviceId: null,
+ camEnabled: false,
+ camDeviceId: null,
+ systemAudioEnabled: false,
+ cursorCaptureMode: "editable-overlay",
+};
+(() => {
+ try {
+ const raw = localStorage.getItem(recordingPrefsStorageKey);
+ if (raw) shimRecordingPrefs = { ...shimRecordingPrefs, ...JSON.parse(raw) };
+ } catch {
+ // ponytail: corrupt/unavailable localStorage — start fresh.
+ }
+})();
+
function createShimElectronAPI() {
return {
assetBaseUrl: "",
@@ -35,6 +82,24 @@ function createShimElectronAPI() {
onRequestSaveBeforeClose: () => () => undefined,
loadProjectFileFromPath: () => Promise.resolve({ success: false, canceled: true }),
getPathForFile: () => "",
+ getSources: () => Promise.resolve(SHIM_SOURCES),
+ selectSource: (source: ShimDesktopSource) => {
+ shimSelectedSource = source;
+ return Promise.resolve(source);
+ },
+ getSelectedSource: () => Promise.resolve(shimSelectedSource),
+ onSelectedSourceChanged: () => () => undefined,
+ getRecordingPrefs: () => Promise.resolve(shimRecordingPrefs),
+ setRecordingPrefs: (patch: Partial<ShimRecordingPrefs>) => {
+ shimRecordingPrefs = { ...shimRecordingPrefs, ...patch };
+ try {
+ localStorage.setItem(recordingPrefsStorageKey, JSON.stringify(shimRecordingPrefs));
+ } catch {
+ // ponytail: localStorage may be full or unavailable; silently skip
+ }
+ return Promise.resolve(shimRecordingPrefs);
+ },
+ onRecordingPrefsChanged: () => () => undefined,
invokeNativeBridge: (req: { domain: string; action: string; payload?: unknown }) => {
console.info("[browser-shim] invokeNativeBridge", req.domain, req.action, req.payload);
return Promise.resolve({
@@ -241,7 +306,7 @@ function createShimBridgeClient() {
timeline: {
clips: [],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/tests/e2e/diagnostic.spec.ts b/tests/e2e/diagnostic.spec.ts
index a27c3a5ea..9a879e4a5 100644
--- a/tests/e2e/diagnostic.spec.ts
+++ b/tests/e2e/diagnostic.spec.ts
@@ -41,7 +41,7 @@ const DOC = {
},
],
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/tests/e2e/roadmap-coverage.spec.ts b/tests/e2e/roadmap-coverage.spec.ts
index b0b74a206..300b1ec69 100644
--- a/tests/e2e/roadmap-coverage.spec.ts
+++ b/tests/e2e/roadmap-coverage.spec.ts
@@ -93,7 +93,7 @@ function makeDoc(
timeline: {
clips,
gaps: [],
- skipRanges: [],
+ trimRanges: [],
muteRanges: [],
speedRanges: (opts.speedRegions ?? []).map((r) => ({ ...r, speed: 1.5 })),
captionRanges: [],