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
fix(preview): un asset orphelin vidait tout le preview
Etienne Lescot33c811c9d1fc
diff --git a/src/components/ai-edition/Preview.test.tsx b/src/components/ai-edition/Preview.test.tsxnew file mode 100644index 000000000..d3498dfeb--- /dev/null+++ b/src/components/ai-edition/Preview.test.tsx@@ -0,0 +1,262 @@+import "@testing-library/jest-dom";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@/contexts/I18nContext";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { Preview } from "./Preview";+import type { VideoSource } from "./VirtualPreview";++vi.mock("@/native/client", () => ({+ nativeBridgeClient: { aiEdition: {} },+}));++// Stand-in for the real canvas (native compositor, editor settings, a live+// <video>): it only has to report WHICH sources it was handed and let a test+// fire the load failure for one of them, which is the entire contract Preview+// owns.+vi.mock("./PreviewCanvas", () => ({+ PreviewCanvas: ({+ videoSources,+ onVideoError,+ }: {+ videoSources: VideoSource[];+ onVideoError?: (assetId: string) => void;+ }) => (+ <div data-testid="preview-canvas" data-sources={videoSources.map((s) => s.id).join(",")}>+ {videoSources.map((source) => (+ <button+ key={source.id}+ type="button"+ data-testid={`fail-${source.id}`}+ onClick={() => onVideoError?.(source.id)}+ >+ {source.src}+ </button>+ ))}+ </div>+ ),+}));++function clip(id: string, assetId: string, startSec: number, endSec: number): AxcutClip {+ return {+ id,+ assetId,+ sourceStartSec: 0,+ sourceEndSec: endSec - startSec,+ timelineStartSec: startSec,+ timelineEndSec: endSec,+ wordRefs: [],+ origin: "user",+ reason: "",+ };+}++function source(id: string): VideoSource {+ return { id, src: `file:///tmp/${id}.mp4`, label: id };+}++function renderPreview(props: {+ videoSources: VideoSource[];+ clips: AxcutClip[];+ hasAsset?: boolean;+ hasProject?: boolean;+}) {+ return render(+ <I18nProvider>+ <Preview+ hasProject={props.hasProject ?? true}+ hasAsset={props.hasAsset ?? true}+ videoSources={props.videoSources}+ clips={props.clips}+ seekTarget={null}+ onTimeChange={vi.fn()}+ onSeek={vi.fn()}+ onLoadedMetadata={vi.fn()}+ onVideoElement={vi.fn()}+ playing={false}+ />+ </I18nProvider>,+ );+}++const canvas = () => screen.queryByTestId("preview-canvas");+const emptyState = () => screen.queryByText(/add a video to get started/i);++describe("Preview follows the timeline, not the asset list", () => {+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ // THE regression: the user imported a file, then moved/deleted it (or removed+ // the clip that used it), leaving a dangling asset in the document. It sorted+ // FIRST in `document.assets`, so it was the source the canvas mounted, its+ // <video> failed, and the whole preview fell back to the empty state — with a+ // perfectly playable clip sitting on the timeline.+ it("never mounts an asset no clip references", () => {+ renderPreview({+ videoSources: [source("dangling"), source("valid")],+ clips: [clip("clip_a", "valid", 0, 24.7)],+ });++ expect(canvas()).toBeInTheDocument();+ expect(canvas()).toHaveAttribute("data-sources", "valid");+ expect(emptyState()).not.toBeInTheDocument();+ });++ // The dead asset can't even report a failure now, but should one arrive for a+ // source that is no longer used, it must not blank a preview built from other+ // sources entirely.+ it("keeps rendering when the unreferenced asset is the only broken one", () => {+ const { rerender } = renderPreview({+ videoSources: [source("dangling")],+ clips: [],+ });+ // No clips yet → fallback to every asset, so the dead one does mount and fail.+ act(() => {+ fireEvent.click(screen.getByTestId("fail-dangling"));+ });+ expect(emptyState()).toBeInTheDocument();++ // A clip lands on a healthy asset: the preview is driven by that clip now,+ // and the earlier failure of an asset nothing references is irrelevant.+ rerender(+ <I18nProvider>+ <Preview+ hasProject={true}+ hasAsset={true}+ videoSources={[source("dangling"), source("valid")]}+ clips={[clip("clip_a", "valid", 0, 24.7)]}+ seekTarget={null}+ onTimeChange={vi.fn()}+ onSeek={vi.fn()}+ onLoadedMetadata={vi.fn()}+ onVideoElement={vi.fn()}+ playing={false}+ />+ </I18nProvider>,+ );++ expect(canvas()).toHaveAttribute("data-sources", "valid");+ });++ // Mounting index 0 is VirtualPreview's own starting point, so the source list+ // has to lead with the asset the playhead needs at 0:00 — not whatever order+ // the assets happen to be stored in.+ it("orders the sources by timeline position", () => {+ renderPreview({+ videoSources: [source("second"), source("first")],+ clips: [clip("clip_b", "second", 10, 20), clip("clip_a", "first", 0, 10)],+ });++ expect(canvas()).toHaveAttribute("data-sources", "first,second");+ });++ // An asset used by two clips must not be handed over twice — VirtualPreview+ // indexes into this list, and a duplicate entry means two indices for one+ // source (and a pointless <video> remount on the boundary between them).+ it("de-duplicates an asset used by several clips", () => {+ renderPreview({+ videoSources: [source("only")],+ clips: [clip("clip_a", "only", 0, 10), clip("clip_b", "only", 10, 20)],+ });++ expect(canvas()).toHaveAttribute("data-sources", "only");+ });++ // The bootstrap path: `handleLoadedMetadata` mints the very first clip from+ // the <video>'s own metadata, so a just-imported asset has to be mounted+ // while nothing references it yet.+ it("falls back to every asset while the timeline is empty", () => {+ renderPreview({ videoSources: [source("fresh_import")], clips: [] });++ expect(canvas()).toHaveAttribute("data-sources", "fresh_import");+ });+});++describe("Preview still degrades to the empty state on a real failure", () => {+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ // The documented intent this fix must not regress: a truncated recording from+ // a bad MediaRecorder capture is referenced by a clip, fails to load, and the+ // user gets the import affordance rather than a broken preview.+ it("shows the empty state when the clip's own asset fails to load", () => {+ renderPreview({+ videoSources: [source("truncated")],+ clips: [clip("clip_a", "truncated", 0, 60)],+ });+ expect(canvas()).toBeInTheDocument();++ act(() => {+ fireEvent.click(screen.getByTestId("fail-truncated"));+ });++ expect(canvas()).not.toBeInTheDocument();+ expect(emptyState()).toBeInTheDocument();+ });++ // Per-source, not a global latch: one dead asset among several used by the+ // timeline leaves the rest renderable (VirtualPreview draws its own overlay+ // over the source that failed).+ it("survives one broken source among several the timeline uses", () => {+ renderPreview({+ videoSources: [source("broken"), source("healthy")],+ clips: [clip("clip_a", "broken", 0, 10), clip("clip_b", "healthy", 10, 20)],+ });++ act(() => {+ fireEvent.click(screen.getByTestId("fail-broken"));+ });+ expect(canvas()).toBeInTheDocument();++ // …and only collapses once nothing is left to render.+ act(() => {+ fireEvent.click(screen.getByTestId("fail-healthy"));+ });+ expect(canvas()).not.toBeInTheDocument();+ expect(emptyState()).toBeInTheDocument();+ });++ // The reset that made the old latch bearable: swapping the media out has to+ // clear the recorded failures, or the empty state would outlive the file that+ // caused it.+ it("clears recorded failures when the source set changes", () => {+ const { rerender } = renderPreview({+ videoSources: [source("truncated")],+ clips: [clip("clip_a", "truncated", 0, 60)],+ });+ act(() => {+ fireEvent.click(screen.getByTestId("fail-truncated"));+ });+ expect(emptyState()).toBeInTheDocument();++ rerender(+ <I18nProvider>+ <Preview+ hasProject={true}+ hasAsset={true}+ videoSources={[source("replacement")]}+ clips={[clip("clip_a", "replacement", 0, 60)]}+ seekTarget={null}+ onTimeChange={vi.fn()}+ onSeek={vi.fn()}+ onLoadedMetadata={vi.fn()}+ onVideoElement={vi.fn()}+ playing={false}+ />+ </I18nProvider>,+ );++ expect(canvas()).toHaveAttribute("data-sources", "replacement");+ });++ it("shows the empty state when the project has no asset at all", () => {+ renderPreview({ videoSources: [], clips: [], hasAsset: false });++ expect(canvas()).not.toBeInTheDocument();+ expect(emptyState()).toBeInTheDocument();+ });+});diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsxindex 65751b93c..03ab1d569 100644--- a/src/components/ai-edition/Preview.tsx+++ b/src/components/ai-edition/Preview.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { CameraFullscreenRegion, ZoomFocus } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import type {@@ -12,13 +12,14 @@ import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";import { EditorEmptyState } from "./EditorEmptyState";import styles from "./NewEditorShell.module.css";import { PreviewCanvas } from "./PreviewCanvas";+import type { VideoSource } from "./VirtualPreview";type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;interface PreviewProps {hasProject: boolean;hasAsset: boolean;- videoSources: import("./VirtualPreview").VideoSource[];+ videoSources: VideoSource[];clips: AxcutClip[];zoomRegions?: AxcutZoomRegion[];speedRegions?: SpeedRegion[];@@ -80,19 +81,53 @@ export function Preview({// re-render at that rate (annotations, captions, crop, Full Camera all animate// against it); the timeline does not.const currentTimeSec = useProjectStore((s) => s.currentTimeSec);+ // ponytail: the preview follows the TIMELINE, not the raw asset list. A+ // document can hold an asset no clip references — an import whose file was+ // later moved or deleted, or one left behind when its clip was removed — and+ // handing the asset list straight to the canvas made `videoSources[0]` (the+ // source VirtualPreview mounts first) that dead asset: its <video> errored,+ // latched the failure flag below, and collapsed the WHOLE preview to the+ // empty state while every clip on the timeline was perfectly playable.+ // Ordered by timeline position, so the first source mounted is the one the+ // playhead actually needs at 0:00.+ // The fallback is load-bearing: the first clip of a fresh import is minted+ // from the <video>'s own loadedmetadata (NewEditorShell.handleLoadedMetadata),+ // so with a still-empty timeline the asset has to be mounted before anything+ // references it.+ const previewSources = useMemo(() => {+ const referenced: VideoSource[] = [];+ for (const clip of [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec)) {+ if (referenced.some((source) => source.id === clip.assetId)) continue;+ const source = videoSources.find((s) => s.id === clip.assetId);+ if (source) referenced.push(source);+ }+ return referenced.length > 0 ? referenced : videoSources;+ }, [clips, videoSources]);+// ponytail: when the <video> fails to load (e.g. a truncated recording// from a bad MediaRecorder capture), swap to the empty state so the user// can import a different file instead of staring at a broken preview.- // Resets when the active source changes (asset path).- const [videoError, setVideoError] = useState(false);- const activeSourceKey = videoSources[0]?.src ?? null;+ // Tracked PER SOURCE rather than as one global latch: with several clips on+ // the timeline, a single dead asset must not blank a preview the other clips+ // can still render — VirtualPreview already shows its own "could not be+ // loaded" overlay for whichever source failed. Only when every source the+ // timeline uses is dead is there nothing left to show.+ // Resets when the set of preview sources changes (asset paths).+ const [failedSourceIds, setFailedSourceIds] = useState<string[]>([]);+ const sourceKey = previewSources.map((source) => `${source.id}::${source.src}`).join("|");const previousSourceKeyRef = useRef<string | null>(null);useEffect(() => {- if (previousSourceKeyRef.current !== activeSourceKey) {- previousSourceKeyRef.current = activeSourceKey;- setVideoError(false);+ if (previousSourceKeyRef.current !== sourceKey) {+ previousSourceKeyRef.current = sourceKey;+ setFailedSourceIds([]);}- }, [activeSourceKey]);+ }, [sourceKey]);+ const handleVideoError = useCallback((assetId: string) => {+ setFailedSourceIds((prev) => (prev.includes(assetId) ? prev : [...prev, assetId]));+ }, []);+ const allSourcesFailed =+ previewSources.length > 0 &&+ previewSources.every((source) => failedSourceIds.includes(source.id));return (<section@@ -102,9 +137,9 @@ export function Preview({data-current-time-sec={currentTimeSec.toFixed(3)}data-is-playing={playing ? "true" : "false"}>- {hasProject && hasAsset && !videoError ? (+ {hasProject && hasAsset && previewSources.length > 0 && !allSourcesFailed ? (<PreviewCanvas- videoSources={videoSources}+ videoSources={previewSources}clips={clips}zoomRegions={zoomRegions}speedRegions={speedRegions}@@ -126,7 +161,7 @@ export function Preview({onLoadedMetadata={onLoadedMetadata}onVideoElement={onVideoElement}currentTimeSec={currentTimeSec}- onVideoError={() => setVideoError(true)}+ onVideoError={handleVideoError}/>) : (<EditorEmptyState hasProject={hasProject} />diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 63e7347d2..4e430d5e8 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -85,7 +85,9 @@ interface PreviewCanvasProps {onLoadedMetadata: (sec: number, assetId: string) => void;onVideoElement: (el: HTMLVideoElement | null) => void;currentTimeSec: number;- onVideoError?: () => void;+ /** Receives the id of the asset whose <video> failed — the caller decides per+ * source whether anything is left to render (see Preview.tsx). */+ onVideoError?: (assetId: string) => void;}// ponytail: fallback only — used until the active source's <video> reportsdiff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 0adc6da6e..178c87f88 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -59,7 +59,10 @@ interface VirtualPreviewProps {) => void;onVideoElement?: (element: HTMLVideoElement | null) => void;videoStyle?: React.CSSProperties;- onVideoError?: () => void;+ /** Called with the id of the asset that failed, not as a bare "the preview is+ * broken" signal: only ONE source is mounted at a time (`activeSource`), so+ * the caller has no other way to tell which of its sources is dead. */+ onVideoError?: (assetId: string) => void;/** Crop of the active clip, as fractions (0-1) of the source frame. Absent/* identity ({x:0,y:0,width:1,height:1}) renders the full frame, unchanged* from before crop support existed. */@@ -581,7 +584,7 @@ export function VirtualPreview({// transport state (single source of truth, see NewEditorShell's// own play/pause/ended listener) actually learns playback stopped.e.currentTarget.pause();- onVideoError?.();+ onVideoError?.(activeSource.id);}}onEnded={() => {// BUG corrigé : ce handler stoppait TOUJOURS la lecture dès que le