Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: sync Google Drive names after video title changes

Richie McIlroy4af91b4d64b3
diff --git a/apps/web/__tests__/unit/video-storage-names.test.ts b/apps/web/__tests__/unit/video-storage-names.test.ts
new file mode 100644
index 000000000..27edfa536
--- /dev/null
+++ b/apps/web/__tests__/unit/video-storage-names.test.ts
@@ -0,0 +1,117 @@
+import type { Video } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { RetryableError } from "workflow";
+
+const { db, start, where, syncVideoDisplayNames, runWorkflowPromise } =
+ vi.hoisted(() => ({
+ db: vi.fn(),
+ start: vi.fn(),
+ where: vi.fn(),
+ syncVideoDisplayNames: vi.fn(),
+ runWorkflowPromise: vi.fn(() => Promise.resolve()),
+ }));
+
+vi.mock("@cap/database", () => ({ db }));
+vi.mock("@cap/database/schema", () => ({
+ videos: { id: "id", storageIntegrationId: "storageIntegrationId" },
+}));
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { syncVideoDisplayNames },
+}));
+vi.mock("drizzle-orm", () => ({
+ eq: (...args: unknown[]) => args,
+}));
+vi.mock("workflow/api", () => ({ start }));
+vi.mock("@/lib/workflow-runtime", () => ({
+ runWorkflowPromise,
+}));
+
+const { enqueueVideoStorageNameSync } = await import(
+ "@/lib/sync-video-storage-names"
+);
+const { syncVideoStorageNamesWorkflow } = await import(
+ "@/workflows/sync-video-storage-names"
+);
+
+const configureVideoLookup = (storageIntegrationId: string | null) => {
+ where.mockResolvedValue([{ storageIntegrationId }]);
+ db.mockReturnValue({
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({ where })),
+ })),
+ });
+};
+
+describe("video storage display name queue", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not start a workflow for S3 or missing videos", async () => {
+ configureVideoLookup(null);
+ await enqueueVideoStorageNameSync("video-s3" as Video.VideoId);
+ expect(start).not.toHaveBeenCalled();
+
+ where.mockResolvedValue([]);
+ await enqueueVideoStorageNameSync("video-missing" as Video.VideoId);
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it("starts the workflow only for videos with a stored integration", async () => {
+ configureVideoLookup("drive-integration");
+
+ await enqueueVideoStorageNameSync("video-drive" as Video.VideoId);
+
+ expect(start).toHaveBeenCalledWith(syncVideoStorageNamesWorkflow, [
+ { videoId: "video-drive" },
+ ]);
+ });
+
+ it("swallows lookup and dispatch errors after a committed title update", async () => {
+ const error = new Error("workflow unavailable");
+ where.mockRejectedValue(error);
+ db.mockReturnValue({
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({ where })),
+ })),
+ });
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await expect(
+ enqueueVideoStorageNameSync("video-error" as Video.VideoId),
+ ).resolves.toBeUndefined();
+ expect(log).toHaveBeenCalled();
+
+ configureVideoLookup("drive-integration");
+ start.mockRejectedValue(error);
+ await expect(
+ enqueueVideoStorageNameSync("video-dispatch-error" as Video.VideoId),
+ ).resolves.toBeUndefined();
+ expect(log).toHaveBeenCalledTimes(2);
+ log.mockRestore();
+ });
+});
+
+describe("video storage display name workflow", () => {
+ it("spaces retries so an upload can finish before names are synchronized", async () => {
+ syncVideoDisplayNames.mockReturnValue({
+ pipe: vi.fn((runner: (effect: unknown) => unknown) => runner({})),
+ });
+ runWorkflowPromise.mockRejectedValueOnce(new Error("Upload pending"));
+ vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await expect(
+ syncVideoStorageNamesWorkflow({ videoId: "video-pending" }),
+ ).rejects.toBeInstanceOf(RetryableError);
+ });
+
+ it("calls the storage synchronizer in a retriable step", async () => {
+ const pipe = vi.fn((runner: (effect: unknown) => unknown) => runner({}));
+ syncVideoDisplayNames.mockReturnValue({ pipe });
+
+ await syncVideoStorageNamesWorkflow({ videoId: "video-drive" });
+
+ expect(syncVideoDisplayNames).toHaveBeenCalledWith("video-drive");
+ expect(pipe).toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/actions/video/create-for-processing.ts b/apps/web/actions/video/create-for-processing.ts
index a3acda737..656d8155e 100644
--- a/apps/web/actions/video/create-for-processing.ts
+++ b/apps/web/actions/video/create-for-processing.ts
@@ -70,12 +70,14 @@ export async function createVideoForServerProcessing({
})} ${date.getFullYear()}`;
const rawFileKey = `${user.id}/${videoId}/raw-upload.mp4`;
+ const videoTitle = `Cap Upload - ${formattedDate}`;
const uploadResult = await StorageService.createUploadTargetForUser(
user.id,
rawFileKey,
{
contentType: "video/mp4",
+ videoTitle,
method: "put",
fields: {
"x-amz-meta-userid": user.id,
@@ -90,7 +92,7 @@ export async function createVideoForServerProcessing({
.insert(videos)
.values({
id: videoId,
- name: `Cap Upload - ${formattedDate}`,
+ name: videoTitle,
ownerId: user.id,
orgId,
source: { type: "webMP4" as const },
diff --git a/apps/web/actions/video/upload.ts b/apps/web/actions/video/upload.ts
index 43fe9d1fa..4dbce3b51 100644
--- a/apps/web/actions/video/upload.ts
+++ b/apps/web/actions/video/upload.ts
@@ -31,6 +31,7 @@ async function getVideoUploadPresignedUrl({
video,
userId,
organizationId,
+ videoTitle,
}: {
fileKey: string;
duration?: string;
@@ -40,6 +41,7 @@ async function getVideoUploadPresignedUrl({
video?: Video.Video;
userId: User.UserId;
organizationId?: Organisation.OrganisationId;
+ videoTitle?: string;
}) {
try {
const contentType = fileKey.endsWith(".aac")
@@ -89,6 +91,7 @@ async function getVideoUploadPresignedUrl({
{
contentType,
fields: Fields,
+ videoTitle,
},
organizationId,
);
@@ -193,6 +196,9 @@ export async function createVideoAndGetUploadUrl({
}
const idToUse = Video.VideoId.make(videoId || nanoId());
+ const videoTitle = `Cap ${
+ isScreenshot ? "Screenshot" : isUpload ? "Upload" : "Recording"
+ } - ${formattedDate}`;
const screenshotExtension =
screenshotContentType?.toLowerCase() === "image/png" ? "png" : "jpg";
@@ -210,13 +216,12 @@ export async function createVideoAndGetUploadUrl({
audioCodec,
userId: user.id,
organizationId: orgId,
+ videoTitle,
});
const videoData = {
id: idToUse,
- name: `Cap ${
- isScreenshot ? "Screenshot" : isUpload ? "Upload" : "Recording"
- } - ${formattedDate}`,
+ name: videoTitle,
ownerId: user.id,
orgId,
source: { type: "webMP4" as const },
diff --git a/apps/web/actions/videos/edit-title.ts b/apps/web/actions/videos/edit-title.ts
index 1c93a32ac..37937c043 100644
--- a/apps/web/actions/videos/edit-title.ts
+++ b/apps/web/actions/videos/edit-title.ts
@@ -3,10 +3,10 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
-import type { VideoMetadata } from "@cap/database/types";
import type { Video } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
export async function editTitle(videoId: Video.VideoId, title: string) {
const user = await getCurrentUser();
@@ -32,18 +32,14 @@ export async function editTitle(videoId: Video.VideoId, title: string) {
}
try {
- const metadata = (video.metadata as VideoMetadata) || {};
-
await db()
.update(videos)
.set({
name: title,
- metadata: {
- ...metadata,
- titleManuallyEdited: true,
- },
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.titleManuallyEdited', true)`,
})
.where(eq(videos.id, videoId));
+ await enqueueVideoStorageNameSync(videoId);
revalidatePath("/dashboard/caps");
revalidatePath("/dashboard/shared-caps");
diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts
index 084b7f1a0..efc18bbed 100644
--- a/apps/web/app/api/mobile/[...route]/route.ts
+++ b/apps/web/app/api/mobile/[...route]/route.ts
@@ -63,6 +63,7 @@ import {
import { createNotification } from "@/lib/Notification";
import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";
import { apiToHandler } from "@/lib/server";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
import { startVideoProcessingWorkflow } from "@/lib/video-processing";
import { importLoomVideoWorkflow } from "@/workflows/import-loom-video";
@@ -2932,7 +2933,10 @@ const ApiLive = HttpApiBuilder.api(Mobile.MobileApiContract).pipe(
yield* database.use((db) =>
db
.update(Db.videos)
- .set({ name: title })
+ .set({
+ name: title,
+ metadata: sql`JSON_SET(COALESCE(${Db.videos.metadata}, JSON_OBJECT()), '$.titleManuallyEdited', true)`,
+ })
.where(
and(
eq(Db.videos.id, path.id),
@@ -2940,6 +2944,9 @@ const ApiLive = HttpApiBuilder.api(Mobile.MobileApiContract).pipe(
),
),
);
+ yield* Effect.promise(() =>
+ enqueueVideoStorageNameSync(path.id),
+ );
yield* Effect.sync(() => {
revalidatePath("/dashboard/caps");
revalidatePath("/dashboard/shared-caps");
diff --git a/apps/web/lib/agent-write.ts b/apps/web/lib/agent-write.ts
index e47abf6c2..f294084b4 100644
--- a/apps/web/lib/agent-write.ts
+++ b/apps/web/lib/agent-write.ts
@@ -14,6 +14,7 @@ import { and, eq, sql } from "drizzle-orm";
import { Effect, Schedule, Schema } from "effect";
import { revalidatePath } from "next/cache";
import { createNotification } from "@/lib/Notification";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
type TransactionCallback = Parameters<DbClient["transaction"]>[0];
type Transaction = Parameters<TransactionCallback>[0];
@@ -623,6 +624,9 @@ export const updateAgentCap = Effect.fn("Agent.updateCap")(function* (input: {
return yield* temporarilyUnavailable(input.requestId);
}
if (result.state === "not_found") return yield* notFound(input.requestId);
+ if (title !== undefined) {
+ yield* Effect.promise(() => enqueueVideoStorageNameSync(input.videoId));
+ }
yield* Effect.try(() => {
revalidatePath("/dashboard/caps");
revalidatePath("/dashboard/shared-caps");
diff --git a/apps/web/lib/sync-video-storage-names.ts b/apps/web/lib/sync-video-storage-names.ts
new file mode 100644
index 000000000..bdc65a3d3
--- /dev/null
+++ b/apps/web/lib/sync-video-storage-names.ts
@@ -0,0 +1,25 @@
+import { db } from "@cap/database";
+import { videos } from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { start } from "workflow/api";
+import { syncVideoStorageNamesWorkflow } from "@/workflows/sync-video-storage-names";
+
+export async function enqueueVideoStorageNameSync(
+ videoId: Video.VideoId,
+): Promise<void> {
+ try {
+ const [video] = await db()
+ .select({ storageIntegrationId: videos.storageIntegrationId })
+ .from(videos)
+ .where(eq(videos.id, videoId));
+ if (!video?.storageIntegrationId) return;
+
+ await start(syncVideoStorageNamesWorkflow, [{ videoId }]);
+ } catch (error) {
+ console.error("Failed to queue video storage name sync", {
+ videoId,
+ error,
+ });
+ }
+}
diff --git a/apps/web/workflows/agent-cap-operation.ts b/apps/web/workflows/agent-cap-operation.ts
index 917321b98..e7225e3f4 100644
--- a/apps/web/workflows/agent-cap-operation.ts
+++ b/apps/web/workflows/agent-cap-operation.ts
@@ -20,6 +20,7 @@ import {
getDomainResponse,
} from "@/actions/organization/domain-utils";
import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
type CapSnapshot = {
@@ -215,6 +216,7 @@ async function createDuplicate(operationId: string, payload: OperationPayload) {
})
.where(eq(Db.agentApiOperations.id, operationId));
});
+ await enqueueVideoStorageNameSync(destinationId);
}
async function deleteCapObjects(payload: OperationPayload) {
diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.ts
index 9ccdde8df..774844ea1 100644
--- a/apps/web/workflows/generate-ai.ts
+++ b/apps/web/workflows/generate-ai.ts
@@ -15,6 +15,7 @@ import { Effect, Option } from "effect";
import { FatalError } from "workflow";
import { isAiConfigured } from "@/lib/ai/provider";
import { AiUnavailableError, runWithAiProviders } from "@/lib/ai/run";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
import { decodeStorageVideo } from "@/lib/video-storage";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
@@ -45,6 +46,16 @@ interface AiResult {
chapters?: { title: string; start: number }[];
}
+const getAffectedRows = (result: unknown) => {
+ if (Array.isArray(result)) {
+ return (
+ (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0
+ );
+ }
+
+ return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
+};
+
const MAX_CHARS_PER_CHUNK = 24000;
const LEGACY_AI_TITLE_FALLBACK = "Generated Title";
const LEGACY_AI_SUMMARY_FALLBACK =
@@ -94,7 +105,7 @@ export async function generateAiWorkflow(payload: GenerateAiWorkflowPayload) {
const transcript = await fetchTranscript(videoId, userId, videoData.video);
if (!transcript) {
- await markSkipped(videoId, videoData.metadata);
+ await markSkipped(videoId);
return {
success: true,
message: "Transcript empty or too short - skipped",
@@ -147,21 +158,18 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {
throw new FatalError("AI metadata already generated");
}
- const processingMetadata = { ...metadata };
- if (processingMetadata.aiTitle === LEGACY_AI_TITLE_FALLBACK) {
- delete processingMetadata.aiTitle;
- }
- if (processingMetadata.summary === LEGACY_AI_SUMMARY_FALLBACK) {
- delete processingMetadata.summary;
+ let processingMetadata = sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.aiGenerationStatus', 'PROCESSING')`;
+ for (const [metadataPath, fallback] of [
+ ["$.aiTitle", LEGACY_AI_TITLE_FALLBACK],
+ ["$.summary", LEGACY_AI_SUMMARY_FALLBACK],
+ ] as const) {
+ processingMetadata = sql`IF(JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, ${metadataPath})) = ${fallback}, JSON_REMOVE(${processingMetadata}, ${metadataPath}), ${processingMetadata})`;
}
await db()
.update(videos)
.set({
- metadata: {
- ...processingMetadata,
- aiGenerationStatus: "PROCESSING",
- },
+ metadata: processingMetadata,
})
.where(eq(videos.id, videoId as Video.VideoId));
@@ -225,21 +233,13 @@ async function markError(videoId: string): Promise<void> {
);
}
-async function markSkipped(
- videoId: string,
- metadata: VideoMetadata,
-): Promise<void> {
+async function markSkipped(videoId: string): Promise<void> {
"use step";
- const currentMetadata = await getCurrentVideoMetadata(videoId, metadata);
-
await db()
.update(videos)
.set({
- metadata: {
- ...currentMetadata,
- aiGenerationStatus: "SKIPPED",
- },
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.aiGenerationStatus', 'SKIPPED')`,
})
.where(eq(videos.id, videoId as Video.VideoId));
}
@@ -371,17 +371,21 @@ async function saveResults(
: metadata;
const currentTitle = currentVideo?.name ?? video.name;
- const updatedMetadata: VideoMetadata = {
- ...currentMetadata,
- aiTitle: generatedTitle || currentMetadata.aiTitle,
- summary: result.summary || currentMetadata.summary,
- chapters: result.chapters || currentMetadata.chapters,
- aiGenerationStatus: "COMPLETE",
- };
+ let metadataUpdate = sql`COALESCE(${videos.metadata}, JSON_OBJECT())`;
+ if (generatedTitle) {
+ metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.aiTitle', ${generatedTitle})`;
+ }
+ if (result.summary) {
+ metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.summary', ${result.summary})`;
+ }
+ if (result.chapters) {
+ metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.chapters', CAST(${JSON.stringify(result.chapters)} AS JSON))`;
+ }
+ metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.aiGenerationStatus', 'COMPLETE')`;
await db()
.update(videos)
- .set({ metadata: updatedMetadata })
+ .set({ metadata: metadataUpdate })
.where(eq(videos.id, videoId as Video.VideoId));
if (
@@ -394,15 +398,19 @@ async function saveResults(
titleManuallyEdited: currentMetadata.titleManuallyEdited,
})
) {
- await db()
+ const titleUpdate = await db()
.update(videos)
.set({ name: generatedTitle })
.where(
and(
eq(videos.id, videoId as Video.VideoId),
eq(videos.name, currentTitle),
+ sql`COALESCE(JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.titleManuallyEdited')), 'false') <> 'true'`,
),
);
+ if (getAffectedRows(titleUpdate) > 0) {
+ await enqueueVideoStorageNameSync(videoId as Video.VideoId);
+ }
}
}
@@ -417,16 +425,6 @@ async function getCurrentVideo(
return currentVideo ?? null;
}
-async function getCurrentVideoMetadata(
- videoId: string,
- fallback: VideoMetadata,
-): Promise<VideoMetadata> {
- const currentVideo = await getCurrentVideo(videoId);
- return currentVideo
- ? (currentVideo.metadata as VideoMetadata) || {}
- : fallback;
-}
-
function parseVttWithTimestamps(vttContent: string): VttSegment[] {
const lines = vttContent.split("\n");
const segments: VttSegment[] = [];
diff --git a/apps/web/workflows/sync-video-storage-names.ts b/apps/web/workflows/sync-video-storage-names.ts
new file mode 100644
index 000000000..46acf17d6
--- /dev/null
+++ b/apps/web/workflows/sync-video-storage-names.ts
@@ -0,0 +1,32 @@
+import { Storage } from "@cap/web-backend/src/Storage/index";
+import { Video } from "@cap/web-domain";
+import { RetryableError } from "workflow";
+import { runWorkflowPromise } from "@/lib/workflow-runtime";
+
+async function syncVideoStorageNamesStep(videoId: string) {
+ "use step";
+
+ try {
+ await Storage.syncVideoDisplayNames(Video.VideoId.make(videoId)).pipe(
+ runWorkflowPromise,
+ );
+ } catch (error) {
+ console.error("Video storage names could not be synchronized", {
+ videoId,
+ error,
+ });
+ throw new RetryableError("Video storage names are not synchronized yet", {
+ retryAfter: "1 minute",
+ });
+ }
+}
+
+syncVideoStorageNamesStep.maxRetries = 60;
+
+export async function syncVideoStorageNamesWorkflow(input: {
+ videoId: string;
+}) {
+ "use workflow";
+
+ await syncVideoStorageNamesStep(input.videoId);
+}
diff --git a/apps/web/workflows/transfer-organization-content.ts b/apps/web/workflows/transfer-organization-content.ts
index a807314e5..84ed45796 100644
--- a/apps/web/workflows/transfer-organization-content.ts
+++ b/apps/web/workflows/transfer-organization-content.ts
@@ -23,6 +23,7 @@ import {
MAX_CONTENT_TRANSFER_FOLDERS,
MAX_CONTENT_TRANSFER_VIDEOS,
} from "@/lib/content-transfer";
+import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
const CONTENT_TRANSFER_UPLOAD_PHASES = new Set<ContentTransferUploadPhase>([
@@ -829,6 +830,7 @@ async function transferOneVideo(
}
}
});
+ await enqueueVideoStorageNameSync(videoId);
const cleanupWarnings: string[] = [];
if (copied) {