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): make the retry budget a rate, not a quota
EtienneLescot3785d0975fdc
diff --git a/src/components/ai-edition/VirtualPreview.mediaError.test.tsx b/src/components/ai-edition/VirtualPreview.mediaError.test.tsxindex 56f0a8f6f..363308f13 100644--- a/src/components/ai-edition/VirtualPreview.mediaError.test.tsx+++ b/src/components/ai-edition/VirtualPreview.mediaError.test.tsx@@ -3,7 +3,7 @@ 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 { MAX_RELOADS_PER_MEDIA, RETRY_DELAYS_MS } from "./mediaError";+import { RELOAD_WINDOW_MS, RETRY_DELAYS_MS } from "./mediaError";import { type VideoSource, VirtualPreview } from "./VirtualPreview";// Same hand-driven rAF as VirtualPreview.playback.test.tsx: the tick is a@@ -297,24 +297,23 @@ describe("VirtualPreview media-error recovery (issue #395)", () => {expect(onVideoError).toHaveBeenCalledWith("a1", "MEDIA_ERR_SRC_NOT_SUPPORTED (4) — code 4");});- // Getting PAST the bad spot re-arms the budget. Without any re-arming a long- // session slowly walks into the same dead end — #395 with a longer fuse.- it("re-arms the budget once playback gets past the failure point", () => {- const { video, onVideoError, onVideoRecovered } = mount();+ // THE long-session guarantee, and the answer to "can a user run out of+ // recoveries?". The budget counts reloads inside a window, so it empties by+ // itself: hiccups spaced minutes apart — which is what a seek storm across+ // an editing session looks like — each get the full budget. A lifetime+ // counter would have made this third failure terminal.+ it("gives a later failure the full budget again once the window has emptied", () => {+ const { video, onVideoError } = mount();- video.seekTo(4);- tick();for (const delay of RETRY_DELAYS_MS) {video.fail(3);advance(delay);}- video.loadedMetadata();- expect(onVideoRecovered).toHaveBeenCalledWith("a1");+ expect(onVideoError).not.toHaveBeenCalled();+ expect(video.loadCalls).toBe(RETRY_DELAYS_MS.length);- video.seekTo(5); // decoded past where it died- tick();+ advance(RELOAD_WINDOW_MS + 1_000);- // 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();@@ -401,27 +400,27 @@ describe("VirtualPreview media-error recovery (issue #395)", () => {expect(onVideoError).toHaveBeenCalledTimes(2); // still terminal, no new cycle});- // The same file had two bad spots 0.47 s apart, each looking like progress- // past the other, so the budget re-armed on every cycle. The ceiling is the- // backstop that keeps the reload count finite regardless.- it("stops reloading at the ceiling when two bad spots keep re-arming the budget", () => {+ // The other half: a file failing FAST does not get to loop quietly. Three+ // failures inside one window is not "an occasional hiccup", and the user is+ // told once — and stays told, because the window emptying afterwards must+ // not restart the cycle behind the card.+ it("reaches the card on a burst inside the window, and stays there", () => {const { video, onVideoError } = mount();- video.play();- // Alternate failure points further apart than the progress margin. Each- // reload completes (a corrupt file's header parses every time), and the- // tick then sees the playhead past the OTHER bad spot — which is what- // re-armed the budget forever in the field.- for (let i = 0; i < 12; i += 1) {- video.seekTo(i % 2 === 0 ? 4 : 6);- tick();+ for (const delay of [...RETRY_DELAYS_MS, 0]) {video.fail(3);- advance(5_000);- video.loadedMetadata();+ advance(delay);}+ expect(onVideoError).toHaveBeenCalledTimes(1);+ const loadsAtGiveUp = video.loadCalls;- expect(video.loadCalls).toBeLessThanOrEqual(MAX_RELOADS_PER_MEDIA);- expect(onVideoError).toHaveBeenCalled();+ // Long enough for every reload to age out of the window.+ advance(RELOAD_WINDOW_MS * 3);+ video.fail(3);+ advance(5_000);++ expect(video.loadCalls).toBe(loadsAtGiveUp);+ expect(onVideoError).toHaveBeenCalledTimes(2);});// The element is keyed on the asset id alone, so pointing an asset at a newdiff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex a69a336ce..0df2ff1ee 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -27,6 +27,7 @@ import {describeMediaError,formatMediaError,mediaErrorDisposition,+ pruneReloads,retryDelayMs,} from "./mediaError";import styles from "./VirtualPreview.module.css";@@ -140,15 +141,16 @@ export function VirtualPreview({// The seek that arrived while another was still running (see applySourceTime).const pendingScrubTargetRef = useRef<number | null>(null);const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);- // Reload bookkeeping for the mounted source (see `reloadActiveSource`).- // `attempts` is spent by failures and re-armed by playing past the point one- // died at — never by elapsed time, and never by a reload merely completing.- // A budget that only counts up is issue #395 with a longer fuse; one handed- // back too easily is a reload loop that never surfaces anything at all.- const retryRef = useRef<{ attempts: number; timer: number | null }>({- attempts: 0,- timer: null,- });+ // When each AUTOMATIC reload happened. The budget is "reloads inside+ // RELOAD_WINDOW_MS", so it expires by itself: a dead file burns it in+ // seconds, while the occasional transient across a long editing session+ // never accumulates. A lifetime count could not tell those apart and would+ // eventually show a card on healthy media (see mediaError.ts).+ const reloadsRef = useRef<number[]>([]);+ // Set when we stop trying, so an expiring window cannot restart the cycle+ // behind the card. Cleared only by Retry or a media change.+ const gaveUpRef = useRef(false);+ const retryTimerRef = useRef<number | null>(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);@@ -156,14 +158,6 @@ export function VirtualPreview({// 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);- // Where the decoder died, while a reload is outstanding. Playing PAST it is- // what re-arms the retry budget: see markSourceLoaded for why a reload- // completing is not evidence of anything.- const failedAtSourceTimeRef = useRef<number | null>(null);- // Reloads spent on the mounted media, ever — the ceiling the budget cannot- // talk its way past (see MAX_RELOADS_PER_MEDIA). Reset only when the media- // changes or the user retries, never by playback progress.- const reloadsRef = 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@@ -336,14 +330,6 @@ export function VirtualPreview({// where a reload has to put the playhead back if it cannot// resolve one from the timeline.lastGoodSourceTimeRef.current = sourceTime;- // …and here is the only place that can prove a reload WORKED:- // the decoder is past the bytes it died on. A quarter second of- // margin so re-decoding the same frame doesn't count as progress.- const failedAt = failedAtSourceTimeRef.current;- if (failedAt !== null && sourceTime > failedAt + 0.25) {- failedAtSourceTimeRef.current = null;- retryRef.current.attempts = 0;- }}// À L'ARRÊT, le `<video>` ne pilote PLUS la position de la timeline.//@@ -619,15 +605,14 @@ export function VirtualPreview({* 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;+ if (retryTimerRef.current !== null) {+ window.clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;}recoveringRef.current = true;- reloadsRef.current += 1;setLoadState("loading");- retryRef.current.timer = window.setTimeout(() => {- retryRef.current.timer = null;+ retryTimerRef.current = window.setTimeout(() => {+ retryTimerRef.current = null;const video = videoRef.current;if (!video) return;// Resolved HERE rather than when the error fired: the user can scrub@@ -693,14 +678,13 @@ export function VirtualPreview({// before any queued macrotask can.// biome-ignore lint/correctness/useExhaustiveDependencies: re-run when the mounted media changesuseEffect(() => {- retryRef.current = { attempts: 0, timer: null };+ reloadsRef.current = [];+ gaveUpRef.current = false;recoveringRef.current = false;- failedAtSourceTimeRef.current = null;- reloadsRef.current = 0;return () => {- if (retryRef.current.timer !== null) {- window.clearTimeout(retryRef.current.timer);- retryRef.current.timer = null;+ if (retryTimerRef.current !== null) {+ window.clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;}};}, [activeSourceKey, activeSource?.src]);@@ -711,9 +695,10 @@ export function VirtualPreview({// biome-ignore lint/correctness/useExhaustiveDependencies: the token bump IS the requestuseEffect(() => {if (!retryToken) return;- retryRef.current.attempts = 0;- failedAtSourceTimeRef.current = null;- reloadsRef.current = 0;+ // Deliberately does NOT record a reload: the user's click must not spend+ // one of the recoveries it is meant to restore.+ reloadsRef.current = [];+ gaveUpRef.current = false;reloadActiveSource(false, 0);}, [retryToken]);@@ -825,9 +810,11 @@ export function VirtualPreview({// "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 nowMs = Date.now();+ reloadsRef.current = pruneReloads(reloadsRef.current, nowMs);+ const reloadsInWindow = reloadsRef.current.length;const disposition = hasSource- ? mediaErrorDisposition(description.code, attemptsSpent, reloadsRef.current)+ ? mediaErrorDisposition(description.code, reloadsInWindow, gaveUpRef.current): "ignore";const detail = formatMediaError(description);// The code is the whole diagnosis, and it used to be thrown@@ -840,8 +827,8 @@ export function VirtualPreview({networkState: el.networkState,readyState: el.readyState,currentTime: el.currentTime,- attemptsSpent,- reloadsSpent: reloadsRef.current,+ reloadsInWindow,+ gaveUp: gaveUpRef.current,disposition,};if (disposition === "ignore") {@@ -856,18 +843,13 @@ export function VirtualPreview({}if (disposition === "retry") {console.warn("[preview] <video> failed, reloading", context);- retryRef.current.attempts = attemptsSpent + 1;- // The bar the reload has to clear before the budget is- // handed back (see the rAF tick).- failedAtSourceTimeRef.current = Number.isFinite(el.currentTime)- ? el.currentTime- : lastGoodSourceTimeRef.current;+ reloadsRef.current.push(nowMs);// 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));+ reloadActiveSource(!el.paused, retryDelayMs(reloadsInWindow));return;}// ponytail: don't blindly advance to the next source — if@@ -877,12 +859,9 @@ export function VirtualPreview({console.error("[preview] <video> failed for good", context);pendingSeekRef.current = null;recoveringRef.current = false;- // Once we have given up, nothing playback does may re-arm the- // budget: leaving this set let the rAF's progress check fire- // on the NEXT bad spot and start the whole cycle again, which- // is what "3 episodes for one broken file" looked like in the- // field. Only Retry or a media change re-arms from here.- failedAtSourceTimeRef.current = null;+ // Latched so an expiring window cannot restart the cycle behind+ // the card. Only Retry or a media change lifts it.+ gaveUpRef.current = true;setLoadState("error");// An 'error' doesn't itself fire 'pause', so make sure the shell's// transport state (single source of truth, see NewEditorShell'sdiff --git a/src/components/ai-edition/mediaError.test.ts b/src/components/ai-edition/mediaError.test.tsindex d11c0c0b6..cfdd7c801 100644--- a/src/components/ai-edition/mediaError.test.ts+++ b/src/components/ai-edition/mediaError.test.ts@@ -2,8 +2,9 @@ import { describe, expect, it } from "vitest";import {describeMediaError,formatMediaError,- MAX_RELOADS_PER_MEDIA,mediaErrorDisposition,+ pruneReloads,+ RELOAD_WINDOW_MS,RETRY_DELAYS_MS,retryDelayMs,} from "./mediaError";@@ -69,20 +70,40 @@ describe("mediaErrorDisposition", () => {expect(mediaErrorDisposition(null, RETRY_DELAYS_MS.length)).toBe("fatal");});- // Measured in the field on a corrupted recording: two bad spots 0.47 s apart,- // each one looking like "progress" past the other, re-armed the budget on- // every cycle. The ceiling is what makes the reload count finite whatever the- // re-arming heuristic concludes.- it("is fatal once the reload ceiling is reached, whatever the budget says", () => {- expect(mediaErrorDisposition(3, 0, MAX_RELOADS_PER_MEDIA - 1)).toBe("retry");- expect(mediaErrorDisposition(3, 0, MAX_RELOADS_PER_MEDIA)).toBe("fatal");- expect(mediaErrorDisposition(2, 0, MAX_RELOADS_PER_MEDIA + 5)).toBe("fatal");+ // The budget counts reloads inside a window, so a long session cannot+ // exhaust it: the confirmed cause of #395 is our own seek storm, which+ // recurs across an editing session and heals every time. A lifetime count+ // would eventually show a card on media a 400 ms reload always repairs.+ it("is fatal only once the window is full", () => {+ expect(mediaErrorDisposition(3, RETRY_DELAYS_MS.length - 1)).toBe("retry");+ expect(mediaErrorDisposition(3, RETRY_DELAYS_MS.length)).toBe("fatal");});- // …but never for a cancelled load. Making code 1 terminal at the ceiling is+ // Without this, a dead file reloads every time the window empties, flashes+ // back on the metadata that always parses, and loses the card behind it.+ it("stays fatal once it has given up, however empty the window", () => {+ expect(mediaErrorDisposition(3, 0, true)).toBe("fatal");+ expect(mediaErrorDisposition(2, 0, true)).toBe("fatal");+ });++ // …but never for a cancelled load, even then. Making code 1 terminal is// exactly how #395 would come back through the side door.- it("still ignores an aborted load at the ceiling", () => {- expect(mediaErrorDisposition(1, 0, MAX_RELOADS_PER_MEDIA * 10)).toBe("ignore");+ it("still ignores an aborted load after giving up", () => {+ expect(mediaErrorDisposition(1, 99, true)).toBe("ignore");+ });+});++describe("pruneReloads", () => {+ it("keeps only what is still inside the window", () => {+ const now = 1_000_000;+ const timestamps = [+ now - RELOAD_WINDOW_MS - 1, // expired+ now - RELOAD_WINDOW_MS, // expired, boundary is exclusive+ now - RELOAD_WINDOW_MS + 1,+ now,+ ];+ expect(pruneReloads(timestamps, now)).toEqual([now - RELOAD_WINDOW_MS + 1, now]);+ expect(pruneReloads([], now)).toEqual([]);});});diff --git a/src/components/ai-edition/mediaError.ts b/src/components/ai-edition/mediaError.tsindex 9e2eaeee4..3cf4ced82 100644--- a/src/components/ai-edition/mediaError.ts+++ b/src/components/ai-edition/mediaError.ts@@ -20,10 +20,9 @@ export const MEDIA_ERROR_NAMES: Record<number, string> = {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. */+/** Delayed rather than immediate: the failure we actually measured is a demuxer+ * that could not keep up (see VirtualPreview's `applySourceTime`), and an+ * instant re-read arrives while it is still saturated. */export const RETRY_DELAYS_MS = [400, 1200] as const;/** A recording that is still being written reports as "unsupported" too, so@@ -31,6 +30,24 @@ export const RETRY_DELAYS_MS = [400, 1200] as const;* unusable. */export const UNSUPPORTED_RETRY_BUDGET = 1;+/**+ * The budget is spent by reloads inside a SLIDING WINDOW, not over the lifetime+ * of the mounted media. That distinction is the whole design:+ *+ * - a genuinely dead file burns the budget in seconds (400 ms + 1200 ms of+ * backoff and a moment of decode), so the user reaches the card almost at+ * once, which is what they need;+ * - a healthy file hit by the occasional transient — the confirmed cause of+ * #395 was our own seek storm, which recurs across an editing session and+ * recovers every time — never accumulates, because the window empties between+ * hiccups. A lifetime count could not tell those apart: it would show a card+ * after enough ordinary editing, on media a 400 ms reload heals every time.+ *+ * A window also removes the need to "re-arm" anything on recovery, which is the+ * mechanism that kept getting this wrong: it expires by itself.+ */+export const RELOAD_WINDOW_MS = 30_000;+export interface MediaErrorDescription {code: number | null;name: string;@@ -58,43 +75,38 @@ export function formatMediaError(description: MediaErrorDescription): string {return description.message ? `${label} — ${description.message}` : label;}-/**- * Hard ceiling on reloads for one mounted media, whatever the budget says.- *- * The budget is re-armed by playback getting past the point it died at, which- * is a heuristic — and a file with two bad spots FURTHER APART than that margin- * re-arms it on every cycle, because each failure looks like progress relative- * to the other. Measured on a deliberately corrupted recording: failures at- * 22.528 s and 22.997 s, 0.47 s apart, produced four reloads per episode- * instead of two. This is the backstop that keeps the count finite whatever the- * heuristic concludes. Reset only by a media change or the user's Retry.- */-export const MAX_RELOADS_PER_MEDIA = RETRY_DELAYS_MS.length * 2;+/** The reload timestamps still inside the window. The single definition of what+ * "recent" means: the caller keeps the returned array and reads its length, so+ * there is no second copy of this predicate to drift from. The caller owns the+ * clock, which keeps this module pure and testable in the node environment. */+export function pruneReloads(timestamps: readonly number[], nowMs: number): number[] {+ return timestamps.filter((at) => nowMs - at < RELOAD_WINDOW_MS);+}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.+ * `reloadsInWindow` counts only AUTOMATIC reloads: a user pressing Retry clears+ * the history, because they clicked knowing something changed.** 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,- reloadsSpent = 0,+ reloadsInWindow: number,+ hasGivenUp = false,): MediaErrorDisposition {- // Still ignored at the ceiling: a cancelled load says nothing about the- // media, and making it terminal once the counter is high is how #395 would- // come back through the side door.if (code === 1) return "ignore";- if (reloadsSpent >= MAX_RELOADS_PER_MEDIA) return "fatal";+ // Once the card is up, the window expiring must not quietly start the cycle+ // again: a dead file would reload every 30 s, flash back to a picture on the+ // metadata that always parses, and lose the card. Only Retry or a media+ // change lifts this.+ if (hasGivenUp) return "fatal";const budget = code === 4 ? UNSUPPORTED_RETRY_BUDGET : RETRY_DELAYS_MS.length;- return attemptsSpent < budget ? "retry" : "fatal";+ return reloadsInWindow < budget ? "retry" : "fatal";}-export function retryDelayMs(attemptsSpent: number): number {- return RETRY_DELAYS_MS[Math.min(attemptsSpent, RETRY_DELAYS_MS.length - 1)];+export function retryDelayMs(reloadsInWindow: number): number {+ return RETRY_DELAYS_MS[Math.min(reloadsInWindow, RETRY_DELAYS_MS.length - 1)];}