Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: recover drained legacy edits from the preserved original

Richie McIlroy055d289981a7
diff --git a/apps/web/__tests__/unit/legacy-video-edit-recovery.test.ts b/apps/web/__tests__/unit/legacy-video-edit-recovery.test.ts
new file mode 100644
index 000000000..25aa39c02
--- /dev/null
+++ b/apps/web/__tests__/unit/legacy-video-edit-recovery.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const list = vi.hoisted(() => vi.fn());
+vi.mock("workflow/runtime", () => ({
+ getWorld: () => ({ runs: { list } }),
+}));
+
+import { assertLegacyEditsQuiescent } from "@/lib/legacy-video-edit-recovery";
+
+beforeEach(() => {
+ list.mockReset().mockResolvedValue({ data: [] });
+ vi.stubEnv("CAP_LEGACY_EDIT_RECOVERY", "enabled");
+});
+afterEach(() => vi.unstubAllEnvs());
+
+describe("legacy edit recovery rollout", () => {
+ it("refuses recovery until older deployments and workers have been drained", async () => {
+ vi.stubEnv("CAP_LEGACY_EDIT_RECOVERY", "");
+ await expect(assertLegacyEditsQuiescent("edit-workflow")).rejects.toThrow(
+ "support recovery",
+ );
+ expect(list).not.toHaveBeenCalled();
+ });
+ it.each(["pending", "running"])(
+ "refuses recovery while an edit is %s",
+ async (status) => {
+ list.mockImplementation(async (query: { status: string }) => ({
+ data: query.status === status ? [{ runId: "active" }] : [],
+ }));
+ await expect(assertLegacyEditsQuiescent("edit-workflow")).rejects.toThrow(
+ "still finishing",
+ );
+ },
+ );
+ it("fails closed when workflow state is unavailable", async () => {
+ list.mockRejectedValue(new Error("Workflow service unavailable"));
+ await expect(assertLegacyEditsQuiescent("edit-workflow")).rejects.toThrow(
+ "Workflow service unavailable",
+ );
+ });
+ it("allows recovery after the explicit drain and runtime checks", async () => {
+ await expect(
+ assertLegacyEditsQuiescent("edit-workflow"),
+ ).resolves.toBeUndefined();
+ expect(list).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowName: "edit-workflow",
+ status: "pending",
+ resolveData: "none",
+ }),
+ );
+ expect(list).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowName: "edit-workflow",
+ status: "running",
+ }),
+ );
+ });
+});
diff --git a/apps/web/__tests__/unit/video-edit-actions.test.ts b/apps/web/__tests__/unit/video-edit-actions.test.ts
new file mode 100644
index 000000000..4294a303d
--- /dev/null
+++ b/apps/web/__tests__/unit/video-edit-actions.test.ts
@@ -0,0 +1,270 @@
+import { User, Video } from "@cap/web-domain";
+import { Effect } from "effect";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ video: {} as Record<string, unknown>,
+ upload: undefined as Record<string, unknown> | undefined,
+ edit: undefined as Record<string, unknown> | undefined,
+ writes: [] as string[],
+ auth: vi.fn(),
+ start: vi.fn(),
+ quiescent: vi.fn(),
+ head: vi.fn(),
+ copy: vi.fn(),
+ access: vi.fn(),
+ fetch: vi.fn(),
+ clear: vi.fn(),
+}));
+vi.mock("@cap/database/schema", () => ({
+ videos: { name: "video", id: "id" },
+ videoUploads: { name: "upload", videoId: "videoId" },
+ videoEdits: { name: "edit", videoId: "videoId" },
+}));
+vi.mock("@cap/database", () => {
+ const client = {
+ select: () => ({
+ from: (table: { name: "video" | "upload" | "edit" }) => ({
+ where: () => {
+ const rows = mocks[table.name]
+ ? [structuredClone(mocks[table.name])]
+ : [];
+ return Object.assign(Promise.resolve(rows), {
+ for: async () => rows,
+ });
+ },
+ }),
+ }),
+ insert: (table: { name: string }) => ({
+ values: async (data: Record<string, unknown>) => {
+ mocks.writes.push(`insert-${table.name}`);
+ mocks.upload = data;
+ },
+ }),
+ delete: (table: { name: string }) => ({
+ where: async () => {
+ mocks.writes.push(`delete-${table.name}`);
+ mocks.upload = undefined;
+ },
+ }),
+ update: (table: { name: string }) => ({
+ set: (data: Record<string, unknown>) => ({
+ where: async () => {
+ mocks.writes.push(`update-${table.name}`);
+ Object.assign(mocks.video, data);
+ },
+ }),
+ }),
+ };
+ return {
+ db: () => ({
+ ...client,
+ transaction: async (run: (tx: typeof client) => Promise<unknown>) => {
+ const snapshot = structuredClone({
+ video: mocks.video,
+ upload: mocks.upload,
+ writes: mocks.writes,
+ });
+ try {
+ return await run(client);
+ } catch (error) {
+ Object.assign(mocks, snapshot);
+ throw error;
+ }
+ },
+ }),
+ };
+});
+vi.mock("@cap/database/auth/session", () => ({ getCurrentUser: mocks.auth }));
+vi.mock("@cap/utils", () => ({
+ userIsPro: (user: { isPro: boolean }) => user.isPro,
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ MEDIA_SERVER_URL: "https://media.test" }),
+}));
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.access },
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+vi.mock("workflow/api", () => ({ start: mocks.start }));
+vi.mock("@/workflows/edit-video", () => ({
+ editVideoWorkflow: Object.assign(vi.fn(), { workflowId: "edit-workflow" }),
+}));
+vi.mock("@/lib/legacy-video-edit-recovery", () => ({
+ assertLegacyEditsQuiescent: mocks.quiescent,
+}));
+vi.mock("@/lib/server", async () => ({
+ runPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+vi.mock("@/lib/video-edit-operation", () => ({
+ clearPendingEdit: mocks.clear,
+}));
+vi.mock("@/utils/flags", () => ({ isAiGenerationEnabled: async () => false }));
+
+import {
+ restoreVideoToOriginal,
+ saveVideoEdits,
+} from "@/actions/videos/save-edits";
+
+const videoId = Video.VideoId.make("video");
+const sourceKey = "owner/video/source/original.mp4";
+const trim = {
+ version: 1 as const,
+ sourceDuration: 10,
+ keepRanges: [{ start: 0, end: 5 }],
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.video = {
+ id: videoId,
+ ownerId: User.UserId.make("owner"),
+ bucket: null,
+ storageIntegrationId: null,
+ source: { type: "webMP4" },
+ duration: 10,
+ metadata: null,
+ };
+ mocks.upload = undefined;
+ mocks.edit = undefined;
+ mocks.writes = [];
+ mocks.auth.mockResolvedValue({ id: "owner", isPro: true });
+ mocks.head.mockReturnValue(Effect.succeed({}));
+ mocks.copy.mockReturnValue(Effect.void);
+ mocks.access.mockReturnValue(
+ Effect.succeed([
+ {
+ bucketName: "bucket",
+ headObject: mocks.head,
+ copyObject: mocks.copy,
+ getInternalSignedObjectUrl: () =>
+ Effect.succeed("https://storage.test/original.mp4"),
+ },
+ ]),
+ );
+ mocks.fetch.mockResolvedValue(
+ new Response(JSON.stringify({ metadata: { duration: 20 } }), {
+ status: 200,
+ }),
+ );
+ vi.stubGlobal("fetch", mocks.fetch);
+});
+afterEach(() => vi.unstubAllGlobals());
+
+function legacyUpload() {
+ mocks.upload = {
+ videoId,
+ rawFileKey: sourceKey,
+ phase: "processing",
+ startedAt: new Date("2026-09-01T00:00:00Z"),
+ updatedAt: new Date("2026-09-01T01:00:00Z"),
+ };
+}
+
+describe("video edit claims and recovery", () => {
+ it("claims the recording before copying its original source", async () => {
+ mocks.head.mockReturnValue(Effect.fail(new Error("Missing")));
+ mocks.copy.mockImplementation(() => {
+ expect(mocks.upload?.phase).toBe("processing");
+ return Effect.void;
+ });
+ await saveVideoEdits(videoId, trim);
+ expect(mocks.copy).toHaveBeenCalledOnce();
+ expect(mocks.start).toHaveBeenCalledOnce();
+ });
+ it("releases a pending claim when the workflow start fails", async () => {
+ mocks.start.mockRejectedValue(new Error("Enqueue failed"));
+ await expect(saveVideoEdits(videoId, trim)).rejects.toThrow(
+ "Enqueue failed",
+ );
+ expect(mocks.clear).toHaveBeenCalledWith(
+ videoId,
+ sourceKey,
+ expect.objectContaining({ token: expect.any(String) }),
+ );
+ });
+ it("preserves a legacy upload when recovery checks fail", async () => {
+ legacyUpload();
+ const upload = structuredClone(mocks.upload);
+ mocks.quiescent.mockRejectedValue(new Error("Still running"));
+ await expect(restoreVideoToOriginal(videoId)).rejects.toThrow(
+ "Still running",
+ );
+ expect(mocks.upload).toEqual(upload);
+ expect(mocks.writes).toEqual([]);
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+ it("restores an interrupted first edit using the original duration even without an edit record", async () => {
+ legacyUpload();
+ await restoreVideoToOriginal(videoId);
+ expect(mocks.quiescent).toHaveBeenCalledWith("edit-workflow");
+ expect(mocks.writes).toEqual([
+ "delete-upload",
+ "insert-upload",
+ "update-video",
+ ]);
+ expect(mocks.start).toHaveBeenCalledWith(expect.any(Function), [
+ expect.objectContaining({
+ sourceKey,
+ editSpec: {
+ version: 1,
+ sourceDuration: 20,
+ keepRanges: [{ start: 0, end: 20 }],
+ },
+ }),
+ ]);
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+ it("refuses to replace a legacy row that changed during original verification", async () => {
+ legacyUpload();
+ mocks.fetch.mockImplementation(async () => {
+ if (mocks.upload)
+ mocks.upload.updatedAt = new Date("2026-09-08T00:00:00Z");
+ return new Response(JSON.stringify({ metadata: { duration: 20 } }), {
+ status: 200,
+ });
+ });
+ await expect(restoreVideoToOriginal(videoId)).rejects.toThrow(
+ "already uploading",
+ );
+ expect(mocks.writes).toEqual([]);
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+ it("preserves recovery state when the original cannot be verified", async () => {
+ legacyUpload();
+ mocks.fetch.mockResolvedValue(
+ new Response(JSON.stringify({ metadata: { duration: 0 } }), {
+ status: 200,
+ }),
+ );
+ await expect(restoreVideoToOriginal(videoId)).rejects.toThrow(
+ "could not be verified",
+ );
+ expect(mocks.writes).toEqual([]);
+ });
+ it.each([
+ [{ id: "other", isPro: true }, "Forbidden"],
+ [{ id: "owner", isPro: false }, "Cap Pro"],
+ ] as const)(
+ "requires the recording owner with edit access",
+ async (user, message) => {
+ legacyUpload();
+ mocks.auth.mockResolvedValue(user);
+ await expect(restoreVideoToOriginal(videoId)).rejects.toThrow(message);
+ expect(mocks.quiescent).not.toHaveBeenCalled();
+ expect(mocks.writes).toEqual([]);
+ },
+ );
+ it("does not use legacy recovery to replace a current operation", async () => {
+ legacyUpload();
+ mocks.video.metadata = { editProcessing: { token: "current" } };
+ await expect(restoreVideoToOriginal(videoId)).rejects.toThrow(
+ "already uploading",
+ );
+ expect(mocks.quiescent).not.toHaveBeenCalled();
+ expect(mocks.writes).toEqual([]);
+ });
+});
diff --git a/apps/web/__tests__/unit/video-edit-processing.test.ts b/apps/web/__tests__/unit/video-edit-processing.test.ts
index 229cca714..8488656f1 100644
--- a/apps/web/__tests__/unit/video-edit-processing.test.ts
+++ b/apps/web/__tests__/unit/video-edit-processing.test.ts
@@ -114,6 +114,9 @@ vi.mock("@/app/s/[videoId]/edit/EditUpgradeGate", () => ({}));
vi.mock("@/app/s/[videoId]/edit/EditVideoClient", () => ({
EditVideoClient: () => null,
}));
+vi.mock("@/app/s/[videoId]/edit/edit-recovery", () => ({
+ EditRecovery: () => null,
+}));
describe("viewing a recording during an edit", () => {
beforeEach(() => {
@@ -152,11 +155,12 @@ describe("viewing a recording during an edit", () => {
const edit = EditVideoPage({
params: Promise.resolve({ videoId: "video123" }),
});
- if (phase === "processing" || phase === "generating_thumbnail") {
- await expect(edit).rejects.toThrow("NEXT_NOT_FOUND");
- } else {
- expect(isValidElement(await edit)).toBe(true);
- }
+ const element = await edit;
+ const { EditRecovery } = await import(
+ "@/app/s/[videoId]/edit/edit-recovery"
+ );
+ expect(isValidElement(element)).toBe(true);
+ expect(element.type).toBe(EditRecovery);
expect(database.state.upload).toBe(upload);
expect(database.remove).not.toHaveBeenCalled();
diff --git a/apps/web/actions/videos/save-edits.ts b/apps/web/actions/videos/save-edits.ts
index 41d4b320f..2ba3c7cc3 100644
--- a/apps/web/actions/videos/save-edits.ts
+++ b/apps/web/actions/videos/save-edits.ts
@@ -5,6 +5,7 @@ import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videoEdits, videos, videoUploads } from "@cap/database/schema";
import type { VideoEditSpec } from "@cap/database/types";
+import { serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
import { Storage } from "@cap/web-backend";
import type { Video } from "@cap/web-domain";
@@ -12,12 +13,13 @@ import { eq } from "drizzle-orm";
import { Effect } from "effect";
import { revalidatePath } from "next/cache";
import { start } from "workflow/api";
+import { assertLegacyEditsQuiescent } from "@/lib/legacy-video-edit-recovery";
import { runPromise } from "@/lib/server";
import {
clearPendingEdit,
type EditOperation,
} from "@/lib/video-edit-operation";
-import { getEditSourceKey } from "@/lib/video-edit-processing";
+import { getEditSourceKey, isEditSourceKey } from "@/lib/video-edit-processing";
import {
areEditSpecsEquivalent,
composeEditSpecs,
@@ -84,10 +86,12 @@ async function markEditProcessing({
video,
sourceKey,
previousSpec,
+ legacyUpload,
}: {
video: typeof videos.$inferSelect;
sourceKey: string;
previousSpec: VideoEditSpec;
+ legacyUpload?: typeof videoUploads.$inferSelect;
}): Promise<EditOperation> {
const startedAt = new Date(Math.floor(Date.now() / 1000) * 1000);
const operation = { token: randomUUID(), startedAt: startedAt.toISOString() };
@@ -111,7 +115,17 @@ async function markEditProcessing({
.from(videoUploads)
.where(eq(videoUploads.videoId, video.id))
.for("update");
- if (upload || (current.metadata && "editProcessing" in current.metadata)) {
+ if (
+ legacyUpload &&
+ upload &&
+ !current.metadata?.editProcessing &&
+ upload.rawFileKey === legacyUpload.rawFileKey &&
+ upload.startedAt.getTime() === legacyUpload.startedAt.getTime() &&
+ upload.updatedAt.getTime() === legacyUpload.updatedAt.getTime() &&
+ upload.phase === legacyUpload.phase
+ ) {
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
+ } else if (upload || current.metadata?.editProcessing) {
throw new Error("Video is already uploading or processing");
}
const [currentEdit] = await tx
@@ -160,7 +174,10 @@ async function markEditProcessing({
return operation;
}
-async function loadEditableVideo(videoId: Video.VideoId) {
+async function loadEditableVideo(
+ videoId: Video.VideoId,
+ recoverLegacy = false,
+) {
const user = await getCurrentUser();
if (!user) throw new Error("Unauthorized");
if (!userIsPro(user)) throw new Error("Cap Pro is required to edit videos");
@@ -182,6 +199,25 @@ async function loadEditableVideo(videoId: Video.VideoId) {
.from(videoUploads)
.where(eq(videoUploads.videoId, videoId));
+ if (
+ recoverLegacy &&
+ activeUpload &&
+ !video.metadata?.editProcessing &&
+ isEditSourceKey({
+ ownerId: video.ownerId,
+ videoId,
+ rawFileKey: activeUpload.rawFileKey,
+ })
+ ) {
+ if (
+ !("workflowId" in editVideoWorkflow) ||
+ typeof editVideoWorkflow.workflowId !== "string"
+ ) {
+ throw new Error("The edit recovery runtime is unavailable");
+ }
+ await assertLegacyEditsQuiescent(editVideoWorkflow.workflowId);
+ return { user, video, legacyUpload: activeUpload };
+ }
if (activeUpload && ACTIVE_UPLOAD_PHASES.has(activeUpload.phase)) {
const message =
activeUpload.phase === "complete"
@@ -192,7 +228,7 @@ async function loadEditableVideo(videoId: Video.VideoId) {
throw new Error(message);
}
- return { user, video };
+ return { user, video, legacyUpload: undefined };
}
export async function saveVideoEdits(
@@ -259,6 +295,7 @@ export async function saveVideoEdits(
},
]);
} catch (error) {
+ await clearPendingEdit(videoId, sourceKey, operation);
throw error instanceof Error
? error
: new Error("Video edit could not start");
@@ -272,42 +309,76 @@ export async function saveVideoEdits(
}
export async function restoreVideoToOriginal(videoId: Video.VideoId) {
- const { user, video } = await loadEditableVideo(videoId);
+ const { user, video, legacyUpload } = await loadEditableVideo(videoId, true);
const [existingEdit] = await db()
.select()
.from(videoEdits)
.where(eq(videoEdits.videoId, videoId));
- if (!existingEdit) {
+ if (!existingEdit && !legacyUpload) {
revalidatePath(`/s/${videoId}/edit`);
return { success: true, skipped: true };
}
- const previousSpec = existingEdit.editSpec;
- const restoredSpec = createIdentityEditSpec(previousSpec.sourceDuration);
-
- if (getEditSpecOutputDuration(restoredSpec) <= 0) {
+ const sourceKey =
+ existingEdit?.sourceKey ?? getEditSourceKey(video.ownerId, video.id);
+ const bucket = await getVideoBucket(video);
+ if (!(await objectExists(bucket, sourceKey)))
throw new Error("Original video is no longer available");
+ let sourceDuration =
+ existingEdit?.editSpec.sourceDuration ?? video.duration ?? 0;
+ if (legacyUpload) {
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ if (!mediaServerUrl)
+ throw new Error("Video recovery is temporarily unavailable");
+ const sourceUrl = await bucket
+ .getInternalSignedObjectUrl(sourceKey, { expiresIn: 300 })
+ .pipe(runPromise);
+ const response = await fetch(`${mediaServerUrl}/video/probe`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-media-server-secret": serverEnv().MEDIA_SERVER_WEBHOOK_SECRET ?? "",
+ },
+ body: JSON.stringify({ videoUrl: sourceUrl }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const result: unknown = await response.json();
+ if (
+ !response.ok ||
+ !result ||
+ typeof result !== "object" ||
+ !("metadata" in result) ||
+ !result.metadata ||
+ typeof result.metadata !== "object" ||
+ !("duration" in result.metadata) ||
+ typeof result.metadata.duration !== "number" ||
+ !Number.isFinite(result.metadata.duration) ||
+ result.metadata.duration <= 0
+ ) {
+ throw new Error("The original video could not be verified for recovery");
+ }
+ sourceDuration = result.metadata.duration;
}
-
- if (areEditSpecsEquivalent(previousSpec, restoredSpec)) {
+ const previousSpec =
+ existingEdit?.editSpec ??
+ createIdentityEditSpec(video.duration ?? sourceDuration);
+ const restoredSpec = createIdentityEditSpec(sourceDuration);
+ if (getEditSpecOutputDuration(restoredSpec) <= 0)
+ throw new Error("Original video is no longer available");
+ if (!legacyUpload && areEditSpecsEquivalent(previousSpec, restoredSpec)) {
revalidatePath(`/s/${videoId}/edit`);
return { success: true, skipped: true };
}
- const sourceKey = existingEdit.sourceKey;
- const bucket = await getVideoBucket(video);
- if (!(await objectExists(bucket, sourceKey))) {
- throw new Error("Original video is no longer available");
- }
-
const aiGenerationEnabled = await isAiGenerationEnabled(user);
const operation = await markEditProcessing({
video,
sourceKey,
previousSpec,
+ legacyUpload,
});
try {
@@ -324,6 +395,7 @@ export async function restoreVideoToOriginal(videoId: Video.VideoId) {
},
]);
} catch (error) {
+ await clearPendingEdit(videoId, sourceKey, operation);
throw error instanceof Error
? error
: new Error("Video restore could not start");
diff --git a/apps/web/app/s/[videoId]/edit/edit-recovery.tsx b/apps/web/app/s/[videoId]/edit/edit-recovery.tsx
new file mode 100644
index 000000000..6aefa9d9c
--- /dev/null
+++ b/apps/web/app/s/[videoId]/edit/edit-recovery.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import type { Video } from "@cap/web-domain";
+import { useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { restoreVideoToOriginal } from "@/actions/videos/save-edits";
+
+export function EditRecovery({ videoId }: { videoId: Video.VideoId }) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [error, setError] = useState<string>();
+ return (
+ <main className="flex min-h-screen items-center justify-center bg-gray-2 p-6">
+ <div className="w-full max-w-md space-y-4 rounded-xl border border-gray-5 bg-gray-1 p-6">
+ <h1 className="text-xl font-medium text-gray-12">
+ Your edit is still processing
+ </h1>
+ <p className="text-sm text-gray-11">
+ If this edit could not finish, you can restore the original recording.
+ Your original source is preserved.
+ </p>
+ {error ? (
+ <p role="alert" className="text-sm text-red-11">
+ {error}
+ </p>
+ ) : null}
+ <button
+ type="button"
+ disabled={pending}
+ className="rounded-lg bg-blue-9 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
+ onClick={() => {
+ setError(undefined);
+ startTransition(async () => {
+ try {
+ await restoreVideoToOriginal(videoId);
+ router.push(`/s/${videoId}`);
+ router.refresh();
+ } catch (cause) {
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : "The original could not be restored. Please try again.",
+ );
+ }
+ });
+ }}
+ >
+ {pending ? "Preparing recovery..." : "Restore original"}
+ </button>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/edit/page.tsx b/apps/web/app/s/[videoId]/edit/page.tsx
index 33fa7e96b..fe64781e2 100644
--- a/apps/web/app/s/[videoId]/edit/page.tsx
+++ b/apps/web/app/s/[videoId]/edit/page.tsx
@@ -5,12 +5,14 @@ import { userIsPro } from "@cap/utils";
import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
+import { isEditSourceKey } from "@/lib/video-edit-processing";
import {
areEditSpecsEquivalent,
createIdentityEditSpec,
} from "@/lib/video-edits";
import { EditUpgradeGate } from "./EditUpgradeGate";
import { EditVideoClient } from "./EditVideoClient";
+import { EditRecovery } from "./edit-recovery";
function isMp4BackedVideo(source: typeof videos.$inferSelect.source) {
return source.type === "desktopMP4" || source.type === "webMP4";
@@ -37,6 +39,7 @@ export default async function EditVideoPage(props: {
isScreenshot: videos.isScreenshot,
transcriptionStatus: videos.transcriptionStatus,
uploadPhase: videoUploads.phase,
+ rawFileKey: videoUploads.rawFileKey,
})
.from(videos)
.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
@@ -57,6 +60,16 @@ export default async function EditVideoPage(props: {
return <EditUpgradeGate />;
}
+ if (
+ video.uploadPhase &&
+ isEditSourceKey({
+ ownerId: video.ownerId,
+ videoId,
+ rawFileKey: video.rawFileKey,
+ })
+ ) {
+ return <EditRecovery videoId={videoId} />;
+ }
if (
video.uploadPhase &&
["uploading", "processing", "generating_thumbnail"].includes(
diff --git a/apps/web/lib/legacy-video-edit-recovery.ts b/apps/web/lib/legacy-video-edit-recovery.ts
new file mode 100644
index 000000000..479de3057
--- /dev/null
+++ b/apps/web/lib/legacy-video-edit-recovery.ts
@@ -0,0 +1,25 @@
+import { getWorld } from "workflow/runtime";
+
+export async function assertLegacyEditsQuiescent(workflowName: string) {
+ if (process.env.CAP_LEGACY_EDIT_RECOVERY !== "enabled") {
+ throw new Error(
+ "This older edit needs support recovery before it can be restored.",
+ );
+ }
+ const world = getWorld();
+ const active = await Promise.all(
+ (["pending", "running"] as const).map((status) =>
+ world.runs.list({
+ workflowName,
+ status,
+ resolveData: "none",
+ pagination: { limit: 1, sortOrder: "desc" },
+ }),
+ ),
+ );
+ if (active.some((runs) => runs.data.length > 0)) {
+ throw new Error(
+ "An earlier edit is still finishing. Please try restoring again shortly.",
+ );
+ }
+}
diff --git a/apps/web/video-edit-recovery.md b/apps/web/video-edit-recovery.md
new file mode 100644
index 000000000..6d384d6f1
--- /dev/null
+++ b/apps/web/video-edit-recovery.md
@@ -0,0 +1,16 @@
+# Video edit recovery
+
+New edits write video, thumbnail and preview objects below an operation-specific `.recording/outputs/edit-<token>/` prefix. Verification precedes publication of those object keys. A failed or timed-out operation can therefore release its lock while a late worker finishes writing unreferenced objects. Late callbacks cannot publish after the operation is released.
+
+Legacy edits wrote to shared output keys and did not persist an operation or workflow run identity. Their upload rows must not be cleared based only on age, a cancellation response, or a missing job on one media-server replica.
+
+Before enabling legacy recovery in production:
+
+1. Drain or disable the older web deployments and server actions that can start legacy edits. Keep the legacy recovery setting disabled during rollout.
+2. Confirm that every earlier edit workflow has completed or failed and that cancelled workflows have no steps still executing. Check all deployments and media-server replicas; a single replica's missing job is insufficient.
+3. Set `CAP_LEGACY_EDIT_RECOVERY=enabled` for the current web deployment only after that drain is complete.
+4. The recording owner can open `/s/<videoId>/edit` and choose **Restore original**. The server rechecks workflow quiescence, verifies the immutable original's duration, and replaces only the unchanged legacy upload row with a new operation. The restored result publishes from its own output keys.
+
+The automatic check conservatively refuses recovery while another edit workflow is pending or running. The rollout setting requires prior manual verification that cancelled runs have no remaining steps or media jobs. If those checks cannot establish quiescence, complete support recovery before enabling this path. Do not delete the original recording or clear its upload row to bypass the check.
+
+After recovery, verify share playback, original duration, captions and a subsequent save. Disable the legacy recovery setting when the historical backlog has been handled. Existing media objects remain preserved; this change does not garbage-collect previous or abandoned edit outputs.