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(recording): suggest cursor-dwell zooms for a freshly imported take

超超超超超级喜欢你的达妮娅91ac0fc1d859
diff --git a/src/components/ai-edition/recordingImport.test.ts b/src/components/ai-edition/recordingImport.test.ts
index 4faea3d5c..ceb7590d6 100644
--- a/src/components/ai-edition/recordingImport.test.ts
+++ b/src/components/ai-edition/recordingImport.test.ts
@@ -5,7 +5,13 @@ import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { undo } from "@/lib/ai-edition/store/undo";
import { clearHistory, past } from "@/lib/ai-edition/store/undoStack";
-import { importPendingRecording } from "./recordingImport";
+import {
+ applyPendingFreshRecordingAutoZooms,
+ consumeFreshRecordingAutoZoomPending,
+ importPendingRecording,
+ markFreshRecordingAutoZoomPending,
+ maybeSaveFreshRecordingAutoZooms,
+} from "./recordingImport";
// The first describe stubs the store actions, so the bridge is never reached
// there. The second one runs the REAL store against these, which is the only way
@@ -14,11 +20,26 @@ const bridge = vi.hoisted(() => ({
create: vi.fn(),
addAsset: vi.fn(),
save: vi.fn(),
+ getTelemetry: vi.fn(async () => []),
+}));
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: {
+ aiEdition: bridge,
+ cursor: { getTelemetry: bridge.getTelemetry },
+ },
}));
-vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: bridge } }));
-const createProject = vi.fn(async () => undefined);
-const addAsset = vi.fn(async () => null);
+// Typed to the store's own action signatures rather than cast through `any`:
+// tsconfig.test.json typechecks this file in CI, so a stub that drifts from the
+// contract it stands in for should fail there instead of passing silently.
+// `createProject` returns a document because the real one does — the import path
+// discards it, but a stub that lies about the shape is a stub that stops catching
+// the day something starts reading it.
+const createProject = vi.fn(
+ async (title: string): Promise<AxcutDocument> =>
+ createEmptyDocument({ projectId: "proj_stub", title }),
+);
+const addAsset = vi.fn(async (): Promise<null> => null);
const replaceTimeline = vi.fn(async () => undefined);
// Read before anything stubs them: the first describe replaces these actions on the
@@ -27,11 +48,19 @@ const realActions = {
createProject: useProjectStore.getState().createProject,
addAsset: useProjectStore.getState().addAsset,
replaceTimeline: useProjectStore.getState().replaceTimeline,
+ saveDocument: useProjectStore.getState().saveDocument,
};
/** Stands in for the main-process recording slot: one value, set and read. */
-function stubElectronApi(screenVideoPath: string | null) {
- let session = screenVideoPath ? { screenVideoPath, createdAt: 0 } : null;
+function stubElectronApi(
+ screenVideoPath: string | null,
+ cursorCaptureMode: "editable-overlay" | "system" = "editable-overlay",
+) {
+ let session: {
+ screenVideoPath: string;
+ createdAt: number;
+ cursorCaptureMode: "editable-overlay" | "system";
+ } | null = screenVideoPath ? { screenVideoPath, createdAt: 0, cursorCaptureMode } : null;
const api = {
getCurrentRecordingSession: vi.fn(async () =>
session ? { success: true, session } : { success: false },
@@ -49,12 +78,11 @@ function stubElectronApi(screenVideoPath: string | null) {
describe("importPendingRecording", () => {
beforeEach(() => {
vi.clearAllMocks();
+ consumeFreshRecordingAutoZoomPending();
useProjectStore.setState({
document: null,
- // biome-ignore lint/suspicious/noExplicitAny: partial action stubs, the rest of the store is untouched
- createProject: createProject as any,
- // biome-ignore lint/suspicious/noExplicitAny: partial action stubs, the rest of the store is untouched
- addAsset: addAsset as any,
+ createProject,
+ addAsset,
replaceTimeline,
});
});
@@ -144,6 +172,7 @@ describe("what the recording import leaves on the undo stack", () => {
beforeEach(() => {
vi.clearAllMocks();
+ consumeFreshRecordingAutoZoomPending();
useProjectStore.getState().clear();
useProjectStore.setState(realActions);
clearHistory();
@@ -187,3 +216,532 @@ describe("what the recording import leaves on the undo stack", () => {
expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(1);
});
});
+
+function dwell(
+ centerMs: number,
+ cx: number,
+ cy: number,
+ count = 6,
+ spanMs = 900,
+): Array<{ timeMs: number; cx: number; cy: number }> {
+ const step = spanMs / (count - 1);
+ return Array.from({ length: count }, (_, i) => ({
+ timeMs: centerMs - spanMs / 2 + i * step,
+ cx,
+ cy,
+ }));
+}
+
+function documentWithClip(durationSec = 10): AxcutDocument {
+ const doc = createEmptyDocument({ projectId: "p_autozoom", title: "Recording" });
+ return {
+ ...doc,
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "rec.mp4",
+ originalPath: "C:\\recordings\\rec.mp4",
+ cameraTrack: null,
+ durationSec,
+ },
+ ],
+ project: { ...doc.project, primaryAssetId: "asset_1" },
+ timeline: {
+ ...doc.timeline,
+ clips: [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: durationSec,
+ timelineStartSec: 0,
+ timelineEndSec: durationSec,
+ wordRefs: [],
+ origin: "system",
+ reason: "",
+ },
+ ],
+ },
+ };
+}
+
+describe("fresh-recording auto-zoom", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ consumeFreshRecordingAutoZoomPending();
+ useProjectStore.setState({
+ document: null,
+ createProject,
+ addAsset,
+ replaceTimeline,
+ });
+ });
+
+ it("marks a successful import as waiting when the document is not ready yet", async () => {
+ stubElectronApi("C:\\recordings\\recording-1.mp4");
+ await importPendingRecording();
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("does not mark when nothing is waiting", async () => {
+ stubElectronApi(null);
+ await importPendingRecording();
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(false);
+ });
+
+ // A system-cursor take writes no `.cursor.json`, so there is never a dwell to
+ // find. Marking it pending anyway left the flag set for the life of the window
+ // and burned all three retries on an empty sidecar.
+ it("does not mark a system-cursor take as waiting", async () => {
+ stubElectronApi("C:\\recordings\\recording-1.mp4", "system");
+ await importPendingRecording();
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(false);
+ });
+
+ it("still marks an editable-cursor take from the same import path", async () => {
+ stubElectronApi("C:\\recordings\\recording-1.mp4", "editable-overlay");
+ await importPendingRecording();
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("applies cursor-dwell zooms once, after duration is known", async () => {
+ markFreshRecordingAutoZoomPending();
+ const next = await applyPendingFreshRecordingAutoZooms(documentWithClip(), {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_test`,
+ });
+ expect(next.zoomRanges).toHaveLength(1);
+ expect(next.zoomRanges[0]).toMatchObject({
+ startMs: 3000,
+ endMs: 5000,
+ focusMode: "auto",
+ });
+ expect(await applyPendingFreshRecordingAutoZooms(next, { enabled: true })).toBe(next);
+ });
+
+ it("skips when the HUD toggle is off", async () => {
+ markFreshRecordingAutoZoomPending();
+ const document = documentWithClip();
+ const next = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: false,
+ getTelemetry: async () => dwell(4000, 0.5, 0.5),
+ });
+ expect(next).toBe(document);
+ expect(next.zoomRanges).toEqual([]);
+ });
+
+ it("keeps the pending flag when the sidecar is still empty, then applies on retry", async () => {
+ markFreshRecordingAutoZoomPending();
+ const document = documentWithClip();
+ const first = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => [],
+ });
+ expect(first).toBe(document);
+ const next = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_retry`,
+ });
+ expect(next.zoomRanges).toHaveLength(1);
+ expect(await applyPendingFreshRecordingAutoZooms(next, { enabled: true })).toBe(next);
+ });
+
+ it("keeps the pending flag when clips are not on the document yet", async () => {
+ markFreshRecordingAutoZoomPending();
+ const document = createEmptyDocument({ projectId: "p_empty", title: "Recording" });
+ const next = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.5, 0.5),
+ });
+ expect(next).toBe(document);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("keeps pending when telemetry is present but no dwell has landed yet", async () => {
+ markFreshRecordingAutoZoomPending();
+ const document = documentWithClip();
+ const moving = Array.from({ length: 8 }, (_, i) => ({
+ timeMs: 1000 + i * 80,
+ cx: 0.2 + i * 0.08,
+ cy: 0.3,
+ }));
+ const first = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => moving,
+ });
+ expect(first).toBe(document);
+ const next = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_late`,
+ });
+ expect(next.zoomRanges).toHaveLength(1);
+ });
+
+ it("keeps pending when telemetry read throws", async () => {
+ markFreshRecordingAutoZoomPending();
+ const document = documentWithClip();
+ const next = await applyPendingFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => {
+ throw new Error("sidecar missing");
+ },
+ });
+ expect(next).toBe(document);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("does not decorate a different project's asset after a leftover pending flag", async () => {
+ markFreshRecordingAutoZoomPending("C:\\recordings\\fresh.mp4");
+ const other = documentWithClip();
+ const next = await applyPendingFreshRecordingAutoZooms(other, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ });
+ expect(next).toBe(other);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("does not decorate a later imported clip while the fresh take is still pending", async () => {
+ const fresh = documentWithClip();
+ const laterPath = "C:\\recordings\\later.mp4";
+ const withLater: AxcutDocument = {
+ ...fresh,
+ assets: [
+ ...fresh.assets,
+ {
+ id: "asset_later",
+ kind: "video",
+ label: "later.mp4",
+ originalPath: laterPath,
+ cameraTrack: null,
+ durationSec: 10,
+ },
+ ],
+ timeline: {
+ ...fresh.timeline,
+ clips: [
+ ...fresh.timeline.clips,
+ {
+ id: "clip_later",
+ assetId: "asset_later",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ wordRefs: [],
+ origin: "system",
+ reason: "",
+ },
+ ],
+ },
+ };
+ markFreshRecordingAutoZoomPending(fresh.assets[0].originalPath);
+ const next = await applyPendingFreshRecordingAutoZooms(withLater, {
+ enabled: true,
+ getTelemetry: async (videoPath) => (videoPath === laterPath ? dwell(14000, 0.4, 0.6) : []),
+ createId: (prefix) => `${prefix}_later`,
+ });
+ expect(next).toBe(withLater);
+ expect(next.zoomRanges).toEqual([]);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("waits for a probed asset duration before generating zooms", async () => {
+ markFreshRecordingAutoZoomPending();
+ const placeholder = documentWithClip(60);
+ placeholder.assets[0].durationSec = undefined;
+ const first = await applyPendingFreshRecordingAutoZooms(placeholder, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ });
+ expect(first).toBe(placeholder);
+ expect(first.zoomRanges).toEqual([]);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("appends to the store document after telemetry, not the caller's snapshot", async () => {
+ const stale = documentWithClip(90);
+ const trimmed = {
+ ...stale,
+ timeline: {
+ ...stale.timeline,
+ clips: [
+ {
+ ...stale.timeline.clips[0],
+ sourceEndSec: 80,
+ timelineEndSec: 80,
+ },
+ ],
+ },
+ };
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ markFreshRecordingAutoZoomPending(stale.assets[0].originalPath);
+ useProjectStore.setState({ document: stale });
+ const pending = applyPendingFreshRecordingAutoZooms(stale, {
+ enabled: true,
+ getTelemetry: async () => {
+ await gate;
+ return dwell(4000, 0.4, 0.6);
+ },
+ createId: (prefix) => `${prefix}_live`,
+ });
+ useProjectStore.setState({ document: trimmed });
+ release();
+ const next = await pending;
+ expect(next.timeline.clips[0].sourceEndSec).toBe(80);
+ expect(next.zoomRanges).toHaveLength(1);
+ });
+
+ it("does not re-apply after a successful save once the user removes the zooms", async () => {
+ const document = documentWithClip();
+ const saveDocument = vi.fn(async (next: AxcutDocument) => {
+ useProjectStore.setState({ document: next });
+ return true;
+ });
+ useProjectStore.setState({
+ document,
+ saveDocument,
+ });
+ markFreshRecordingAutoZoomPending(document.assets[0].originalPath);
+ await expect(
+ maybeSaveFreshRecordingAutoZooms(document, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_once`,
+ }),
+ ).resolves.toBe(true);
+ expect(useProjectStore.getState().document?.zoomRanges).toHaveLength(1);
+
+ const cleared = {
+ ...useProjectStore.getState().document,
+ zoomRanges: [],
+ } as AxcutDocument;
+ useProjectStore.setState({ document: cleared });
+ await expect(
+ maybeSaveFreshRecordingAutoZooms(cleared, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ }),
+ ).resolves.toBe(false);
+ expect(useProjectStore.getState().document?.zoomRanges).toEqual([]);
+ });
+
+ it("does not overwrite an in-flight user save with stale zooms", async () => {
+ const stale = documentWithClip(90);
+ const trimmed = {
+ ...stale,
+ timeline: {
+ ...stale.timeline,
+ clips: [
+ {
+ ...stale.timeline.clips[0],
+ sourceEndSec: 80,
+ timelineEndSec: 80,
+ },
+ ],
+ },
+ };
+ let releaseUserSave!: () => void;
+ const userSaveGate = new Promise<void>((resolve) => {
+ releaseUserSave = resolve;
+ });
+ let releaseTelemetry!: () => void;
+ const telemetryGate = new Promise<void>((resolve) => {
+ releaseTelemetry = resolve;
+ });
+ let saveCalls = 0;
+ bridge.save.mockImplementation(async (document: unknown) => {
+ saveCalls += 1;
+ if (saveCalls === 1) await userSaveGate;
+ return { success: true, document };
+ });
+ useProjectStore.setState({
+ document: stale,
+ saveDocument: realActions.saveDocument,
+ });
+ markFreshRecordingAutoZoomPending(stale.assets[0].originalPath);
+ const userSave = useProjectStore.getState().saveDocument(trimmed, { history: true });
+ const autoZoom = maybeSaveFreshRecordingAutoZooms(stale, {
+ enabled: true,
+ getTelemetry: async () => {
+ await telemetryGate;
+ return dwell(4000, 0.4, 0.6);
+ },
+ createId: (prefix) => `${prefix}_race`,
+ });
+ releaseTelemetry();
+ releaseUserSave();
+ await expect(userSave).resolves.toBe(true);
+ await expect(autoZoom).resolves.toBe(true);
+ const stored = useProjectStore.getState().document;
+ expect(stored?.timeline.clips[0].sourceEndSec).toBe(80);
+ expect(stored?.zoomRanges).toHaveLength(1);
+ });
+
+ // Contention is an exit, not a rebase: recomputing onto the document the other
+ // writer just produced only races that writer again. The attempt is dropped
+ // with pending intact so a retry runs against a settled document.
+ it("exits without writing when a user save lands mid-attempt", async () => {
+ const stale = documentWithClip(90);
+ const trimmed = {
+ ...stale,
+ timeline: {
+ ...stale.timeline,
+ clips: [{ ...stale.timeline.clips[0], sourceEndSec: 80, timelineEndSec: 80 }],
+ },
+ };
+ bridge.save.mockImplementation(async (document: unknown) => ({ success: true, document }));
+ useProjectStore.setState({ document: stale, saveDocument: realActions.saveDocument });
+ markFreshRecordingAutoZoomPending(stale.assets[0].originalPath);
+ let userSaveLanded = false;
+
+ const result = await maybeSaveFreshRecordingAutoZooms(stale, {
+ enabled: true,
+ // Runs between the two `waitForDocumentSaves` calls, which is exactly the
+ // window a rebase would have gone through. The save fires ONCE: if it
+ // fired again on a second suggestion pass, a rebasing implementation
+ // would bail on the newer write instead of on the contention itself, and
+ // this test would pass against the behaviour it exists to rule out.
+ getTelemetry: async () => {
+ if (!userSaveLanded) {
+ userSaveLanded = true;
+ await useProjectStore.getState().saveDocument(trimmed, { history: true });
+ }
+ return dwell(4000, 0.4, 0.6);
+ },
+ createId: (prefix) => `${prefix}_contended`,
+ });
+
+ expect(result).toBe(false);
+ const stored = useProjectStore.getState().document;
+ expect(stored?.timeline.clips[0].sourceEndSec).toBe(80);
+ expect(stored?.zoomRanges).toEqual([]);
+ // Still pending: the retries are what eventually apply the zooms.
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+
+ it("keeps pending when a later user save wipes zooms before they settle", async () => {
+ const stale = documentWithClip(90);
+ const trimmed = {
+ ...stale,
+ timeline: {
+ ...stale.timeline,
+ clips: [
+ {
+ ...stale.timeline.clips[0],
+ sourceEndSec: 80,
+ timelineEndSec: 80,
+ },
+ ],
+ },
+ };
+ let releaseAutoZoomIpc!: () => void;
+ const autoZoomIpcGate = new Promise<void>((resolve) => {
+ releaseAutoZoomIpc = resolve;
+ });
+ let releaseUserIpc!: () => void;
+ const userIpcGate = new Promise<void>((resolve) => {
+ releaseUserIpc = resolve;
+ });
+ let autoZoomStarted!: () => void;
+ const autoZoomStartedGate = new Promise<void>((resolve) => {
+ autoZoomStarted = resolve;
+ });
+ let userStarted!: () => void;
+ const userStartedGate = new Promise<void>((resolve) => {
+ userStarted = resolve;
+ });
+ let saveCalls = 0;
+ bridge.save.mockImplementation(async (document: unknown) => {
+ saveCalls += 1;
+ if (saveCalls === 1) {
+ autoZoomStarted();
+ await autoZoomIpcGate;
+ } else {
+ userStarted();
+ await userIpcGate;
+ }
+ return { success: true, document };
+ });
+ useProjectStore.setState({
+ document: stale,
+ saveDocument: realActions.saveDocument,
+ });
+ markFreshRecordingAutoZoomPending(stale.assets[0].originalPath);
+ const autoZoom = maybeSaveFreshRecordingAutoZooms(stale, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_after`,
+ });
+ await autoZoomStartedGate;
+ const userSave = useProjectStore.getState().saveDocument(trimmed, { history: true });
+ await userStartedGate;
+ releaseAutoZoomIpc();
+ releaseUserIpc();
+ await expect(userSave).resolves.toBe(true);
+ await expect(autoZoom).resolves.toBe(true);
+ const wiped = useProjectStore.getState().document;
+ expect(wiped?.timeline.clips[0].sourceEndSec).toBe(80);
+ expect(wiped?.zoomRanges).toEqual([]);
+
+ await expect(
+ maybeSaveFreshRecordingAutoZooms(wiped as AxcutDocument, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_rebase`,
+ }),
+ ).resolves.toBe(true);
+ const recovered = useProjectStore.getState().document;
+ expect(recovered?.timeline.clips[0].sourceEndSec).toBe(80);
+ expect(recovered?.zoomRanges).toHaveLength(1);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(false);
+ });
+ // Waiting on somebody else's write is only half of it: this path's OWN write
+ // can hang too. `saveDocument` never rejects, so a main process that stops
+ // answering leaves the await pending forever — inside the shared chain, which
+ // then takes every retry down with it.
+ //
+ // LAST in this file on purpose: the abandoned save is never released, so it
+ // leaves the in-flight counter raised for anything that runs after it.
+ it("gives up on a write that never answers, and leaves the chain usable", async () => {
+ const doc = documentWithClip(90);
+ bridge.save.mockReturnValue(new Promise(() => undefined));
+ useProjectStore.setState({ document: doc, saveDocument: realActions.saveDocument });
+ markFreshRecordingAutoZoomPending(doc.assets[0].originalPath);
+
+ await expect(
+ maybeSaveFreshRecordingAutoZooms(doc, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_stuck`,
+ saveTimeoutMs: 10,
+ waitTimeoutMs: 10,
+ }),
+ ).resolves.toBe(false);
+ // Nothing was written, and the attempt is still owed.
+ expect(useProjectStore.getState().document?.zoomRanges).toEqual([]);
+
+ // The chain let go: a later attempt runs instead of queueing behind a promise
+ // that is never coming back. (The abandoned save still holds the in-flight
+ // counter, so this one waits out its own deadline rather than resolving idle
+ // — which is the point: degraded, not wedged.)
+ bridge.save.mockImplementation(async (document: unknown) => ({ success: true, document }));
+ await expect(
+ maybeSaveFreshRecordingAutoZooms(doc, {
+ enabled: true,
+ getTelemetry: async () => dwell(4000, 0.4, 0.6),
+ createId: (prefix) => `${prefix}_after`,
+ saveTimeoutMs: 1_000,
+ waitTimeoutMs: 10,
+ }),
+ ).resolves.toBe(false);
+ expect(consumeFreshRecordingAutoZoomPending()).toBe(true);
+ });
+});
diff --git a/src/components/ai-edition/recordingImport.ts b/src/components/ai-edition/recordingImport.ts
index 9a3474397..a8e68beb6 100644
--- a/src/components/ai-edition/recordingImport.ts
+++ b/src/components/ai-edition/recordingImport.ts
@@ -14,7 +14,297 @@
// derived `currentVideoPath`); the only renderer that still needs the session
// after this point is the CLI runner, which lives in its own process.
-import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import type { CursorTelemetryPoint } from "@/components/video-editor/types";
+import { createId } from "@/lib/ai-edition/document/ids";
+import type { AxcutDocument } from "@/lib/ai-edition/schema";
+import {
+ DOCUMENT_SAVES_WAIT_TIMEOUT_MS,
+ saveWithDeadline,
+ useProjectStore,
+ waitForDocumentSaves,
+} from "@/lib/ai-edition/store/projectStore";
+import {
+ appendAutoZoomSuggestions,
+ collectAutoZoomSuggestionsForDocument,
+} from "@/lib/ai-edition/timeline/apply-auto-zooms";
+import { nativeBridgeClient } from "@/native/client";
+
+// Fresh recordings used to get cursor-dwell zooms on load (legacy editor
+// `autoZoomEnabled`, default on). The ai-edition import only seeded a clip, so
+// the wand still worked but a new take landed un-zoomed. This flag is the
+// one-shot hand-off: set as soon as the asset is on the document, then taken
+// only after a real apply attempt (clips exist, duration is probed, and
+// telemetry was readable, or the toggle is off). Keeping it across an
+// empty-clip / empty-sidecar / placeholder-duration pass is what lets metadata
+// win the race against the helper flush. The path stops a leftover flag from
+// decorating a later, unrelated project in the same window. A successful save
+// records the project id so a later undo or delete cannot be silently re-seeded.
+let pendingFreshRecordingAutoZoom = false;
+let pendingFreshRecordingAutoZoomPath: string | null = null;
+let appliedFreshRecordingAutoZoomProjectId: string | null = null;
+let pendingFreshRecordingAutoZoomTimers: ReturnType<typeof setTimeout>[] = [];
+let freshRecordingAutoZoomSaveChain: Promise<void> = Promise.resolve();
+
+const FRESH_RECORDING_AUTO_ZOOM_RETRY_MS = [500, 1500, 3000];
+
+function clearFreshRecordingAutoZoomTimers(): void {
+ for (const timer of pendingFreshRecordingAutoZoomTimers) {
+ clearTimeout(timer);
+ }
+ pendingFreshRecordingAutoZoomTimers = [];
+}
+
+function scheduleFreshRecordingAutoZoomRetries(): void {
+ clearFreshRecordingAutoZoomTimers();
+ for (const delayMs of FRESH_RECORDING_AUTO_ZOOM_RETRY_MS) {
+ pendingFreshRecordingAutoZoomTimers.push(
+ setTimeout(() => {
+ if (!pendingFreshRecordingAutoZoom) return;
+ const document = useProjectStore.getState().document;
+ if (document) {
+ void maybeSaveFreshRecordingAutoZooms(document);
+ }
+ }, delayMs),
+ );
+ }
+}
+
+export function markFreshRecordingAutoZoomPending(assetPath?: string): void {
+ pendingFreshRecordingAutoZoom = true;
+ pendingFreshRecordingAutoZoomPath = assetPath ?? null;
+ appliedFreshRecordingAutoZoomProjectId = null;
+ scheduleFreshRecordingAutoZoomRetries();
+}
+
+function clearFreshRecordingAutoZoomPending(): void {
+ pendingFreshRecordingAutoZoom = false;
+ pendingFreshRecordingAutoZoomPath = null;
+ clearFreshRecordingAutoZoomTimers();
+}
+
+export function consumeFreshRecordingAutoZoomPending(): boolean {
+ const was = pendingFreshRecordingAutoZoom;
+ clearFreshRecordingAutoZoomPending();
+ appliedFreshRecordingAutoZoomProjectId = null;
+ freshRecordingAutoZoomSaveChain = Promise.resolve();
+ return was;
+}
+
+export type ApplyFreshRecordingAutoZoomsDeps = {
+ enabled?: boolean;
+ getTelemetry?: (videoPath: string) => Promise<CursorTelemetryPoint[] | null | undefined>;
+ createId?: (prefix: string) => string;
+ /** Deadline for this path's own write. Tests use a short one. */
+ saveTimeoutMs?: number;
+ /** Deadline for waiting on writes somebody else started. Tests shorten it. */
+ waitTimeoutMs?: number;
+};
+
+async function readAutoZoomPref(): Promise<boolean> {
+ try {
+ const prefs = await window.electronAPI?.getRecordingPrefs?.();
+ return prefs?.autoZoomEnabled !== false;
+ } catch {
+ return true;
+ }
+}
+
+function pendingFreshRecordingAsset(document: AxcutDocument) {
+ if (pendingFreshRecordingAutoZoomPath) {
+ return document.assets.find(
+ (asset) => asset.originalPath === pendingFreshRecordingAutoZoomPath,
+ );
+ }
+ const primaryId = document.project.primaryAssetId;
+ return document.assets.find((asset) => asset.id === primaryId) ?? document.assets[0];
+}
+
+function hasProbedDurationForPendingAsset(document: AxcutDocument): boolean {
+ const asset = pendingFreshRecordingAsset(document);
+ return (
+ asset != null &&
+ asset.durationSec != null &&
+ Number.isFinite(asset.durationSec) &&
+ asset.durationSec > 0
+ );
+}
+
+function clipExtentSignature(document: AxcutDocument): string {
+ return document.timeline.clips
+ .map(
+ (clip) =>
+ `${clip.id}:${clip.assetId}:${clip.sourceStartSec}:${clip.sourceEndSec ?? ""}:${clip.timelineStartSec}:${clip.timelineEndSec}`,
+ )
+ .join("|");
+}
+
+function canApplyFreshRecordingAutoZooms(document: AxcutDocument): boolean {
+ if (!pendingFreshRecordingAutoZoom) return false;
+ if (appliedFreshRecordingAutoZoomProjectId === document.project.id) return false;
+ if ((document.zoomRanges?.length ?? 0) > 0) return false;
+ if ((document.timeline?.clips?.length ?? 0) === 0) return false;
+ if (!hasProbedDurationForPendingAsset(document)) return false;
+ if (
+ pendingFreshRecordingAutoZoomPath &&
+ !document.assets.some((asset) => asset.originalPath === pendingFreshRecordingAutoZoomPath)
+ ) {
+ return false;
+ }
+ return true;
+}
+
+function liveDocument(fallback: AxcutDocument): AxcutDocument {
+ return useProjectStore.getState().document ?? fallback;
+}
+
+export async function applyPendingFreshRecordingAutoZooms(
+ document: AxcutDocument,
+ deps: ApplyFreshRecordingAutoZoomsDeps = {},
+): Promise<AxcutDocument> {
+ if (!pendingFreshRecordingAutoZoom) return document;
+ if (appliedFreshRecordingAutoZoomProjectId === document.project.id) {
+ clearFreshRecordingAutoZoomPending();
+ return document;
+ }
+ const enabled = deps.enabled ?? (await readAutoZoomPref());
+ if (!enabled) {
+ clearFreshRecordingAutoZoomPending();
+ return liveDocument(document);
+ }
+ const start = liveDocument(document);
+ if ((start.zoomRanges?.length ?? 0) > 0) {
+ clearFreshRecordingAutoZoomPending();
+ appliedFreshRecordingAutoZoomProjectId = start.project.id;
+ return start;
+ }
+ if (!canApplyFreshRecordingAutoZooms(start)) {
+ return start;
+ }
+ const inner =
+ deps.getTelemetry ?? ((videoPath: string) => nativeBridgeClient.cursor.getTelemetry(videoPath));
+ const getTelemetry = async (videoPath: string) => {
+ try {
+ return await inner(videoPath);
+ } catch {
+ // Sidecar may not be readable yet. Keep pending for the delayed retries.
+ return [];
+ }
+ };
+ const collectFrom = async (source: AxcutDocument) => {
+ const scoped = pendingFreshRecordingAutoZoomPath
+ ? {
+ ...source,
+ assets: source.assets.filter(
+ (asset) => asset.originalPath === pendingFreshRecordingAutoZoomPath,
+ ),
+ }
+ : source;
+ return collectAutoZoomSuggestionsForDocument(scoped, getTelemetry);
+ };
+
+ const firstSignature = clipExtentSignature(start);
+ let suggestions = await collectFrom(start);
+ let latest = liveDocument(start);
+ if (latest.project.id !== start.project.id) {
+ return latest;
+ }
+ if ((latest.zoomRanges?.length ?? 0) > 0) {
+ clearFreshRecordingAutoZoomPending();
+ appliedFreshRecordingAutoZoomProjectId = latest.project.id;
+ return latest;
+ }
+ if (!canApplyFreshRecordingAutoZooms(latest)) {
+ return latest;
+ }
+ if (clipExtentSignature(latest) !== firstSignature) {
+ suggestions = await collectFrom(latest);
+ latest = liveDocument(latest);
+ if (latest.project.id !== start.project.id) return latest;
+ if ((latest.zoomRanges?.length ?? 0) > 0) {
+ clearFreshRecordingAutoZoomPending();
+ appliedFreshRecordingAutoZoomProjectId = latest.project.id;
+ return latest;
+ }
+ if (!canApplyFreshRecordingAutoZooms(latest)) return latest;
+ }
+ if (suggestions.length === 0) {
+ // Do not consume: a mid-flush sidecar can have samples but no dwell yet
+ // (the qualifying sit is often the last second of the take).
+ return latest;
+ }
+ return appendAutoZoomSuggestions(latest, suggestions, deps.createId ?? createId);
+}
+
+export async function maybeSaveFreshRecordingAutoZooms(
+ document: AxcutDocument,
+ deps: ApplyFreshRecordingAutoZoomsDeps = {},
+): Promise<boolean> {
+ const writeFreshRecordingAutoZooms = async (): Promise<boolean> => {
+ try {
+ // A wait that times out has told us nothing about what is on disk, so the
+ // only safe move is to abandon this attempt with pending still set: the
+ // retries below rebase onto whatever the stuck save eventually leaves.
+ if ((await waitForDocumentSaves(deps.waitTimeoutMs)) === "timeout") return false;
+ const latest = liveDocument(document);
+ const next = await applyPendingFreshRecordingAutoZooms(latest, deps);
+ if ((await waitForDocumentSaves(deps.waitTimeoutMs)) === "timeout") return false;
+ const current = liveDocument(document);
+ if (current.project.id !== latest.project.id) return false;
+ if ((current.zoomRanges?.length ?? 0) > 0) {
+ appliedFreshRecordingAutoZoomProjectId = current.project.id;
+ clearFreshRecordingAutoZoomPending();
+ return false;
+ }
+ // Contention means exit, not rebase. If the document moved while the
+ // suggestion pass ran, this attempt is working from a snapshot that is
+ // already history — recomputing onto the newer one just races the writer
+ // that produced it. Drop the attempt with pending still set; the
+ // 500/1500/3000 ms retries run against a settled document instead.
+ if (current !== latest) return false;
+ const toSave = next;
+ const storedNow = liveDocument(document);
+ if (storedNow !== latest) return false;
+ if (toSave === latest || toSave === storedNow) return false;
+ if (storedNow.project.id !== latest.project.id) return false;
+ const saved = await saveWithDeadline(
+ useProjectStore.getState().saveDocument(toSave, { history: true }),
+ deps.saveTimeoutMs ?? DOCUMENT_SAVES_WAIT_TIMEOUT_MS,
+ );
+ // The write never answered. Keep pending and let go of the chain, so the
+ // retries get to run instead of queueing behind a promise that is not
+ // coming back.
+ if (saved === "timeout") return false;
+ // A trim (or any other edit) can start after this save was submitted and
+ // still be in flight when it returns: `waitForDocumentSaves` before the
+ // write only sees saves that have already begun. Wait again, then look at
+ // the store — if that later write landed on the unzoomed snapshot, keep
+ // pending so a retry can try again. A timeout here says the same thing for
+ // a different reason: we cannot tell what landed, so do not clear pending.
+ if ((await waitForDocumentSaves(deps.waitTimeoutMs)) === "timeout") return saved;
+ const stored = useProjectStore.getState().document;
+ if (saved && stored && (stored.zoomRanges?.length ?? 0) > 0) {
+ appliedFreshRecordingAutoZoomProjectId = stored.project.id;
+ clearFreshRecordingAutoZoomPending();
+ }
+ return saved;
+ } catch (error) {
+ // `saveDocument` reports failure by returning false, so anything thrown
+ // here came from the suggestion pass or a bridge call. Pending stays set
+ // and the retries fire silently — log it, or the whole path is invisible.
+ console.warn("[recording] fresh-recording auto-zoom write failed:", error);
+ return false;
+ }
+ };
+ const done = freshRecordingAutoZoomSaveChain.then(
+ writeFreshRecordingAutoZooms,
+ writeFreshRecordingAutoZooms,
+ );
+ freshRecordingAutoZoomSaveChain = done.then(
+ () => undefined,
+ () => undefined,
+ );
+ return done;
+}
/**
* Imports the recording the HUD handed over into a new project, and consumes the
@@ -31,10 +321,23 @@ export async function importPendingRecording(): Promise<boolean> {
const result = await api.getCurrentRecordingSession();
const screenPath = result.success ? result.session?.screenVideoPath : undefined;
if (!screenPath) return false;
+ const cursorCaptureMode = result.success ? result.session?.cursorCaptureMode : undefined;
const label = screenPath.split(/[\\/]/).pop() || "Recording";
await useProjectStore.getState().createProject(`Recording ${new Date().toLocaleString()}`);
await useProjectStore.getState().addAsset(screenPath, label);
+ // Mark before the video element can fire `loadedmetadata`. The asset path is
+ // already on the document; waiting until the 60s seed finished let the first
+ // metadata pass consume nothing and the second never arrive.
+ //
+ // Except for a system-cursor take, which writes no `.cursor.json` at all: the
+ // toggle stays on in prefs (it is only disabled in the UI while that mode is
+ // picked), so without this the flag was set for a recording that can never
+ // produce a dwell, and all three retries ran against an empty sidecar. What
+ // governs is the mode THIS take was recorded in, not the current preference.
+ if (cursorCaptureMode !== "system") {
+ markFreshRecordingAutoZoomPending(screenPath);
+ }
// Consumed: the recording now lives in a project. Cleared here rather than
// after the timeline seed below so a failure down there can't hand the same
// recording to the next editor window.
@@ -58,5 +361,9 @@ export async function importPendingRecording(): Promise<boolean> {
history: false,
});
}
+ const latest = useProjectStore.getState().document;
+ if (latest) {
+ await maybeSaveFreshRecordingAutoZooms(latest);
+ }
return true;
}
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index c9e5d395b..c973d3a44 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -47,6 +47,7 @@ type ShimRecordingPrefs = {
camDeviceId: string | null;
systemAudioEnabled: boolean;
cursorCaptureMode: "editable-overlay" | "system";
+ autoZoomEnabled: boolean;
};
const recordingPrefsStorageKey = "browser-shim-recording-prefs";
let shimRecordingPrefs: ShimRecordingPrefs = {
@@ -57,6 +58,7 @@ let shimRecordingPrefs: ShimRecordingPrefs = {
camDeviceId: null,
systemAudioEnabled: false,
cursorCaptureMode: "editable-overlay",
+ autoZoomEnabled: true,
};
(() => {
try {