Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: make recording completion and import processing durable
Richie McIlroy9d8c05210cc1
diff --git a/apps/desktop/src-tauri/src/api.rs b/apps/desktop/src-tauri/src/api.rsindex 7c482d0ee..f0c598b4a 100644--- a/apps/desktop/src-tauri/src/api.rs+++ b/apps/desktop/src-tauri/src/api.rs@@ -329,34 +329,6 @@ pub struct Organization {pub brand_colors: OrganizationBrandColors,}-pub async fn signal_recording_complete(- app: &AppHandle,- video_id: &str,-) -> Result<(), AuthedApiError> {- let resp = app- .authed_api_request("/api/upload/recording-complete", |client, url| {- client- .post(url)- .header("Content-Type", "application/json")- .json(&serde_json::json!({- "videoId": video_id,- }))- })- .await- .map_err(|err| format!("api/signal_recording_complete/request: {err}"))?;-- if !resp.status().is_success() {- let status = resp.status().as_u16();- let error_body = resp- .text()- .await- .unwrap_or_else(|_| "<no response body>".to_string());- return Err(format!("api/signal_recording_complete/{status}: {error_body}").into());- }-- Ok(())-}-pub async fn verify_recording_complete(app: &AppHandle,video_id: &str,diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex ed1bbf960..e743e56a3 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -3534,16 +3534,6 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res};let recording_dir = current_recording.recording_dir().clone();- if let InProgressRecording::Instant {- video_upload_info, ..- } = ¤t_recording- {- let _ = open_external_link(- app.clone(),- recording_stopped_share_url(&video_upload_info.link),- );- }-let recording_outcome = match current_recording.stop().await {Ok(completed) => Ok(completed),Err((e, ctx)) => {@@ -4618,6 +4608,12 @@ async fn handle_recording_finish(return Ok(false);}+ AppSounds::StopRecording.play();+ let _ = open_external_link(+ app.clone(),+ recording_stopped_share_url(&video_upload_info.link),+ );+let app = app.clone();let is_camera_only =matches!(recording.display_source, ScreenCaptureTarget::CameraOnly);@@ -4743,11 +4739,9 @@ async fn handle_recording_finish();editor_took_foreground =apply_post_studio_editor_behaviour(app, recording_dir, duration).await;+ AppSounds::StopRecording.play();}- // Play sound to indicate recording has stopped- AppSounds::StopRecording.play();-Ok(editor_took_foreground)}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex d8e6c8cf6..3ad982420 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1802,46 +1802,6 @@ impl SegmentUploader {}}- {- let mut signal_ok = false;- for attempt in 0..3u32 {- match api::signal_recording_complete(&app, &video_id).await {- Ok(()) => {- signal_ok = true;- break;- }- Err(e) => {- warn!(- attempt = attempt + 1,- "Failed to signal recording complete: {e}"- );- if attempt < 2 {- tokio::time::sleep(Duration::from_millis(- 1000 * (1 << attempt) as u64,- ))- .await;- }- }- }- }- if !signal_ok {- error!("All attempts to signal recording complete failed for {video_id}");-- session.persist_upload(UploadMeta::SegmentUpload {- video_id: video_id.clone(),- pre_created_video: pre_created_video.clone(),- recording_dir: recording_dir.clone(),- })?;-- emit_upload_complete(&app, &video_id);-- return Err(format!(- "Failed to signal recording complete for {video_id} after 3 attempts"- )- .into());- }- }-await_upload_verification(&app, &video_id, &verification, &session).await?;emit_upload_complete(&app, &video_id);diff --git a/apps/web/__tests__/unit/media-processing-workflows.test.ts b/apps/web/__tests__/unit/media-processing-workflows.test.tsnew file mode 100644index 000000000..2f789c88c--- /dev/null+++ b/apps/web/__tests__/unit/media-processing-workflows.test.ts@@ -0,0 +1,251 @@+import { Effect } from "effect";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ rows: [] as unknown[][],+ where: vi.fn(),+ write: vi.fn(),+ getAccess: vi.fn(),+ get: vi.fn(),+ put: vi.fn(),+ head: vi.fn(),+ remove: vi.fn(),+ fetch: vi.fn(),+ sleep: vi.fn(),+}));++vi.mock("@cap/database", () => ({+ db: () => ({+ select: () => ({+ from: () => ({+ where: mocks.where,+ innerJoin: () => ({ where: mocks.where }),+ }),+ }),+ update: () => ({ set: () => ({ where: mocks.write }) }),+ delete: () => ({ where: mocks.write }),+ }),+}));+vi.mock("@cap/database/schema", () => ({+ videos: { id: "id" },+ videoUploads: { videoId: "videoId" },+ users: {},+ agentApiOperations: {},+}));+vi.mock("@cap/env", () => ({+ serverEnv: () => ({+ MEDIA_SERVER_URL: "https://worker.example.com",+ WEB_URL: "https://cap.example.com",+ MEDIA_SERVER_WEBHOOK_SECRET: "test-secret",+ }),+}));+vi.mock("@cap/web-domain", () => ({+ Video: {+ VideoId: { make: (id: string) => id },+ Video: { decodeSync: (value: unknown) => value },+ },+}));+vi.mock("@cap/web-backend/src/Storage/index", () => ({+ Storage: { getAccessForVideo: mocks.getAccess },+}));+vi.mock("@/lib/workflow-runtime", () => ({+ runWorkflowPromise: (effect: Effect.Effect<unknown>) =>+ Effect.runPromise(effect),+}));+vi.mock("@/lib/video-storage", () => ({+ decodeStorageVideo: (value: unknown) => value,+}));+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: vi.fn() }));+vi.mock("@/lib/ai-generation-entitlement", () => ({+ isAiGenerationEnabledForUser: () => false,+}));+vi.mock("workflow", () => ({+ sleep: mocks.sleep,+ FatalError: class FatalError extends Error {},+}));++import { importLoomVideoWorkflow } from "@/workflows/import-loom-video";+import { processVideoWorkflow } from "@/workflows/process-video";++const payload = {+ videoId: "video",+ userId: "owner",+ rawFileKey: "owner/video/raw-upload.mp4",+ bucketId: null,+ loomVideoId: "loom-video",+};+const video = { id: "video", createdAt: new Date(), updatedAt: new Date() };+const metadata = { duration: 30, width: 1920, height: 1080, fps: 30 };+const pending = { phase: "processing", processingProgress: 25 };++describe("media processing workflows", () => {+ beforeEach(() => {+ mocks.rows = [];+ mocks.where+ .mockReset()+ .mockImplementation(async () => mocks.rows.shift() ?? []);+ mocks.write.mockResolvedValue(undefined);+ mocks.getAccess.mockImplementation(() =>+ Effect.succeed([+ {+ getInternalSignedObjectUrl: mocks.get,+ getInternalPresignedPutUrl: mocks.put,+ headObject: mocks.head,+ deleteObject: mocks.remove,+ },+ ]),+ );+ mocks.get.mockImplementation((key: string) =>+ Effect.succeed(`https://storage.example.com/${key}`),+ );+ mocks.put.mockImplementation((key: string) =>+ Effect.succeed(`https://storage.example.com/${key}?upload=1`),+ );+ mocks.head.mockImplementation(() =>+ Effect.succeed({ ContentLength: 2048 }),+ );+ mocks.remove.mockImplementation(() => Effect.void);+ mocks.sleep.mockResolvedValue(undefined);+ vi.stubGlobal("fetch", mocks.fetch);+ mocks.fetch.mockReset().mockImplementation(async (url: string) => {+ if (url.startsWith("https://www.loom.com/")) {+ return Response.json({ url: "https://cdn.loom.com/original.mp4" });+ }+ if (url.startsWith("https://worker.example.com/")) {+ return Response.json({ jobId: "job-1", status: "queued" });+ }+ throw new Error("Video bytes must not pass through Vercel");+ });+ });++ it("dispatches an uploaded recording once while completion is delayed", async () => {+ mocks.rows = [+ [video],+ [{ ...pending, rawFileKey: payload.rawFileKey }],+ [video],+ [pending],+ [pending],+ [],+ [metadata],+ [video],+ [],+ ];+ await expect(processVideoWorkflow(payload)).resolves.toMatchObject({+ success: true,+ metadata,+ });+ expect(mocks.fetch).toHaveBeenCalledOnce();+ expect(mocks.sleep.mock.calls).toEqual([[5_000], [10_000]]);+ expect(mocks.remove).toHaveBeenCalledWith(payload.rawFileKey);+ });++ it("keeps uploaded source data when processing fails", async () => {+ mocks.rows = [+ [video],+ [{ ...pending, rawFileKey: payload.rawFileKey }],+ [video],+ [{ ...pending, processingError: "Worker failed" }],+ [video],+ [{ ...pending, processingError: "Worker failed" }],+ [video],+ [{ ...pending, processingError: "Worker failed" }],+ ];+ await expect(processVideoWorkflow(payload)).rejects.toThrow(+ "Worker failed",+ );+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.fetch).toHaveBeenCalledTimes(3);+ expect(mocks.sleep.mock.calls).toEqual([[15_000], [30_000]]);+ });++ it("recovers from a confirmed worker failure with a bounded durable retry", async () => {+ mocks.rows = [+ [video],+ [{ ...pending, rawFileKey: payload.rawFileKey }],+ [video],+ [{ ...pending, processingError: "Temporary storage failure" }],+ [video],+ [],+ [metadata],+ [video],+ [],+ ];+ await expect(processVideoWorkflow(payload)).resolves.toMatchObject({+ success: true,+ });+ expect(mocks.fetch).toHaveBeenCalledTimes(2);+ expect(mocks.sleep.mock.calls).toEqual([[15_000]]);+ });++ it("sends Loom media directly to the worker with a required original destination", async () => {+ mocks.rows = [[video], [pending], [], [metadata]];+ await expect(importLoomVideoWorkflow(payload)).resolves.toMatchObject({+ success: true,+ });+ expect(mocks.get).not.toHaveBeenCalled();+ const calls = mocks.fetch.mock.calls;+ expect(calls).toHaveLength(2);+ expect(calls[1]?.[0]).toBe("https://worker.example.com/video/import");+ expect(JSON.parse(calls[1]?.[1].body)).toMatchObject({+ videoUrl: "https://cdn.loom.com/original.mp4",+ sourcePresignedUrl:+ "https://storage.example.com/owner/video/raw-upload.mp4?upload=1",+ priority: "bulk",+ });+ expect(mocks.remove).not.toHaveBeenCalled();+ });++ it("reuses a preserved Loom upload when retrying", async () => {+ mocks.rows = [[video], [video], [], [metadata]];+ await importLoomVideoWorkflow({ ...payload, reuseExistingRawUpload: true });+ expect(mocks.fetch).toHaveBeenCalledOnce();+ expect(mocks.fetch.mock.calls[0]?.[0]).toBe(+ "https://worker.example.com/video/process",+ );+ expect(mocks.get).toHaveBeenCalledWith(+ payload.rawFileKey,+ expect.anything(),+ );+ });++ it("retries a failed Loom worker from its preserved original", async () => {+ mocks.rows = [+ [video],+ [{ ...pending, processingError: "Temporary processing failure" }],+ [video],+ [video],+ [],+ [metadata],+ ];+ await importLoomVideoWorkflow(payload);+ expect(mocks.fetch.mock.calls.map(([url]) => url)).toEqual([+ "https://www.loom.com/api/campaigns/sessions/loom-video/transcoded-url",+ "https://worker.example.com/video/import",+ "https://worker.example.com/video/process",+ ]);+ expect(mocks.get).toHaveBeenCalledWith(+ payload.rawFileKey,+ expect.anything(),+ );+ });++ it("supports Loom streaming fallbacks without reading a nonexistent raw object", async () => {+ mocks.fetch.mockImplementation(async (url: string) =>+ Response.json(+ url.startsWith("https://www.loom.com/")+ ? { url: "https://cdn.loom.com/master.m3u8" }+ : { jobId: "job-1" },+ ),+ );+ mocks.rows = [[video], [], [metadata]];+ await importLoomVideoWorkflow(payload);+ expect(mocks.get).not.toHaveBeenCalled();+ expect(mocks.fetch.mock.calls.at(-1)?.[0]).toBe(+ "https://worker.example.com/video/process",+ );+ expect(JSON.parse(mocks.fetch.mock.calls.at(-1)?.[1].body)).toMatchObject({+ videoUrl: "https://cdn.loom.com/master.m3u8",+ inputExtension: ".m3u8",+ });+ });+});diff --git a/apps/web/__tests__/unit/recording-complete.test.ts b/apps/web/__tests__/unit/recording-complete.test.tsindex 56cdc8e09..4d0077d67 100644--- a/apps/web/__tests__/unit/recording-complete.test.ts+++ b/apps/web/__tests__/unit/recording-complete.test.ts@@ -76,14 +76,14 @@ describe("recording completion acknowledgement", () => {});it.each([false, true])(- "returns a retryable non-2xx until the source is secured (proof: %s)",+ "keeps uncommitted sources pending without acknowledging legacy uploads (proof: %s)",async (hasProof) => {mocks.queue.mockRejectedValueOnce(new SourceCommitPendingError());const response = await request({videoId: "recording",...(hasProof ? { verification } : {}),});- expect(response.status).toBe(503);+ expect(response.status).toBe(hasProof ? 202 : 503);expect(response.headers.get("Retry-After")).toBe("5");expect(await response.json()).toMatchObject({success: false,@@ -113,7 +113,7 @@ describe("recording completion acknowledgement", () => {videoId: "recording",...(hasProof ? { verification } : {}),});- expect(response.status).toBe(503);+ expect(response.status).toBe(hasProof ? 202 : 503);expect(mocks.queue).toHaveBeenCalledOnce();},);diff --git a/apps/web/__tests__/unit/upload-progress-playback.test.ts b/apps/web/__tests__/unit/upload-progress-playback.test.tsindex 303f3ef27..5346b3fbe 100644--- a/apps/web/__tests__/unit/upload-progress-playback.test.ts+++ b/apps/web/__tests__/unit/upload-progress-playback.test.ts@@ -6,6 +6,38 @@ import {shouldDeferPlaybackSource,shouldReloadPlaybackAfterUploadCompletes,} from "@/app/s/[videoId]/_components/ProgressCircle";+import { isRecordingUpload } from "@/app/s/[videoId]/_components/upload-progress";++describe("recording state after stopping or reloading", () => {+ it("does not label a pending status request as an active recording", () => {+ expect(isRecordingUpload({ status: "fetching" }, false)).toBe(false);+ expect(isRecordingUpload(null, false)).toBe(false);+ });++ it("keeps a stopped recording stopped while its final segments upload", () => {+ const upload = {+ status: "uploading" as const,+ lastUpdated: new Date(),+ progress: 95,+ };+ expect(isRecordingUpload(upload, true)).toBe(false);+ expect(isRecordingUpload(upload, false)).toBe(true);+ });++ it("does not label server processing as an active recording", () => {+ expect(+ isRecordingUpload(+ {+ status: "processing",+ lastUpdated: new Date(),+ progress: 5,+ message: "Securing recording...",+ },+ false,+ ),+ ).toBe(false);+ });+});describe("shouldDeferPlaybackSource", () => {it.each([diff --git a/apps/web/__tests__/unit/video-processing-status.test.ts b/apps/web/__tests__/unit/video-processing-status.test.tsnew file mode 100644index 000000000..979821b2a--- /dev/null+++ b/apps/web/__tests__/unit/video-processing-status.test.ts@@ -0,0 +1,110 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ rows: [] as unknown[][],+ where: vi.fn(),+ sleep: vi.fn(),+ now: 0,+}));++vi.mock("@cap/database", () => ({+ db: () => ({+ select: () => ({ from: () => ({ where: mocks.where }) }),+ }),+}));+vi.mock("@cap/database/schema", () => ({+ videos: { id: "id" },+ videoUploads: { videoId: "videoId" },+}));+vi.mock("@cap/web-domain", () => ({+ Video: { VideoId: { make: (id: string) => id } },+}));+vi.mock("workflow", () => ({+ sleep: mocks.sleep,+ FatalError: class FatalError extends Error {},+}));++import {+ readVideoProcessingStatus,+ waitForVideoProcessing,+} from "@/workflows/video-processing-status";++const metadata = { duration: 30, width: 1920, height: 1080, fps: 30 };+const pending = {+ phase: "processing",+ processingProgress: 25,+ processingMessage: "Processing video...",+ processingError: null,+};++describe("durable video processing completion", () => {+ beforeEach(() => {+ mocks.rows = [];+ mocks.now = 0;+ vi.spyOn(Date, "now").mockImplementation(() => mocks.now);+ mocks.where.mockReset().mockImplementation(async () => mocks.rows.shift());+ mocks.sleep.mockReset().mockImplementation(async (delay: number) => {+ mocks.now += delay;+ });+ });++ afterEach(() => vi.restoreAllMocks());++ it("accepts a callback that already completed without sleeping", async () => {+ mocks.rows = [[], [metadata]];+ await expect(waitForVideoProcessing("video")).resolves.toEqual(metadata);+ expect(mocks.sleep).not.toHaveBeenCalled();+ });++ it("suspends between status reads and observes a delayed callback", async () => {+ mocks.rows = [[pending], [pending], [pending], [], [metadata]];+ await expect(waitForVideoProcessing("video")).resolves.toEqual(metadata);+ expect(mocks.sleep.mock.calls).toEqual([[5_000], [10_000], [15_000]]);+ });++ it("supports an explicit complete row", async () => {+ mocks.rows = [[{ ...pending, phase: "complete" }], [metadata]];+ await expect(waitForVideoProcessing("video")).resolves.toEqual(metadata);+ });++ it.each([+ { ...pending, processingError: "Download failed" },+ { ...pending, phase: "error", processingMessage: "Download failed" },+ ])("propagates worker failures without another wait", async (upload) => {+ mocks.rows = [[upload]];+ await expect(waitForVideoProcessing("video")).rejects.toThrow(+ "Download failed",+ );+ expect(mocks.sleep).not.toHaveBeenCalled();+ });++ it.each([undefined, { ...metadata, width: null }, { ...metadata, fps: 0 }])(+ "does not treat a missing upload as proof of valid output",+ async (video) => {+ mocks.rows = [[], video ? [video] : []];+ await expect(waitForVideoProcessing("video")).rejects.toThrow(+ "Processing completed but video metadata is missing",+ );+ },+ );++ it("preserves unknown duration without inventing a positive duration", async () => {+ mocks.rows = [[], [{ ...metadata, duration: null }]];+ await expect(readVideoProcessingStatus("video")).resolves.toEqual({+ status: "complete",+ metadata: { ...metadata, duration: 0 },+ });+ });++ it("bounds waiting when a worker never completes", async () => {+ mocks.where.mockResolvedValue([pending]);+ await expect(waitForVideoProcessing("video")).rejects.toThrow(+ "Video processing timed out while processing 25% Processing video...",+ );+ expect(mocks.now).toBeLessThanOrEqual(60 * 60 * 1000 + 30_000);+ expect(mocks.sleep.mock.calls.length).toBeLessThan(130);+ expect(Math.max(...mocks.sleep.mock.calls.map(([delay]) => delay))).toBe(+ 30_000,+ );+ });+});diff --git a/apps/web/app/api/upload/[...route]/recording-complete.ts b/apps/web/app/api/upload/[...route]/recording-complete.tsindex 25a85dee0..dbbdae8cf 100644--- a/apps/web/app/api/upload/[...route]/recording-complete.ts+++ b/apps/web/app/api/upload/[...route]/recording-complete.ts@@ -85,7 +85,7 @@ export const app = new Hono().post(if (error instanceof SourceCommitPendingError) {return c.json({ success: false, status: error.code, error: error.message },- 503,+ verification ? 202 : 503,);}console.error("[recording-complete] Finalization unavailable:", error);diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex eeca8be43..2917c8a34 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -463,6 +463,7 @@ export const Share = ({const initialSeekDone = useRef(false);useEffect(() => {+ if (data.source.type === "desktopSegments") return;if (!searchParams.has("recordingStopped")) return;const url = new URL(window.location.href);@@ -472,7 +473,7 @@ export const Share = ({"",`${url.pathname}${url.search}${url.hash}`,);- }, [searchParams]);+ }, [data.source.type, searchParams]);const handleSeek = useCallback((time: number) => {const v =diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsxindex c3d98b177..745e5a5d7 100644--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx@@ -30,6 +30,7 @@ import {} from "./RecordingInProgress";import { ShareableLinkLimitOverlay } from "./ShareableLinkLimitOverlay";import {+ isRecordingUpload,shouldDeferPlaybackSource,shouldReloadPlaybackAfterUploadCompletes,type UploadProgress,@@ -332,9 +333,7 @@ export const ShareVideo = forwardRef<const isActivelyRecording =isSegmentsSource &&(data.hasActiveUpload ?? false) &&- !userConfirmedStopped &&- (segmentUploadProgress?.status === "fetching" ||- segmentUploadProgress?.status === "uploading");+ isRecordingUpload(segmentUploadProgress, userConfirmedStopped);const isProcessingInProgress =isSegmentsSource &&@@ -356,10 +355,17 @@ export const ShareVideo = forwardRef<setConfirmStoppedError(null);try {- const result = await finalizeDesktopSegmentsRecording({+ await finalizeDesktopSegmentsRecording({videoId: data.id,});- setUserConfirmedStopped(result.status !== "source-committing");+ setUserConfirmedStopped(true);+ const url = new URL(window.location.href);+ url.searchParams.set("recordingStopped", "1");+ window.history.replaceState(+ window.history.state,+ "",+ `${url.pathname}${url.search}${url.hash}`,+ );router.refresh();} catch (error) {setConfirmStoppedError(diff --git a/apps/web/app/s/[videoId]/_components/upload-progress.ts b/apps/web/app/s/[videoId]/_components/upload-progress.tsindex 0b8c2f046..de9024dd6 100644--- a/apps/web/app/s/[videoId]/_components/upload-progress.ts+++ b/apps/web/app/s/[videoId]/_components/upload-progress.ts@@ -44,6 +44,13 @@ export function shouldDeferPlaybackSource();}+export function isRecordingUpload(+ uploadProgress: UploadProgress | null,+ recordingStopped: boolean,+): boolean {+ return !recordingStopped && uploadProgress?.status === "uploading";+}+export function shouldReloadPlaybackAfterUploadCompletes(previousUploadProgress: UploadProgress | null,uploadProgress: UploadProgress | null,diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.tsindex b782d6abc..e821e92d8 100644--- a/apps/web/workflows/import-loom-video.ts+++ b/apps/web/workflows/import-loom-video.ts@@ -12,6 +12,11 @@ import {isMediaServerCapacityError,} from "@/lib/media-server-backpressure";import { runWorkflowPromise } from "@/lib/workflow-runtime";+import {+ type ProcessedVideoMetadata,+ VideoProcessingFailedError,+ waitForVideoProcessing,+} from "./video-processing-status";interface ImportLoomPayload {videoId: string;@@ -27,15 +32,9 @@ interface ImportLoomPayload {const MINIMUM_VIDEO_SIZE = 1024;const MEDIA_SERVER_START_MAX_ATTEMPTS = 2;const MEDIA_SERVER_START_RETRY_BASE_MS = 250;-const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 720;-const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5000;const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;-function isPositiveNumber(value: number | null): value is number {- return typeof value === "number" && Number.isFinite(value) && value > 0;-}-function getValidDuration(duration: number) {return Number.isFinite(duration) && duration > 0 ? duration : undefined;}@@ -45,17 +44,16 @@ function isStreamingUrl(url: string): boolean {return path.endsWith(".m3u8") || path.endsWith(".mpd");}-function isGoogleDriveResumableUrl(url: string): boolean {- return url.includes("googleapis.com/upload/drive/");-}-async function fetchLoomCdnUrl(videoId: string,endpoint: string,includeBody: boolean,): Promise<string | null> {try {- const options: RequestInit = { method: "POST" };+ const options: RequestInit = {+ method: "POST",+ signal: AbortSignal.timeout(15_000),+ };if (includeBody) {options.headers = {"Content-Type": "application/json",@@ -112,27 +110,6 @@ async function fetchFreshLoomDownloadUrl(loomVideoId: string): Promise<string> {);}-async function downloadVideoContent(downloadUrl: string): Promise<Buffer> {- const loomResponse = await fetch(downloadUrl);- if (!loomResponse.ok) {- throw new FatalError(- `Failed to download from Loom: ${loomResponse.status} ${loomResponse.statusText}`,- );- }-- const contentType = loomResponse.headers.get("content-type") ?? "";- if (- contentType.includes("text/html") ||- contentType.includes("application/json")- ) {- throw new FatalError(- `Loom returned non-video content (${contentType}). The download URL may have expired.`,- );- }-- return Buffer.from(await loomResponse.arrayBuffer());-}-interface VideoProcessingResult {success: boolean;message: string;@@ -145,8 +122,7 @@ interface VideoProcessingResult {}interface LoomProcessingInput {- sourceVideoUrl?: string;- inputExtension?: string;+ importFromLoom?: boolean;}async function claimAgentImport(operationId: string | undefined) {@@ -225,31 +201,46 @@ export async function importLoomVideoWorkflow(try {const reuseExistingRawUpload =payload.reuseExistingRawUpload && (await hasExistingLoomUpload(payload));- const processingInput: LoomProcessingInput = reuseExistingRawUpload+ let processingInput: LoomProcessingInput = reuseExistingRawUpload? {}- : await downloadLoomToS3(payload);-- let result: MediaServerProcessResult;- let capacityRetryCount = 0;- while (true) {+ : { importFromLoom: true };++ let metadata: ProcessedVideoMetadata;+ for (let processingAttempt = 0; ; processingAttempt++) {+ let capacityRetryCount = 0;+ while (true) {+ try {+ await processVideoOnMediaServer(payload, processingInput);+ break;+ } catch (error) {+ if (!isMediaServerCapacityError(error)) throw error;+ await markLoomImportWaitingForCapacity(payload.videoId);+ await sleep(`${Math.min(180, 30 + capacityRetryCount * 15)}s`);+ capacityRetryCount++;+ }+ }try {- result = await processVideoOnMediaServer(payload, processingInput);+ metadata = await waitForVideoProcessing(payload.videoId);break;} catch (error) {- if (!isMediaServerCapacityError(error)) throw error;+ if (+ !(error instanceof VideoProcessingFailedError) ||+ processingAttempt >= 2+ ) {+ throw error;+ }await markLoomImportWaitingForCapacity(payload.videoId);- await sleep(`${Math.min(180, 30 + capacityRetryCount * 15)}s`);- capacityRetryCount++;+ if (await hasExistingLoomUpload(payload)) processingInput = {};+ await sleep(15_000 * (processingAttempt + 1));}}-- await saveMetadataAndComplete(payload.videoId, result.metadata);+ await saveMetadataAndComplete(payload.videoId, metadata);await completeAgentImport(payload.agentOperationId, payload.videoId);return {success: true,message: "Loom video imported successfully",- metadata: result.metadata,+ metadata,};} catch (error) {const errorMessage = error instanceof Error ? error.message : String(error);@@ -307,122 +298,6 @@ async function hasExistingLoomUpload();}-async function downloadLoomToS3(- payload: ImportLoomPayload,-): Promise<LoomProcessingInput> {- "use step";-- const { videoId, loomVideoId, rawFileKey } = payload;-- await db()- .update(videoUploads)- .set({- phase: "uploading",- processingProgress: 0,- processingMessage: "Downloading from Loom...",- rawFileKey,- updatedAt: new Date(),- })- .where(eq(videoUploads.videoId, videoId as Video.VideoId));-- const freshDownloadUrl = await fetchFreshLoomDownloadUrl(loomVideoId);-- if (isStreamingUrl(freshDownloadUrl)) {- await db()- .update(videoUploads)- .set({- phase: "processing",- processingProgress: 0,- processingMessage: "Starting video processing...",- updatedAt: new Date(),- })- .where(eq(videoUploads.videoId, videoId as Video.VideoId));-- return {- sourceVideoUrl: freshDownloadUrl,- inputExtension: getInputExtension(freshDownloadUrl),- };- }-- const presignedPutUrl = await Effect.gen(function* () {- const [video] = yield* Effect.promise(() =>- db()- .select()- .from(videos)- .where(eq(videos.id, Video.VideoId.make(videoId))),- );- if (!video) {- return yield* Effect.fail(new FatalError("Video does not exist"));- }- const videoDomain = Video.Video.decodeSync({- ...video,- bucketId: video.bucket,- storageIntegrationId: video.storageIntegrationId,- createdAt: video.createdAt.toISOString(),- updatedAt: video.updatedAt.toISOString(),- metadata: video.metadata,- });- const [bucket] = yield* Storage.getAccessForVideo(videoDomain);- return yield* bucket.getInternalPresignedPutUrl(- rawFileKey,- {- ContentType: "video/mp4",- },- { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },- );- }).pipe(runWorkflowPromise);-- const videoBuffer = await downloadVideoContent(freshDownloadUrl);-- if (videoBuffer.length < MINIMUM_VIDEO_SIZE) {- throw new FatalError(- `Downloaded file is too small (${videoBuffer.length} bytes). The video may not be available for download.`,- );- }-- const uploadHeaders: Record<string, string> = {- "Content-Type": "video/mp4",- "Content-Length": videoBuffer.length.toString(),- };- if (isGoogleDriveResumableUrl(presignedPutUrl) && videoBuffer.length > 0) {- uploadHeaders["Content-Range"] =- `bytes 0-${videoBuffer.length - 1}/${videoBuffer.length}`;- }-- const uploadResponse = await fetch(presignedPutUrl, {- method: "PUT",- body: new Uint8Array(videoBuffer),- headers: uploadHeaders,- });-- if (!uploadResponse.ok) {- throw new FatalError(- `Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`,- );- }-- await db()- .update(videoUploads)- .set({- phase: "processing",- processingProgress: 0,- processingMessage: "Starting video processing...",- updatedAt: new Date(),- })- .where(eq(videoUploads.videoId, videoId as Video.VideoId));-- return {};-}--interface MediaServerProcessResult {- metadata: {- duration: number;- width: number;- height: number;- fps: number;- };-}-async function waitForRetry(delayMs: number): Promise<void> {await new Promise((resolve) => setTimeout(resolve, delayMs));}@@ -433,6 +308,7 @@ async function startMediaServerProcessJob(videoId: string;userId: string;videoUrl: string;+ sourcePresignedUrl?: string;outputPresignedUrl: string;thumbnailPresignedUrl: string;previewGifPresignedUrl: string;@@ -450,7 +326,8 @@ async function startMediaServerProcessJob(headers["x-media-server-secret"] = body.webhookSecret;}- const response = await fetch(`${mediaServerUrl}/video/process`, {+ const endpoint = body.sourcePresignedUrl ? "import" : "process";+ const response = await fetch(`${mediaServerUrl}/video/${endpoint}`, {method: "POST",headers,body: JSON.stringify(body),@@ -498,7 +375,7 @@ async function startMediaServerProcessJob(async function processVideoOnMediaServer(payload: ImportLoomPayload,processingInput: LoomProcessingInput,-): Promise<MediaServerProcessResult> {+): Promise<void> {"use step";const { videoId, userId, rawFileKey, loomVideoId } = payload;@@ -511,8 +388,12 @@ async function processVideoOnMediaServer(const webhookBaseUrl =serverEnv().MEDIA_SERVER_WEBHOOK_URL || serverEnv().WEB_URL;+ const loomSourceUrl = processingInput.importFromLoom+ ? await fetchFreshLoomDownloadUrl(loomVideoId)+ : undefined;const {rawVideoUrl,+ sourcePresignedUrl,outputPresignedUrl,thumbnailPresignedUrl,previewGifPresignedUrl,@@ -539,9 +420,19 @@ async function processVideoOnMediaServer(const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;const previewGifKey = `${userId}/${videoId}/preview/animated-preview.gif`;- const rawVideoUrl = yield* bucket.getInternalSignedObjectUrl(rawFileKey, {- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,- });+ const rawVideoUrl = loomSourceUrl+ ? loomSourceUrl+ : yield* bucket.getInternalSignedObjectUrl(rawFileKey, {+ expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,+ });+ const sourcePresignedUrl =+ loomSourceUrl && !isStreamingUrl(loomSourceUrl)+ ? yield* bucket.getInternalPresignedPutUrl(+ rawFileKey,+ { ContentType: "video/mp4" },+ { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },+ )+ : undefined;const outputPresignedUrl = yield* bucket.getInternalPresignedPutUrl(outputKey,@@ -568,6 +459,7 @@ async function processVideoOnMediaServer(return {rawVideoUrl,+ sourcePresignedUrl,outputPresignedUrl,thumbnailPresignedUrl,previewGifPresignedUrl,@@ -576,12 +468,6 @@ async function processVideoOnMediaServer(const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress?retryable=true`;const webhookSecret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;- const sourceVideoUrl = processingInput.sourceVideoUrl- ? await fetchFreshLoomDownloadUrl(loomVideoId)- : rawVideoUrl;- const inputExtension = processingInput.sourceVideoUrl- ? getInputExtension(sourceVideoUrl)- : processingInput.inputExtension;await db().update(videoUploads)@@ -597,113 +483,16 @@ async function processVideoOnMediaServer(await startMediaServerProcessJob(mediaServerUrl, {videoId,userId,- videoUrl: sourceVideoUrl,+ videoUrl: rawVideoUrl,+ sourcePresignedUrl,outputPresignedUrl,thumbnailPresignedUrl,previewGifPresignedUrl,webhookUrl,webhookSecret: webhookSecret || undefined,- inputExtension,+ inputExtension: getInputExtension(rawVideoUrl),priority: "bulk",});-- return await waitForProcessingCompletion(videoId);-}--function getMetadataFromVideoRow(- video:- | {- duration: number | null;- width: number | null;- height: number | null;- fps: number | null;- }- | undefined,-): MediaServerProcessResult["metadata"] | null {- if (- !video ||- !isPositiveNumber(video.width) ||- !isPositiveNumber(video.height) ||- !isPositiveNumber(video.fps)- ) {- return null;- }-- return {- duration: isPositiveNumber(video.duration) ? video.duration : 0,- width: video.width,- height: video.height,- fps: video.fps,- };-}--async function getCompletedMetadata(- videoId: string,-): Promise<MediaServerProcessResult["metadata"] | null> {- const [video] = await db()- .select({- duration: videos.duration,- width: videos.width,- height: videos.height,- fps: videos.fps,- })- .from(videos)- .where(eq(videos.id, videoId as Video.VideoId));-- return getMetadataFromVideoRow(video);-}--async function waitForProcessingCompletion(- videoId: string,-): Promise<MediaServerProcessResult> {- let lastStatus = "processing";-- for (- let attempt = 0;- attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;- attempt++- ) {- await waitForRetry(MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS);-- const [upload] = await db()- .select({- phase: videoUploads.phase,- processingProgress: videoUploads.processingProgress,- processingMessage: videoUploads.processingMessage,- processingError: videoUploads.processingError,- })- .from(videoUploads)- .where(eq(videoUploads.videoId, videoId as Video.VideoId));-- if (!upload || upload.phase === "complete") {- const metadata = await getCompletedMetadata(videoId);- if (!metadata) {- throw new Error("Processing completed but video metadata is missing");- }-- return { metadata };- }-- if (upload.processingError) {- throw new Error(upload.processingError);- }-- if (upload.phase === "error") {- throw new Error(upload.processingMessage || "Loom import failed");- }-- lastStatus = [- upload.phase,- typeof upload.processingProgress === "number"- ? `${upload.processingProgress}%`- : null,- upload.processingMessage,- ]- .filter(Boolean)- .join(" ");- }-- throw new Error(`Video processing timed out while ${lastStatus}`);}async function saveMetadataAndComplete(diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.tsindex 6740ee24d..9d3a32110 100644--- a/apps/web/workflows/process-video.ts+++ b/apps/web/workflows/process-video.ts@@ -13,6 +13,11 @@ import {import { transcribeVideo } from "@/lib/transcribe";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";+import {+ type ProcessedVideoMetadata,+ VideoProcessingFailedError,+ waitForVideoProcessing,+} from "./video-processing-status";interface ProcessVideoWorkflowPayload {videoId: string;@@ -46,26 +51,41 @@ export async function processVideoWorkflow(try {await validateProcessingRequest(videoId, rawFileKey);- let result: MediaServerProcessResult;- let capacityRetryCount = 0;- while (true) {+ let metadata: ProcessedVideoMetadata;+ for (let processingAttempt = 0; ; processingAttempt++) {+ let capacityRetryCount = 0;+ while (true) {+ try {+ await processVideoOnMediaServer(+ videoId,+ userId,+ rawFileKey,+ bucketId,+ );+ break;+ } catch (error) {+ if (!isMediaServerCapacityError(error)) throw error;+ await markVideoWaitingForCapacity(videoId);+ await sleep(`${Math.min(120, 15 + capacityRetryCount * 15)}s`);+ capacityRetryCount++;+ }+ }try {- result = await processVideoOnMediaServer(- videoId,- userId,- rawFileKey,- bucketId,- );+ metadata = await waitForVideoProcessing(videoId);break;} catch (error) {- if (!isMediaServerCapacityError(error)) throw error;+ if (+ !(error instanceof VideoProcessingFailedError) ||+ processingAttempt >= 2+ ) {+ throw error;+ }await markVideoWaitingForCapacity(videoId);- await sleep(`${Math.min(120, 15 + capacityRetryCount * 15)}s`);- capacityRetryCount++;+ await sleep(15_000 * (processingAttempt + 1));}}- await saveMetadataAndComplete(videoId, result.metadata);+ await saveMetadataAndComplete(videoId, metadata);const outputKey = `${userId}/${videoId}/result.mp4`;if (rawFileKey !== outputKey) {@@ -77,7 +97,7 @@ export async function processVideoWorkflow(return {success: true,message: "Video processing completed",- metadata: result.metadata,+ metadata,};} catch (error) {const errorMessage = error instanceof Error ? error.message : String(error);@@ -124,26 +144,11 @@ async function validateProcessingRequest(}}-interface MediaServerProcessResult {- metadata: {- duration: number;- width: number;- height: number;- fps: number;- };-}-const MEDIA_SERVER_START_MAX_ATTEMPTS = 2;const MEDIA_SERVER_START_RETRY_BASE_MS = 250;-const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 720;-const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5000;const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;-function isPositiveNumber(value: number | null): value is number {- return typeof value === "number" && Number.isFinite(value) && value > 0;-}-function getInputExtension(rawFileKey: string): string {const parts = rawFileKey.split(".");const extension = parts.at(-1)?.toLowerCase();@@ -254,7 +259,7 @@ async function processVideoOnMediaServer(userId: string,rawFileKey: string,_bucketId: string | null,-): Promise<MediaServerProcessResult> {+): Promise<void> {"use step";const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;@@ -344,104 +349,6 @@ async function processVideoOnMediaServer(webhookSecret: webhookSecret || undefined,inputExtension: getInputExtension(rawFileKey),});-- return await waitForProcessingCompletion(videoId);-}--function getMetadataFromVideoRow(- video:- | {- duration: number | null;- width: number | null;- height: number | null;- fps: number | null;- }- | undefined,-): MediaServerProcessResult["metadata"] | null {- if (- !video ||- !isPositiveNumber(video.width) ||- !isPositiveNumber(video.height) ||- !isPositiveNumber(video.fps)- ) {- return null;- }-- return {- duration: isPositiveNumber(video.duration) ? video.duration : 0,- width: video.width,- height: video.height,- fps: video.fps,- };-}--async function getCompletedMetadata(- videoId: string,-): Promise<MediaServerProcessResult["metadata"] | null> {- const [video] = await db()- .select({- duration: videos.duration,- width: videos.width,- height: videos.height,- fps: videos.fps,- })- .from(videos)- .where(eq(videos.id, videoId as Video.VideoId));-- return getMetadataFromVideoRow(video);-}--async function waitForProcessingCompletion(- videoId: string,-): Promise<MediaServerProcessResult> {- let lastStatus = "processing";-- for (- let attempt = 0;- attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;- attempt++- ) {- await waitForRetry(MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS);-- const [upload] = await db()- .select({- phase: videoUploads.phase,- processingProgress: videoUploads.processingProgress,- processingMessage: videoUploads.processingMessage,- processingError: videoUploads.processingError,- })- .from(videoUploads)- .where(eq(videoUploads.videoId, videoId as Video.VideoId));-- if (!upload || upload.phase === "complete") {- const metadata = await getCompletedMetadata(videoId);- if (!metadata) {- throw new Error("Processing completed but video metadata is missing");- }-- return { metadata };- }-- if (upload.processingError) {- throw new Error(upload.processingError);- }-- if (upload.phase === "error") {- throw new Error(upload.processingMessage || "Video processing failed");- }-- lastStatus = [- upload.phase,- typeof upload.processingProgress === "number"- ? `${upload.processingProgress}%`- : null,- upload.processingMessage,- ]- .filter(Boolean)- .join(" ");- }-- throw new Error(`Video processing timed out while ${lastStatus}`);}async function saveMetadataAndComplete(diff --git a/apps/web/workflows/video-processing-status.ts b/apps/web/workflows/video-processing-status.tsnew file mode 100644index 000000000..8ff993a2e--- /dev/null+++ b/apps/web/workflows/video-processing-status.ts@@ -0,0 +1,111 @@+import { db } from "@cap/database";+import { videos, videoUploads } from "@cap/database/schema";+import { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { FatalError, sleep } from "workflow";++export interface ProcessedVideoMetadata {+ duration: number;+ width: number;+ height: number;+ fps: number;+}++type ProcessingStatus =+ | { status: "complete"; metadata: ProcessedVideoMetadata }+ | { status: "pending"; message: string }+ | { status: "failed"; message: string }+ | { status: "error"; message: string };++export class VideoProcessingFailedError extends Error {}++function isPositiveNumber(value: number | null): value is number {+ return typeof value === "number" && Number.isFinite(value) && value > 0;+}++export async function readVideoProcessingStatus(+ videoId: string,+): Promise<ProcessingStatus> {+ "use step";++ const [upload] = await db()+ .select({+ phase: videoUploads.phase,+ processingProgress: videoUploads.processingProgress,+ processingMessage: videoUploads.processingMessage,+ processingError: videoUploads.processingError,+ })+ .from(videoUploads)+ .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));++ if (!upload || upload.phase === "complete") {+ const [video] = await db()+ .select({+ duration: videos.duration,+ width: videos.width,+ height: videos.height,+ fps: videos.fps,+ })+ .from(videos)+ .where(eq(videos.id, Video.VideoId.make(videoId)));+ if (+ !video ||+ !isPositiveNumber(video.width) ||+ !isPositiveNumber(video.height) ||+ !isPositiveNumber(video.fps)+ ) {+ return {+ status: "error",+ message: "Processing completed but video metadata is missing",+ };+ }+ return {+ status: "complete",+ metadata: {+ duration: isPositiveNumber(video.duration) ? video.duration : 0,+ width: video.width,+ height: video.height,+ fps: video.fps,+ },+ };+ }+ if (upload.processingError || upload.phase === "error") {+ return {+ status: "failed",+ message:+ upload.processingError ||+ upload.processingMessage ||+ "Video processing failed",+ };+ }+ return {+ status: "pending",+ message: [+ upload.phase,+ typeof upload.processingProgress === "number"+ ? `${upload.processingProgress}%`+ : null,+ upload.processingMessage,+ ]+ .filter(Boolean)+ .join(" "),+ };+}++export async function waitForVideoProcessing(+ videoId: string,+): Promise<ProcessedVideoMetadata> {+ const deadline = Date.now() + 60 * 60 * 1000;+ let lastStatus = "processing";+ for (let attempt = 0; Date.now() < deadline; attempt++) {+ const result = await readVideoProcessingStatus(videoId);+ if (result.status === "complete") return result.metadata;+ if (result.status === "failed") {+ throw new VideoProcessingFailedError(result.message);+ }+ if (result.status === "error") throw new FatalError(result.message);+ lastStatus = result.message;+ await sleep(Math.min(5_000 * (attempt + 1), 30_000));+ }+ throw new FatalError(`Video processing timed out while ${lastStatus}`);+}diff --git a/crates/recording/src/upload_verification.rs b/crates/recording/src/upload_verification.rsindex 1d1fb1deb..cb7b3db00 100644--- a/crates/recording/src/upload_verification.rs+++ b/crates/recording/src/upload_verification.rs@@ -186,6 +186,7 @@ mod tests {"already-processing","already-complete","complete",+ "source-commit-pending",] {assert!(request