Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): run the fresh-take auto-zoom pass on the metadata write queue
超超超超超级喜欢你的达妮娅7d550e965c08
diff --git a/src/components/ai-edition/NewEditorShell.loadedMetadata.test.ts b/src/components/ai-edition/NewEditorShell.loadedMetadata.test.tsnew file mode 100644index 000000000..f9c869553--- /dev/null+++ b/src/components/ai-edition/NewEditorShell.loadedMetadata.test.ts@@ -0,0 +1,183 @@+// What one `loadedmetadata` event does once it reaches the front of the queue.+//+// The queue is why this is worth its own test: the shell puts this step on+// `useSequentialTimelineOps` alongside the user's own edits, so a step that never+// finishes holds that queue — and everything behind it. The pure decision+// (`documentAfterProbedDuration`) is covered next door; this covers what surrounds+// it — the guards, the bounded save, and what the auto-zoom pass is handed.+import { beforeEach, 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 { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { runLoadedMetadataWrite } from "./NewEditorShell";++const PROJECT = "proj_a";++/** A fresh import: one video asset on the document, nothing on the timeline yet. */+function freshImport(): AxcutDocument {+ const doc = createEmptyDocument({ projectId: PROJECT, title: "A" });+ return {+ ...doc,+ project: { ...doc.project, primaryAssetId: "asset_1" },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "screen.mp4",+ originalPath: "/tmp/screen.mp4",+ cameraTrack: null,+ },+ ],+ };+}++/** Stands in for a save that answers, installing its result the way the real one does. */+function settlingSave() {+ return vi.fn(async (document: AxcutDocument) => {+ useProjectStore.setState({ document });+ return true;+ });+}++describe("runLoadedMetadataWrite", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useProjectStore.setState({ document: freshImport() });+ });++ it("folds the probed length in and hands auto-zoom the saved document", async () => {+ const saveDocument = settlingSave();+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ expect(saveDocument).toHaveBeenCalledTimes(1);+ const saved = saveDocument.mock.calls[0][0];+ expect(saved.timeline.clips).toHaveLength(1);+ expect(saved.assets[0].durationSec).toBe(12.5);+ // Not the pre-save snapshot: auto-zoom appends to whatever is on the store now.+ expect(autoZoom).toHaveBeenCalledWith(useProjectStore.getState().document);+ expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(1);+ });++ // THE reason the save is bounded. `saveDocument` awaits the bridge with no+ // deadline of its own and never rejects, so a main process that stops answering+ // leaves this step pending for the life of the renderer — and every edit queued+ // behind it waits with it, this take's auto-zoom included. Without the deadline+ // this test does not fail with a wrong value, it never finishes.+ it("gives up on a save that never answers instead of holding the queue", async () => {+ const saveDocument = vi.fn(() => new Promise<boolean>(() => undefined));+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom, saveTimeoutMs: 20 });++ expect(saveDocument).toHaveBeenCalledTimes(1);+ // The step let go and carried on, with the document the store actually holds+ // — the stuck write never installed one.+ expect(autoZoom).toHaveBeenCalledTimes(1);+ expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(0);+ });++ // The switch that happens DURING the save, which the guard at the top cannot+ // see. Auto-zoom would not write zooms into the new project — the pending-path+ // guard refuses it — but the passes before that check clear the pending flag on+ // whatever document they are handed, so the take that was actually imported+ // would lose its auto-zoom without a trace.+ it("stops when the project changes while the save is in flight", async () => {+ // Carrying assets on purpose: an assetless document is turned away a line+ // later for a different reason, and this test would then pass without the+ // ownership check it exists to cover.+ const other = { ...freshImport(), project: { ...freshImport().project, id: "proj_b" } };+ const saveDocument = vi.fn(async () => {+ useProjectStore.setState({ document: other });+ return true;+ });+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ expect(saveDocument).toHaveBeenCalledTimes(1);+ expect(autoZoom).not.toHaveBeenCalled();+ });++ // Same for the project being closed outright: there is nothing left for this+ // event to belong to, and the pre-switch snapshot is not a stand-in for it.+ it("stops when the project is closed while the save is in flight", async () => {+ const saveDocument = vi.fn(async () => {+ useProjectStore.setState({ document: null });+ return true;+ });+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ expect(autoZoom).not.toHaveBeenCalled();+ });++ // The event is bound to the project that owned the video when it fired, and the+ // queue puts real time between the two.+ it("writes nothing when the project changed before it ran", async () => {+ const saveDocument = settlingSave();+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", "proj_switched_away_from", { autoZoom });++ expect(saveDocument).not.toHaveBeenCalled();+ expect(autoZoom).not.toHaveBeenCalled();+ });++ it("writes nothing without a document, or without assets", async () => {+ const saveDocument = settlingSave();+ const autoZoom = vi.fn(async () => undefined);++ useProjectStore.setState({ document: null, saveDocument });+ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ const empty = createEmptyDocument({ projectId: PROJECT, title: "A" });+ useProjectStore.setState({ document: empty, saveDocument });+ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ expect(saveDocument).not.toHaveBeenCalled();+ expect(autoZoom).not.toHaveBeenCalled();+ });++ // Nothing to fold in is not a reason to skip auto-zoom: a second event for a+ // document that already has its length still has to let the suggestion pass run.+ it("still runs auto-zoom when the document needs no write", async () => {+ const saveDocument = settlingSave();+ useProjectStore.setState({ saveDocument });+ const autoZoom = vi.fn(async () => undefined);++ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });+ saveDocument.mockClear();+ await runLoadedMetadataWrite(12.5, "asset_1", PROJECT, { autoZoom });++ expect(saveDocument).not.toHaveBeenCalled();+ expect(autoZoom).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 966926aa0..3cb39c479 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -14,7 +14,10 @@ import {migrateProjectDataToAxcutDocument,migrateRawDocumentToCurrent,} from "@/lib/ai-edition/document/migrate";-import { documentAfterProbedDuration } from "@/lib/ai-edition/document/timeline";+import {+ documentAfterProbedDuration,+ PLACEHOLDER_DURATION_SEC,+} from "@/lib/ai-edition/document/timeline";import {type InsertSide,insertDocumentWord,@@ -22,8 +25,13 @@ import {setDocumentWordText,} from "@/lib/ai-edition/document/transcript";import { isModalOpen } from "@/lib/ai-edition/modalGuard";-import { type AxcutAudioTrack, type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";-import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import {+ type AxcutAudioTrack,+ type AxcutClip,+ type AxcutDocument,+ documentSchema,+} from "@/lib/ai-edition/schema";+import { saveWithDeadline, useProjectStore } from "@/lib/ai-edition/store/projectStore";import {useAssetTranscriptions,useAutoTranscription,@@ -58,7 +66,7 @@ import {type UnsavedChoice,} from "./Modals";import { Preview } from "./Preview";-import { importPendingRecording } from "./recordingImport";+import { importPendingRecording, maybeSaveFreshRecordingAutoZooms } from "./recordingImport";import { AddAudioLayerDialog } from "./v4/AddAudioLayerDialog";import v4 from "./v4/EditorShellV4.module.css";import { type EditorMode, EditorTopBar } from "./v4/EditorTopBar";@@ -112,6 +120,65 @@ export const DEFAULT_TIMELINE_HEIGHT_PX = 392;export const MIN_TIMELINE_HEIGHT_PX = 160;export const MAX_TIMELINE_HEIGHT_PX = 560;+/**+ * What one `loadedmetadata` event does, from the front of the write queue.+ *+ * Exported because it is only reachable from outside the component: the event+ * arrives through Preview, PreviewCanvas, VirtualPreview and a real `<video>`+ * decoding real media, which no test environment here provides. The decision+ * itself lives in `documentAfterProbedDuration`, and is tested next to it.+ *+ * Every store read is at call time, not from a closure. By the time this runs the+ * document may have moved on, and `originatingProjectId` is what says whether it+ * moved to a different project.+ */+export async function runLoadedMetadataWrite(+ durationSec: number,+ assetId: string,+ originatingProjectId: string | undefined,+ deps: {+ /** Defaults to the real auto-zoom pass; injected in tests. */+ autoZoom?: (document: AxcutDocument) => Promise<unknown>;+ saveTimeoutMs?: number;+ } = {},+): Promise<void> {+ // ponytail: WebM recordings from MediaRecorder report NaN/Infinity until the+ // main-process EBML fix lands. Seed against a placeholder so the timeline never+ // gets stuck empty; `documentAfterProbedDuration` is what refuses to write it over+ // a length something already measured. Auto-zoom is not fooled by it either --+ // `hasProbedDurationForPendingAsset` asks the CLIPS, not the asset, and a clip+ // still sitting at the placeholder reads as waiting.+ const knownSec =+ Number.isFinite(durationSec) && durationSec > 0 ? durationSec : PLACEHOLDER_DURATION_SEC;+ const state = useProjectStore.getState();+ const next = documentAfterProbedDuration(state.document, assetId, knownSec, originatingProjectId);+ if (next) {+ // `history: false`: this is the probed duration being folded into the document+ // on load, not something the user did — an undo landing on it would empty their+ // timeline. Auto-zoom below is a later, undoable suggestion.+ //+ // Awaited so the queue can serialise it, but bounded: `saveDocument` awaits the+ // bridge with no deadline of its own and never rejects, so a main process that+ // stops answering would hold this queue slot — and every edit behind it — for+ // the life of the renderer. The abandoned write is safe to let go of.+ await saveWithDeadline(state.saveDocument(next, { history: false }), deps.saveTimeoutMs);+ }+ // Re-checked rather than assumed: the await above is exactly when a project+ // switch lands, and the check inside the decision spoke only for the document as+ // it was before it. Handing the auto-zoom pass another project's document would+ // not write zooms into it — `canApplyFreshRecordingAutoZooms` refuses a document+ // that does not hold the pending recording — but the passes before that check DO+ // clear the pending flag on what they are given, so the take that was actually+ // imported would silently lose its auto-zoom. A closed project ends the step for+ // the same reason: there is nothing left this event belongs to.+ const settled = useProjectStore.getState().document;+ if (!settled || settled.project.id !== originatingProjectId) return;+ // A document with no assets has no take to suggest zooms for. The auto-zoom pass+ // would refuse it anyway; not calling it keeps "nothing to do" meaning nothing.+ if (settled.assets.length === 0) return;+ await (deps.autoZoom ?? maybeSaveFreshRecordingAutoZooms)(settled);+}+export function NewEditorShell() {const te = useScopedT("editor");const document = useProjectStore((s) => s.document);@@ -420,14 +487,10 @@ export function NewEditorShell() {const handleLoadedMetadata = useCallback((durationSec: number, assetId: string) => {- // ponytail: WebM recordings from MediaRecorder report NaN/Infinity- // until the main-process EBML fix lands. Fall back to a 60s seed if- // duration is unknown so the timeline never gets stuck on an empty- // placeholder.- const known = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : 60;- setSourceDuration(known);- // Read before queueing: this is the project the event belongs to. What the- // decision does with it is `documentAfterProbedDuration`'s business.+ setSourceDuration(+ Number.isFinite(durationSec) && durationSec > 0 ? durationSec : PLACEHOLDER_DURATION_SEC,+ );+ // Read before queueing: this is the project the event belongs to.const originatingProjectId = useProjectStore.getState().document?.project.id;// On the shared write queue, and reading the document inside it. Folding a// probed duration in is a read-modify-write of the whole document, which is@@ -436,24 +499,12 @@ export function NewEditorShell() {// returns the PRE-edit document while a user's save is still in flight (the// store is only written once the bridge answers), and the full snapshot built// from it lands after theirs and takes their edit with it.- void enqueueTimelineWrite(async () => {- const state = useProjectStore.getState();- const next = documentAfterProbedDuration(- state.document,- assetId,- known,- originatingProjectId,- );- if (!next) return;- // `history: false`: this is the probed duration being folded into the- // document on load, not something the user did — an undo landing on it would- // empty their timeline.- //- // Awaited, not `void`ed: the queue only serialises what it can see finish, so- // a fire-and-forget write would let the next queued edit read a document this- // one has not committed yet.- await state.saveDocument(next, { history: false });- });+ //+ // The auto-zoom pass goes on the same queued task rather than after it, so a+ // fresh take's suggestions are serialised against user edits too.+ void enqueueTimelineWrite(() =>+ runLoadedMetadataWrite(durationSec, assetId, originatingProjectId),+ );},[setSourceDuration, enqueueTimelineWrite],);diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 4a58c0fb6..fa6f62a48 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -125,7 +125,18 @@ const DECLARED: WritePath[] = [w("src/components/ai-edition/NewEditorShell.tsx", "handleConfirmUnsaved", "save", "gesture"),// The probed duration folded into the document when the <video> loads. Twice:// the first clip seed, and the backfill for clips still on a placeholder length.- w("src/components/ai-edition/NewEditorShell.tsx", "handleLoadedMetadata", "save", "automatic"),+ // It sits in `runLoadedMetadataWrite` rather than the handler because the handler+ // only puts it on the write queue — the write itself, and its deadline, are there.+ w("src/components/ai-edition/NewEditorShell.tsx", "runLoadedMetadataWrite", "save", "automatic"),+ // Auto-zoom regions suggested for a freshly imported recording. `history: true`+ // on purpose: unlike the probed duration above, this is a suggestion the user is+ // meant to be able to undo.+ w(+ "src/components/ai-edition/recordingImport.ts",+ "writeFreshRecordingAutoZooms",+ "save",+ "gesture",+ ),// Renaming the project from the title field.w("src/components/ai-edition/NewEditorShell.tsx", "handleRenameProject", "save", "gesture"),// Ctrl+S / File > Save.