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): stop a single media error from emptying the editor
EtienneLescotb7fd648227fb
diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssindex bb96cc6ce..bebed2d50 100644--- a/src/components/ai-edition/NewEditorShell.module.css+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -643,6 +643,66 @@width: 12px;height: 12px;}++/* ─── preview media failure (PreviewErrorCard) ──────────────────── */+/* Overlays the stage instead of replacing it: the native compositor is still+ painting the last composed frame underneath, and leaving that frame visible is+ what tells the user their project is fine (issue #395). Translucent, not+ opaque, for the same reason. */+.previewFailure {+ position: absolute;+ inset: 0;+ z-index: 3;+ display: grid;+ place-items: center;+ padding: var(--sp-4);+ background: rgba(9, 9, 11, 0.72);+ backdrop-filter: blur(2px);+}+.previewFailureCard {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--sp-3);+ max-width: min(38ch, 100%);+ text-align: center;+}+.previewFailureIconRing {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 40px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.05);+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);+}+.previewFailureIcon {+ width: 20px;+ height: 20px;+ color: var(--muted-foreground, rgba(255, 255, 255, 0.6));+}+.previewFailureTitle {+ margin: 0;+ font-size: 1.05rem;+ font-weight: 600;+ color: var(--fg-2);+}+.previewFailureDescription {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.5;+ color: var(--muted-foreground, rgba(255, 255, 255, 0.55));+}+/* Selectable: it exists to be copied into a bug report. */+.previewFailureDetail {+ margin: 0;+ font-size: 0.6875rem;+ font-family: var(--font-mono, ui-monospace, monospace);+ color: var(--muted-foreground, rgba(255, 255, 255, 0.35));+ user-select: text;+ word-break: break-word;+}.previewEmptyDialog {max-width: 24rem;padding: var(--sp-5);diff --git a/src/components/ai-edition/Preview.test.tsx b/src/components/ai-edition/Preview.test.tsxindex 294ad4c30..651e4ab91 100644--- a/src/components/ai-edition/Preview.test.tsx+++ b/src/components/ai-edition/Preview.test.tsx@@ -12,27 +12,43 @@ vi.mock("@/native/client", () => ({}));// 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.+// <video>): it only has to report WHICH sources it was handed, let a test fire+// the terminal failure and the recovery for one of them, and show what retry+// token it was given — which is the entire contract Preview owns.vi.mock("./PreviewCanvas", () => ({PreviewCanvas: ({videoSources,onVideoError,+ onVideoRecovered,+ retryToken,}: {videoSources: VideoSource[];- onVideoError?: (assetId: string) => void;+ onVideoError?: (assetId: string, detail: string) => void;+ onVideoRecovered?: (assetId: string) => void;+ retryToken?: number;}) => (- <div data-testid="preview-canvas" data-sources={videoSources.map((s) => s.id).join(",")}>+ <div+ data-testid="preview-canvas"+ data-sources={videoSources.map((s) => s.id).join(",")}+ data-retry-token={retryToken}+ >{videoSources.map((source) => (- <button- key={source.id}- type="button"- data-testid={`fail-${source.id}`}- onClick={() => onVideoError?.(source.id)}- >- {source.src}- </button>+ <div key={source.id}>+ <button+ type="button"+ data-testid={`fail-${source.id}`}+ onClick={() => onVideoError?.(source.id, "MEDIA_ERR_DECODE (3)")}+ >+ {source.src}+ </button>+ <button+ type="button"+ data-testid={`recover-${source.id}`}+ onClick={() => onVideoRecovered?.(source.id)}+ >+ recover+ </button>+ </div>))}</div>),@@ -56,13 +72,13 @@ function source(id: string): VideoSource {return { id, src: `file:///tmp/${id}.mp4`, label: id };}-function renderPreview(props: {+function previewProps(props: {videoSources: VideoSource[];clips: AxcutClip[];hasAsset?: boolean;hasProject?: boolean;}) {- return render(+ return (<I18nProvider><PreviewhasProject={props.hasProject ?? true}@@ -76,12 +92,21 @@ function renderPreview(props: {onVideoElement={vi.fn()}playing={false}/>- </I18nProvider>,+ </I18nProvider>);}+function renderPreview(props: Parameters<typeof previewProps>[0]) {+ return render(previewProps(props));+}+const canvas = () => screen.queryByTestId("preview-canvas");const emptyState = () => screen.queryByText(/add a video to get started/i);+const errorCard = () => screen.queryByTestId("preview-error-card");+const click = (testId: string) =>+ act(() => {+ fireEvent.click(screen.getByTestId(testId));+ });describe("Preview follows the timeline, not the asset list", () => {afterEach(() => {@@ -105,42 +130,6 @@ describe("Preview follows the timeline, not the asset list", () => {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.@@ -173,85 +162,123 @@ describe("Preview follows the timeline, not the asset list", () => {expect(canvas()).toHaveAttribute("data-sources", "fresh_import");});++ // A clip landing on a healthy asset takes over the preview regardless of what+ // happened to the asset that was mounted before it.+ it("switches to the asset a new clip references", () => {+ const { rerender } = renderPreview({ videoSources: [source("dangling")], clips: [] });+ click("fail-dangling");++ rerender(+ previewProps({+ videoSources: [source("dangling"), source("valid")],+ clips: [clip("clip_a", "valid", 0, 24.7)],+ }),+ );++ expect(canvas()).toHaveAttribute("data-sources", "valid");+ });});-describe("Preview still degrades to the empty state on a real failure", () => {+// Issue #395. Every test below used to assert the opposite — that a media+// failure collapsed the stage to the import screen. The intent was right (say+// something, offer a way out); the verdict was wrong, because the failure is+// recoverable, the project is intact, and the native canvas is still painting.+describe("Preview keeps the stage when the media fails", () => {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", () => {+ it("shows a retry card over the canvas instead of the empty state", () => {renderPreview({videoSources: [source("truncated")],clips: [clip("clip_a", "truncated", 0, 60)],});++ click("fail-truncated");+expect(canvas()).toBeInTheDocument();+ expect(errorCard()).toBeInTheDocument();+ expect(emptyState()).not.toBeInTheDocument();+ });- act(() => {- fireEvent.click(screen.getByTestId("fail-truncated"));- });+ // The MediaError code is the one thing that makes a user's report actionable;+ // it used to be discarded entirely.+ it("puts the media error on the card", () => {+ renderPreview({ videoSources: [source("truncated")], clips: [] });+ click("fail-truncated");- expect(canvas()).not.toBeInTheDocument();- expect(emptyState()).toBeInTheDocument();+ expect(errorCard()).toHaveTextContent("MEDIA_ERR_DECODE (3)");});- // 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", () => {+ // The whole point of the fix: a dead source is not a dead editor, and the+ // stage must stay mounted no matter how many sources report failure.+ it("keeps the canvas when every source the timeline uses fails", () => {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"));- });+ click("fail-broken");+ click("fail-healthy");+expect(canvas()).toBeInTheDocument();+ expect(emptyState()).not.toBeInTheDocument();+ });++ // Self-healing: VirtualPreview reports a decoded frame, so the card must go —+ // otherwise it outlives its own failure, which is the latch again in a+ // quieter form.+ it("drops the card when the source decodes again", () => {+ renderPreview({ videoSources: [source("flaky")], clips: [] });- // …and only collapses once nothing is left to render.+ click("fail-flaky");+ expect(errorCard()).toBeInTheDocument();++ click("recover-flaky");+ expect(errorCard()).not.toBeInTheDocument();+ });++ it("bumps the retry token and clears the card when the user retries", () => {+ renderPreview({ videoSources: [source("truncated")], clips: [] });+ expect(canvas()).toHaveAttribute("data-retry-token", "0");++ click("fail-truncated");act(() => {- fireEvent.click(screen.getByTestId("fail-healthy"));+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));});- expect(canvas()).not.toBeInTheDocument();- expect(emptyState()).toBeInTheDocument();++ expect(canvas()).toHaveAttribute("data-retry-token", "1");+ expect(errorCard()).not.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", () => {+ // Swapping the media out has to clear the failure, or the card would outlive+ // the file that caused it.+ it("clears the failure 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();+ click("fail-truncated");+ expect(errorCard()).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>,+ previewProps({+ videoSources: [source("replacement")],+ clips: [clip("clip_a", "replacement", 0, 60)],+ }),);expect(canvas()).toHaveAttribute("data-sources", "replacement");+ expect(errorCard()).not.toBeInTheDocument();+ });+});++describe("Preview shows the empty state only when there is nothing to show", () => {+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();});it("shows the empty state when the project has no asset at all", () => {@@ -260,4 +287,33 @@ describe("Preview still degrades to the empty state on a real failure", () => {expect(canvas()).not.toBeInTheDocument();expect(emptyState()).toBeInTheDocument();});++ it("shows the empty state when the project has no usable source", () => {+ renderPreview({ videoSources: [], clips: [] });++ expect(canvas()).not.toBeInTheDocument();+ expect(emptyState()).toBeInTheDocument();+ });++ it("shows the empty state when there is no project", () => {+ renderPreview({ videoSources: [], clips: [], hasProject: false, hasAsset: false });++ expect(emptyState()).not.toBeInTheDocument();+ expect(screen.getByText(/no project open/i)).toBeInTheDocument();+ });++ // The guard for #395 itself: no failure, however reported, may reach the+ // branch that tells a user with media loaded that they have none.+ it("never reaches the empty state while the project has media", () => {+ renderPreview({+ videoSources: [source("a"), source("b")],+ clips: [clip("clip_a", "a", 0, 10), clip("clip_b", "b", 10, 20)],+ });++ for (const id of ["a", "b"]) {+ click(`fail-${id}`);+ expect(emptyState()).not.toBeInTheDocument();+ expect(canvas()).toBeInTheDocument();+ }+ });});diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsxindex 03ab1d569..89e5db7c6 100644--- a/src/components/ai-edition/Preview.tsx+++ b/src/components/ai-edition/Preview.tsx@@ -12,6 +12,7 @@ import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";import { EditorEmptyState } from "./EditorEmptyState";import styles from "./NewEditorShell.module.css";import { PreviewCanvas } from "./PreviewCanvas";+import { PreviewErrorCard } from "./PreviewErrorCard";import type { VideoSource } from "./VirtualPreview";type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;@@ -104,30 +105,49 @@ export function Preview({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.- // 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[]>([]);+ // ponytail: a media failure used to fall through to `EditorEmptyState`, and+ // that is issue #395: ONE `error` event on the hidden <video> — including the+ // MEDIA_ERR_ABORTED every cross-asset clip boundary produces by design —+ // latched an id into a list that nothing short of a remount could clear, and+ // the editor told a user whose project was perfectly intact to "add a video to+ // get started". Ctrl+R or a trip through the Rec/Media stage was the only way+ // back, because both unmount this component.+ //+ // Two things replace it. VirtualPreview now classifies the error and reloads+ // the source itself, so a transient decode/network blip never reaches here at+ // all. What does reach here is a source that gave up after those retries, and+ // it is shown as a card OVER the still-mounted canvas — which goes on painting+ // the last good frame, because the pixels come from the native compositor and+ // the <video> is only a decode clock (see PreviewCanvas's header comment). The+ // empty state is left answering exactly one question: is there anything in+ // this project to show?+ //+ // One failure slot rather than a set: only ever ONE source is mounted+ // (VirtualPreview indexes into `videoSources`), so the failure being reported+ // is always the one the playhead needs, and any source reporting healthy means+ // the mounted one is.+ const [failure, setFailure] = useState<{ assetId: string; detail: string } | null>(null);+ const [retryToken, setRetryToken] = useState(0);const sourceKey = previewSources.map((source) => `${source.id}::${source.src}`).join("|");const previousSourceKeyRef = useRef<string | null>(null);useEffect(() => {if (previousSourceKeyRef.current !== sourceKey) {previousSourceKeyRef.current = sourceKey;- setFailedSourceIds([]);+ setFailure(null);}}, [sourceKey]);- const handleVideoError = useCallback((assetId: string) => {- setFailedSourceIds((prev) => (prev.includes(assetId) ? prev : [...prev, assetId]));+ const handleVideoError = useCallback((assetId: string, detail: string) => {+ setFailure({ assetId, detail });+ }, []);+ // Fires on every canplay, so on every seek: `setFailure(null)` against an+ // already-null state is a React bail-out, and the healthy path costs nothing.+ const handleVideoRecovered = useCallback(() => {+ setFailure((prev) => (prev === null ? prev : null));+ }, []);+ const handleRetry = useCallback(() => {+ setFailure(null);+ setRetryToken((token) => token + 1);}, []);- const allSourcesFailed =- previewSources.length > 0 &&- previewSources.every((source) => failedSourceIds.includes(source.id));return (<section@@ -137,32 +157,41 @@ export function Preview({data-current-time-sec={currentTimeSec.toFixed(3)}data-is-playing={playing ? "true" : "false"}>- {hasProject && hasAsset && previewSources.length > 0 && !allSourcesFailed ? (- <PreviewCanvas- videoSources={previewSources}- clips={clips}- zoomRegions={zoomRegions}- speedRegions={speedRegions}- cameraFullscreenRegions={cameraFullscreenRegions}- 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={handleVideoError}- />+ {hasProject && hasAsset && previewSources.length > 0 ? (+ <>+ <PreviewCanvas+ videoSources={previewSources}+ clips={clips}+ zoomRegions={zoomRegions}+ speedRegions={speedRegions}+ cameraFullscreenRegions={cameraFullscreenRegions}+ 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={handleVideoError}+ onVideoRecovered={handleVideoRecovered}+ retryToken={retryToken}+ />+ {/* Sibling of the canvas, inside `.previewWrap` (already+ position: relative) — NOT inside VirtualPreview's `.videoFrame`,+ which carries the live zoom transform and would translate the+ Retry button off the stage at high zoom. */}+ {failure ? <PreviewErrorCard detail={failure.detail} onRetry={handleRetry} /> : null}+ </>) : (<EditorEmptyState hasProject={hasProject} />)}diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 86879fd12..3bf042a09 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -85,9 +85,14 @@ interface PreviewCanvasProps {onLoadedMetadata: (sec: number, assetId: string) => void;onVideoElement: (el: HTMLVideoElement | null) => void;currentTimeSec: number;- /** 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;+ /** Receives the id of the asset whose <video> gave up, plus the MediaError+ * detail for the card. Transient failures are reloaded inside VirtualPreview+ * and never reach here (see Preview.tsx). */+ onVideoError?: (assetId: string, detail: string) => void;+ /** The mounted source decoded a frame again — see VirtualPreview. */+ onVideoRecovered?: (assetId: string) => void;+ /** Bumped to force a reload of the mounted source (the Retry button). */+ retryToken?: number;}// ponytail: fallback only — used until the active source's <video> reportsdiff --git a/src/components/ai-edition/PreviewErrorCard.tsx b/src/components/ai-edition/PreviewErrorCard.tsxnew file mode 100644index 000000000..0a1d90f30--- /dev/null+++ b/src/components/ai-edition/PreviewErrorCard.tsx@@ -0,0 +1,47 @@+// Shown over the preview when the decode clock gave up on the mounted source+// (issue #395). Deliberately an overlay, not a replacement: the native+// compositor keeps painting the last composed frame underneath, and that frame+// is the evidence the project is intact — which is exactly what the old+// behaviour (collapsing to the "add a video to get started" empty state)+// destroyed along with the user's confidence.+//+// The copy does not claim to know WHY: the two causes we know of — a file that+// moved and a file still being written — are indistinguishable from here+// without a filesystem round trip, and guessing wrong is how an error message+// sends someone re-importing media that was never gone.++import { AlertCircle, RotateCcw } from "lucide-react";+import { useScopedT } from "@/contexts/I18nContext";+import styles from "./NewEditorShell.module.css";++interface PreviewErrorCardProps {+ /** The MediaError, formatted — kept on screen because it is the one thing+ * that makes a user's bug report actionable (see mediaError.ts). */+ detail: string;+ onRetry: () => void;+}++export function PreviewErrorCard({ detail, onRetry }: PreviewErrorCardProps) {+ const t = useScopedT("editor");++ return (+ <div className={styles.previewFailure} role="alert" data-testid="preview-error-card">+ <div className={styles.previewFailureCard}>+ <div className={styles.previewFailureIconRing}>+ <AlertCircle className={styles.previewFailureIcon} />+ </div>+ <h2 className={styles.previewFailureTitle}>{t("preview.mediaError.title")}</h2>+ <p className={styles.previewFailureDescription}>{t("preview.mediaError.description")}</p>+ <button type="button" onClick={onRetry} className={styles.previewEmptyPrimaryButton}>+ <RotateCcw className={styles.previewEmptyButtonIcon} />+ {t("preview.mediaError.retry")}+ </button>+ {detail ? (+ <p className={styles.previewFailureDetail}>+ {t("preview.mediaError.detail", { detail })}+ </p>+ ) : null}+ </div>+ </div>+ );+}diff --git a/src/components/ai-edition/VirtualPreview.mediaError.test.tsx b/src/components/ai-edition/VirtualPreview.mediaError.test.tsxnew file mode 100644index 000000000..852263624--- /dev/null+++ b/src/components/ai-edition/VirtualPreview.mediaError.test.tsx@@ -0,0 +1,322 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom";+import { act, cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AxcutClip } from "@/lib/ai-edition/schema";+import { RETRY_DELAYS_MS } from "./mediaError";+import { type VideoSource, VirtualPreview } from "./VirtualPreview";++// Same hand-driven rAF as VirtualPreview.playback.test.tsx: the tick is a+// subject here too (it must go quiet while a reload is in flight), so frames are+// run one at a time rather than by the browser.+let frameCallbacks: FrameRequestCallback[] = [];++beforeEach(() => {+ frameCallbacks = [];+ vi.useFakeTimers();+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {+ frameCallbacks.push(cb);+ return frameCallbacks.length;+ });+ vi.stubGlobal("cancelAnimationFrame", () => {+ // Frames are drained by `tick()`, never scheduled, so there is nothing to+ // cancel — the stub only exists so the effect's cleanup has something to call.+ });+ // Every case here deliberately provokes the logging the fix added; silence it+ // so a passing run stays readable.+ for (const level of ["debug", "warn", "error"] as const) {+ vi.spyOn(console, level).mockImplementation(() => {+ // swallowed on purpose+ });+ }+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++function tick() {+ const pending = frameCallbacks;+ frameCallbacks = [];+ act(() => {+ for (const cb of pending) cb(0);+ });+}++function advance(ms: number) {+ act(() => {+ vi.advanceTimersByTime(ms);+ });+}++function clip(id: string, assetId: string, timelineStartSec: number): AxcutClip {+ return {+ id,+ assetId,+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec,+ timelineEndSec: timelineStartSec + 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ };+}++/** A `<video>` jsdom will not drive: the test owns its clock, and load/play/pause+ * are recorded rather than performed (jsdom implements none of them). */+function driveVideo(element: HTMLVideoElement) {+ let currentTime = 0;+ let paused = true;+ let error: { code: number; message: string } | null = null;+ Object.defineProperty(element, "currentTime", {+ configurable: true,+ get: () => currentTime,+ set: (next: number) => {+ currentTime = next;+ },+ });+ Object.defineProperty(element, "paused", { configurable: true, get: () => paused });+ Object.defineProperty(element, "readyState", { configurable: true, get: () => 4 });+ Object.defineProperty(element, "duration", { configurable: true, get: () => 10 });+ Object.defineProperty(element, "error", { configurable: true, get: () => error });+ element.load = vi.fn(() => {+ // What the real load() does to the position, and why the resume point+ // cannot be read off the element after a failure.+ currentTime = 0;+ });+ element.play = vi.fn(() => {+ paused = false;+ return Promise.resolve();+ });+ element.pause = vi.fn(() => {+ paused = true;+ });+ return {+ play: () => {+ paused = false;+ },+ seekTo: (next: number) => {+ currentTime = next;+ },+ /** Fire an `error` event carrying a real MediaError code. */+ fail: (code: number | null, message = `code ${code}`) => {+ error = code === null ? null : { code, message };+ act(() => {+ fireEvent.error(element);+ });+ },+ loadedMetadata: () => {+ error = null;+ act(() => {+ fireEvent.loadedMetadata(element);+ });+ },+ get currentTime() {+ return currentTime;+ },+ get loadCalls() {+ return (element.load as ReturnType<typeof vi.fn>).mock.calls.length;+ },+ get pauseCalls() {+ return (element.pause as ReturnType<typeof vi.fn>).mock.calls.length;+ },+ get playCalls() {+ return (element.play as ReturnType<typeof vi.fn>).mock.calls.length;+ },+ };+}++const SOURCES: VideoSource[] = [{ id: "a1", src: "file:///tmp/a1.mp4", label: "a1" }];++function mount(clips: AxcutClip[] = [clip("clip_1", "a1", 0)]) {+ const onVideoError = vi.fn<(assetId: string, detail: string) => void>();+ const onVideoRecovered = vi.fn<(assetId: string) => void>();+ const onTimeChange = vi.fn<(timeSec: number) => void>();+ const tree = (retryToken: number) => (+ <VirtualPreview+ videoSources={SOURCES}+ clips={clips}+ onTimeChange={onTimeChange}+ onVideoError={onVideoError}+ onVideoRecovered={onVideoRecovered}+ retryToken={retryToken}+ />+ );+ const view = render(tree(0));+ const element = view.container.querySelector("video");+ if (!element) throw new Error("no <video> rendered");+ const video = driveVideo(element as HTMLVideoElement);+ // How the real app resolves its first clip: metadata arrives, the component+ // seeks to its current virtual time, and that seek names the active clip.+ video.loadedMetadata();+ onVideoRecovered.mockClear();+ return {+ view,+ video,+ element: element as HTMLVideoElement,+ onVideoError,+ onVideoRecovered,+ onTimeChange,+ bumpRetryToken: (token: number) => view.rerender(tree(token)),+ };+}++describe("VirtualPreview media-error recovery (issue #395)", () => {+ // THE bug. A cross-asset clip boundary remounts the keyed <video> mid-load and+ // Chromium reports MEDIA_ERR_ABORTED for it — ordinary, expected, and it used+ // to be enough to collapse the whole preview for the rest of the session.+ it("ignores an aborted load entirely", () => {+ const { video, onVideoError } = mount();++ video.fail(1);+ advance(5_000);++ expect(onVideoError).not.toHaveBeenCalled();+ expect(video.loadCalls).toBe(0);+ expect(video.pauseCalls).toBe(0);+ });++ it("reloads the source after a decode failure instead of reporting it", () => {+ const { video, onVideoError } = mount();++ video.fail(3);+ expect(onVideoError).not.toHaveBeenCalled();+ expect(video.loadCalls).toBe(0);++ advance(RETRY_DELAYS_MS[0]);+ expect(video.loadCalls).toBe(1);+ expect(onVideoError).not.toHaveBeenCalled();+ });++ // The resume point has to be resolved from the playhead at reload time:+ // `video.currentTime` reads 0 after load(), so trusting the element would+ // silently rewind the user to the start of the clip.+ it("comes back at the playhead, not at zero", () => {+ const { video } = mount();++ video.play();+ video.seekTo(4);+ tick();++ video.fail(3);+ advance(RETRY_DELAYS_MS[0]);+ expect(video.currentTime).toBe(0); // load() reset it++ video.loadedMetadata();+ expect(video.currentTime).toBeCloseTo(4, 5);+ // …and playback resumes, because it was playing when the failure hit.+ expect(video.playCalls).toBeGreaterThan(0);+ });++ // An `error` does not fire `pause`, so `v.paused` — the gate the rest of the+ // tick relies on — is still false while the decoder is dead. Without its own+ // guard the tick would keep taking clip-boundary decisions on a frozen clock+ // and clobber the seek queued for the reload.+ it("stops steering the timeline while a reload is in flight", () => {+ const clips = [clip("clip_1", "a1", 0), clip("clip_2", "a1", 10)];+ const { video, onTimeChange } = mount(clips);++ video.play();+ video.seekTo(9.96); // the frame where the boundary advance would fire+ video.fail(3);+ onTimeChange.mockClear();++ tick();++ expect(onTimeChange).not.toHaveBeenCalled();+ expect(video.currentTime).toBe(9.96);+ });++ it("gives up after the retry budget and reports the media error", () => {+ const { video, onVideoError } = mount();++ for (const delay of RETRY_DELAYS_MS) {+ video.fail(3);+ advance(delay);+ }+ expect(onVideoError).not.toHaveBeenCalled();+ expect(video.loadCalls).toBe(RETRY_DELAYS_MS.length);++ video.fail(3);+ advance(5_000);++ expect(onVideoError).toHaveBeenCalledWith("a1", "MEDIA_ERR_DECODE (3) — code 3");+ expect(video.loadCalls).toBe(RETRY_DELAYS_MS.length); // no further reload+ expect(video.pauseCalls).toBe(1); // transport told, once, on the way out+ });++ it("gives an unsupported source exactly one look", () => {+ const { video, onVideoError } = mount();++ video.fail(4);+ advance(RETRY_DELAYS_MS[0]);+ expect(video.loadCalls).toBe(1);+ expect(onVideoError).not.toHaveBeenCalled();++ video.fail(4);+ expect(onVideoError).toHaveBeenCalledWith("a1", "MEDIA_ERR_SRC_NOT_SUPPORTED (4) — code 4");+ });++ // Success re-arms the budget. Without this a long session slowly walks into+ // the same dead end — #395 with a longer fuse.+ it("re-arms the budget on a successful load", () => {+ const { video, onVideoError, onVideoRecovered } = mount();++ for (const delay of RETRY_DELAYS_MS) {+ video.fail(3);+ advance(delay);+ }+ video.loadedMetadata();+ expect(onVideoRecovered).toHaveBeenCalledWith("a1");++ // A fresh failure now gets the full budget again rather than being fatal.+ video.fail(3);+ advance(RETRY_DELAYS_MS[0]);+ expect(onVideoError).not.toHaveBeenCalled();+ expect(video.loadCalls).toBe(RETRY_DELAYS_MS.length + 1);+ });++ it("treats an error with no MediaError as transient", () => {+ const { video, onVideoError } = mount();++ video.fail(null);+ advance(RETRY_DELAYS_MS[0]);++ expect(video.loadCalls).toBe(1);+ expect(onVideoError).not.toHaveBeenCalled();+ });++ // The user's lever: it must work even from the terminal state, and even while+ // a backoff is pending.+ it("reloads immediately when the retry token is bumped", () => {+ const { video, onVideoError, bumpRetryToken } = mount();++ for (const delay of [...RETRY_DELAYS_MS, 0]) {+ video.fail(3);+ advance(delay);+ }+ expect(onVideoError).toHaveBeenCalledTimes(1);+ const loadsBefore = video.loadCalls;++ act(() => bumpRetryToken(1));+ advance(0);++ expect(video.loadCalls).toBe(loadsBefore + 1);+ });++ // A reload scheduled for an element that is going away must never fire: the+ // <video> is keyed on the asset id, so the timer can outlive its element.+ it("does not reload an unmounted element", () => {+ const { view, video } = mount();++ video.fail(3);+ view.unmount();+ advance(5_000);++ expect(video.loadCalls).toBe(0);+ });+});diff --git a/src/components/ai-edition/VirtualPreview.module.css b/src/components/ai-edition/VirtualPreview.module.cssindex 41eb59b5d..78d84a06f 100644--- a/src/components/ai-edition/VirtualPreview.module.css+++ b/src/components/ai-edition/VirtualPreview.module.css@@ -35,18 +35,6 @@max-height: none;}-.overlay {- position: absolute;- display: flex;- align-items: center;- justify-content: center;- color: var(--muted-foreground);- font-size: 0.875rem;- background: var(--card);- padding: 0.75rem 1.25rem;- border-radius: 0.5rem;-}-.controls {display: flex;align-items: center;diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex c3eb6cbbd..0d6766f47 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -23,6 +23,12 @@ import {computeZoomPreviewTransform,IDENTITY_ZOOM_TRANSFORM,} from "@/lib/ai-edition/timeline/zoom-preview";+import {+ describeMediaError,+ formatMediaError,+ mediaErrorDisposition,+ retryDelayMs,+} from "./mediaError";import styles from "./VirtualPreview.module.css";export interface VideoSource {@@ -63,8 +69,20 @@ interface VirtualPreviewProps {videoStyle?: React.CSSProperties;/** 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;+ * the caller has no other way to tell which of its sources is dead.+ * Fires only once the retry budget below is spent — a transient decode or+ * network blip is reloaded here and never reaches the caller. `detail`+ * carries the MediaError code for the card and for bug reports. */+ onVideoError?: (assetId: string, detail: string) => void;+ /** The mounted source produced a frame again — after a reload, or simply+ * because the playhead moved onto a healthy asset. The caller needs this to+ * drop a failure it is showing; without it, a card outlives its failure and+ * we are back to a latch, only quieter. */+ onVideoRecovered?: (assetId: string) => void;+ /** Bumped by the caller's Retry button. A user-initiated reload always runs:+ * it cancels any pending backoff and starts the budget over, because the+ * user clicked knowing something changed (they put the file back). */+ retryToken?: number;/** 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. */@@ -89,6 +107,8 @@ export function VirtualPreview({onVideoElement,videoStyle,onVideoError,+ onVideoRecovered,+ retryToken,cropRegion,clockRef,}: VirtualPreviewProps) {@@ -118,6 +138,20 @@ export function VirtualPreview({const isProgrammaticSeekRef = useRef(false);const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);+ // Reload bookkeeping for the mounted source (see `reloadActiveSource`).+ // `attempts` is spent by failures and reset by a SUCCESS, never by elapsed+ // time — a budget that only counts up is issue #395 with a longer fuse.+ const retryRef = useRef<{ attempts: number; timer: number | null }>({+ attempts: 0,+ timer: null,+ });+ // True from the moment a reload is scheduled until the element produces+ // metadata again. Read by the rAF tick, which must not steer a dead decoder.+ const recoveringRef = useRef(false);+ // The last position read off a healthy element. `video.currentTime` is 0+ // after load(), and 0 after a load that failed before decoding a frame, so+ // it cannot be the fallback resume point — that is a silent rewind.+ const lastGoodSourceTimeRef = useRef(0);// Which clip the rAF tick below believes is currently playing — set// whenever a seek unambiguously resolves one (via locateVirtualPosition,// timeline position → clip). Passed back into locateSourcePosition so@@ -177,6 +211,8 @@ export function VirtualPreview({playbackClipsRef.current = playbackClips;const videoSourcesRef = useRef(videoSources);videoSourcesRef.current = videoSources;+ const activeSourceRef = useRef(activeSource);+ activeSourceRef.current = activeSource;const sourceIndexRef = useRef(sourceIndex);sourceIndexRef.current = sourceIndex;const virtualTimeSecRef = useRef(virtualTimeSec);@@ -218,6 +254,18 @@ export function VirtualPreview({clockRef.current.playbackRate = v.playbackRate;clockRef.current.virtualTimeSec = virtualTimeSecRef.current;}+ // A reload is in flight: the decoder is dead and `currentTime` is+ // frozen (or already reset to 0), so every decision below — trim+ // skipping, the clip-boundary advance, the unmapped-position+ // fallback — would be taken on a lie, and the seeks two of them fire+ // would clobber the resume queued for the reload. Deliberately BELOW+ // the clock publish: the webcam overlay freezes on the last good+ // position rather than jumping. Note this cannot ride on `v.paused`,+ // the gate the rest of the tick uses — an `error` does not fire+ // `pause`, so a failure mid-playback leaves `paused` false.+ if (recoveringRef.current) {+ return;+ }const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;// Trims only trim ahead during actual playback — scrubbing/paused seeks are// intentionally NOT clamped, so the user can navigate freely into a trim while@@ -271,6 +319,10 @@ export function VirtualPreview({// against drawing a black frame into the cursor overlay.if (v.readyState >= 2) {setSourceTimeSec(v.currentTime);+ // Sampled here, where the decoder is known good, because this is+ // where a reload has to put the playhead back if it cannot+ // resolve one from the timeline.+ lastGoodSourceTimeRef.current = v.currentTime;}// À L'ARRÊT, le `<video>` ne pilote PLUS la position de la timeline.//@@ -492,6 +544,92 @@ export function VirtualPreview({}}, []);+ /**+ * Re-run the media load algorithm on the mounted element after a delay, and+ * queue the position to come back to. Everything is read through refs, so the+ * callback is stable and the scheduled work always sees current state.+ */+ const reloadActiveSource = useCallback((play: boolean, delayMs: number) => {+ if (retryRef.current.timer !== null) {+ window.clearTimeout(retryRef.current.timer);+ retryRef.current.timer = null;+ }+ recoveringRef.current = true;+ setLoadState("loading");+ retryRef.current.timer = window.setTimeout(() => {+ retryRef.current.timer = null;+ const video = videoRef.current;+ if (!video) return;+ // Resolved HERE rather than when the error fired: the user can scrub+ // during the backoff, and the position they left the playhead on is+ // the one that has to come back. An asset switch queued in the+ // meantime is newer intent still, so it wins outright.+ if (!pendingSeekRef.current) {+ const position = locateVirtualPosition(clipsRef.current, virtualTimeSecRef.current);+ // `locateVirtualPosition` answers for whatever clip the playhead+ // is on, which after a boundary advance can belong to a DIFFERENT+ // asset — its source time would be a meaningless offset into the+ // file we are about to reload.+ const clipIsOnThisSource = position?.clip.assetId === activeSourceRef.current?.id;+ if (position && clipIsOnThisSource) {+ // The rAF resumes against this; leaving it stale would resolve+ // the next tick against the clip we were on before the failure.+ activeClipIdRef.current = position.clip.id;+ }+ const resumeSec =+ position && clipIsOnThisSource ? position.sourceTimeSec : lastGoodSourceTimeRef.current;+ pendingSeekRef.current = {+ sourceTimeSec: Number.isFinite(resumeSec) ? resumeSec : 0,+ play,+ };+ }+ // The restore itself rides the cross-asset path `onLoadedMetadata`+ // already implements — one resume path in this component, not two.+ //+ // load() and nothing else: per spec it unconditionally re-runs the+ // media load algorithm. Re-assigning `src` first (the obvious+ // alternative) starts a SECOND load that aborts the first, which+ // surfaces as a spurious MEDIA_ERR_ABORTED.+ video.load();+ }, delayMs);+ }, []);++ /** A frame decoded — whatever went wrong is over. Success, not elapsed time,+ * is what re-arms the retry budget, and it is the only signal the caller has+ * that a failure it is showing can be dropped. */+ const markSourceHealthy = useCallback(() => {+ recoveringRef.current = false;+ retryRef.current.attempts = 0;+ const id = activeSourceRef.current?.id;+ if (id) onVideoRecovered?.(id);+ }, [onVideoRecovered]);++ // Reload bookkeeping belongs to the MOUNTED element: the <video> is keyed on+ // the asset id, so a source swap replaces it, and a reload scheduled for the+ // old one must never fire against its replacement. React runs this cleanup+ // before any queued macrotask can.+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-run on source swap+ useEffect(() => {+ retryRef.current = { attempts: 0, timer: null };+ recoveringRef.current = false;+ return () => {+ if (retryRef.current.timer !== null) {+ window.clearTimeout(retryRef.current.timer);+ retryRef.current.timer = null;+ }+ };+ }, [activeSourceKey]);++ // The caller's Retry button. Same path as an automatic reload so the two+ // cannot drift, but with a fresh budget and no delay: the user clicked+ // because they know something changed.+ // biome-ignore lint/correctness/useExhaustiveDependencies: the token bump IS the request+ useEffect(() => {+ if (!retryToken) return;+ retryRef.current.attempts = 0;+ reloadActiveSource(false, 0);+ }, [retryToken]);+// BUG corrigé : cet effet listait `seekToVirtualTime`/`seekToSourceTime` en dépendances// — mais `seekToVirtualTime` change d'identité (nouveau `useCallback`) à chaque fois que// `sourceIndex` change, y compris quand CE MÊME effet vient de le faire changer (switch@@ -518,7 +656,10 @@ export function VirtualPreview({}, [seekTarget]);return (- <div className={styles.container}>+ // The load state no longer paints anything here (Preview owns failure UI+ // now), but it is still the honest read of what the decode clock is doing —+ // worth one attribute for tests and for a screenshot in a bug report.+ <div className={styles.container} data-load-state={loadState}>{activeSource ? (<><div ref={videoFrameRef} className={styles.videoFrame}>@@ -542,6 +683,7 @@ export function VirtualPreview({playsInlineonLoadedMetadata={(e) => {setLoadState("ready");+ markSourceHealthy();// ponytail: forward the raw duration (possibly NaN for// MediaRecorder WebMs) to the parent. handleLoadedMetadata// falls back to a 60s seed when it isn't finite so the@@ -576,19 +718,69 @@ export function VirtualPreview({}}}onWaiting={() => setLoadState("loading")}- onCanPlay={() => setLoadState("ready")}+ onCanPlay={() => {+ setLoadState("ready");+ markSourceHealthy();+ }}onError={(e) => {+ const el = e.currentTarget;+ const description = describeMediaError(el.error);+ // An element whose source was torn out from under it reports a+ // "load failure" that says nothing about the media (Chromium+ // calls it "Empty src attribute"). Never act on that.+ const hasSource = Boolean(el.getAttribute("src")) || Boolean(el.currentSrc);+ const attemptsSpent = retryRef.current.attempts;+ const disposition = hasSource+ ? mediaErrorDisposition(description.code, attemptsSpent)+ : "ignore";+ const detail = formatMediaError(description);+ // The code is the whole diagnosis, and it used to be thrown+ // away — which is why issue #395 could only ever be reported+ // as "the preview disappeared". Keep it, whatever we decide.+ const context = {+ assetId: activeSource.id,+ src: activeSource.src,+ detail,+ networkState: el.networkState,+ readyState: el.readyState,+ currentTime: el.currentTime,+ attemptsSpent,+ disposition,+ };+ if (disposition === "ignore") {+ // Routine: every cross-asset clip boundary remounts this+ // element mid-load. `debug`, not `warn` — this fires during+ // ordinary playback and must not read as a problem.+ console.debug(+ "[preview] ignoring a <video> error from a cancelled load",+ context,+ );+ return;+ }+ if (disposition === "retry") {+ console.warn("[preview] <video> failed, reloading", context);+ retryRef.current.attempts = attemptsSpent + 1;+ // Deliberately no pause(): a 400 ms reload should be a blip+ // the user never sees, and pausing here would flip the+ // shell's transport for it. What keeps the rAF from+ // steering the dead decoder in the meantime is+ // `recoveringRef`, set by reloadActiveSource.+ reloadActiveSource(!el.paused, retryDelayMs(attemptsSpent));+ return;+ }// ponytail: don't blindly advance to the next source — if// the failed source owns the current virtual clip, the// next sourceIndex will seekToVirtualTime right back into// the same failed asset, looping. Fail the preview.+ console.error("[preview] <video> failed for good", context);pendingSeekRef.current = null;+ recoveringRef.current = false;setLoadState("error");// An 'error' doesn't itself fire 'pause', so make sure the shell's// transport state (single source of truth, see NewEditorShell's// own play/pause/ended listener) actually learns playback stopped.- e.currentTarget.pause();- onVideoError?.(activeSource.id);+ el.pause();+ onVideoError?.(activeSource.id, detail);}}onEnded={() => {// BUG corrigé : ce handler stoppait TOUJOURS la lecture dès que le@@ -626,14 +818,14 @@ export function VirtualPreview({// handles clip-end advancement, so dropping the event// handler here is safe./>- {/* Plus d'overlay « Loading preview… » : il reflétait l'état du <video>- CACHÉ (source horloge/audio), pas la preview RÉELLE — le canvas natif,- qui montre déjà une image valide pendant que le <video> re-seek. Il- recouvrait donc une bonne image à chaque scrub, pour rien. On garde- seulement l'erreur, qui, elle, signale un vrai échec de chargement. */}- {loadState === "error" && (- <div className={styles.overlay}>Video preview could not be loaded.</div>- )}+ {/* Plus d'overlay ici du tout. « Loading preview… » reflétait l'état du+ <video> CACHÉ (source horloge/audio), pas la preview RÉELLE — le canvas+ natif, qui montre déjà une image valide pendant que le <video> re-seek.+ L'overlay d'erreur, lui, est parti chez Preview (#395) : il vivait dans+ .videoFrame, sur lequel l'effet de zoom écrit `style.transform`, donc à+ 3× il partait hors cadre ; il n'était pas traduit ; et surtout il ne+ proposait rien — l'échec est désormais une carte avec un bouton+ Réessayer, rendue au-dessus de la dernière image composée. */}</div>{/* The native D3D canvas already draws the recorded-cursor sprite as partof the composited frame (same cursor sidecar file, single source ofdiff --git a/src/components/ai-edition/mediaError.test.ts b/src/components/ai-edition/mediaError.test.tsnew file mode 100644index 000000000..5a3a433a1--- /dev/null+++ b/src/components/ai-edition/mediaError.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import {+ describeMediaError,+ formatMediaError,+ mediaErrorDisposition,+ RETRY_DELAYS_MS,+ retryDelayMs,+} from "./mediaError";++describe("describeMediaError", () => {+ it("names a known code", () => {+ expect(describeMediaError({ code: 3, message: "PIPELINE_ERROR_DECODE" })).toEqual({+ code: 3,+ name: "MEDIA_ERR_DECODE",+ message: "PIPELINE_ERROR_DECODE",+ });+ });++ // An `error` event can arrive with no MediaError attached; the caller still has to+ // decide something, so this must not throw or produce `undefined` fields.+ it("survives a missing error object", () => {+ expect(describeMediaError(null)).toEqual({+ code: null,+ name: "MEDIA_ERR_UNKNOWN",+ message: "",+ });+ expect(describeMediaError({ code: 99 }).name).toBe("MEDIA_ERR_UNKNOWN");+ });++ it("formats a line a bug report can carry", () => {+ expect(formatMediaError(describeMediaError({ code: 2, message: "boom" }))).toBe(+ "MEDIA_ERR_NETWORK (2) — boom",+ );+ expect(formatMediaError(describeMediaError({ code: 2 }))).toBe("MEDIA_ERR_NETWORK (2)");+ expect(formatMediaError(describeMediaError(null))).toBe("MEDIA_ERR_UNKNOWN");+ });+});++describe("mediaErrorDisposition", () => {+ // THE regression (issue #395): a cancelled load is not a broken file. Every+ // cross-asset clip boundary remounts the <video> and every reload calls load() on+ // a possibly-loading element, so acting on code 1 — even just counting it — is what+ // let a healthy editor talk itself into an error screen.+ it("always ignores MEDIA_ERR_ABORTED, at any attempt count", () => {+ for (const attempts of [0, 1, 2, 3, 99]) {+ expect(mediaErrorDisposition(1, attempts)).toBe("ignore");+ }+ });++ it("retries a decode or network failure, then gives up", () => {+ for (const code of [2, 3]) {+ expect(mediaErrorDisposition(code, 0)).toBe("retry");+ expect(mediaErrorDisposition(code, 1)).toBe("retry");+ expect(mediaErrorDisposition(code, 2)).toBe("fatal");+ }+ });++ // A recording the capture process is still writing reports as "unsupported", so the+ // code gets one look — but only one, because it is also what a genuinely unplayable+ // file reports and re-reading that is pure latency.+ it("gives an unsupported source exactly one retry", () => {+ expect(mediaErrorDisposition(4, 0)).toBe("retry");+ expect(mediaErrorDisposition(4, 1)).toBe("fatal");+ });++ it("treats an unknown failure as transient", () => {+ expect(mediaErrorDisposition(null, 0)).toBe("retry");+ expect(mediaErrorDisposition(null, RETRY_DELAYS_MS.length)).toBe("fatal");+ });+});++describe("retryDelayMs", () => {+ it("backs off, then holds at the last delay", () => {+ expect(retryDelayMs(0)).toBe(RETRY_DELAYS_MS[0]);+ expect(retryDelayMs(1)).toBe(RETRY_DELAYS_MS[1]);+ expect(retryDelayMs(50)).toBe(RETRY_DELAYS_MS[RETRY_DELAYS_MS.length - 1]);+ });+});diff --git a/src/components/ai-edition/mediaError.ts b/src/components/ai-edition/mediaError.tsnew file mode 100644index 000000000..b626f7134--- /dev/null+++ b/src/components/ai-edition/mediaError.ts@@ -0,0 +1,82 @@+// What to do about an HTMLMediaElement `error` event in the preview.+//+// Split out of VirtualPreview's `onError` so the decision table is testable+// without a DOM. The absence of that table is issue #395: ANY error event, of+// any kind, was treated as "this asset is dead", and one such event collapsed+// the whole preview to the "add a video to get started" empty state for the+// rest of the session.+//+// MEDIA_ERR_ABORTED is the one we must never act on. It is what a *cancelled*+// load looks like, and the preview cancels loads as a matter of course: the+// <video> is keyed on `activeSource.id`, so every cross-asset clip boundary+// remounts it mid-fetch, and our own reload calls load() on an element that may+// still be loading. Counting those against a failure budget is how a healthy+// editor talks itself into an error screen.++export const MEDIA_ERROR_NAMES: Record<number, string> = {+ 1: "MEDIA_ERR_ABORTED",+ 2: "MEDIA_ERR_NETWORK",+ 3: "MEDIA_ERR_DECODE",+ 4: "MEDIA_ERR_SRC_NOT_SUPPORTED",+};++/** Delayed rather than immediate: the likeliest transient causes are a file the+ * capture process has not finished writing and a momentarily unreadable file+ * (an antivirus pass, a Windows share lock). An instant re-read sees the same+ * bytes and burns an attempt for nothing. */+export const RETRY_DELAYS_MS = [400, 1200] as const;++/** A recording that is still being written reports as "unsupported" too, so+ * code 4 gets one cheap look before we believe the browser that the file is+ * unusable. */+export const UNSUPPORTED_RETRY_BUDGET = 1;++export interface MediaErrorDescription {+ code: number | null;+ name: string;+ message: string;+}++/** Typed structurally rather than as `MediaError` so this module carries no DOM+ * dependency and its test can run in the default node environment. */+export function describeMediaError(+ error: { readonly code?: number; readonly message?: string } | null | undefined,+): MediaErrorDescription {+ const code = typeof error?.code === "number" ? error.code : null;+ return {+ code,+ name: (code !== null ? MEDIA_ERROR_NAMES[code] : undefined) ?? "MEDIA_ERR_UNKNOWN",+ message: error?.message ?? "",+ };+}++/** One line for the console and for the error card — the code is what makes a+ * user's bug report actionable, since we cannot reproduce their decoder. */+export function formatMediaError(description: MediaErrorDescription): string {+ const label =+ description.code === null ? description.name : `${description.name} (${description.code})`;+ return description.message ? `${label} — ${description.message}` : label;+}++export type MediaErrorDisposition = "ignore" | "retry" | "fatal";++/**+ * `attemptsSpent` is reset by a successful load, not by elapsed time: success is+ * the only honest evidence that the source recovered. A budget that only ever+ * counts up is issue #395 again with a longer fuse.+ *+ * A null code (an error event carrying no MediaError) rides the full budget —+ * we know nothing, so we try.+ */+export function mediaErrorDisposition(+ code: number | null,+ attemptsSpent: number,+): MediaErrorDisposition {+ if (code === 1) return "ignore";+ const budget = code === 4 ? UNSUPPORTED_RETRY_BUDGET : RETRY_DELAYS_MS.length;+ return attemptsSpent < budget ? "retry" : "fatal";+}++export function retryDelayMs(attemptsSpent: number): number {+ return RETRY_DELAYS_MS[Math.min(attemptsSpent, RETRY_DELAYS_MS.length - 1)];+}diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex b472ea7dc..204034acd 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "معاينة الفيديو",- "webcamPreview": "معاينة كاميرا الويب (اسحب لتغيير الموضع)"+ "webcamPreview": "معاينة كاميرا الويب (اسحب لتغيير الموضع)",+ "mediaError": {+ "title": "توقّفت المعاينة",+ "description": "تعذّر فك ترميز الفيديو. ربما نُقل الملف أو ما زال قيد الكتابة — مشروعك نفسه سليم.",+ "retry": "إعادة المحاولة",+ "detail": "التفاصيل: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "تعليق توضيحي",diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex 10d8ef618..f1a336bb0 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Video preview",- "webcamPreview": "Webcam preview (drag to reposition)"+ "webcamPreview": "Webcam preview (drag to reposition)",+ "mediaError": {+ "title": "Preview stopped",+ "description": "The video couldn't be decoded. The file may have been moved, or it may still be finishing writing — your project itself is intact.",+ "retry": "Try again",+ "detail": "Details: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Annotation",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex 1b8dadafd..0160fa679 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Vista previa del vídeo",- "webcamPreview": "Vista previa de la webcam (arrastra para reubicar)"+ "webcamPreview": "Vista previa de la webcam (arrastra para reubicar)",+ "mediaError": {+ "title": "Vista previa detenida",+ "description": "No se pudo decodificar el vídeo. Puede que el archivo se haya movido o que aún se esté terminando de escribir; tu proyecto está intacto.",+ "retry": "Reintentar",+ "detail": "Detalles: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Anotación",diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 333298dd7..60b065428 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Aperçu vidéo",- "webcamPreview": "Aperçu webcam (glisser pour repositionner)"+ "webcamPreview": "Aperçu webcam (glisser pour repositionner)",+ "mediaError": {+ "title": "Aperçu interrompu",+ "description": "La vidéo n'a pas pu être décodée. Le fichier a peut-être été déplacé, ou son écriture n'est pas terminée — votre projet, lui, est intact.",+ "retry": "Réessayer",+ "detail": "Détails : {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Annotation",diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 0d4df5c7f..cf5a2b644 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Anteprima video",- "webcamPreview": "Anteprima webcam (trascina per riposizionare)"+ "webcamPreview": "Anteprima webcam (trascina per riposizionare)",+ "mediaError": {+ "title": "Anteprima interrotta",+ "description": "Non è stato possibile decodificare il video. Il file potrebbe essere stato spostato o essere ancora in fase di scrittura: il progetto è intatto.",+ "retry": "Riprova",+ "detail": "Dettagli: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Annotazione",diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex 3b48038c1..46ef5164a 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "動画プレビュー",- "webcamPreview": "ウェブカメラのプレビュー(ドラッグで位置変更)"+ "webcamPreview": "ウェブカメラのプレビュー(ドラッグで位置変更)",+ "mediaError": {+ "title": "プレビューを停止しました",+ "description": "動画をデコードできませんでした。ファイルが移動されたか、まだ書き込み中の可能性があります。プロジェクト自体は損なわれていません。",+ "retry": "再試行",+ "detail": "詳細: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "注釈",diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex dabd14757..32e5af668 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "영상 미리보기",- "webcamPreview": "웹캠 미리보기 (끌어서 위치 변경)"+ "webcamPreview": "웹캠 미리보기 (끌어서 위치 변경)",+ "mediaError": {+ "title": "미리보기가 중단되었습니다",+ "description": "영상을 디코딩할 수 없습니다. 파일이 이동되었거나 아직 저장이 끝나지 않았을 수 있습니다. 프로젝트 자체는 그대로입니다.",+ "retry": "다시 시도",+ "detail": "세부 정보: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "주석",diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex d65fd23d2..c8321be40 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Pré-visualização do vídeo",- "webcamPreview": "Pré-visualização da webcam (arraste para reposicionar)"+ "webcamPreview": "Pré-visualização da webcam (arraste para reposicionar)",+ "mediaError": {+ "title": "Pré-visualização interrompida",+ "description": "Não foi possível decodificar o vídeo. O arquivo pode ter sido movido ou ainda estar sendo gravado — seu projeto continua intacto.",+ "retry": "Tentar novamente",+ "detail": "Detalhes: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Anotação",diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex 11eeda92b..c5337daee 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Предпросмотр видео",- "webcamPreview": "Предпросмотр камеры (перетащите, чтобы переместить)"+ "webcamPreview": "Предпросмотр камеры (перетащите, чтобы переместить)",+ "mediaError": {+ "title": "Предпросмотр остановлен",+ "description": "Не удалось декодировать видео. Возможно, файл был перемещён или ещё дописывается — сам проект не пострадал.",+ "retry": "Повторить",+ "detail": "Подробности: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Аннотация",diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex b0a42ca3b..545f22ba2 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Video önizlemesi",- "webcamPreview": "Web kamerası önizlemesi (taşımak için sürükleyin)"+ "webcamPreview": "Web kamerası önizlemesi (taşımak için sürükleyin)",+ "mediaError": {+ "title": "Önizleme durdu",+ "description": "Video çözümlenemedi. Dosya taşınmış ya da hâlâ yazılıyor olabilir — projeniz olduğu gibi duruyor.",+ "retry": "Yeniden dene",+ "detail": "Ayrıntılar: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Açıklama",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 2e61a7c40..bed9ceebf 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "Xem trước video",- "webcamPreview": "Xem trước webcam (kéo để đổi vị trí)"+ "webcamPreview": "Xem trước webcam (kéo để đổi vị trí)",+ "mediaError": {+ "title": "Xem trước đã dừng",+ "description": "Không thể giải mã video. Tệp có thể đã bị di chuyển hoặc vẫn đang được ghi xong — dự án của bạn vẫn nguyên vẹn.",+ "retry": "Thử lại",+ "detail": "Chi tiết: {{detail}}"+ }},"annotationOverlay": {"imageAlt": "Chú thích",diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 2e52b942e..666ad7f80 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "视频预览",- "webcamPreview": "摄像头预览(拖动可重新定位)"+ "webcamPreview": "摄像头预览(拖动可重新定位)",+ "mediaError": {+ "title": "预览已停止",+ "description": "无法解码该视频。文件可能已被移动,或仍在写入中——你的项目本身完好无损。",+ "retry": "重试",+ "detail": "详细信息:{{detail}}"+ }},"annotationOverlay": {"imageAlt": "批注",diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 032bb91e5..931326526 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -363,7 +363,13 @@},"preview": {"videoPreview": "影片預覽",- "webcamPreview": "攝影機預覽(拖曳可重新定位)"+ "webcamPreview": "攝影機預覽(拖曳可重新定位)",+ "mediaError": {+ "title": "預覽已停止",+ "description": "無法解碼此影片。檔案可能已被移動,或仍在寫入中——你的專案本身完好無缺。",+ "retry": "重試",+ "detail": "詳細資訊:{{detail}}"+ }},"annotationOverlay": {"imageAlt": "註解",diff --git a/technical-documentation/architecture/preview.md b/technical-documentation/architecture/preview.mdindex 666207c52..d30bc0002 100644--- a/technical-documentation/architecture/preview.md+++ b/technical-documentation/architecture/preview.md@@ -237,6 +237,54 @@ the decoder swap, awaits `setActiveClip`, and re-reads the live transport *now*(not from a captured `isPlaying`) before resuming — so a user pause that landsin the middle of a clip transition is honoured, not silently undone.+## When the decode clock fails++The hidden `<video>` is a clock and an audio source, not the picture — the+pixels come from the native canvas. So its failing is not the preview failing,+and the invariant since [#395](https://github.com/getopenscreen/openscreen/issues/395)+is: **a media error can never render `EditorEmptyState`**. That component now+answers exactly one question — is there anything in this project to show? — and+`Preview.tsx`'s render condition (`hasProject && hasAsset && previewSources.length > 0`)+takes no failure input at all.++What replaced it, in two layers:++- **Classify, then reload**+ ([`mediaError.ts`](../../src/components/ai-edition/mediaError.ts), applied in+ `VirtualPreview`'s `onError`). `MEDIA_ERR_ABORTED` is ignored outright and+ never counted: the `<video>` is keyed on `activeSource.id`, so every+ cross-asset clip boundary remounts it mid-load and Chromium reports exactly+ that. `MEDIA_ERR_SRC_NOT_SUPPORTED` gets one retry (a recording the capture+ process is still writing reports as unsupported); everything else — including+ an `error` event carrying no `MediaError` — rides `RETRY_DELAYS_MS`. The+ reload is a plain `load()`: re-assigning `src` first would start a second load+ that aborts the first and emit a spurious abort. The budget is reset by a+ **successful** load, not by elapsed time — without that, the fourth transient+ failure of a long session is terminal, which is #395 with a longer fuse.+- **Resume through the existing path.** The reload queues `pendingSeekRef` and+ lets `onLoadedMetadata` restore position and playback — the same path a+ cross-asset seek uses, so the component has one resume path rather than two.+ The position is resolved **at reload time**, not when the error fired, because+ the user can scrub during the backoff: it comes from `locateVirtualPosition`+ against the live playhead, guarded by an `assetId` check (that function+ answers for whatever clip the playhead is on, which after a boundary advance+ can belong to a different asset), and falls back to a source time sampled+ while the decoder was known good. `video.currentTime` is *not* usable here —+ it reads 0 after `load()`.++While a reload is in flight the rAF tick returns early (`recoveringRef`),+publishing the clock but taking no decision. This cannot ride on the `v.paused`+gate the rest of the tick uses: an `error` does not fire `pause`, so a failure+during playback leaves `paused` false, and the tick would go on making+trim/boundary decisions against a frozen clock and clobber the queued resume.++Only once the budget is spent does `Preview` hear about it, and it renders+`PreviewErrorCard` **over** the still-mounted canvas — the last composed frame+stays visible, which is the evidence the project is intact. The card carries the+`MediaError` code, because a user's report is otherwise unactionable: the reason+#395 could only ever be described as "the preview disappeared" is that the code+was thrown away.+## Known gaps- **Live preview is video-only.** `crates/compositor/src/live.rs` (1628 lines) handles only