Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: preserve video edit state when viewing share pages

Richie McIlroyedb4734d1bdb
diff --git a/apps/web/__tests__/unit/video-edit-processing.test.ts b/apps/web/__tests__/unit/video-edit-processing.test.ts
new file mode 100644
index 000000000..229cca714
--- /dev/null
+++ b/apps/web/__tests__/unit/video-edit-processing.test.ts
@@ -0,0 +1,167 @@
+import { Context, Effect } from "effect";
+import { isValidElement } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type EditUpload = {
+ phase: "processing" | "generating_thumbnail" | "complete" | "error";
+ updatedAt: Date;
+ processingProgress: number;
+ rawFileKey: string;
+};
+
+const database = vi.hoisted(() => {
+ const state: { upload: EditUpload | null } = { upload: null };
+ let selection: Record<string, unknown> | undefined;
+ const where = vi.fn(async () => {
+ if (selection && "editSpec" in selection) return [];
+ return [
+ {
+ id: "video123",
+ name: "Long recording",
+ ownerId: "owner123",
+ owner: { id: "owner123" },
+ duration: 2032,
+ width: 1920,
+ height: 1080,
+ source: { type: "desktopMP4" },
+ isScreenshot: false,
+ password: null,
+ organizationTombstoneAt: null,
+ ...state.upload,
+ uploadPhase: state.upload?.phase ?? null,
+ hasActiveUpload: Boolean(state.upload),
+ activeUploadRawFileKey: state.upload?.rawFileKey ?? null,
+ },
+ ];
+ });
+ const query = {
+ from: () => query,
+ leftJoin: () => query,
+ innerJoin: () => query,
+ where,
+ };
+ const select = vi.fn((fields?: Record<string, unknown>) => {
+ selection = fields;
+ return query;
+ });
+ const remove = vi.fn(() => ({
+ where: vi.fn(async () => {
+ state.upload = null;
+ return [{ affectedRows: 1 }];
+ }),
+ }));
+ return { state, select, remove, insert: vi.fn(), update: vi.fn() };
+});
+
+const viewPolicy = Context.GenericTag<{
+ canViewLoaded: () => Effect.Effect<void>;
+}>("EditNavigationViewPolicy");
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: database.select,
+ delete: database.remove,
+ insert: database.insert,
+ update: database.update,
+ }),
+}));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "owner123", isPro: true }),
+}));
+vi.mock("@cap/utils", () => ({ userIsPro: () => true }));
+vi.mock("@cap/ui", () => ({}));
+vi.mock("@cap/web-backend", () => ({
+ provideOptionalAuth: <A>(effect: A) => effect,
+}));
+vi.mock("@cap/web-backend/src/Videos/VideosPolicy", () => ({
+ VideosPolicy: viewPolicy,
+}));
+vi.mock("@/lib/server", () => ({
+ runPromise: (
+ effect: Effect.Effect<
+ unknown,
+ unknown,
+ Context.Tag.Identifier<typeof viewPolicy>
+ >,
+ ) =>
+ Effect.runPromise(
+ Effect.provideService(effect, viewPolicy, {
+ canViewLoaded: () => Effect.void,
+ }),
+ ),
+}));
+vi.mock("next/navigation", () => ({
+ notFound: () => {
+ throw new Error("NEXT_NOT_FOUND");
+ },
+}));
+vi.mock("@/actions/videos/get-analytics", () => ({}));
+vi.mock("@/app/(org)/dashboard/dashboard-data", () => ({}));
+vi.mock("@/lib/ai/provider", () => ({}));
+vi.mock("@/lib/desktop-segments-recovery", () => ({}));
+vi.mock("@/lib/Notification", () => ({}));
+vi.mock("@/lib/public-share-video", () => ({}));
+vi.mock("@/lib/shareable-link-quota", () => ({}));
+vi.mock("@/lib/transcribe", () => ({}));
+vi.mock("@/utils/flags", () => ({}));
+vi.mock("@/app/s/[videoId]/_components/PasswordOverlay", () => ({
+ PasswordOverlay: () => null,
+}));
+vi.mock("@/app/s/[videoId]/_components/PendingRecordingShare", () => ({}));
+vi.mock("@/app/s/[videoId]/_components/ShareHeader", () => ({}));
+vi.mock("@/app/s/[videoId]/Share", () => ({}));
+vi.mock("@/app/s/[videoId]/edit/EditUpgradeGate", () => ({}));
+vi.mock("@/app/s/[videoId]/edit/EditVideoClient", () => ({
+ EditVideoClient: () => null,
+}));
+
+describe("viewing a recording during an edit", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ database.state.upload = null;
+ });
+
+ it.each([
+ ["processing", 15],
+ ["generating_thumbnail", 90],
+ ["complete", 100],
+ ["error", 15],
+ ] as const)(
+ "preserves an old %s edit while rendering the share and edit pages",
+ async (phase, processingProgress) => {
+ const upload: EditUpload = {
+ phase,
+ processingProgress,
+ updatedAt: new Date(Date.now() - 60 * 60 * 1000),
+ rawFileKey: "owner123/video123/source/original.mp4",
+ };
+ database.state.upload = upload;
+ const { default: ShareVideoPage } = await import(
+ "@/app/s/[videoId]/page"
+ );
+ const share = await ShareVideoPage({
+ params: Promise.resolve({ videoId: "video123" }),
+ searchParams: Promise.resolve({}),
+ });
+ expect(isValidElement(share)).toBe(true);
+ expect(database.state.upload).toBe(upload);
+
+ const { default: EditVideoPage } = await import(
+ "@/app/s/[videoId]/edit/page"
+ );
+ 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);
+ }
+
+ expect(database.state.upload).toBe(upload);
+ expect(database.remove).not.toHaveBeenCalled();
+ expect(database.insert).not.toHaveBeenCalled();
+ expect(database.update).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/web/app/s/[videoId]/edit/page.tsx b/apps/web/app/s/[videoId]/edit/page.tsx
index 3ee65368a..33fa7e96b 100644
--- a/apps/web/app/s/[videoId]/edit/page.tsx
+++ b/apps/web/app/s/[videoId]/edit/page.tsx
@@ -5,7 +5,6 @@ import { userIsPro } from "@cap/utils";
import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
-import { reconcileStaleEditUpload } from "@/lib/video-edit-processing";
import {
areEditSpecsEquivalent,
createIdentityEditSpec,
@@ -26,8 +25,6 @@ export default async function EditVideoPage(props: {
if (!user) notFound();
- await reconcileStaleEditUpload(videoId);
-
const [video] = await db()
.select({
id: videos.id,
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index c803a6e83..4879e1844 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -66,10 +66,7 @@ import {
} from "@/lib/social-crawlers";
import { transcribeVideo } from "@/lib/transcribe";
import { canUserDownloadVideo } from "@/lib/video-download-permissions";
-import {
- isEditSourceKey,
- reconcileStaleEditUpload,
-} from "@/lib/video-edit-processing";
+import { isEditSourceKey } from "@/lib/video-edit-processing";
import {
areEditSpecsEquivalent,
createIdentityEditSpec,
@@ -328,8 +325,6 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
const awaitRecording =
isValidVideoIdParam(videoId) && hasRecordingStoppedParam(searchParams);
- await reconcileStaleEditUpload(videoId);
-
return Effect.gen(function* () {
const videosPolicy = yield* VideosPolicy;
diff --git a/apps/web/lib/video-edit-processing.ts b/apps/web/lib/video-edit-processing.ts
index ac818cc40..2b1cd24f2 100644
--- a/apps/web/lib/video-edit-processing.ts
+++ b/apps/web/lib/video-edit-processing.ts
@@ -1,21 +1,3 @@
-import { db } from "@cap/database";
-import { videos, videoUploads } from "@cap/database/schema";
-import type { Video } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
-
-const SECOND = 1000;
-const MINUTE = 60 * SECOND;
-const STALE_EDIT_PROCESSING_START_MS = 15 * MINUTE;
-const STALE_EDIT_PROCESSING_PROGRESS_MS = 10 * MINUTE;
-const STALE_EDIT_THUMBNAIL_MS = 5 * MINUTE;
-
-type UploadPhase =
- | "uploading"
- | "processing"
- | "generating_thumbnail"
- | "complete"
- | "error";
-
export function getEditSourceKey(ownerId: string, videoId: string) {
return `${ownerId}/${videoId}/source/original.mp4`;
}
@@ -31,71 +13,3 @@ export function isEditSourceKey({
}) {
return rawFileKey === getEditSourceKey(ownerId, videoId);
}
-
-function shouldClearEditUpload(input: {
- phase: UploadPhase;
- updatedAt: Date;
- processingProgress: number;
-}) {
- if (input.phase === "error") {
- return true;
- }
-
- const ageMs = Date.now() - input.updatedAt.getTime();
-
- if (input.phase === "complete") {
- return ageMs > STALE_EDIT_THUMBNAIL_MS;
- }
-
- if (input.phase === "processing") {
- if (
- input.processingProgress === 0 &&
- ageMs > STALE_EDIT_PROCESSING_START_MS
- ) {
- return true;
- }
-
- return ageMs > STALE_EDIT_PROCESSING_PROGRESS_MS;
- }
-
- if (input.phase === "generating_thumbnail") {
- return ageMs > STALE_EDIT_THUMBNAIL_MS;
- }
-
- return false;
-}
-
-export async function reconcileStaleEditUpload(videoId: Video.VideoId) {
- const [record] = await db()
- .select({
- ownerId: videos.ownerId,
- rawFileKey: videoUploads.rawFileKey,
- phase: videoUploads.phase,
- updatedAt: videoUploads.updatedAt,
- processingProgress: videoUploads.processingProgress,
- })
- .from(videos)
- .leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
- .where(eq(videos.id, videoId));
-
- if (
- !record?.phase ||
- !record.updatedAt ||
- record.processingProgress == null ||
- !isEditSourceKey({
- ownerId: record.ownerId,
- videoId,
- rawFileKey: record.rawFileKey,
- }) ||
- !shouldClearEditUpload({
- phase: record.phase,
- updatedAt: record.updatedAt,
- processingProgress: record.processingProgress,
- })
- ) {
- return false;
- }
-
- await db().delete(videoUploads).where(eq(videoUploads.videoId, videoId));
- return true;
-}