Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): harden live/early transcription against races and runaway polling

Richie McIlroyc38bb9e8e9d6
diff --git a/apps/web/__tests__/integration/transcribe-early-segments.test.ts b/apps/web/__tests__/integration/transcribe-early-segments.test.ts
index d5a2e4ea5..38ba565a2 100644
--- a/apps/web/__tests__/integration/transcribe-early-segments.test.ts
+++ b/apps/web/__tests__/integration/transcribe-early-segments.test.ts
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
getObject: vi.fn(),
getInternalSignedObjectUrl: vi.fn(),
startAiGeneration: vi.fn(),
+ startWorkflow: vi.fn(),
updates: [] as Record<string, unknown>[],
}));
@@ -90,6 +91,7 @@ vi.mock("@cap/database", () => ({
vi.mock("drizzle-orm", () => ({
and: (...conditions: unknown[]) => ({ conditions }),
eq: (field: unknown, value: unknown) => ({ field, value }),
+ isNull: (field: unknown) => ({ isNull: field }),
sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({
strings,
values,
@@ -102,6 +104,10 @@ vi.mock("workflow", () => ({
FatalError: class FatalError extends Error {},
}));
+vi.mock("workflow/api", () => ({
+ start: mocks.startWorkflow,
+}));
+
vi.mock("assemblyai", () => ({
AssemblyAI: class {
transcripts = { transcribe: mocks.transcribe };
@@ -171,8 +177,14 @@ const manifest = {
version: 5,
video_init_uploaded: true,
audio_init_uploaded: true,
- video_segments: [{ index: 1, duration: 2 }, { index: 2, duration: 2 }],
- audio_segments: [{ index: 1, duration: 2 }, { index: 2, duration: 2.5 }],
+ video_segments: [
+ { index: 1, duration: 2 },
+ { index: 2, duration: 2 },
+ ],
+ audio_segments: [
+ { index: 1, duration: 2 },
+ { index: 2, duration: 2.5 },
+ ],
is_complete: true,
};
@@ -183,6 +195,8 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {
videoRow.duration = null;
videoRow.source = { type: "desktopSegments" };
mocks.transcribe.mockReset();
+ mocks.startWorkflow.mockReset();
+ mocks.startWorkflow.mockResolvedValue(undefined);
mocks.transcribe.mockResolvedValue({
...assemblyAIEditResponse,
audio_duration: 4,
@@ -233,9 +247,7 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {
const signedKeys = mocks.getInternalSignedObjectUrl.mock.calls.map(
(call) => call[0],
);
- expect(signedKeys).toContain(
- "user-456/video-123/segments/audio/init.mp4",
- );
+ expect(signedKeys).toContain("user-456/video-123/segments/audio/init.mp4");
expect(signedKeys).toContain(
"user-456/video-123/segments/audio/segment_001.m4s",
);
@@ -262,8 +274,11 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {
(call) => call[0] === "user-456/video-123/transcription.edit.v3.json",
);
const stored = parseEditTranscript(
- decryptEditTranscriptObject(write?.[1] as string, "user-456", "video-123") ??
- "",
+ decryptEditTranscriptObject(
+ write?.[1] as string,
+ "user-456",
+ "video-123",
+ ) ?? "",
);
expect(stored?.durationMs).toBe(4500);
@@ -295,11 +310,19 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {
expect(mocks.updates).not.toContainEqual({
transcriptionStatus: "COMPLETE",
});
+ // and the video is re-offered to the normal (non-early) path, because
+ // the post-mux queue may already have run and been rejected by the claim
+ expect(mocks.startWorkflow).toHaveBeenCalledTimes(1);
+ expect(mocks.startWorkflow.mock.calls[0]?.[1]).toEqual([
+ { videoId: "video-123", userId: "user-456", aiGenerationEnabled: false },
+ ]);
});
it("defers when the manifest exists but is not complete", async () => {
mocks.getObject.mockImplementation(() =>
- pipeValue(Option.some(JSON.stringify({ ...manifest, is_complete: false }))),
+ pipeValue(
+ Option.some(JSON.stringify({ ...manifest, is_complete: false })),
+ ),
);
const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");
@@ -338,7 +361,8 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {
expect(result.success).toBe(true);
expect(mocks.transcribe).not.toHaveBeenCalled();
- expect(mocks.updates.at(-1)).toEqual({ transcriptionStatus: "NO_AUDIO" });
+ expect(mocks.updates).toContainEqual({ transcriptionStatus: "NO_AUDIO" });
+ expect(mocks.updates).not.toContainEqual({ transcriptionStatus: "ERROR" });
});
it("falls back to segment audio in the normal path when no muxed source exists", async () => {
diff --git a/apps/web/__tests__/integration/transcribe-workflow.test.ts b/apps/web/__tests__/integration/transcribe-workflow.test.ts
index 60a997ac0..a88a9a6ff 100644
--- a/apps/web/__tests__/integration/transcribe-workflow.test.ts
+++ b/apps/web/__tests__/integration/transcribe-workflow.test.ts
@@ -89,6 +89,7 @@ vi.mock("@cap/database", () => ({
vi.mock("drizzle-orm", () => ({
and: (...conditions: unknown[]) => ({ conditions }),
eq: (field: unknown, value: unknown) => ({ field, value }),
+ isNull: (field: unknown) => ({ isNull: field }),
sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({
strings,
values,
@@ -101,6 +102,10 @@ vi.mock("workflow", () => ({
FatalError: class FatalError extends Error {},
}));
+vi.mock("workflow/api", () => ({
+ start: vi.fn(),
+}));
+
vi.mock("assemblyai", () => ({
AssemblyAI: class {
transcripts = { transcribe: mocks.transcribe };
diff --git a/apps/web/__tests__/unit/live-transcribe-core.test.ts b/apps/web/__tests__/unit/live-transcribe-core.test.ts
index 4df930ca2..ac3d32a34 100644
--- a/apps/web/__tests__/unit/live-transcribe-core.test.ts
+++ b/apps/web/__tests__/unit/live-transcribe-core.test.ts
@@ -88,7 +88,15 @@ describe("planNextLiveChunk", () => {
manifest: {
...baseManifest,
// segment 3 missing: only 1..2 may be considered
- audio_segments: [seg(1), seg(2), seg(4), seg(5), seg(6), seg(7), seg(8)],
+ audio_segments: [
+ seg(1),
+ seg(2),
+ seg(4),
+ seg(5),
+ seg(6),
+ seg(7),
+ seg(8),
+ ],
is_complete: true,
},
lastProcessedIndex: 0,
@@ -104,6 +112,26 @@ describe("planNextLiveChunk", () => {
}
});
+ it("transcribes segment 0 of a 0-based manifest from the fresh-cursor sentinel", () => {
+ const decision = planNextLiveChunk({
+ manifest: {
+ ...baseManifest,
+ audio_segments: [seg(0), seg(1), seg(2)],
+ is_complete: true,
+ },
+ lastProcessedIndex: -1,
+ targetSeconds: 15,
+ });
+ expect(decision).toMatchObject({
+ action: "chunk",
+ startMs: 0,
+ durationMs: 6000,
+ });
+ if (decision.action === "chunk") {
+ expect(decision.entries.map((entry) => entry.index)).toEqual([0, 1, 2]);
+ }
+ });
+
it("finishes when a completed manifest has nothing contiguous left", () => {
expect(
planNextLiveChunk({
@@ -174,11 +202,7 @@ describe("live transcript artifact", () => {
startMs: 0,
durationMs: 4000,
lastAudioSegmentIndex: 2,
- words: offsetChunkWords(
- [{ text: "First", start: 0, end: 900 }],
- 0,
- 4000,
- ),
+ words: offsetChunkWords([{ text: "First", start: 0, end: 900 }], 0, 4000),
languageCode: "en",
nowIso: "2026-08-03T00:00:05.000Z",
});
diff --git a/apps/web/__tests__/unit/segments-audio.test.ts b/apps/web/__tests__/unit/segments-audio.test.ts
index ab3759184..e7e9f51fe 100644
--- a/apps/web/__tests__/unit/segments-audio.test.ts
+++ b/apps/web/__tests__/unit/segments-audio.test.ts
@@ -53,7 +53,12 @@ describe("planSegmentsAudioExtraction", () => {
const plan = planSegmentsAudioExtraction({
...completeManifest,
// bare numbers use the 3.0s fallback duration, matching /api/playlist
- audio_segments: [{ index: 2, duration: 1.5 }, 3, { index: 2, duration: 9 }, 1],
+ audio_segments: [
+ { index: 2, duration: 1.5 },
+ 3,
+ { index: 2, duration: 9 },
+ 1,
+ ],
});
expect(plan).toEqual({
diff --git a/apps/web/actions/videos/get-live-transcript.ts b/apps/web/actions/videos/get-live-transcript.ts
index 493d76e50..6e0792bad 100644
--- a/apps/web/actions/videos/get-live-transcript.ts
+++ b/apps/web/actions/videos/get-live-transcript.ts
@@ -21,6 +21,8 @@ export type GetLiveTranscriptResult = {
content?: string;
state?: LiveTranscriptState;
updatedAt?: string;
+ /** Nothing will ever become available for this caller — stop polling. */
+ stop?: boolean;
};
/**
@@ -44,18 +46,29 @@ export async function getLiveTranscript(
}).pipe(provideOptionalAuth, EffectRuntime.runPromiseExit);
if (Exit.isFailure(exit)) {
- return { success: false, message: "Video not found" };
+ return { success: false, stop: true, message: "Video not found" };
}
const video = exit.value[0]?.video;
if (!video) {
- return { success: false, message: "Video not found" };
+ return { success: false, stop: true, message: "Video not found" };
}
- // Once the canonical transcript exists the live one is superseded (and
- // normally already deleted); send clients to getTranscript instead.
+ // Once the canonical transcription resolved — successfully or not — the
+ // live transcript is superseded; polling can never produce anything new.
if (video.transcriptionStatus === "COMPLETE") {
- return { success: false, message: "Transcript is ready" };
+ return { success: false, stop: true, message: "Transcript is ready" };
+ }
+ if (
+ video.transcriptionStatus === "ERROR" ||
+ video.transcriptionStatus === "SKIPPED" ||
+ video.transcriptionStatus === "NO_AUDIO"
+ ) {
+ return {
+ success: false,
+ stop: true,
+ message: "Transcript is not available",
+ };
}
try {
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index ec2223bd2..2db9602e7 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -19,6 +19,7 @@ import { zValidator } from "@hono/zod-validator";
import { and, count, eq, lte } from "drizzle-orm";
import { Effect, Option } from "effect";
import { Hono } from "hono";
+import { after } from "next/server";
import { z } from "zod";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import { maybeStartLiveTranscription } from "@/lib/live-transcribe";
@@ -153,11 +154,15 @@ app.get(
!video.isScreenshot &&
!isScreenshot
) {
- await maybeStartLiveTranscription({
- videoId: video.id,
- ownerId: user.id,
- orgId: video.orgId,
- });
+ // Off the response path: this endpoint gates recording start on
+ // the desktop, so workflow dispatch must never delay it.
+ after(() =>
+ maybeStartLiveTranscription({
+ videoId: video.id,
+ ownerId: user.id,
+ orgId: video.orgId,
+ }),
+ );
}
return c.json({
@@ -326,11 +331,15 @@ app.get(
});
if (recordingMode === "desktopSegments" && !isScreenshot) {
- await maybeStartLiveTranscription({
- videoId: idToUse,
- ownerId: user.id,
- orgId: videoOrgId,
- });
+ // Off the response path: this endpoint gates recording start on the
+ // desktop, so workflow dispatch must never delay it.
+ after(() =>
+ maybeStartLiveTranscription({
+ videoId: idToUse,
+ ownerId: user.id,
+ orgId: videoOrgId,
+ }),
+ );
}
try {
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index 7020cf4c1..da5d7c1fb 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -235,16 +235,21 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
const isLiveTranscriptEnabled =
data.source?.type === "desktopSegments" &&
data.metadata?.liveTranscript != null &&
- data.transcriptionStatus !== "COMPLETE";
+ // Only while the canonical transcription is unresolved; terminal states
+ // (COMPLETE, ERROR, SKIPPED, NO_AUDIO) can never produce live content.
+ (data.transcriptionStatus == null ||
+ data.transcriptionStatus === "PROCESSING");
const { data: liveTranscript } = useLiveTranscript(
data.id,
isLiveTranscriptEnabled,
);
+ const liveTranscriptContent =
+ liveTranscript?.kind === "ready" ? liveTranscript.content : null;
const liveTranscriptData = useMemo(
- () => (liveTranscript?.content ? parseVTT(liveTranscript.content) : []),
- [liveTranscript?.content],
+ () => (liveTranscriptContent ? parseVTT(liveTranscriptContent) : []),
+ [liveTranscriptContent],
);
const showLiveTranscript =
@@ -501,7 +506,8 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
if (isTranscriptionProcessing && !hasTimedOut) {
if (showLiveTranscript) {
- const isLiveActive = liveTranscript?.state === "active";
+ const isLiveActive =
+ liveTranscript?.kind === "ready" && liveTranscript.state === "active";
return (
<div className="flex flex-col h-full">
diff --git a/apps/web/hooks/use-live-transcript.ts b/apps/web/hooks/use-live-transcript.ts
index 04f909267..1d8bcac99 100644
--- a/apps/web/hooks/use-live-transcript.ts
+++ b/apps/web/hooks/use-live-transcript.ts
@@ -3,11 +3,17 @@ import { useQuery } from "@tanstack/react-query";
import { getLiveTranscript } from "@/actions/videos/get-live-transcript";
import type { LiveTranscriptState } from "@/lib/live-transcribe-core";
-export interface LiveTranscriptData {
- content: string;
- state: LiveTranscriptState;
- updatedAt?: string;
-}
+export type LiveTranscriptData =
+ | {
+ kind: "ready";
+ content: string;
+ state: LiveTranscriptState;
+ updatedAt?: string;
+ }
+ /** No artifact yet — the first chunk hasn't landed; keep polling. */
+ | { kind: "pending" }
+ /** The server said nothing will ever appear for us — stop polling. */
+ | { kind: "stopped" };
/** Live transcription is still appending; poll often enough to feel live. */
const ACTIVE_POLL_INTERVAL = 5000;
@@ -24,12 +30,14 @@ const SETTLED_POLL_INTERVAL = 15000;
export const useLiveTranscript = (videoId: Video.VideoId, enabled: boolean) => {
return useQuery({
queryKey: ["liveTranscript", videoId],
- queryFn: async (): Promise<LiveTranscriptData | null> => {
+ queryFn: async (): Promise<LiveTranscriptData> => {
const result = await getLiveTranscript(videoId);
- if (!result.success || !result.content) return null;
+ if (result.stop) return { kind: "stopped" };
+ if (!result.success || !result.content) return { kind: "pending" };
return {
+ kind: "ready",
content: result.content,
state: result.state ?? "active",
updatedAt: result.updatedAt,
@@ -37,10 +45,12 @@ export const useLiveTranscript = (videoId: Video.VideoId, enabled: boolean) => {
},
enabled,
refetchInterval: (query) => {
- const state = query.state.data?.state;
- return state === "complete" || state === "stopped"
- ? SETTLED_POLL_INTERVAL
- : ACTIVE_POLL_INTERVAL;
+ const data = query.state.data;
+ if (data?.kind === "stopped") return false;
+ if (data?.kind === "ready" && data.state !== "active") {
+ return SETTLED_POLL_INTERVAL;
+ }
+ return ACTIVE_POLL_INTERVAL;
},
refetchIntervalInBackground: false,
staleTime: 0,
diff --git a/apps/web/lib/live-transcribe-core.ts b/apps/web/lib/live-transcribe-core.ts
index e23096df9..bba28632e 100644
--- a/apps/web/lib/live-transcribe-core.ts
+++ b/apps/web/lib/live-transcribe-core.ts
@@ -180,6 +180,10 @@ export function getLiveTranscriptObjectKey(ownerId: string, videoId: string) {
return `${ownerId}/${videoId}/transcription.live.json`;
}
+/** Sentinel for "nothing processed yet": 0 is a legitimate segment index in
+ * 0-based manifests, so the cursor starts below every real index. */
+export const LIVE_TRANSCRIPT_NO_SEGMENTS = -1;
+
export function createEmptyLiveTranscript(
nowIso: string,
): LiveTranscriptArtifact {
@@ -187,7 +191,7 @@ export function createEmptyLiveTranscript(
version: LIVE_TRANSCRIPT_VERSION,
state: "active",
languageCode: null,
- lastAudioSegmentIndex: 0,
+ lastAudioSegmentIndex: LIVE_TRANSCRIPT_NO_SEGMENTS,
transcribedDurationMs: 0,
words: [],
vtt: editTranscriptWordsToCaptionVtt([]),
diff --git a/apps/web/lib/segments-audio-download.ts b/apps/web/lib/segments-audio-download.ts
index 064a310c4..ec3c19996 100644
--- a/apps/web/lib/segments-audio-download.ts
+++ b/apps/web/lib/segments-audio-download.ts
@@ -6,8 +6,12 @@ import { createWriteStream } from "node:fs";
* Node.js modules in) can import the planners; only step code imports this.
*/
-/** Segment fetches beyond this are almost certainly a bug, not a recording. */
-const MAX_SEGMENTS_AUDIO_BYTES = 1_536 * 1024 * 1024;
+/**
+ * Sized so concat fMP4 + extracted mp3 both fit a 512MB serverless /tmp with
+ * headroom (~2h of 192kbps AAC). Beyond it the caller gets a clean
+ * "unavailable" and defers to the post-mux path instead of ENOSPC/OOM.
+ */
+const MAX_SEGMENTS_AUDIO_BYTES = 192 * 1024 * 1024;
const DEFAULT_DOWNLOAD_CONCURRENCY = 8;
diff --git a/apps/web/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.ts
index 6720fdb42..df3b4a45f 100644
--- a/apps/web/workflows/live-transcribe.ts
+++ b/apps/web/workflows/live-transcribe.ts
@@ -24,6 +24,7 @@ import {
createEmptyLiveTranscript,
getLiveTranscriptObjectKey,
LIVE_TRANSCRIBE,
+ LIVE_TRANSCRIPT_NO_SEGMENTS,
type LiveTranscriptState,
offsetChunkWords,
parseLiveTranscript,
@@ -195,7 +196,7 @@ async function initLiveTranscription(
// Resume from a previous run's artifact after a crash/redeploy so already
// paid-for chunks are never re-transcribed.
- let lastAudioSegmentIndex = 0;
+ let lastAudioSegmentIndex = LIVE_TRANSCRIPT_NO_SEGMENTS;
let transcribedDurationMs = 0;
let languageCode: string | null = null;
try {
@@ -400,6 +401,21 @@ async function processNextLiveChunk(options: {
nowIso: new Date().toISOString(),
});
+ // Polling + the AssemblyAI round trip can take minutes; re-check that the
+ // canonical pipeline didn't complete meanwhile, or this write would
+ // re-create the artifact it just deleted (an orphan billed forever).
+ const [current] = await db()
+ .select({ transcriptionStatus: videos.transcriptionStatus })
+ .from(videos)
+ .where(eq(videos.id, videoId as Video.VideoId));
+ if (
+ current?.transcriptionStatus === "COMPLETE" ||
+ current?.transcriptionStatus === "SKIPPED" ||
+ current?.transcriptionStatus === "NO_AUDIO"
+ ) {
+ return { outcome: "canonical-done" };
+ }
+
const body = JSON.stringify(updated);
await bucket
.putObject(artifactKey, body, { contentType: "application/json" })
diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.ts
index e975bb096..1452d7d9e 100644
--- a/apps/web/workflows/transcribe.ts
+++ b/apps/web/workflows/transcribe.ts
@@ -18,9 +18,10 @@ import {
Video,
} from "@cap/web-domain";
import { AssemblyAI } from "assemblyai";
-import { and, eq, sql } from "drizzle-orm";
+import { and, eq, isNull, sql } from "drizzle-orm";
import { Either, Option, Schema } from "effect";
import { FatalError } from "workflow";
+import { start } from "workflow/api";
import { getAssemblyAITranscriptionOptions } from "@/lib/assemblyai";
import {
ENHANCED_AUDIO_CONTENT_TYPE,
@@ -120,10 +121,14 @@ export async function transcribeVideoWorkflow(
}
if (segments.status !== "ok" || !segments.audioUrl) {
- // Give the claim back so the normal post-mux queue re-triggers; the
- // worst case of the early path must be today's timing, not an ERROR.
- await deferEarlyTranscription(videoId);
+ // The early path must never end worse than today's timing: clean up
+ // while we still hold the claim, release it, then explicitly re-offer
+ // the video to the normal path — the post-mux queue may have already
+ // run and been rejected by our claim, so we cannot rely on it firing
+ // again.
await cleanupTempAudio(videoId, userId, videoData.video);
+ await deferEarlyTranscription(videoId);
+ await requeueAfterEarlyDefer(videoId, userId, aiGenerationEnabled);
return {
success: true,
message: `Early transcription deferred: ${
@@ -338,6 +343,33 @@ async function validateEditTranscriptBackfill(
return video;
}
+/**
+ * Every terminal transcription outcome must clear the live-transcription
+ * metadata flag, or share pages keep polling for a live transcript that can
+ * never resolve. Guarded so videos without the flag see a 0-row update.
+ */
+async function clearLiveTranscriptFlag(videoId: string): Promise<void> {
+ try {
+ await db()
+ .update(videos)
+ .set({
+ metadata: sql`JSON_REMOVE(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript')`,
+ updatedAt: sql`${videos.updatedAt}`,
+ })
+ .where(
+ and(
+ eq(videos.id, videoId as Video.VideoId),
+ sql`JSON_EXTRACT(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript') IS NOT NULL`,
+ ),
+ );
+ } catch (error) {
+ console.warn(
+ `[transcribe] Failed to clear live transcript flag for ${videoId}`,
+ error,
+ );
+ }
+}
+
async function markSkipped(videoId: string): Promise<void> {
"use step";
@@ -345,6 +377,7 @@ async function markSkipped(videoId: string): Promise<void> {
.update(videos)
.set({ transcriptionStatus: "SKIPPED" })
.where(eq(videos.id, videoId as Video.VideoId));
+ await clearLiveTranscriptFlag(videoId);
}
async function markNoAudio(videoId: string): Promise<void> {
@@ -354,6 +387,7 @@ async function markNoAudio(videoId: string): Promise<void> {
.update(videos)
.set({ transcriptionStatus: "NO_AUDIO" })
.where(eq(videos.id, videoId as Video.VideoId));
+ await clearLiveTranscriptFlag(videoId);
}
async function markError(videoId: string): Promise<void> {
@@ -368,6 +402,7 @@ async function markError(videoId: string): Promise<void> {
eq(videos.transcriptionStatus, "PROCESSING"),
),
);
+ await clearLiveTranscriptFlag(videoId);
}
async function deferEarlyTranscription(videoId: string): Promise<void> {
@@ -384,6 +419,61 @@ async function deferEarlyTranscription(videoId: string): Promise<void> {
);
}
+/**
+ * After an early-path deferral, put the video back on the normal
+ * transcription path. Mirrors lib/transcribe.ts semantics without importing
+ * it (that would be a module cycle): no-op while the mux still owns the
+ * upload row — its completion queues transcription — otherwise claim and
+ * start a normal (non-early) workflow right away.
+ */
+async function requeueAfterEarlyDefer(
+ videoId: string,
+ userId: string,
+ aiGenerationEnabled: boolean,
+): Promise<void> {
+ "use step";
+
+ const upload = await db()
+ .select({ phase: videoUploads.phase })
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId))
+ .limit(1);
+
+ if (
+ upload[0]?.phase === "uploading" ||
+ upload[0]?.phase === "processing" ||
+ upload[0]?.phase === "generating_thumbnail"
+ ) {
+ return;
+ }
+
+ const claim = await db()
+ .update(videos)
+ .set({ transcriptionStatus: "PROCESSING" })
+ .where(
+ and(
+ eq(videos.id, videoId as Video.VideoId),
+ isNull(videos.transcriptionStatus),
+ ),
+ );
+ const affectedRows = Array.isArray(claim)
+ ? ((claim[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0)
+ : ((claim as { affectedRows?: number } | undefined)?.affectedRows ?? 0);
+ if (affectedRows === 0) return;
+
+ try {
+ await start(transcribeVideoWorkflow, [
+ { videoId, userId, aiGenerationEnabled },
+ ]);
+ } catch (error) {
+ await db()
+ .update(videos)
+ .set({ transcriptionStatus: null })
+ .where(eq(videos.id, videoId as Video.VideoId));
+ throw error;
+ }
+}
+
async function extractAudio(
videoId: string,
userId: string,
@@ -812,19 +902,13 @@ async function saveTranscription(
await bucket
.deleteObject(getLiveTranscriptObjectKey(userId, videoId))
.pipe(runWorkflowPromise);
- await db()
- .update(videos)
- .set({
- metadata: sql`JSON_REMOVE(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript')`,
- updatedAt: sql`${videos.updatedAt}`,
- })
- .where(eq(videos.id, videoId as Video.VideoId));
} catch (error) {
console.warn(
`[transcribe] Failed to clean up live transcript for ${videoId}`,
error,
);
}
+ await clearLiveTranscriptFlag(videoId);
}
}