Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add get-edit-transcript action with backfill

Richie McIlroyeeb81ba9e18d
diff --git a/apps/web/__tests__/unit/get-edit-transcript.test.ts b/apps/web/__tests__/unit/get-edit-transcript.test.ts
new file mode 100644
index 000000000..06e5d5916
--- /dev/null
+++ b/apps/web/__tests__/unit/get-edit-transcript.test.ts
@@ -0,0 +1,462 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { Option } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ decodeStorageVideo: vi.fn(),
+ getAccessForVideo: vi.fn(),
+ getCurrentUser: vi.fn(),
+ runPromise: vi.fn(),
+ start: vi.fn(),
+}));
+
+const schema = vi.hoisted(() => ({
+ videos: {
+ id: "videos.id",
+ metadata: "videos.metadata",
+ updatedAt: "videos.updatedAt",
+ },
+ videoEdits: {
+ videoId: "videoEdits.videoId",
+ editSpec: "videoEdits.editSpec",
+ },
+}));
+
+vi.mock("@cap/database", () => ({
+ db: mocks.db,
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+
+vi.mock("@cap/database/schema", () => schema);
+
+vi.mock("@cap/utils", () => ({
+ userIsPro: () => true,
+}));
+
+vi.mock("@cap/web-backend", () => ({
+ Storage: {
+ getAccessForVideo: mocks.getAccessForVideo,
+ },
+}));
+
+vi.mock("drizzle-orm", () => ({
+ and: vi.fn((...conditions: unknown[]) => ({ conditions })),
+ eq: vi.fn((left: unknown, right: unknown) => ({ left, right })),
+ sql: vi.fn((strings: TemplateStringsArray, ...values: unknown[]) => ({
+ strings,
+ values,
+ })),
+}));
+
+vi.mock("workflow/api", () => ({
+ start: mocks.start,
+}));
+
+vi.mock("@/lib/server", () => ({
+ runPromise: mocks.runPromise,
+}));
+
+vi.mock("@/lib/edit-transcript-storage", () => ({
+ decryptEditTranscriptObject: (value: string) => value,
+}));
+
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: mocks.decodeStorageVideo,
+}));
+
+vi.mock("@/workflows/transcribe", () => ({
+ backfillEditTranscriptWorkflow: vi.fn(),
+}));
+
+vi.mock("server-only", () => ({}));
+
+type PipeValue<T> = {
+ pipe: (runner: (value: T) => unknown) => unknown;
+};
+
+function pipeValue<T>(value: T): PipeValue<T> {
+ return {
+ pipe: (runner) => runner(value),
+ };
+}
+
+function createDatabase(
+ video: Record<string, unknown>,
+ edit?: Record<string, unknown>,
+) {
+ const currentVideo: Record<string, unknown> = {
+ metadata: null,
+ updatedAt: new Date("2026-07-30T00:00:00.000Z"),
+ ...video,
+ };
+ const transactionContext = new AsyncLocalStorage<boolean>();
+ const lockedSelect = {
+ select: vi.fn(),
+ from: vi.fn(),
+ where: vi.fn(),
+ for: vi.fn(),
+ };
+ lockedSelect.select.mockReturnValue(lockedSelect);
+ lockedSelect.from.mockReturnValue(lockedSelect);
+ lockedSelect.where.mockReturnValue(lockedSelect);
+ lockedSelect.for.mockImplementation(async () => [currentVideo]);
+
+ const transactionUpdate = {
+ set: vi.fn(),
+ where: vi.fn(),
+ };
+ transactionUpdate.set.mockImplementation(
+ (values: Record<string, unknown>) => {
+ if (
+ typeof values.metadata === "object" &&
+ values.metadata !== null &&
+ "values" in values.metadata &&
+ Array.isArray(values.metadata.values)
+ ) {
+ const encodedStatus = values.metadata.values.find(
+ (value) =>
+ typeof value === "string" && value.startsWith('{"status":'),
+ );
+ if (typeof encodedStatus === "string") {
+ currentVideo.metadata = {
+ editTranscriptBackfill: JSON.parse(encodedStatus),
+ };
+ }
+ }
+ return transactionUpdate;
+ },
+ );
+ transactionUpdate.where.mockResolvedValue([{ affectedRows: 1 }]);
+
+ const select = vi.fn(() => ({
+ from: vi.fn((table: unknown) => ({
+ where: vi
+ .fn()
+ .mockResolvedValue(
+ table === schema.videoEdits ? (edit ? [edit] : []) : [currentVideo],
+ ),
+ })),
+ }));
+ const update = vi.fn(() => ({
+ set: vi.fn(() => ({
+ where: vi.fn().mockResolvedValue([{ affectedRows: 1 }]),
+ })),
+ }));
+
+ let transactionTail = Promise.resolve();
+ const transaction = vi.fn(
+ <T>(
+ callback: (
+ tx: typeof lockedSelect & { update: typeof update },
+ ) => Promise<T>,
+ ): Promise<T> => {
+ const result = transactionTail.then(() =>
+ transactionContext.run(true, () =>
+ callback({
+ ...lockedSelect,
+ update: vi.fn(() => transactionUpdate),
+ }),
+ ),
+ );
+ transactionTail = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ },
+ );
+
+ return {
+ database: { select, transaction, update },
+ isTransactionActive: () => transactionContext.getStore() === true,
+ lockedSelect,
+ };
+}
+
+function createBucket(
+ objects: Map<string, string>,
+ isTransactionActive = () => false,
+) {
+ return {
+ getObject: vi.fn((key: string) => {
+ if (isTransactionActive()) {
+ throw new Error("Storage read occurred inside a database transaction");
+ }
+ return pipeValue(Option.fromNullable(objects.get(key)));
+ }),
+ };
+}
+
+const video = {
+ id: "video-1",
+ ownerId: "user-1",
+ duration: 25,
+ source: { type: "webMP4" },
+ isScreenshot: false,
+ transcriptionStatus: "COMPLETE",
+ updatedAt: new Date("2026-07-30T00:00:00.000Z"),
+};
+
+const TRANSCRIPT_KEY = "user-1/video-1/transcription.edit.v3.json";
+
+function storedOriginalTranscript(durationMs = 25_000) {
+ return JSON.stringify({
+ version: 3,
+ speechModelUsed: "universal-3-5-pro",
+ durationMs,
+ languageCode: "en",
+ words: [
+ {
+ id: "word-0-1000-1500",
+ text: "before",
+ startMs: 1_000,
+ endMs: 1_500,
+ confidence: 0.9,
+ speaker: null,
+ channel: null,
+ },
+ {
+ id: "word-1-6000-6500",
+ text: "kept",
+ startMs: 6_000,
+ endMs: 6_500,
+ confidence: 0.9,
+ speaker: null,
+ channel: null,
+ },
+ {
+ id: "word-2-20000-20500",
+ text: "after",
+ startMs: 20_000,
+ endMs: 20_500,
+ confidence: 0.9,
+ speaker: null,
+ channel: null,
+ },
+ ],
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getCurrentUser.mockResolvedValue({ id: "user-1" });
+ mocks.runPromise.mockImplementation((value) => Promise.resolve(value));
+ mocks.start.mockResolvedValue({ runId: "run-1" });
+});
+
+describe("requestEditTranscript", () => {
+ it("serializes concurrent requests and starts one paid transcript job", async () => {
+ const objects = new Map<string, string>();
+ const { database, isTransactionActive, lockedSelect } =
+ createDatabase(video);
+ const bucket = createBucket(objects, isTransactionActive);
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+ mocks.start.mockImplementation(async () => {
+ if (isTransactionActive()) {
+ throw new Error(
+ "Workflow start occurred inside a database transaction",
+ );
+ }
+ return { runId: "run-1" };
+ });
+
+ const { requestEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+ const [first, second] = await Promise.all([
+ requestEditTranscript("video-1" as never),
+ requestEditTranscript("video-1" as never),
+ ]);
+
+ expect(first).toEqual({ status: "processing" });
+ expect(second).toEqual({ status: "processing" });
+ expect(mocks.start).toHaveBeenCalledTimes(1);
+ expect(lockedSelect.for).toHaveBeenCalledTimes(2);
+ expect(lockedSelect.for).toHaveBeenCalledWith("update");
+ expect(mocks.start.mock.calls[0]?.[1]?.[0]).toMatchObject({
+ videoId: "video-1",
+ userId: "user-1",
+ requestId: expect.any(String),
+ });
+ });
+
+ it("returns a current cached sidecar without starting another job", async () => {
+ const objects = new Map<string, string>([
+ [
+ TRANSCRIPT_KEY,
+ JSON.stringify({
+ version: 3,
+ speechModelUsed: "universal-3-5-pro",
+ durationMs: 25_000,
+ languageCode: "en",
+ words: [],
+ }),
+ ],
+ ]);
+ const bucket = createBucket(objects);
+ const { database } = createDatabase(video);
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+
+ const { requestEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+ const response = await requestEditTranscript("video-1" as never);
+
+ expect(response.status).toBe("ready");
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it("remaps the stored original words through the video's edit spec", async () => {
+ const objects = new Map<string, string>([
+ [TRANSCRIPT_KEY, storedOriginalTranscript()],
+ ]);
+ const bucket = createBucket(objects);
+ const { database } = createDatabase(
+ { ...video, duration: 10 },
+ {
+ editSpec: {
+ version: 1,
+ sourceDuration: 25,
+ keepRanges: [{ start: 5, end: 15 }],
+ },
+ },
+ );
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+
+ const { requestEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+ const response = await requestEditTranscript("video-1" as never);
+
+ if (response.status !== "ready") {
+ throw new Error(`Expected a ready transcript, got ${response.status}`);
+ }
+ expect(response.transcript.durationMs).toBe(10_000);
+ expect(
+ response.transcript.words.map((word) => [
+ word.id,
+ word.startMs,
+ word.endMs,
+ ]),
+ ).toEqual([["word-1-6000-6500", 1_000, 1_500]]);
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it("does not expose workflow startup errors to the client", async () => {
+ const bucket = createBucket(new Map());
+ const { database } = createDatabase(video);
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+ mocks.start.mockRejectedValue(
+ new Error("provider account and request identifiers"),
+ );
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => undefined);
+
+ const { requestEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+ const response = await requestEditTranscript("video-1" as never);
+
+ expect(response).toEqual({
+ status: "error",
+ message: "Transcript preparation could not start. Try again.",
+ });
+ expect(JSON.stringify(response)).not.toContain("provider account");
+ consoleError.mockRestore();
+ });
+});
+
+describe("getEditTranscript", () => {
+ it("remaps stored words instead of reporting them as stale", async () => {
+ const objects = new Map<string, string>([
+ [TRANSCRIPT_KEY, storedOriginalTranscript()],
+ ]);
+ const bucket = createBucket(objects);
+ const { database } = createDatabase(
+ { ...video, duration: 10 },
+ {
+ editSpec: {
+ version: 1,
+ sourceDuration: 25,
+ keepRanges: [{ start: 5, end: 15 }],
+ },
+ },
+ );
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+
+ const { getEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+ const response = await getEditTranscript("video-1" as never);
+
+ if (response.status !== "ready") {
+ throw new Error(`Expected a ready transcript, got ${response.status}`);
+ }
+ expect(response.transcript.words.map((word) => word.text)).toEqual([
+ "kept",
+ ]);
+ });
+
+ it("reports missing when the sidecar no longer matches the original media", async () => {
+ const objects = new Map<string, string>([
+ [TRANSCRIPT_KEY, storedOriginalTranscript(18_000)],
+ ]);
+ const bucket = createBucket(objects);
+ const { database } = createDatabase(
+ { ...video, duration: 10 },
+ {
+ editSpec: {
+ version: 1,
+ sourceDuration: 25,
+ keepRanges: [{ start: 5, end: 15 }],
+ },
+ },
+ );
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+
+ const { getEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+
+ expect(await getEditTranscript("video-1" as never)).toEqual({
+ status: "missing",
+ });
+ });
+
+ it("reports only a generic message for a failed backfill", async () => {
+ const bucket = createBucket(new Map());
+ const { database } = createDatabase({
+ ...video,
+ metadata: {
+ editTranscriptBackfill: {
+ status: "error",
+ requestId: "request-1",
+ requestedAt: "2026-07-30T00:00:00.000Z",
+ message: "private provider detail",
+ },
+ },
+ });
+ mocks.db.mockReturnValue(database);
+ mocks.getAccessForVideo.mockReturnValue(pipeValue([bucket]));
+
+ const { getEditTranscript } = await import(
+ "@/actions/videos/get-edit-transcript"
+ );
+
+ expect(await getEditTranscript("video-1" as never)).toEqual({
+ status: "error",
+ message: "Transcript preparation failed. Try again.",
+ });
+ });
+});
diff --git a/apps/web/actions/videos/get-edit-transcript.ts b/apps/web/actions/videos/get-edit-transcript.ts
new file mode 100644
index 000000000..7cb1b5c21
--- /dev/null
+++ b/apps/web/actions/videos/get-edit-transcript.ts
@@ -0,0 +1,312 @@
+"use server";
+
+import { randomUUID } from "node:crypto";
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videoEdits, videos } from "@cap/database/schema";
+import { userIsPro } from "@cap/utils";
+import { Storage } from "@cap/web-backend";
+import type { Video } from "@cap/web-domain";
+import { and, eq, sql } from "drizzle-orm";
+import { Option } from "effect";
+import { start } from "workflow/api";
+import {
+ type EditTranscript,
+ type EditTranscriptBackfillStatus,
+ getEditTranscriptBackfillStatus,
+ getEditTranscriptObjectKey,
+ parseEditTranscript,
+ remapEditTranscriptThroughSpec,
+} from "@/lib/edit-transcript";
+import { decryptEditTranscriptObject } from "@/lib/edit-transcript-storage";
+import { runPromise } from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
+import { backfillEditTranscriptWorkflow } from "@/workflows/transcribe";
+
+type EditTranscriptResponse =
+ | { status: "ready"; transcript: EditTranscript }
+ | { status: "missing" }
+ | { status: "processing" }
+ | { status: "error"; message: string };
+
+const BACKFILL_STALE_AFTER_MS = 60 * 60 * 1000;
+const PUBLIC_ERROR_MESSAGES = new Set([
+ "Unauthorized",
+ "Cap Pro is required",
+ "Video not found",
+ "Transcript editing is not available for this video",
+ "Transcript is not ready",
+]);
+
+function isMp4BackedVideo(source: typeof videos.$inferSelect.source) {
+ return source.type === "desktopMP4" || source.type === "webMP4";
+}
+
+function isEditableTranscriptVideo(video: typeof videos.$inferSelect) {
+ return (
+ video.transcriptionStatus === "COMPLETE" &&
+ !video.isScreenshot &&
+ isMp4BackedVideo(video.source) &&
+ Boolean(video.duration && video.duration > 0)
+ );
+}
+
+function getPublicErrorMessage(error: unknown, fallback: string) {
+ return isPublicError(error) ? error.message : fallback;
+}
+
+function isPublicError(error: unknown): error is Error {
+ return error instanceof Error && PUBLIC_ERROR_MESSAGES.has(error.message);
+}
+
+async function loadEditableTranscriptVideo(videoId: Video.VideoId) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+ if (!userIsPro(user)) throw new Error("Cap Pro is required");
+
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+ if (!video || video.ownerId !== user.id) throw new Error("Video not found");
+ if (!isEditableTranscriptVideo(video)) {
+ if (video.transcriptionStatus !== "COMPLETE") {
+ throw new Error("Transcript is not ready");
+ }
+ throw new Error("Transcript editing is not available for this video");
+ }
+
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
+ ).pipe(runPromise);
+
+ return { user, video, bucket };
+}
+
+async function getOptionalObject(
+ bucket: Awaited<ReturnType<typeof loadEditableTranscriptVideo>>["bucket"],
+ key: string,
+) {
+ const object = await bucket.getObject(key).pipe(runPromise);
+ return Option.isSome(object) ? object.value : null;
+}
+
+function isFreshProcessingStatus(status: EditTranscriptBackfillStatus) {
+ if (status.status !== "processing") return false;
+ const requestedAt = Date.parse(status.requestedAt);
+ return (
+ Number.isFinite(requestedAt) &&
+ Date.now() - requestedAt < BACKFILL_STALE_AFTER_MS
+ );
+}
+
+function isDurationCurrent(durationMs: number, expectedSeconds: number) {
+ return Math.abs(durationMs - Math.round(expectedSeconds * 1000)) <= 250;
+}
+
+/**
+ * Reads the stored word transcript. Stored words always describe the ORIGINAL
+ * media, so for edited videos they are checked against the edit spec's source
+ * duration and remapped onto the current output timeline before being returned.
+ */
+async function readCurrentEditTranscript(
+ bucket: Awaited<ReturnType<typeof loadEditableTranscriptVideo>>["bucket"],
+ video: typeof videos.$inferSelect,
+): Promise<EditTranscript | null> {
+ const content = await getOptionalObject(
+ bucket,
+ getEditTranscriptObjectKey(video.ownerId, video.id),
+ );
+ const decrypted = content
+ ? decryptEditTranscriptObject(content, video.ownerId, video.id)
+ : null;
+ const transcript = decrypted ? parseEditTranscript(decrypted) : null;
+ if (!transcript) return null;
+
+ const [edit] = await db()
+ .select({ editSpec: videoEdits.editSpec })
+ .from(videoEdits)
+ .where(eq(videoEdits.videoId, video.id));
+
+ if (!edit?.editSpec) {
+ return isDurationCurrent(transcript.durationMs, video.duration ?? 0)
+ ? transcript
+ : null;
+ }
+
+ return isDurationCurrent(transcript.durationMs, edit.editSpec.sourceDuration)
+ ? remapEditTranscriptThroughSpec(transcript, edit.editSpec)
+ : null;
+}
+
+export async function getEditTranscript(
+ videoId: Video.VideoId,
+): Promise<EditTranscriptResponse> {
+ try {
+ const { video, bucket } = await loadEditableTranscriptVideo(videoId);
+ const transcript = await readCurrentEditTranscript(bucket, video);
+
+ if (transcript) {
+ return { status: "ready", transcript };
+ }
+
+ const status = getEditTranscriptBackfillStatus(video.metadata);
+ if (status && isFreshProcessingStatus(status)) {
+ return { status: "processing" };
+ }
+ if (status?.status === "processing") {
+ return {
+ status: "error",
+ message: "Transcript preparation stalled. Try again.",
+ };
+ }
+ if (status?.status === "error") {
+ return {
+ status: "error",
+ message: "Transcript preparation failed. Try again.",
+ };
+ }
+ return { status: "missing" };
+ } catch (error) {
+ if (!isPublicError(error)) {
+ console.error(
+ `[editTranscript] Failed to load transcript for ${videoId}`,
+ error,
+ );
+ }
+ return {
+ status: "error",
+ message: getPublicErrorMessage(error, "Transcript unavailable"),
+ };
+ }
+}
+
+async function claimEditTranscriptBackfill(
+ videoId: Video.VideoId,
+ userId: string,
+) {
+ return db().transaction(async (tx) => {
+ const [video] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId))
+ .for("update");
+ if (!video || video.ownerId !== userId) throw new Error("Video not found");
+ if (!isEditableTranscriptVideo(video)) {
+ throw new Error("Transcript editing is not available for this video");
+ }
+
+ const existing = getEditTranscriptBackfillStatus(video.metadata);
+ if (existing && isFreshProcessingStatus(existing)) {
+ return { claimed: false as const };
+ }
+
+ const requestId = randomUUID();
+ const status = {
+ status: "processing",
+ requestId,
+ requestedAt: new Date().toISOString(),
+ };
+ await tx
+ .update(videos)
+ .set({
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.editTranscriptBackfill', CAST(${JSON.stringify(status)} AS JSON))`,
+ updatedAt: video.updatedAt,
+ })
+ .where(eq(videos.id, videoId));
+
+ return { claimed: true as const, requestId };
+ });
+}
+
+async function setEditTranscriptBackfillError(
+ videoId: Video.VideoId,
+ requestId: string,
+) {
+ await db()
+ .update(videos)
+ .set({
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.editTranscriptBackfill.status', 'error')`,
+ updatedAt: sql`${videos.updatedAt}`,
+ })
+ .where(
+ and(
+ eq(videos.id, videoId),
+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.editTranscriptBackfill.requestId')) = ${requestId}`,
+ ),
+ );
+}
+
+async function clearEditTranscriptBackfill(
+ videoId: Video.VideoId,
+ requestId: string,
+) {
+ await db()
+ .update(videos)
+ .set({
+ metadata: sql`JSON_REMOVE(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.editTranscriptBackfill')`,
+ updatedAt: sql`${videos.updatedAt}`,
+ })
+ .where(
+ and(
+ eq(videos.id, videoId),
+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.editTranscriptBackfill.requestId')) = ${requestId}`,
+ ),
+ );
+}
+
+export async function requestEditTranscript(
+ videoId: Video.VideoId,
+): Promise<EditTranscriptResponse> {
+ try {
+ const { user, video, bucket } = await loadEditableTranscriptVideo(videoId);
+ const transcript = await readCurrentEditTranscript(bucket, video);
+ if (transcript) {
+ return { status: "ready", transcript };
+ }
+
+ const claim = await claimEditTranscriptBackfill(videoId, user.id);
+ if (!claim.claimed) {
+ return { status: "processing" };
+ }
+
+ const transcriptAfterClaim = await readCurrentEditTranscript(bucket, video);
+ if (transcriptAfterClaim) {
+ await clearEditTranscriptBackfill(videoId, claim.requestId);
+ return { status: "ready", transcript: transcriptAfterClaim };
+ }
+
+ try {
+ await start(backfillEditTranscriptWorkflow, [
+ {
+ videoId,
+ userId: user.id,
+ requestId: claim.requestId,
+ },
+ ]);
+ } catch (error) {
+ console.error(
+ `[editTranscript] Failed to start backfill for ${videoId}`,
+ error,
+ );
+ await setEditTranscriptBackfillError(videoId, claim.requestId);
+ return {
+ status: "error",
+ message: "Transcript preparation could not start. Try again.",
+ };
+ }
+
+ return { status: "processing" };
+ } catch (error) {
+ if (!isPublicError(error)) {
+ console.error(
+ `[editTranscript] Failed to request transcript for ${videoId}`,
+ error,
+ );
+ }
+ return {
+ status: "error",
+ message: getPublicErrorMessage(error, "Transcript unavailable"),
+ };
+ }
+}