Skip to content

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

fix: close the rest of the auto-zoom write race, and stop the seed clobbering a measured length

EtienneLescot193bfb1b717f
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 34810eea7..966926aa0 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -14,10 +14,7 @@ import {
migrateProjectDataToAxcutDocument,
migrateRawDocumentToCurrent,
} from "@/lib/ai-edition/document/migrate";
-import {
- applyProbedDuration,
- replaceTimeline as replaceTimelineOp,
-} from "@/lib/ai-edition/document/timeline";
+import { documentAfterProbedDuration } from "@/lib/ai-edition/document/timeline";
import {
type InsertSide,
insertDocumentWord,
@@ -25,12 +22,7 @@ import {
setDocumentWordText,
} from "@/lib/ai-edition/document/transcript";
import { isModalOpen } from "@/lib/ai-edition/modalGuard";
-import {
- type AxcutAudioTrack,
- type AxcutClip,
- type AxcutDocument,
- documentSchema,
-} from "@/lib/ai-edition/schema";
+import { type AxcutAudioTrack, type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
useAssetTranscriptions,
@@ -120,59 +112,6 @@ export const DEFAULT_TIMELINE_HEIGHT_PX = 392;
export const MIN_TIMELINE_HEIGHT_PX = 160;
export const MAX_TIMELINE_HEIGHT_PX = 560;
-/**
- * What a `loadedmetadata` event should write, or `null` for "write nothing".
- *
- * Exported because it is the only part of this path a test can reach: the event
- * arrives through Preview -> PreviewCanvas -> VirtualPreview and a real <video>,
- * none of which jsdom fires. Keeping the decision here and the queueing in the
- * component means the two guards below are testable without standing all four up.
- *
- * `originatingProjectId` is the project that was open when the event fired. It
- * matters because the write is queued: by the time this runs the user may have
- * switched, and `knownSec` came off the OLD video, so applying it to the new
- * project is simply a wrong number. `saveDocument`'s epoch check cannot catch
- * that — the write is issued after the switch rather than across it.
- */
-export function documentAfterProbedDuration(
- doc: AxcutDocument | null,
- assetId: string,
- knownSec: number,
- originatingProjectId: string | undefined,
-): AxcutDocument | null {
- if (!doc || doc.assets.length === 0) return null;
- if (doc.project.id !== originatingProjectId) return null;
- if (doc.timeline.clips.length === 0) {
- // ponytail: replaceTimeline derives clip length from asset.durationSec, which
- // import never populates — without this the first auto-created clip silently
- // comes out empty (normalizeIntervals clamps against a 0 duration, dropping it).
- const primaryAssetId = doc.project.primaryAssetId ?? doc.assets[0]?.id;
- // Only the asset that actually fired. `replaceTimeline` pins every clip it
- // builds to the primary asset, and the seed sizes that clip from `knownSec` —
- // so seeding on an event from any OTHER asset writes one video's length under
- // another's id. Not a lost seed: the primary's own event does its own seeding.
- if (!primaryAssetId || primaryAssetId !== assetId) return null;
- const docWithDuration: AxcutDocument = {
- ...doc,
- assets: doc.assets.map((a) =>
- a.id === primaryAssetId ? { ...a, durationSec: knownSec } : a,
- ),
- };
- return replaceTimelineOp(
- docWithDuration,
- [{ startSec: 0, endSec: knownSec }],
- "Auto-created full-duration clip",
- );
- }
- // The pure document layer patches only the clips of THIS asset that are still
- // waiting for a real length (the pre-probe placeholder, or the extent-less clip a
- // legacy v2 import mints), shifts what follows, and brings the modifiers along —
- // anchoring the ones migration had to leave unanchored. It returns the document
- // untouched when nothing is waiting, which is this function's "write nothing".
- const next = applyProbedDuration(doc, assetId, knownSec);
- return next === doc ? null : next;
-}
-
export function NewEditorShell() {
const te = useScopedT("editor");
const document = useProjectStore((s) => s.document);
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index a4b41ff32..86524447c 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -1491,27 +1491,38 @@ export function V4Timeline({
}
setAutoBusy(true);
try {
- // Read once, up front: every clip reserves against the zooms the document
- // ALREADY holds, and two clips can never contest the same stretch of ruler, so
- // nothing here depends on the order the assets are visited — which is what lets
- // their telemetry be fetched concurrently rather than one IPC round trip after
- // another. `Promise.all` preserves input order, so the suggestions come out in
- // the same sequence a loop would have produced.
- const existingRegions = tl.zoomRegions.map((z) => ({ startMs: z.startMs, endMs: z.endMs }));
+ // Telemetry first, and nothing derived from the document until it is back.
+ // `Promise.all` preserves input order, so the suggestions still come out in the
+ // same sequence a loop would have produced.
const perSource = await Promise.all(
- sources.map(async (source) => {
- const telemetry =
- (await nativeBridgeClient.cursor.getTelemetry(fromFileUrl(source.src))) ?? [];
- return buildAutoZoomSuggestionsForClips({
- cursorTelemetry: telemetry,
- assetId: source.id,
- clips,
- existingRegions,
- defaultDurationMs: 2000,
- });
+ sources.map(async (source) => ({
+ assetId: source.id,
+ telemetry: (await nativeBridgeClient.cursor.getTelemetry(fromFileUrl(source.src))) ?? [],
+ })),
+ );
+ // Read AFTER the round trip, not before it. `addZoomsBulk` anchors what comes out
+ // of here against the document IT reads at write time, so building the spans from
+ // the pre-await `clips` puts the two halves on different rulers: a trim landing
+ // during the wait moves every clip, and a span that no longer falls in one is
+ // stored unanchored. A stale `zoomRegions` is the same shape one step over — a
+ // zoom the user added during the wait would not be reserved, and the region
+ // minted here would sit on top of it.
+ //
+ // Still read ONCE for every asset rather than per asset: each clip reserves
+ // against the zooms the document already holds, and two clips can never contest
+ // the same stretch of ruler, so nothing depends on the order they are visited.
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ const existingRegions = doc.zoomRanges.map((z) => ({ startMs: z.startMs, endMs: z.endMs }));
+ const suggestions: AutoZoomSuggestion[] = perSource.flatMap(({ assetId, telemetry }) =>
+ buildAutoZoomSuggestionsForClips({
+ cursorTelemetry: telemetry,
+ assetId,
+ clips: doc.timeline.clips,
+ existingRegions,
+ defaultDurationMs: 2000,
}),
);
- const suggestions: AutoZoomSuggestion[] = perSource.flat();
if (suggestions.length === 0) {
toast.info(t("toolbar.noAutoZoomMoments"), {
description: t("toolbar.noAutoZoomMomentsDescription"),
diff --git a/src/components/ai-edition/NewEditorShell.probedDuration.test.tsx b/src/lib/ai-edition/document/probedDuration.test.ts
similarity index 79%
rename from src/components/ai-edition/NewEditorShell.probedDuration.test.tsx
rename to src/lib/ai-edition/document/probedDuration.test.ts
index 284cdf65e..1f7aac939 100644
--- a/src/components/ai-edition/NewEditorShell.probedDuration.test.tsx
+++ b/src/lib/ai-edition/document/probedDuration.test.ts
@@ -1,36 +1,15 @@
// The decision a `loadedmetadata` event makes, on its own.
//
// The event itself arrives through Preview -> PreviewCanvas -> VirtualPreview and a
-// real <video>, which no test environment here can decode, so the component cannot
-// be driven end to end. `documentAfterProbedDuration` is the part that decides what gets
-// written, and both guards below live in it: the queue the shell puts this write on
+// real <video>, which no test environment here can decode, so the component cannot be
+// driven end to end. `documentAfterProbedDuration` is the part that decides what gets
+// written, and every guard below lives in it: the queue the shell puts this write on
// is what makes them necessary, because it puts real time between the event and the
// write. The queue's own serialization is covered by useSequentialTimelineOps.test.
-import { describe, expect, it, vi } from "vitest";
-
-vi.mock("@/contexts/ShortcutsContext", async () => {
- const { DEFAULT_SHORTCUTS } = await import("@/lib/shortcuts");
- return {
- useShortcuts: () => ({
- shortcuts: DEFAULT_SHORTCUTS,
- isMac: false,
- isConfigOpen: false,
- openConfig: vi.fn(),
- closeConfig: vi.fn(),
- setShortcuts: vi.fn(),
- persistShortcuts: () => Promise.resolve(true),
- }),
- };
-});
-
-vi.mock("@/contexts/I18nContext", () => ({
- useI18n: () => ({ locale: "en", setLocale: vi.fn() }),
- useScopedT: () => (key: string) => key,
-}));
-
-import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";
+import { describe, expect, it } from "vitest";
import { type AxcutDocument, createEmptyDocument, documentSchema } from "@/lib/ai-edition/schema";
-import { documentAfterProbedDuration } from "./NewEditorShell";
+import { migrateProjectDataToAxcutDocument } from "./migrate";
+import { documentAfterProbedDuration } from "./timeline";
const PROJECT = "proj_a";
@@ -123,6 +102,22 @@ describe("documentAfterProbedDuration", () => {
).toBeNull();
});
+ // Empty is not the same as unseeded — the user can delete their only clip — and
+ // `knownSec` is 60 whenever the <video> reports a non-finite duration. Overwriting
+ // here traded a real length for the fallback under `history: false`.
+ it("keeps a length the asset already carries, and sizes the seed against it", () => {
+ const doc = emptyTimeline("asset_1", ["asset_1"]);
+ const measured: AxcutDocument = {
+ ...doc,
+ assets: doc.assets.map((a) => ({ ...a, durationSec: 26.517 })),
+ };
+
+ const next = documentAfterProbedDuration(measured, "asset_1", 60, PROJECT);
+
+ expect(next?.assets[0].durationSec).toBe(26.517);
+ expect(next?.timeline.clips[0].timelineEndSec).toBeCloseTo(26.517, 3);
+ });
+
it("writes nothing without a document or without assets", () => {
expect(documentAfterProbedDuration(null, "asset_1", 30, PROJECT)).toBeNull();
expect(
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 8ae93098f..f997ddc18 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -562,6 +562,70 @@ export function applyProbedDuration(
);
}
+/**
+ * What a `loadedmetadata` event should write, or `null` for "write nothing".
+ *
+ * Lives here rather than in the component that fires it because it is pure document
+ * logic: `applyProbedDuration` above and `replaceTimeline` below are the whole body.
+ *
+ * `originatingProjectId` is the project that was open when the event fired. It matters
+ * because the write is queued (`NewEditorShell.handleLoadedMetadata` puts it on the
+ * shared timeline write queue): by the time this runs the user may have switched, and
+ * `knownSec` came off the OLD video, so applying it to the new project is simply a wrong
+ * number. `saveDocument`'s epoch check cannot catch that — the write is issued after the
+ * switch rather than across it.
+ */
+export function documentAfterProbedDuration(
+ doc: AxcutDocument | null,
+ assetId: string,
+ knownSec: number,
+ originatingProjectId: string | undefined,
+): AxcutDocument | null {
+ if (!doc || doc.assets.length === 0) return null;
+ if (doc.project.id !== originatingProjectId) return null;
+ if (doc.timeline.clips.length === 0) {
+ // ponytail: replaceTimeline derives clip length from asset.durationSec, which
+ // import never populates — without this the first auto-created clip silently
+ // comes out empty (normalizeIntervals clamps against a 0 duration, dropping it).
+ const primaryAssetId = doc.project.primaryAssetId ?? doc.assets[0]?.id;
+ // Only the asset that actually fired. `replaceTimeline` pins every clip it
+ // builds to the primary asset, and the seed sizes that clip from `knownSec` —
+ // so seeding on an event from any OTHER asset writes one video's length under
+ // another's id. Not a lost seed: the primary's own event does its own seeding.
+ if (!primaryAssetId || primaryAssetId !== assetId) return null;
+ const docWithDuration: AxcutDocument = {
+ ...doc,
+ // Only a length that was never measured, which is `applyProbedDuration`'s rule
+ // above widened to cover a stored 0 — the seed exists to give `replaceTimeline` a
+ // duration to clamp against, and a 0 defeats that exactly as a missing one does.
+ //
+ // An empty timeline is NOT proof the asset is unmeasured: the user can delete
+ // their only clip. And `knownSec` is the 60 s fallback whenever a MediaRecorder
+ // WebM reports a non-finite duration, so writing it unconditionally traded a real
+ // 26.517 for 60 under `history: false`, with no undo to get it back. Left alone,
+ // the recorded length is what the clip below is clamped against, which is the
+ // right number either way.
+ assets: doc.assets.map((a) =>
+ a.id === primaryAssetId && !(a.durationSec && a.durationSec > 0)
+ ? { ...a, durationSec: knownSec }
+ : a,
+ ),
+ };
+ return replaceTimeline(
+ docWithDuration,
+ [{ startSec: 0, endSec: knownSec }],
+ "Auto-created full-duration clip",
+ );
+ }
+ // The pure document layer patches only the clips of THIS asset that are still
+ // waiting for a real length (the pre-probe placeholder, or the extent-less clip a
+ // legacy v2 import mints), shifts what follows, and brings the modifiers along —
+ // anchoring the ones migration had to leave unanchored. It returns the document
+ // untouched when nothing is waiting, which is this function's "write nothing".
+ const next = applyProbedDuration(doc, assetId, knownSec);
+ return next === doc ? null : next;
+}
+
/** One interval of a rebuilt timeline, plus the identity it inherits. `keepClipId`
* is set when the CALLER'S raw interval is (to the epsilon) an existing clip's own
* source window: the same stretch of media, so the same clip. */
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index e9ad26df1..9721e3d18 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -1655,4 +1655,32 @@ describe("useTimeline.addZoomsBulk reads the document at write time", () => {
"Edited while the wand was busy",
);
});
+
+ // Reading the document fresh is what makes this reachable: the spans were built
+ // from the OLD project's telemetry and its ruler, so writing them into whatever is
+ // loaded now puts one project's zooms in another. `saveDocument`'s epoch check does
+ // not cover it -- the write is issued after the switch, not across it.
+ it("writes nothing when the project changed during the telemetry wait", async () => {
+ const { result } = renderTimeline();
+ const addZoomsBulk = result.current.addZoomsBulk;
+
+ // The user switches projects while the wand is off fetching telemetry.
+ act(() => {
+ useProjectStore.setState({
+ projectId: "proj_switched_to",
+ document: sampleDoc,
+ revision: 2,
+ });
+ });
+
+ let added: number | undefined;
+ await act(async () => {
+ added = await addZoomsBulk([
+ { span: { start: 1000, end: 2000 }, focus: { cx: 0.5, cy: 0.5 } },
+ ]);
+ });
+
+ expect(added).toBe(0);
+ expect(bridgeMocks.save).not.toHaveBeenCalled();
+ });
});
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 860b9f13f..a16605f32 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -343,6 +343,13 @@ export function useTimeline() {
// reason as `applyClipEdit`, `setTrimEntries` and `insertClipAt`.
const doc = useProjectStore.getState().document;
if (!doc || suggestions.length === 0) return 0;
+ // The same wait makes the PROJECT stale, and reading the document fresh is what
+ // exposes it: the suggestions were built from the OLD project's telemetry and its
+ // ruler, so applying them to whatever is loaded now writes one project's zooms into
+ // another. `saveDocument`'s epoch check cannot see this one -- the write is issued
+ // after the switch, not across it -- which is the same reason
+ // `documentAfterProbedDuration` carries an `originatingProjectId`.
+ if (useProjectStore.getState().projectId !== projectId) return 0;
const anchored = suggestions.flatMap((s) =>
anchorRegionsWithDerivedMs(
[
@@ -369,7 +376,7 @@ export function useTimeline() {
if (!(await saveDocument(next, { history: true }))) return 0;
return suggestions.length;
},
- [saveDocument],
+ [projectId, saveDocument],
);
const addTrim = useCallback(