Skip to content

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

fix(preview): stop the reload cycle a two-spot file can keep alive

EtienneLescotbc0f64689e2a
diff --git a/src/components/ai-edition/VirtualPreview.mediaError.test.tsx b/src/components/ai-edition/VirtualPreview.mediaError.test.tsx
index 1329e0223..56f0a8f6f 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 { RETRY_DELAYS_MS } from "./mediaError";
+import { MAX_RELOADS_PER_MEDIA, RETRY_DELAYS_MS } from "./mediaError";
import { type VideoSource, VirtualPreview } from "./VirtualPreview";
// Same hand-driven rAF as VirtualPreview.playback.test.tsx: the tick is a
@@ -374,6 +374,56 @@ describe("VirtualPreview media-error recovery (issue #395)", () => {
expect(video.loadCalls).toBe(loadsBefore + 1);
});
+ // Field regression, caught by breaking a real recording: once the card is up,
+ // playback getting past the failure point must NOT hand the budget back. It
+ // used to, so the next bad spot started the whole retry cycle again — three
+ // full episodes for one broken file.
+ it("does not re-arm itself after it has given up", () => {
+ const { video, onVideoError } = mount();
+
+ video.play();
+ video.seekTo(4);
+ tick();
+ for (const delay of [...RETRY_DELAYS_MS, 0]) {
+ video.fail(3);
+ advance(delay);
+ }
+ expect(onVideoError).toHaveBeenCalledTimes(1);
+ const loadsAtGiveUp = video.loadCalls;
+
+ // Playback carries on past where it died — the shape that used to re-arm.
+ video.seekTo(6);
+ tick();
+ video.fail(3);
+ advance(5_000);
+
+ expect(video.loadCalls).toBe(loadsAtGiveUp);
+ 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", () => {
+ 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();
+ video.fail(3);
+ advance(5_000);
+ video.loadedMetadata();
+ }
+
+ expect(video.loadCalls).toBeLessThanOrEqual(MAX_RELOADS_PER_MEDIA);
+ expect(onVideoError).toHaveBeenCalled();
+ });
+
// The element is keyed on the asset id alone, so pointing an asset at a new
// file reloads the SAME element — and a budget spent on the old file must not
// be charged to the new one. Nothing in the app re-points an asset today, but
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 4bf6f6fc8..68c3e7d3b 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -158,6 +158,10 @@ export function VirtualPreview({
// 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
@@ -582,6 +586,7 @@ export function VirtualPreview({
retryRef.current.timer = null;
}
recoveringRef.current = true;
+ reloadsRef.current += 1;
setLoadState("loading");
retryRef.current.timer = window.setTimeout(() => {
retryRef.current.timer = null;
@@ -653,6 +658,7 @@ export function VirtualPreview({
retryRef.current = { attempts: 0, timer: null };
recoveringRef.current = false;
failedAtSourceTimeRef.current = null;
+ reloadsRef.current = 0;
return () => {
if (retryRef.current.timer !== null) {
window.clearTimeout(retryRef.current.timer);
@@ -669,6 +675,7 @@ export function VirtualPreview({
if (!retryToken) return;
retryRef.current.attempts = 0;
failedAtSourceTimeRef.current = null;
+ reloadsRef.current = 0;
reloadActiveSource(false, 0);
}, [retryToken]);
@@ -773,7 +780,7 @@ export function VirtualPreview({
const hasSource = Boolean(el.getAttribute("src")) || Boolean(el.currentSrc);
const attemptsSpent = retryRef.current.attempts;
const disposition = hasSource
- ? mediaErrorDisposition(description.code, attemptsSpent)
+ ? mediaErrorDisposition(description.code, attemptsSpent, reloadsRef.current)
: "ignore";
const detail = formatMediaError(description);
// The code is the whole diagnosis, and it used to be thrown
@@ -787,6 +794,7 @@ export function VirtualPreview({
readyState: el.readyState,
currentTime: el.currentTime,
attemptsSpent,
+ reloadsSpent: reloadsRef.current,
disposition,
};
if (disposition === "ignore") {
@@ -822,6 +830,12 @@ 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;
setLoadState("error");
// An 'error' doesn't itself fire 'pause', so make sure the shell's
// transport state (single source of truth, see NewEditorShell's
diff --git a/src/components/ai-edition/mediaError.test.ts b/src/components/ai-edition/mediaError.test.ts
index 5a3a433a1..d11c0c0b6 100644
--- a/src/components/ai-edition/mediaError.test.ts
+++ b/src/components/ai-edition/mediaError.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
describeMediaError,
formatMediaError,
+ MAX_RELOADS_PER_MEDIA,
mediaErrorDisposition,
RETRY_DELAYS_MS,
retryDelayMs,
@@ -67,6 +68,22 @@ describe("mediaErrorDisposition", () => {
expect(mediaErrorDisposition(null, 0)).toBe("retry");
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");
+ });
+
+ // …but never for a cancelled load. Making code 1 terminal at the ceiling 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");
+ });
});
describe("retryDelayMs", () => {
diff --git a/src/components/ai-edition/mediaError.ts b/src/components/ai-edition/mediaError.ts
index b626f7134..9e2eaeee4 100644
--- a/src/components/ai-edition/mediaError.ts
+++ b/src/components/ai-edition/mediaError.ts
@@ -58,6 +58,19 @@ 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;
+
export type MediaErrorDisposition = "ignore" | "retry" | "fatal";
/**
@@ -71,8 +84,13 @@ export type MediaErrorDisposition = "ignore" | "retry" | "fatal";
export function mediaErrorDisposition(
code: number | null,
attemptsSpent: number,
+ reloadsSpent = 0,
): 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";
const budget = code === 4 ? UNSUPPORTED_RETRY_BUDGET : RETRY_DELAYS_MS.length;
return attemptsSpent < budget ? "retry" : "fatal";
}
diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.json
index 204034acd..80dedcf6d 100644
--- a/src/i18n/locales/ar/editor.json
+++ b/src/i18n/locales/ar/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "معاينة كاميرا الويب (اسحب لتغيير الموضع)",
"mediaError": {
"title": "توقّفت المعاينة",
- "description": "تعذّر فك ترميز الفيديو. ربما نُقل الملف أو ما زال قيد الكتابة — مشروعك نفسه سليم.",
+ "description": "تعذّر فك ترميز الفيديو. قد يكون الملف تالفًا، أو ما زال قيد الكتابة، أو لم يعد في المكان الذي يتوقعه المشروع — مشروعك نفسه سليم.",
"retry": "إعادة المحاولة",
"detail": "التفاصيل: {{detail}}"
}
diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.json
index f1a336bb0..429803556 100644
--- a/src/i18n/locales/en/editor.json
+++ b/src/i18n/locales/en/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "The video couldn't be decoded. The file may be damaged, still being written, or no longer where the project expects it — your project itself is intact.",
"retry": "Try again",
"detail": "Details: {{detail}}"
}
diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.json
index 0160fa679..0e052ad78 100644
--- a/src/i18n/locales/es/editor.json
+++ b/src/i18n/locales/es/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "No se pudo decodificar el vídeo. El archivo puede estar dañado, aún escribiéndose, o ya no estar donde el proyecto lo espera; tu proyecto está intacto.",
"retry": "Reintentar",
"detail": "Detalles: {{detail}}"
}
diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.json
index 60b065428..5df6ab06d 100644
--- a/src/i18n/locales/fr/editor.json
+++ b/src/i18n/locales/fr/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "La vidéo n'a pas pu être décodée. Le fichier est peut-être endommagé, en cours d'écriture, ou plus à l'emplacement attendu — votre projet, lui, est intact.",
"retry": "Réessayer",
"detail": "Détails : {{detail}}"
}
diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.json
index cf5a2b644..c19fc3543 100644
--- a/src/i18n/locales/it/editor.json
+++ b/src/i18n/locales/it/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "Non è stato possibile decodificare il video. Il file potrebbe essere danneggiato, ancora in scrittura o non più dove il progetto lo cerca: il progetto è intatto.",
"retry": "Riprova",
"detail": "Dettagli: {{detail}}"
}
diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.json
index 46ef5164a..516640491 100644
--- a/src/i18n/locales/ja-JP/editor.json
+++ b/src/i18n/locales/ja-JP/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "ウェブカメラのプレビュー(ドラッグで位置変更)",
"mediaError": {
"title": "プレビューを停止しました",
- "description": "動画をデコードできませんでした。ファイルが移動されたか、まだ書き込み中の可能性があります。プロジェクト自体は損なわれていません。",
+ "description": "動画をデコードできませんでした。ファイルが破損しているか、まだ書き込み中か、プロジェクトが参照している場所にない可能性があります。プロジェクト自体は損なわれていません。",
"retry": "再試行",
"detail": "詳細: {{detail}}"
}
diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.json
index 32e5af668..f2ebcdc01 100644
--- a/src/i18n/locales/ko-KR/editor.json
+++ b/src/i18n/locales/ko-KR/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "웹캠 미리보기 (끌어서 위치 변경)",
"mediaError": {
"title": "미리보기가 중단되었습니다",
- "description": "영상을 디코딩할 수 없습니다. 파일이 이동되었거나 아직 저장이 끝나지 않았을 수 있습니다. 프로젝트 자체는 그대로입니다.",
+ "description": "영상을 디코딩할 수 없습니다. 파일이 손상되었거나, 아직 저장 중이거나, 프로젝트가 기대한 위치에 없을 수 있습니다. 프로젝트 자체는 그대로입니다.",
"retry": "다시 시도",
"detail": "세부 정보: {{detail}}"
}
diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.json
index c8321be40..c5ab7154a 100644
--- a/src/i18n/locales/pt-BR/editor.json
+++ b/src/i18n/locales/pt-BR/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "Não foi possível decodificar o vídeo. O arquivo pode estar danificado, ainda sendo gravado ou não estar mais onde o projeto espera — seu projeto continua intacto.",
"retry": "Tentar novamente",
"detail": "Detalhes: {{detail}}"
}
diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.json
index c5337daee..881ea68d3 100644
--- a/src/i18n/locales/ru/editor.json
+++ b/src/i18n/locales/ru/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "Предпросмотр камеры (перетащите, чтобы переместить)",
"mediaError": {
"title": "Предпросмотр остановлен",
- "description": "Не удалось декодировать видео. Возможно, файл был перемещён или ещё дописывается — сам проект не пострадал.",
+ "description": "Не удалось декодировать видео. Файл может быть повреждён, ещё записываться или больше не находиться там, где его ожидает проект — сам проект не пострадал.",
"retry": "Повторить",
"detail": "Подробности: {{detail}}"
}
diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.json
index 545f22ba2..dfe1832fd 100644
--- a/src/i18n/locales/tr/editor.json
+++ b/src/i18n/locales/tr/editor.json
@@ -366,7 +366,7 @@
"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.",
+ "description": "Video çözümlenemedi. Dosya bozulmuş, hâlâ yazılıyor ya da projenin beklediği yerde olmayabilir — projeniz olduğu gibi duruyor.",
"retry": "Yeniden dene",
"detail": "Ayrıntılar: {{detail}}"
}
diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.json
index e272183f6..ee17bc1b8 100644
--- a/src/i18n/locales/vi/editor.json
+++ b/src/i18n/locales/vi/editor.json
@@ -366,7 +366,7 @@
"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 chưa được ghi xong — dự án của bạn vẫn nguyên vẹn.",
+ "description": "Không thể giải mã video. Tệp có thể đã hỏng, vẫn đang được ghi, hoặc không còn ở nơi dự án mong đợi — dự án của bạn vẫn nguyên vẹn.",
"retry": "Thử lại",
"detail": "Chi tiết: {{detail}}"
}
diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.json
index 666ad7f80..41be4e22f 100644
--- a/src/i18n/locales/zh-CN/editor.json
+++ b/src/i18n/locales/zh-CN/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "摄像头预览(拖动可重新定位)",
"mediaError": {
"title": "预览已停止",
- "description": "无法解码该视频。文件可能已被移动,或仍在写入中——你的项目本身完好无损。",
+ "description": "无法解码该视频。文件可能已损坏、仍在写入中,或已不在项目预期的位置——你的项目本身完好无损。",
"retry": "重试",
"detail": "详细信息:{{detail}}"
}
diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.json
index 931326526..de53c8676 100644
--- a/src/i18n/locales/zh-TW/editor.json
+++ b/src/i18n/locales/zh-TW/editor.json
@@ -366,7 +366,7 @@
"webcamPreview": "攝影機預覽(拖曳可重新定位)",
"mediaError": {
"title": "預覽已停止",
- "description": "無法解碼此影片。檔案可能已被移動,或仍在寫入中——你的專案本身完好無缺。",
+ "description": "無法解碼此影片。檔案可能已損毀、仍在寫入中,或已不在專案預期的位置——你的專案本身完好無缺。",
"retry": "重試",
"detail": "詳細資訊:{{detail}}"
}