Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): stop the post-mux queue racing live promotion on short videos
Richie McIlroyac6c436260ce
diff --git a/apps/web/__tests__/integration/transcribe.test.ts b/apps/web/__tests__/integration/transcribe.test.tsindex d63784a6f..79cd1edae 100644--- a/apps/web/__tests__/integration/transcribe.test.ts+++ b/apps/web/__tests__/integration/transcribe.test.ts@@ -152,6 +152,65 @@ describe("transcribeVideo", () => {});describe("transcription disabled scenarios", () => {+ it("defers to a provably fresh live transcription instead of racing it", async () => {+ mockQueryResult = [+ {+ video: {+ id: "video-123",+ transcriptionStatus: null,+ settings: null,+ metadata: {+ liveTranscript: {+ status: "active",+ updatedAt: new Date().toISOString(),+ },+ },+ },+ bucket: null,+ settings: null,+ orgSettings: null,+ },+ ];++ const result = await transcribeVideo(+ "video-123" as Video.VideoId,+ "user-456",+ );++ expect(result.success).toBe(true);+ expect(result.message).toContain("Live transcription in progress");+ expect(mockStart).not.toHaveBeenCalled();+ });++ it("ignores a stale live claim so a dead workflow can never block transcription", async () => {+ mockQueryResult = [+ {+ video: {+ id: "video-123",+ transcriptionStatus: null,+ settings: null,+ metadata: {+ liveTranscript: {+ status: "active",+ updatedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),+ },+ },+ },+ bucket: null,+ settings: null,+ orgSettings: null,+ },+ ];++ const result = await transcribeVideo(+ "video-123" as Video.VideoId,+ "user-456",+ );++ expect(result.success).toBe(true);+ expect(mockStart).toHaveBeenCalledTimes(1);+ });+it("skips transcription when video settings disable it", async () => {mockQueryResult = [{diff --git a/apps/web/lib/transcribe.ts b/apps/web/lib/transcribe.tsindex 94ecde9cd..7455f1c80 100644--- a/apps/web/lib/transcribe.ts+++ b/apps/web/lib/transcribe.ts@@ -25,6 +25,11 @@ export type TranscribeVideoOptions = {const TRANSCRIPTION_ALREADY_HANDLED_MESSAGE ="Transcription already completed, in progress, or awaiting manual retry";+/** How recently a live-transcription claim must have been stamped to defer+ * to it. Chunks stamp every ~10s; 3 minutes tolerates long retries without+ * letting a dead workflow block transcription forever. */+const LIVE_CLAIM_FRESHNESS_MS = 3 * 60 * 1000;+const getAffectedRows = (result: unknown) => {if (Array.isArray(result)) {return (@@ -118,6 +123,27 @@ export async function transcribeVideo(};}+ // A live transcription that is provably still running (its claim is+ // freshness-stamped every chunk) is seconds away from promoting itself to+ // canonical; claiming now would race it and transcribe the same audio+ // twice. A stale stamp means the workflow died - proceed normally. The+ // live workflow's own full-pass fallback uses earlyFromSegments, which is+ // exempt so it can never deadlock against its opener.+ if (!options.earlyFromSegments) {+ const live = video.metadata?.liveTranscript;+ const stampedAt = live?.updatedAt ? Date.parse(live.updatedAt) : Number.NaN;+ if (+ live?.status === "active" &&+ Number.isFinite(stampedAt) &&+ Date.now() - stampedAt < LIVE_CLAIM_FRESHNESS_MS+ ) {+ return {+ success: true,+ message: "Live transcription in progress",+ };+ }+ }+if (!options.earlyFromSegments) {const upload = await db().select({ phase: videoUploads.phase })diff --git a/apps/web/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.tsindex bc185e06f..04cab1044 100644--- a/apps/web/workflows/live-transcribe.ts+++ b/apps/web/workflows/live-transcribe.ts@@ -63,6 +63,10 @@ type ChunkStepResult =lastAudioSegmentIndex: number;transcribedDurationMs: number;languageCode: string | null;+ /** This chunk was the recording's final one: the manifest is complete+ * and coverage is now full, so promotion can start immediately+ * without another poll round-trip. */+ recordingComplete?: boolean;}| { outcome: "chunk-failed"; failedAtIndex: number; reason: string }| { outcome: "waiting" }@@ -138,6 +142,10 @@ export async function liveTranscribeWorkflow(chunkCount++;idleSteps = 0;failuresAtIndex = 0;+ if (result.recordingComplete) {+ outcome = "done";+ break;+ }continue;}@@ -309,6 +317,7 @@ async function processNextLiveChunk(options: {// time costs one held invocation, not hundreds of queued step dispatches.const pollDeadline = Date.now() + LIVE_TRANSCRIBE.MAX_POLL_MS_PER_STEP;let decision: ReturnType<typeof planNextLiveChunk> | null = null;+ let decodedManifest: Video.SegmentManifestType | null = null;while (Date.now() < pollDeadline) {const manifestContent = await bucket@@ -334,6 +343,7 @@ async function processNextLiveChunk(options: {});if (next.action !== "wait") {decision = next;+ decodedManifest = decoded.right;break;}}@@ -396,6 +406,7 @@ async function processNextLiveChunk(options: {}`,};}+ await touchLiveClaim(videoId);return {outcome: "chunk",lastAudioSegmentIndex: chunkEndIndex,@@ -490,6 +501,21 @@ async function processNextLiveChunk(options: {.putObject(artifactKey, body, { contentType: "application/json" }).pipe(runWorkflowPromise);+ // Freshness-stamp the claim so other transcription triggers (post-mux+ // webhook, share-page retries) keep deferring to this workflow.+ await touchLiveClaim(videoId);++ // If this chunk completed full coverage of a finished recording, tell+ // the workflow to promote right away instead of paying another poll+ // round-trip - this latency is the stop-to-final-transcript feel.+ const next = decodedManifest+ ? planNextLiveChunk({+ manifest: decodedManifest,+ lastProcessedIndex: chunkEndIndex,+ targetSeconds,+ })+ : ({ action: "wait" } as const);+console.log(`[liveTranscribe] ${videoId} chunk ${lastProcessedIndex + 1}..${chunkEndIndex} (${decision.durationMs}ms, ${words.length} words)`,);@@ -499,6 +525,7 @@ async function processNextLiveChunk(options: {lastAudioSegmentIndex: chunkEndIndex,transcribedDurationMs: updated.transcribedDurationMs,languageCode: updated.languageCode,+ recordingComplete: next.action === "done",};} catch (error) {const reason = error instanceof Error ? error.message : String(error);@@ -513,6 +540,33 @@ async function processNextLiveChunk(options: {}}+/**+ * Re-stamp the live claim's freshness so other transcription triggers keep+ * deferring to this workflow (lib/transcribe.ts checks the stamp age). A+ * no-op once the claim was cleared or finished.+ */+async function touchLiveClaim(videoId: string): Promise<void> {+ try {+ await db()+ .update(videos)+ .set({+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript.updatedAt', ${new Date().toISOString()})`,+ updatedAt: sql`${videos.updatedAt}`,+ })+ .where(+ and(+ eq(videos.id, videoId as Video.VideoId),+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.liveTranscript.status')) = 'active'`,+ ),+ );+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to stamp live claim for ${videoId}`,+ error,+ );+ }+}+type PromotionResult = { promoted: boolean; reason?: string };/**