Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(recorder): add unit tests for recording pipeline, uploader, spool, and backup

Richie McIlroy9252097321b3
diff --git a/apps/web/__tests__/unit/instant-recording-uploader.test.ts b/apps/web/__tests__/unit/instant-recording-uploader.test.ts
new file mode 100644
index 000000000..47b7a32b9
--- /dev/null
+++ b/apps/web/__tests__/unit/instant-recording-uploader.test.ts
@@ -0,0 +1,731 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ InstantRecordingUploader,
+ MultipartCompletionUncertainError,
+} from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/instant-mp4-uploader";
+import type { VideoId } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-types";
+
+const STREAMED_PART_BYTES = 5 * 1024 * 1024 + 128;
+const OVERFLOW_PART_BYTES = 129 * 1024 * 1024;
+const FINALIZED_BLOB_BYTES = 129 * 1024 * 1024;
+
+type UploadOutcome =
+ | { type: "success"; etag: string }
+ | { type: "network-error" }
+ | { type: "pending" };
+
+class MockXMLHttpRequest {
+ static outcomes: UploadOutcome[] = [];
+ static abortedCount = 0;
+
+ upload = {
+ onprogress: null as ((event: ProgressEvent<EventTarget>) => void) | null,
+ };
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onabort: (() => void) | null = null;
+ ontimeout: (() => void) | null = null;
+ status = 0;
+ statusText = "";
+ timeout = 0;
+ private headers = new Map<string, string>();
+ private completed = false;
+
+ static setOutcomes(outcomes: UploadOutcome[]) {
+ MockXMLHttpRequest.outcomes = [...outcomes];
+ MockXMLHttpRequest.abortedCount = 0;
+ }
+
+ open() {}
+
+ setRequestHeader(name: string, value: string) {
+ this.headers.set(name.toLowerCase(), value);
+ }
+
+ getResponseHeader(name: string) {
+ return this.headers.get(name.toLowerCase()) ?? null;
+ }
+
+ send(part: Blob) {
+ const outcome = MockXMLHttpRequest.outcomes.shift();
+ if (!outcome) {
+ throw new Error("Missing upload outcome");
+ }
+
+ this.upload.onprogress?.({
+ lengthComputable: true,
+ loaded: part.size,
+ total: part.size,
+ } as ProgressEvent<EventTarget>);
+
+ if (outcome.type === "pending") {
+ return;
+ }
+
+ if (outcome.type === "network-error") {
+ this.completed = true;
+ this.onerror?.();
+ return;
+ }
+
+ this.completed = true;
+ this.status = 200;
+ this.statusText = "OK";
+ this.headers.set("etag", `"${outcome.etag}"`);
+ this.onload?.();
+ }
+
+ abort() {
+ if (this.completed) {
+ return;
+ }
+
+ this.completed = true;
+ MockXMLHttpRequest.abortedCount += 1;
+ this.onabort?.();
+ }
+}
+
+const makeJsonResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+
+const makeBlob = (size: number, type: string) =>
+ new Blob([new Uint8Array(size)], { type });
+const videoId = "video-123" as VideoId;
+
+describe("InstantRecordingUploader", () => {
+ beforeEach(() => {
+ vi.stubGlobal("window", globalThis as typeof globalThis & Window);
+ vi.stubGlobal(
+ "XMLHttpRequest",
+ MockXMLHttpRequest as unknown as typeof XMLHttpRequest,
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it("uploads streamed chunks and completes multipart with the raw subpath", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/presign-part") {
+ expect(body).toMatchObject({
+ videoId,
+ uploadId: "upload-123",
+ partNumber: 1,
+ subpath: "raw-upload.webm",
+ });
+ return makeJsonResponse({
+ presignedUrl: "https://uploads.example/part-1",
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ expect(body).toMatchObject({
+ videoId,
+ uploadId: "upload-123",
+ subpath: "raw-upload.webm",
+ durationInSecs: 12,
+ width: 1920,
+ height: 1080,
+ });
+ expect(body.parts).toHaveLength(1);
+ expect(body.parts[0]).toMatchObject({
+ partNumber: 1,
+ etag: "etag-1",
+ });
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([{ type: "success", etag: "etag-1" }]);
+
+ const setUploadStatus = vi.fn();
+ const sendProgressUpdate = vi.fn().mockResolvedValue(undefined);
+ const onChunkStateChange = vi.fn();
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus,
+ sendProgressUpdate,
+ onChunkStateChange,
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ await uploader.finalize({
+ durationSeconds: 12,
+ width: 1920,
+ height: 1080,
+ subpath: "raw-upload.webm",
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(sendProgressUpdate).toHaveBeenLastCalledWith(chunk.size, chunk.size);
+ expect(setUploadStatus).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ status: "uploadingVideo",
+ capId: videoId,
+ progress: 100,
+ }),
+ );
+ expect(onChunkStateChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ partNumber: 1,
+ status: "complete",
+ }),
+ ]);
+ });
+
+ it("completes multipart uploads with parts ordered by part number", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/part-${body.partNumber}`,
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ expect(body.parts).toEqual([
+ expect.objectContaining({ partNumber: 1, etag: "etag-1" }),
+ expect.objectContaining({ partNumber: 2, etag: "etag-2" }),
+ ]);
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([
+ { type: "success", etag: "etag-1" },
+ { type: "success", etag: "etag-2" },
+ ]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ onChunkStateChange: vi.fn(),
+ });
+
+ const firstChunk = makeBlob(
+ STREAMED_PART_BYTES,
+ "video/webm;codecs=vp9,opus",
+ );
+ const secondChunk = makeBlob(
+ STREAMED_PART_BYTES,
+ "video/webm;codecs=vp9,opus",
+ );
+
+ uploader.handleChunk(firstChunk, firstChunk.size);
+ uploader.handleChunk(secondChunk, firstChunk.size + secondChunk.size);
+
+ await uploader.finalize({
+ durationSeconds: 14,
+ subpath: "raw-upload.webm",
+ });
+ });
+
+ it("retries a failed part upload before completing", async () => {
+ vi.useFakeTimers();
+
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = input.toString();
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/${fetchMock.mock.calls.length}`,
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ });
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([
+ { type: "network-error" },
+ { type: "success", etag: "etag-retried" },
+ ]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ onChunkStateChange: vi.fn(),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ const finalizePromise = uploader.finalize({
+ durationSeconds: 8,
+ subpath: "raw-upload.webm",
+ });
+
+ await vi.runAllTimersAsync();
+ await finalizePromise;
+
+ const presignCalls = fetchMock.mock.calls.filter(
+ ([input]) => input.toString() === "/api/upload/multipart/presign-part",
+ );
+ expect(presignCalls).toHaveLength(2);
+ });
+
+ it("retries a stalled part upload before completing", async () => {
+ vi.useFakeTimers();
+
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = input.toString();
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/${fetchMock.mock.calls.length}`,
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ });
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([
+ { type: "pending" },
+ { type: "success", etag: "etag-after-stall" },
+ ]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ onChunkStateChange: vi.fn(),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ const finalizePromise = uploader.finalize({
+ durationSeconds: 8,
+ subpath: "raw-upload.webm",
+ });
+
+ await vi.advanceTimersByTimeAsync(30_500);
+ await finalizePromise;
+
+ const presignCalls = fetchMock.mock.calls.filter(
+ ([input]) => input.toString() === "/api/upload/multipart/presign-part",
+ );
+ expect(presignCalls).toHaveLength(2);
+ expect(MockXMLHttpRequest.abortedCount).toBe(1);
+ });
+
+ it("marks the uploader as fatal after the final retry fails", async () => {
+ vi.useFakeTimers();
+
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = input.toString();
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/${fetchMock.mock.calls.length}`,
+ });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ });
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([
+ { type: "network-error" },
+ { type: "network-error" },
+ { type: "network-error" },
+ ]);
+
+ const onFatalError = vi.fn();
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ onChunkStateChange: vi.fn(),
+ onFatalError,
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ const finalizePromise = uploader.finalize({
+ durationSeconds: 8,
+ subpath: "raw-upload.webm",
+ });
+ const finalizeExpectation = expect(finalizePromise).rejects.toThrow(
+ "Failed to upload part 1: network error",
+ );
+
+ await vi.runAllTimersAsync();
+ await finalizeExpectation;
+ expect(onFatalError).toHaveBeenCalledTimes(1);
+ expect(() => uploader.handleChunk(chunk, chunk.size)).toThrow(
+ "Failed to upload part 1: network error",
+ );
+ });
+
+ it("fails finalize when server-side processing cannot start", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/presign-part") {
+ expect(body).toMatchObject({
+ videoId,
+ uploadId: "upload-123",
+ partNumber: 1,
+ subpath: "raw-upload.webm",
+ });
+ return makeJsonResponse({
+ presignedUrl: "https://uploads.example/part-1",
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ return makeJsonResponse({
+ success: true,
+ processingStarted: false,
+ });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([{ type: "success", etag: "etag-1" }]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ await expect(
+ uploader.finalize({
+ durationSeconds: 12,
+ subpath: "raw-upload.webm",
+ }),
+ ).rejects.toThrow("Video uploaded, but processing could not start");
+ });
+
+ it("treats interrupted multipart completion as uncertain instead of fatal cleanup", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/presign-part") {
+ expect(body).toMatchObject({
+ videoId,
+ uploadId: "upload-123",
+ partNumber: 1,
+ subpath: "raw-upload.webm",
+ });
+ return makeJsonResponse({
+ presignedUrl: "https://uploads.example/part-1",
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ return new Response("gateway timeout", { status: 504 });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([{ type: "success", etag: "etag-1" }]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ await expect(
+ uploader.finalize({
+ durationSeconds: 12,
+ subpath: "raw-upload.webm",
+ }),
+ ).rejects.toBeInstanceOf(MultipartCompletionUncertainError);
+ });
+
+ it("surfaces upload overflow before multipart completion", async () => {
+ const onOverflow = vi.fn();
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ onOverflow,
+ });
+
+ const chunk = makeBlob(OVERFLOW_PART_BYTES, "video/webm;codecs=vp9,opus");
+
+ expect(() => uploader.handleChunk(chunk, chunk.size)).toThrow(
+ "Upload could not keep up with recording",
+ );
+ expect(onOverflow).toHaveBeenCalledTimes(1);
+ await expect(
+ uploader.finalize({
+ durationSeconds: 20,
+ subpath: "raw-upload.webm",
+ }),
+ ).rejects.toThrow("Upload could not keep up with recording");
+ });
+
+ it("uploads large finalized blobs in multiple parts without hitting live overflow limits", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: `https://uploads.example/part-${body.partNumber}`,
+ });
+ }
+
+ if (url === "/api/upload/multipart/complete") {
+ expect(body.parts).toHaveLength(9);
+ expect(body.parts[0]).toMatchObject({
+ partNumber: 1,
+ etag: "etag-1",
+ });
+ expect(body.parts[8]).toMatchObject({
+ partNumber: 9,
+ etag: "etag-9",
+ });
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes(
+ Array.from({ length: 9 }, (_, index) => ({
+ type: "success" as const,
+ etag: `etag-${index + 1}`,
+ })),
+ );
+
+ const sendProgressUpdate = vi.fn().mockResolvedValue(undefined);
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/mp4",
+ subpath: "raw-upload.mp4",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate,
+ onChunkStateChange: vi.fn(),
+ });
+
+ await uploader.finalize({
+ finalBlob: makeBlob(FINALIZED_BLOB_BYTES, "video/mp4"),
+ durationSeconds: 180,
+ subpath: "raw-upload.mp4",
+ });
+
+ const presignCalls = fetchMock.mock.calls.filter(
+ ([input]) => input.toString() === "/api/upload/multipart/presign-part",
+ );
+ expect(presignCalls).toHaveLength(9);
+ expect(sendProgressUpdate).toHaveBeenLastCalledWith(
+ FINALIZED_BLOB_BYTES,
+ FINALIZED_BLOB_BYTES,
+ );
+ });
+
+ it("aborts multipart uploads with the raw subpath on cancel", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input.toString();
+ const body = init?.body ? JSON.parse(init.body as string) : null;
+
+ if (url === "/api/upload/multipart/abort") {
+ expect(body).toEqual({
+ videoId,
+ uploadId: "upload-123",
+ subpath: "raw-upload.webm",
+ });
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ },
+ );
+
+ vi.stubGlobal("fetch", fetchMock);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+
+ await uploader.cancel();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("aborts in-flight part uploads immediately on cancel", async () => {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = input.toString();
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: "https://uploads.example/part-1",
+ });
+ }
+
+ if (url === "/api/upload/multipart/abort") {
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ });
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([{ type: "pending" }]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/upload/multipart/presign-part",
+ expect.objectContaining({
+ method: "POST",
+ }),
+ );
+ expect(MockXMLHttpRequest.outcomes).toHaveLength(0);
+ await uploader.cancel();
+
+ expect(MockXMLHttpRequest.abortedCount).toBe(1);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/upload/multipart/abort",
+ expect.objectContaining({
+ method: "POST",
+ }),
+ );
+ });
+
+ it("cancels cleanly while waiting to retry a failed part upload", async () => {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = input.toString();
+
+ if (url === "/api/upload/multipart/presign-part") {
+ return makeJsonResponse({
+ presignedUrl: "https://uploads.example/part-1",
+ });
+ }
+
+ if (url === "/api/upload/multipart/abort") {
+ return makeJsonResponse({ success: true });
+ }
+
+ throw new Error(`Unexpected fetch call: ${url}`);
+ });
+
+ vi.stubGlobal("fetch", fetchMock);
+ MockXMLHttpRequest.setOutcomes([{ type: "network-error" }]);
+
+ const uploader = new InstantRecordingUploader({
+ videoId,
+ uploadId: "upload-123",
+ mimeType: "video/webm;codecs=vp9,opus",
+ subpath: "raw-upload.webm",
+ setUploadStatus: vi.fn(),
+ sendProgressUpdate: vi.fn().mockResolvedValue(undefined),
+ });
+
+ const chunk = makeBlob(STREAMED_PART_BYTES, "video/webm;codecs=vp9,opus");
+ uploader.handleChunk(chunk, chunk.size);
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ await expect(
+ Promise.race([
+ uploader.cancel().then(() => "cancelled"),
+ new Promise((resolve) => setTimeout(() => resolve("timeout"), 50)),
+ ]),
+ ).resolves.toBe("cancelled");
+ });
+});
diff --git a/apps/web/__tests__/unit/local-recording-backup.test.ts b/apps/web/__tests__/unit/local-recording-backup.test.ts
new file mode 100644
index 000000000..596153f8d
--- /dev/null
+++ b/apps/web/__tests__/unit/local-recording-backup.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import {
+ appendLocalRecordingChunk,
+ finalizeLocalRecording,
+ initialLocalRecordingState,
+} from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/local-recording-backup";
+
+const makeBlob = (size: number, type = "video/webm;codecs=vp9,opus") =>
+ new Blob([new Uint8Array(size)], { type });
+
+describe("local recording backup", () => {
+ it("retains a full local copy when configured for capped streaming backup", () => {
+ const firstChunk = makeBlob(3);
+ const secondChunk = makeBlob(4);
+
+ const afterFirstChunk = appendLocalRecordingChunk(
+ initialLocalRecordingState(),
+ firstChunk,
+ { mode: "capped", maxBytes: 10 },
+ );
+ const afterSecondChunk = appendLocalRecordingChunk(
+ afterFirstChunk,
+ secondChunk,
+ { mode: "capped", maxBytes: 10 },
+ );
+
+ const blob = finalizeLocalRecording(afterSecondChunk);
+
+ expect(afterSecondChunk.overflowed).toBe(false);
+ expect(afterSecondChunk.retainedBytes).toBe(7);
+ expect(blob?.size).toBe(7);
+ expect(blob?.type).toBe("video/webm;codecs=vp9,opus");
+ });
+
+ it("drops the backup copy after the capped limit is exceeded", () => {
+ const firstChunk = makeBlob(6);
+ const secondChunk = makeBlob(5);
+ const thirdChunk = makeBlob(3);
+
+ const afterFirstChunk = appendLocalRecordingChunk(
+ initialLocalRecordingState(),
+ firstChunk,
+ { mode: "capped", maxBytes: 10 },
+ );
+ const afterSecondChunk = appendLocalRecordingChunk(
+ afterFirstChunk,
+ secondChunk,
+ { mode: "capped", maxBytes: 10 },
+ );
+ const afterThirdChunk = appendLocalRecordingChunk(
+ afterSecondChunk,
+ thirdChunk,
+ { mode: "capped", maxBytes: 10 },
+ );
+
+ const blob = finalizeLocalRecording(afterThirdChunk);
+
+ expect(afterSecondChunk.overflowed).toBe(true);
+ expect(afterSecondChunk.retainedBytes).toBe(0);
+ expect(afterSecondChunk.chunks).toHaveLength(0);
+ expect(afterThirdChunk.overflowed).toBe(true);
+ expect(afterThirdChunk.retainedBytes).toBe(0);
+ expect(afterThirdChunk.chunks).toHaveLength(0);
+ expect(blob).toBeNull();
+ });
+
+ it("keeps the uncapped buffered fallback intact", () => {
+ const state = appendLocalRecordingChunk(
+ initialLocalRecordingState(),
+ makeBlob(12, "video/mp4"),
+ { mode: "full" },
+ );
+
+ const blob = finalizeLocalRecording(state);
+
+ expect(state.overflowed).toBe(false);
+ expect(blob?.size).toBe(12);
+ expect(blob?.type).toBe("video/mp4");
+ });
+});
diff --git a/apps/web/__tests__/unit/multipart-upload-utils.test.ts b/apps/web/__tests__/unit/multipart-upload-utils.test.ts
new file mode 100644
index 000000000..179488ef7
--- /dev/null
+++ b/apps/web/__tests__/unit/multipart-upload-utils.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import {
+ getMultipartFileKey,
+ getSubpath,
+ isRawRecorderUpload,
+} from "@/app/api/upload/[...route]/multipart-utils";
+
+describe("multipart upload utils", () => {
+ it("builds a multipart file key from video id and subpath", () => {
+ expect(
+ getMultipartFileKey("user-123", {
+ videoId: "video-456",
+ subpath: "raw-upload.webm",
+ }),
+ ).toBe("user-123/video-456/raw-upload.webm");
+ });
+
+ it("defaults the multipart subpath to result.mp4", () => {
+ const input: { subpath?: string } = {};
+
+ expect(
+ getMultipartFileKey("user-123", {
+ videoId: "video-456",
+ }),
+ ).toBe("user-123/video-456/result.mp4");
+ expect(getSubpath(input)).toBe("result.mp4");
+ });
+
+ it("parses deprecated fileKey input into the current user-scoped key", () => {
+ expect(
+ getMultipartFileKey("user-123", {
+ fileKey: "legacy-owner/video-456/raw-upload.webm",
+ }),
+ ).toBe("user-123/video-456/raw-upload.webm");
+ expect(
+ getSubpath({
+ fileKey: "legacy-owner/video-456/raw-upload.webm",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("detects raw recorder uploads", () => {
+ expect(isRawRecorderUpload("raw-upload.webm")).toBe(true);
+ expect(isRawRecorderUpload("raw-upload.mp4")).toBe(true);
+ expect(isRawRecorderUpload("result.mp4")).toBe(false);
+ });
+
+ it("rejects missing video ids", () => {
+ expect(() =>
+ getMultipartFileKey("user-123", {
+ subpath: "raw-upload.webm",
+ }),
+ ).toThrow("Video id not found");
+ });
+});
diff --git a/apps/web/__tests__/unit/recording-spool-fallback.test.ts b/apps/web/__tests__/unit/recording-spool-fallback.test.ts
new file mode 100644
index 000000000..f6d7cc34a
--- /dev/null
+++ b/apps/web/__tests__/unit/recording-spool-fallback.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from "vitest";
+import { moveRecordingSpoolToInMemoryBackup } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-spool-fallback";
+
+const blobToText = async (blob: Blob) =>
+ new TextDecoder().decode(await blob.arrayBuffer());
+
+describe("moveRecordingSpoolToInMemoryBackup", () => {
+ it("merges recovered chunks with later in-memory chunks without duplicating them", async () => {
+ let retainedChunks = [new Blob(["older"], { type: "video/webm" })];
+ let releaseRecovery: (() => void) | null = null;
+
+ const replaceLocalRecording = vi.fn((chunks: Blob[]) => {
+ retainedChunks = chunks;
+ });
+
+ const transitionPromise = moveRecordingSpoolToInMemoryBackup({
+ spool: {
+ recoverBlob: () =>
+ new Promise<Blob>((resolve) => {
+ releaseRecovery = () =>
+ resolve(new Blob(["persisted"], { type: "video/webm" }));
+ }),
+ },
+ setLocalRecordingStrategy: () => {
+ retainedChunks = [];
+ },
+ getRetainedChunks: () => [...retainedChunks],
+ replaceLocalRecording,
+ });
+
+ retainedChunks = [
+ ...retainedChunks,
+ new Blob(["later"], { type: "video/webm" }),
+ ];
+
+ releaseRecovery?.();
+ await transitionPromise;
+
+ expect(replaceLocalRecording).toHaveBeenCalledTimes(1);
+ expect(retainedChunks).toHaveLength(2);
+ expect(await blobToText(new Blob(retainedChunks))).toBe("persistedlater");
+ });
+});
diff --git a/apps/web/__tests__/unit/recording-spool.test.ts b/apps/web/__tests__/unit/recording-spool.test.ts
new file mode 100644
index 000000000..17849bd6f
--- /dev/null
+++ b/apps/web/__tests__/unit/recording-spool.test.ts
@@ -0,0 +1,438 @@
+import { describe, expect, it } from "vitest";
+import {
+ deleteRecoveredRecordingSpool,
+ RecordingSpool,
+ type RecordingSpoolBackend,
+ RecordingSpoolBackpressureError,
+ type RecordingSpoolSessionRecord,
+ recoverOrphanedRecordingSpools,
+} from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-spool";
+
+class MemoryRecordingSpoolBackend implements RecordingSpoolBackend {
+ private readonly sessions = new Map<string, RecordingSpoolSessionRecord>();
+ private readonly chunks = new Map<
+ string,
+ Array<{ index: number; blob: Blob }>
+ >();
+ private readonly failureAtIndex: number | null;
+ private readonly readFailureSessionId: string | null;
+
+ constructor(options?: {
+ failureAtIndex?: number | null;
+ readFailureSessionId?: string | null;
+ }) {
+ this.failureAtIndex = options?.failureAtIndex ?? null;
+ this.readFailureSessionId = options?.readFailureSessionId ?? null;
+ }
+
+ async initialize() {}
+
+ async createSession(session: RecordingSpoolSessionRecord) {
+ this.sessions.set(session.sessionId, session);
+ }
+
+ async appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ) {
+ if (this.failureAtIndex === index) {
+ throw new Error(`Failed to persist chunk ${index}`);
+ }
+
+ this.sessions.set(session.sessionId, session);
+ const existingChunks = this.chunks.get(session.sessionId) ?? [];
+ existingChunks.push({ index, blob: chunk });
+ this.chunks.set(session.sessionId, existingChunks);
+ }
+
+ async readChunks(sessionId: string) {
+ if (this.readFailureSessionId === sessionId) {
+ throw new Error(`Failed to read chunks for ${sessionId}`);
+ }
+
+ return [...(this.chunks.get(sessionId) ?? [])]
+ .sort((left, right) => left.index - right.index)
+ .map((chunk) => chunk.blob);
+ }
+
+ async listSessions() {
+ return [...this.sessions.values()];
+ }
+
+ async deleteSession(sessionId: string) {
+ this.sessions.delete(sessionId);
+ this.chunks.delete(sessionId);
+ }
+
+ getSessionCount() {
+ return this.sessions.size;
+ }
+
+ getChunkCount(sessionId: string) {
+ return this.chunks.get(sessionId)?.length ?? 0;
+ }
+}
+
+const blobToText = async (blob: Blob) =>
+ new TextDecoder().decode(await blob.arrayBuffer());
+
+class DelayedRecordingSpoolBackend implements RecordingSpoolBackend {
+ private readonly sessions = new Map<string, RecordingSpoolSessionRecord>();
+ private readonly chunks = new Map<
+ string,
+ Array<{ index: number; blob: Blob }>
+ >();
+ private resolveAppend: (() => void) | null = null;
+ private pendingAppend: Promise<void> | null = null;
+
+ async initialize() {}
+
+ async createSession(session: RecordingSpoolSessionRecord) {
+ this.sessions.set(session.sessionId, session);
+ }
+
+ async appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ) {
+ this.sessions.set(session.sessionId, session);
+
+ if (!this.pendingAppend) {
+ this.pendingAppend = new Promise<void>((resolve) => {
+ this.resolveAppend = resolve;
+ });
+ }
+
+ await this.pendingAppend;
+
+ const existingChunks = this.chunks.get(session.sessionId) ?? [];
+ existingChunks.push({ index, blob: chunk });
+ this.chunks.set(session.sessionId, existingChunks);
+ }
+
+ async readChunks(sessionId: string) {
+ return [...(this.chunks.get(sessionId) ?? [])]
+ .sort((left, right) => left.index - right.index)
+ .map((entry) => entry.blob);
+ }
+
+ async listSessions() {
+ return [...this.sessions.values()];
+ }
+
+ async deleteSession(sessionId: string) {
+ this.sessions.delete(sessionId);
+ this.chunks.delete(sessionId);
+ }
+
+ releaseAppend() {
+ this.resolveAppend?.();
+ this.resolveAppend = null;
+ this.pendingAppend = null;
+ }
+}
+
+describe("RecordingSpool", () => {
+ it("persists chunks in order and rebuilds the recording blob", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm;codecs=vp9,opus",
+ sessionId: "session-1",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["first-"], { type: "video/webm" }));
+ await spool.appendChunk(new Blob(["second"], { type: "video/webm" }));
+
+ expect(spool.chunkCount).toBe(2);
+ expect(spool.totalBytes).toBe(12);
+
+ const blob = await spool.toBlob();
+
+ expect(blob).not.toBeNull();
+ expect(blob?.type).toBe("video/webm;codecs=vp9,opus");
+ expect(await blobToText(blob as Blob)).toBe("first-second");
+ });
+
+ it("keeps queued chunk indexes unique when appends overlap", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-overlap",
+ },
+ backend,
+ );
+
+ await Promise.all([
+ spool.appendChunk(new Blob(["first-"], { type: "video/webm" })),
+ spool.appendChunk(new Blob(["second-"], { type: "video/webm" })),
+ spool.appendChunk(new Blob(["third"], { type: "video/webm" })),
+ ]);
+
+ const blob = await spool.toBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("first-second-third");
+ expect(spool.chunkCount).toBe(3);
+ expect(backend.getChunkCount("session-overlap")).toBe(3);
+ });
+
+ it("cleans up persisted state when disposed", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-2",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk"], { type: "video/webm" }));
+ expect(backend.getSessionCount()).toBe(1);
+ expect(backend.getChunkCount("session-2")).toBe(1);
+
+ await spool.dispose();
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("session-2")).toBe(0);
+ });
+
+ it("fails fast when the pending spool backlog grows beyond its limit", async () => {
+ const backend = new DelayedRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-backpressure",
+ maxPendingChunkBytes: 6,
+ },
+ backend,
+ );
+
+ const firstWrite = spool.appendChunk(
+ new Blob(["1234"], { type: "video/webm" }),
+ );
+
+ await expect(
+ spool.appendChunk(new Blob(["5678"], { type: "video/webm" })),
+ ).rejects.toBeInstanceOf(RecordingSpoolBackpressureError);
+
+ backend.releaseAppend();
+ await Promise.allSettled([firstWrite]);
+
+ const recoveredBlob = await spool.recoverBlob();
+
+ expect(await blobToText(recoveredBlob as Blob)).toBe("12345678");
+ });
+
+ it("surfaces storage write failures", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-3",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+ await expect(spool.toBlob()).rejects.toThrow("Failed to persist chunk 1");
+ });
+
+ it("recovers the persisted data and failed in-memory chunk after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-4",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+
+ const blob = await spool.recoverBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("chunk-1chunk-2");
+ });
+
+ it("keeps queued in-memory chunks available after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-5",
+ },
+ backend,
+ );
+
+ const firstWrite = spool.appendChunk(
+ new Blob(["chunk-1|"], { type: "video/webm" }),
+ );
+ const secondWrite = spool.appendChunk(
+ new Blob(["chunk-2|"], { type: "video/webm" }),
+ );
+ const thirdWrite = spool.appendChunk(
+ new Blob(["chunk-3"], { type: "video/webm" }),
+ );
+
+ await firstWrite;
+ await expect(secondWrite).rejects.toThrow("Failed to persist chunk 1");
+ await expect(thirdWrite).rejects.toThrow("Failed to persist chunk 1");
+
+ const blob = await spool.recoverBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("chunk-1|chunk-2|chunk-3");
+ });
+
+ it("cleans up persisted state after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-cleanup",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+
+ await spool.dispose();
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("session-cleanup")).toBe(0);
+ });
+
+ it("recovers orphaned spools in newest-first order without deleting them", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "older",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "older",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["older"], { type: "video/webm" }),
+ );
+ await backend.createSession({
+ sessionId: "newer",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 300,
+ updatedAt: 400,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "newer",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 300,
+ updatedAt: 400,
+ },
+ 0,
+ new Blob(["newer"], { type: "video/webm" }),
+ );
+
+ const recovered = await recoverOrphanedRecordingSpools(backend);
+ const [newer, older] = recovered;
+
+ expect(recovered.map((item) => item.sessionId)).toEqual(["newer", "older"]);
+ if (!newer || !older) {
+ throw new Error("Expected recovered recordings");
+ }
+ expect(await blobToText(newer.blob)).toBe("newer");
+ expect(await blobToText(older.blob)).toBe("older");
+ expect(backend.getSessionCount()).toBe(2);
+ expect(backend.getChunkCount("newer")).toBe(1);
+ expect(backend.getChunkCount("older")).toBe(1);
+ });
+
+ it("deletes recovered spools only when explicitly dismissed", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "dismiss-me",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "dismiss-me",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["stale"], { type: "video/webm" }),
+ );
+
+ await deleteRecoveredRecordingSpool("dismiss-me", backend);
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("dismiss-me")).toBe(0);
+ });
+
+ it("preserves sessions that fail during recovery so they can be retried later", async () => {
+ const backend = new MemoryRecordingSpoolBackend({
+ readFailureSessionId: "stuck",
+ });
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "stuck",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "stuck",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["stuck"], { type: "video/webm" }),
+ );
+
+ const recovered = await recoverOrphanedRecordingSpools(backend);
+
+ expect(recovered).toEqual([]);
+ expect(backend.getSessionCount()).toBe(1);
+ expect(backend.getChunkCount("stuck")).toBe(1);
+ });
+});
diff --git a/apps/web/__tests__/unit/recovered-recording-cache.test.ts b/apps/web/__tests__/unit/recovered-recording-cache.test.ts
new file mode 100644
index 000000000..0672caabe
--- /dev/null
+++ b/apps/web/__tests__/unit/recovered-recording-cache.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock(
+ "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-spool",
+ () => ({
+ recoverOrphanedRecordingSpools: vi.fn(),
+ }),
+);
+
+describe("recovered recording cache", () => {
+ afterEach(async () => {
+ const { resetRecoveredRecordingSpoolsCache } = await import(
+ "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recovered-recording-cache"
+ );
+ resetRecoveredRecordingSpoolsCache();
+ vi.clearAllMocks();
+ });
+
+ it("keeps undismissed recovered recordings available across repeated loads", async () => {
+ const recoverOrphanedRecordingSpools = vi.mocked(
+ (
+ await import(
+ "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-spool"
+ )
+ ).recoverOrphanedRecordingSpools,
+ );
+ recoverOrphanedRecordingSpools.mockResolvedValue([
+ {
+ sessionId: "first",
+ mimeType: "video/webm",
+ totalBytes: 1,
+ chunkCount: 1,
+ createdAt: 1,
+ updatedAt: 2,
+ blob: new Blob(["a"], { type: "video/webm" }),
+ },
+ {
+ sessionId: "second",
+ mimeType: "video/webm",
+ totalBytes: 1,
+ chunkCount: 1,
+ createdAt: 3,
+ updatedAt: 4,
+ blob: new Blob(["b"], { type: "video/webm" }),
+ },
+ ]);
+
+ const {
+ loadRecoveredRecordingSpools,
+ removeRecoveredRecordingSpoolFromCache,
+ } = await import(
+ "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recovered-recording-cache"
+ );
+
+ const firstLoad = await loadRecoveredRecordingSpools();
+ expect(firstLoad.map((spool) => spool.sessionId)).toEqual([
+ "first",
+ "second",
+ ]);
+
+ removeRecoveredRecordingSpoolFromCache("first");
+
+ const secondLoad = await loadRecoveredRecordingSpools();
+ expect(secondLoad.map((spool) => spool.sessionId)).toEqual(["second"]);
+ expect(recoverOrphanedRecordingSpools).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/__tests__/unit/upload-progress-playback.test.ts b/apps/web/__tests__/unit/upload-progress-playback.test.ts
new file mode 100644
index 000000000..9fb1cda4e
--- /dev/null
+++ b/apps/web/__tests__/unit/upload-progress-playback.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "vitest";
+import {
+ canRetryFailedProcessing,
+ getStalledProcessingMessage,
+ getUploadFailureMessage,
+ shouldDeferPlaybackSource,
+ shouldReloadPlaybackAfterUploadCompletes,
+} from "@/app/s/[videoId]/_components/ProgressCircle";
+
+describe("shouldDeferPlaybackSource", () => {
+ it.each([
+ { status: "fetching" },
+ {
+ status: "uploading",
+ lastUpdated: new Date(),
+ progress: 10,
+ },
+ {
+ status: "processing",
+ lastUpdated: new Date(),
+ progress: 42,
+ message: "Processing video...",
+ },
+ {
+ status: "generating_thumbnail",
+ lastUpdated: new Date(),
+ progress: 90,
+ },
+ ])("returns true for active upload state %#", (uploadProgress) => {
+ expect(shouldDeferPlaybackSource(uploadProgress as never)).toBe(true);
+ });
+
+ it.each([
+ null,
+ {
+ status: "error",
+ lastUpdated: new Date(),
+ errorMessage: "Processing failed",
+ },
+ {
+ status: "failed",
+ lastUpdated: new Date(),
+ },
+ ])("returns false for non-blocking state %#", (uploadProgress) => {
+ expect(shouldDeferPlaybackSource(uploadProgress as never)).toBe(false);
+ });
+
+ it("allows retry only for owner-visible processing errors", () => {
+ expect(
+ canRetryFailedProcessing(
+ {
+ status: "error",
+ lastUpdated: new Date(),
+ errorMessage: "Video processing timed out",
+ },
+ true,
+ ),
+ ).toBe(true);
+ expect(
+ canRetryFailedProcessing(
+ {
+ status: "error",
+ lastUpdated: new Date(),
+ errorMessage: "Video processing timed out",
+ },
+ false,
+ ),
+ ).toBe(false);
+ expect(
+ canRetryFailedProcessing(
+ {
+ status: "failed",
+ lastUpdated: new Date(),
+ } as never,
+ true,
+ ),
+ ).toBe(false);
+ });
+
+ it("uses upload-specific failure messaging", () => {
+ expect(
+ getUploadFailureMessage(
+ {
+ status: "error",
+ lastUpdated: new Date(),
+ errorMessage: "Video uploaded, but processing could not start.",
+ },
+ true,
+ ),
+ ).toBe("Video uploaded, but processing could not start.");
+ expect(
+ getUploadFailureMessage(
+ {
+ status: "error",
+ lastUpdated: new Date(),
+ errorMessage: null,
+ },
+ false,
+ ),
+ ).toBe(
+ "Processing failed. Ask the owner to retry processing or re-upload the recording.",
+ );
+ expect(
+ getUploadFailureMessage(
+ {
+ status: "failed",
+ lastUpdated: new Date(),
+ } as never,
+ false,
+ ),
+ ).toBe(
+ "Upload stalled before processing finished. Re-upload the recording to continue.",
+ );
+ });
+
+ it("reloads playback when upload progress clears before media finishes loading", () => {
+ expect(
+ shouldReloadPlaybackAfterUploadCompletes(
+ {
+ status: "processing",
+ lastUpdated: new Date(),
+ progress: 80,
+ message: "Finishing video...",
+ },
+ null,
+ false,
+ ),
+ ).toBe(true);
+ expect(
+ shouldReloadPlaybackAfterUploadCompletes(
+ {
+ status: "processing",
+ lastUpdated: new Date(),
+ progress: 80,
+ message: "Finishing video...",
+ },
+ null,
+ true,
+ ),
+ ).toBe(false);
+ expect(shouldReloadPlaybackAfterUploadCompletes(null, null, false)).toBe(
+ false,
+ );
+ });
+
+ it("detects processing that never actually started", () => {
+ expect(
+ getStalledProcessingMessage({
+ phase: "processing",
+ updatedAt: new Date(Date.now() - 91_000),
+ processingProgress: 0,
+ }),
+ ).toBe("Video processing did not start. Retry processing.");
+
+ expect(
+ getStalledProcessingMessage({
+ phase: "processing",
+ updatedAt: new Date(Date.now() - 30_000),
+ processingProgress: 0,
+ }),
+ ).toBeNull();
+ });
+
+ it("detects processing that stalled after starting", () => {
+ expect(
+ getStalledProcessingMessage({
+ phase: "processing",
+ updatedAt: new Date(Date.now() - 11 * 60 * 1000),
+ processingProgress: 25,
+ }),
+ ).toBe("Video processing stalled. Retry processing.");
+ });
+});
diff --git a/apps/web/__tests__/unit/video-processing.test.ts b/apps/web/__tests__/unit/video-processing.test.ts
new file mode 100644
index 000000000..e9ae285a4
--- /dev/null
+++ b/apps/web/__tests__/unit/video-processing.test.ts
@@ -0,0 +1,160 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const updateWhereMock = vi.fn();
+const selectWhereMock = vi.fn();
+const startMock = vi.fn();
+
+const dbMock = vi.fn(() => ({
+ update: vi.fn(() => ({
+ set: vi.fn(() => ({
+ where: updateWhereMock,
+ })),
+ })),
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: selectWhereMock,
+ })),
+ })),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: dbMock,
+}));
+
+vi.mock("server-only", () => ({}));
+
+vi.mock("workflow/api", () => ({
+ start: startMock,
+}));
+
+vi.mock("@/workflows/process-video", () => ({
+ processVideoWorkflow: Symbol("processVideoWorkflow"),
+}));
+
+describe("video processing starts", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not start a duplicate workflow when processing is already running", async () => {
+ updateWhereMock.mockResolvedValueOnce({ affectedRows: 0 });
+ selectWhereMock.mockResolvedValueOnce([
+ {
+ videoId: "video-123",
+ phase: "processing",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ },
+ ]);
+
+ const { startVideoProcessingWorkflow } = await import(
+ "@/lib/video-processing"
+ );
+
+ await expect(
+ startVideoProcessingWorkflow({
+ videoId: "video-123" as never,
+ userId: "user-123",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ bucketId: null,
+ processingMessage: "Starting video processing...",
+ startFailureMessage: "Video processing could not start.",
+ }),
+ ).resolves.toBe("already-processing");
+
+ expect(startMock).not.toHaveBeenCalled();
+ });
+
+ it("starts the workflow after claiming the upload row", async () => {
+ updateWhereMock.mockResolvedValueOnce({ affectedRows: 1 });
+ startMock.mockResolvedValueOnce(undefined);
+
+ const { startVideoProcessingWorkflow } = await import(
+ "@/lib/video-processing"
+ );
+
+ await expect(
+ startVideoProcessingWorkflow({
+ videoId: "video-123" as never,
+ userId: "user-123",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ bucketId: null,
+ processingMessage: "Starting video processing...",
+ startFailureMessage: "Video processing could not start.",
+ mode: "multipart",
+ }),
+ ).resolves.toBe("started");
+
+ expect(startMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("starts the workflow when mysql returns affectedRows in the first tuple slot", async () => {
+ updateWhereMock.mockResolvedValueOnce([{ affectedRows: 1 }]);
+ startMock.mockResolvedValueOnce(undefined);
+
+ const { startVideoProcessingWorkflow } = await import(
+ "@/lib/video-processing"
+ );
+
+ await expect(
+ startVideoProcessingWorkflow({
+ videoId: "video-123" as never,
+ userId: "user-123",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ bucketId: null,
+ processingMessage: "Starting video processing...",
+ startFailureMessage: "Video processing could not start.",
+ mode: "multipart",
+ }),
+ ).resolves.toBe("started");
+
+ expect(startMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("force restarts a stale processing row", async () => {
+ updateWhereMock.mockResolvedValueOnce({ affectedRows: 1 });
+ startMock.mockResolvedValueOnce(undefined);
+
+ const { startVideoProcessingWorkflow } = await import(
+ "@/lib/video-processing"
+ );
+
+ await expect(
+ startVideoProcessingWorkflow({
+ videoId: "video-123" as never,
+ userId: "user-123",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ bucketId: null,
+ processingMessage: "Retrying video processing...",
+ startFailureMessage: "Video processing could not restart.",
+ forceRestart: true,
+ }),
+ ).resolves.toBe("started");
+
+ expect(startMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("marks the upload as errored when workflow start fails", async () => {
+ updateWhereMock
+ .mockResolvedValueOnce({ affectedRows: 1 })
+ .mockResolvedValueOnce({ affectedRows: 1 });
+ startMock.mockRejectedValueOnce(new Error("temporary failure"));
+
+ const { startVideoProcessingWorkflow } = await import(
+ "@/lib/video-processing"
+ );
+
+ await expect(
+ startVideoProcessingWorkflow({
+ videoId: "video-123" as never,
+ userId: "user-123",
+ rawFileKey: "user-123/video-123/raw-upload.webm",
+ bucketId: null,
+ processingMessage: "Starting video processing...",
+ startFailureMessage: "Video processing could not start.",
+ }),
+ ).rejects.toThrow("temporary failure");
+
+ expect(startMock).toHaveBeenCalledTimes(1);
+ expect(updateWhereMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/__tests__/unit/web-recorder-utils.test.ts b/apps/web/__tests__/unit/web-recorder-utils.test.ts
new file mode 100644
index 000000000..ac4188cd5
--- /dev/null
+++ b/apps/web/__tests__/unit/web-recorder-utils.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+import {
+ selectRecordingPipelineFromSupport,
+ shouldPreferStreamingUpload,
+} from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-utils";
+
+describe("selectRecordingPipelineFromSupport", () => {
+ it("prefers streaming webm when webm and mp4 are both supported and streaming is preferred", () => {
+ const supportedTypes = new Set([
+ "video/webm;codecs=vp9,opus",
+ 'video/mp4;codecs="avc1.42E01E,mp4a.40.2"',
+ ]);
+
+ const pipeline = selectRecordingPipelineFromSupport(
+ true,
+ (candidate) => supportedTypes.has(candidate),
+ { preferStreamingUpload: true },
+ );
+
+ expect(pipeline).toEqual({
+ mode: "streaming-webm",
+ mimeType: "video/webm;codecs=vp9,opus",
+ fileExtension: "webm",
+ supportsProgressiveUpload: true,
+ });
+ });
+
+ it("prefers buffered mp4 when streaming uploads are not preferred", () => {
+ const supportedTypes = new Set([
+ "video/webm;codecs=vp9,opus",
+ 'video/mp4;codecs="avc1.42E01E,mp4a.40.2"',
+ ]);
+
+ const pipeline = selectRecordingPipelineFromSupport(
+ true,
+ (candidate) => supportedTypes.has(candidate),
+ { preferStreamingUpload: false },
+ );
+
+ expect(pipeline).toEqual({
+ mode: "buffered-raw",
+ mimeType: 'video/mp4;codecs="avc1.42E01E,mp4a.40.2"',
+ fileExtension: "mp4",
+ supportsProgressiveUpload: false,
+ });
+ });
+
+ it("falls back to buffered mp4 when webm is unavailable", () => {
+ const supportedTypes = new Set(['video/mp4;codecs="avc1.42E01E"']);
+
+ const pipeline = selectRecordingPipelineFromSupport(false, (candidate) =>
+ supportedTypes.has(candidate),
+ );
+
+ expect(pipeline).toEqual({
+ mode: "buffered-raw",
+ mimeType: 'video/mp4;codecs="avc1.42E01E"',
+ fileExtension: "mp4",
+ supportsProgressiveUpload: false,
+ });
+ });
+
+ it("falls back to buffered webm when streaming uploads are not preferred and mp4 is unavailable", () => {
+ const supportedTypes = new Set(["video/webm;codecs=vp9,opus"]);
+
+ const pipeline = selectRecordingPipelineFromSupport(
+ true,
+ (candidate) => supportedTypes.has(candidate),
+ { preferStreamingUpload: false },
+ );
+
+ expect(pipeline).toEqual({
+ mode: "buffered-raw",
+ mimeType: "video/webm;codecs=vp9,opus",
+ fileExtension: "webm",
+ supportsProgressiveUpload: false,
+ });
+ });
+
+ it("uses streaming webm when mp4 is unavailable and streaming is preferred", () => {
+ const supportedTypes = new Set(["video/webm;codecs=vp9,opus"]);
+
+ const pipeline = selectRecordingPipelineFromSupport(
+ true,
+ (candidate) => supportedTypes.has(candidate),
+ { preferStreamingUpload: true },
+ );
+
+ expect(pipeline).toEqual({
+ mode: "streaming-webm",
+ mimeType: "video/webm;codecs=vp9,opus",
+ fileExtension: "webm",
+ supportsProgressiveUpload: true,
+ });
+ });
+
+ it("returns null when no supported recorder mime type is available", () => {
+ expect(selectRecordingPipelineFromSupport(true, () => false)).toBeNull();
+ });
+});
+
+describe("shouldPreferStreamingUpload", () => {
+ it("enables streaming uploads for chromium-like browsers", () => {
+ expect(
+ shouldPreferStreamingUpload({
+ userAgent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
+ }),
+ ).toBe(true);
+ });
+
+ it("disables streaming uploads for safari and firefox", () => {
+ expect(
+ shouldPreferStreamingUpload({
+ userAgent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",
+ }),
+ ).toBe(false);
+ expect(
+ shouldPreferStreamingUpload({
+ userAgent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:141.0) Gecko/20100101 Firefox/141.0",
+ }),
+ ).toBe(false);
+ });
+});