Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): promote live transcript to canonical, halving transcription cost
Richie McIlroy6e05008a12a1
diff --git a/apps/web/__tests__/unit/desktop-video-create.test.ts b/apps/web/__tests__/unit/desktop-video-create.test.tsindex 135421d0d..26b316743 100644--- a/apps/web/__tests__/unit/desktop-video-create.test.ts+++ b/apps/web/__tests__/unit/desktop-video-create.test.ts@@ -78,6 +78,12 @@ vi.mock("@/lib/google-drive-storage-quota", () => ({invalidateGoogleDriveStorageQuotaCache: vi.fn(),}));+// The live-transcription stack drags in the whole workflow graph+// (server-only modules included); these tests only care that create works.+vi.mock("@/lib/live-transcribe", () => ({+ maybeStartLiveTranscription: vi.fn(async () => "skipped"),+}));+vi.mock("drizzle-orm", () => ({and: vi.fn((...args: unknown[]) => args),eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),diff --git a/apps/web/__tests__/unit/live-transcribe-core.test.ts b/apps/web/__tests__/unit/live-transcribe-core.test.tsindex 89ea39ea0..383f60ffa 100644--- a/apps/web/__tests__/unit/live-transcribe-core.test.ts+++ b/apps/web/__tests__/unit/live-transcribe-core.test.ts@@ -1,8 +1,10 @@import { describe, expect, it } from "vitest";import {applyChunkToLiveTranscript,+ canPromoteLiveTranscript,createEmptyLiveTranscript,isNoSpokenAudioError,+ liveTranscriptToEditTranscript,offsetChunkWords,parseLiveTranscript,planNextLiveChunk,@@ -246,6 +248,95 @@ describe("live transcript artifact", () => {});});+describe("canPromoteLiveTranscript", () => {+ const fullCoverage = (overrides = {}) => ({+ ...createEmptyLiveTranscript("2026-08-03T00:00:00.000Z"),+ lastAudioSegmentIndex: 3,+ transcribedDurationMs: 6000,+ ...overrides,+ });+ const completeManifest = {+ ...baseManifest,+ audio_segments: [seg(1), seg(2), seg(3)],+ is_complete: true,+ };++ it("promotes only full gap-free coverage", () => {+ expect(canPromoteLiveTranscript(fullCoverage(), completeManifest)).toEqual({+ ok: true,+ });+ });++ it("declines incomplete manifests, partial coverage, and skipped chunks", () => {+ expect(+ canPromoteLiveTranscript(fullCoverage(), {+ ...completeManifest,+ is_complete: false,+ }).ok,+ ).toBe(false);+ expect(+ canPromoteLiveTranscript(+ fullCoverage({ lastAudioSegmentIndex: 2 }),+ completeManifest,+ ).ok,+ ).toBe(false);+ expect(+ canPromoteLiveTranscript(+ fullCoverage({ hasGaps: true }),+ completeManifest,+ ).ok,+ ).toBe(false);+ });++ it("declines manifests with segment index gaps", () => {+ expect(+ canPromoteLiveTranscript(fullCoverage({ lastAudioSegmentIndex: 4 }), {+ ...completeManifest,+ audio_segments: [seg(1), seg(2), seg(4)],+ }).ok,+ ).toBe(false);+ });++ it("declines recordings with no audio", () => {+ expect(+ canPromoteLiveTranscript(fullCoverage(), {+ ...completeManifest,+ audio_segments: [],+ }).ok,+ ).toBe(false);+ });+});++describe("liveTranscriptToEditTranscript", () => {+ it("shapes accumulated words as a canonical v3 edit transcript", () => {+ const artifact = applyChunkToLiveTranscript(+ createEmptyLiveTranscript("2026-08-03T00:00:00.000Z"),+ {+ startMs: 0,+ durationMs: 4000,+ lastAudioSegmentIndex: 2,+ words: offsetChunkWords(+ [{ text: "Hello", start: 10, end: 500 }],+ 0,+ 4000,+ ),+ languageCode: "en",+ nowIso: "2026-08-03T00:00:05.000Z",+ },+ );++ const edit = liveTranscriptToEditTranscript(artifact, "universal-3-5-pro");+ expect(edit).toMatchObject({+ version: 3,+ speechModelUsed: "universal-3-5-pro",+ durationMs: 4000,+ languageCode: "en",+ });+ expect(edit.words).toHaveLength(1);+ expect(edit.words[0]).toMatchObject({ text: "Hello", startMs: 10 });+ });+});+describe("isNoSpokenAudioError", () => {it("recognizes speech-free chunks as valid empties, not failures", () => {// exact message observed from the real API on a silent recordingdiff --git a/apps/web/lib/desktop-segments-finalization.ts b/apps/web/lib/desktop-segments-finalization.tsindex 3db75ec03..8481675ee 100644--- a/apps/web/lib/desktop-segments-finalization.ts+++ b/apps/web/lib/desktop-segments-finalization.ts@@ -1,5 +1,5 @@import { db } from "@cap/database";-import { users, videoUploads } from "@cap/database/schema";+import { users, videos, videoUploads } from "@cap/database/schema";import type { User, Video } from "@cap/web-domain";import { and, eq, notInArray } from "drizzle-orm";import { start } from "workflow/api";@@ -30,6 +30,20 @@ async function queueEarlySegmentsTranscription({videoId: Video.VideoId;userId: User.UserId;}): Promise<void> {+ // An active live transcription is seconds away from promoting itself to+ // canonical (or queueing this exact fallback itself); starting a full+ // pass now would pay for the same audio twice.+ const [video] = await db()+ .select({ metadata: videos.metadata })+ .from(videos)+ .where(eq(videos.id, videoId));+ if (video?.metadata?.liveTranscript?.status === "active") {+ console.log(+ `[queueEarlySegmentsTranscription] Live transcription active for ${videoId}; deferring to promotion`,+ );+ return;+ }+const [owner] = await db().select({email: users.email,diff --git a/apps/web/lib/live-transcribe-core.ts b/apps/web/lib/live-transcribe-core.tsindex fa59a3f9b..f83dd7402 100644--- a/apps/web/lib/live-transcribe-core.ts+++ b/apps/web/lib/live-transcribe-core.ts@@ -1,5 +1,7 @@import type { Video } from "@cap/web-domain";import {+ EDIT_TRANSCRIPT_VERSION,+ type EditTranscript,type EditTranscriptWord,editTranscriptWordsToCaptionVtt,} from "@/lib/edit-transcript";@@ -191,6 +193,10 @@ export interface LiveTranscriptArtifact {words: EditTranscriptWord[];vtt: string;updatedAt: string;+ /** A chunk was skipped after repeated failures, so some speech is missing.+ * Disqualifies the artifact from being promoted to the canonical+ * transcript; the full-pass fallback covers the recording instead. */+ hasGaps?: boolean;}export function getLiveTranscriptObjectKey(ownerId: string, videoId: string) {@@ -213,6 +219,7 @@ export function createEmptyLiveTranscript(words: [],vtt: editTranscriptWordsToCaptionVtt([]),updatedAt: nowIso,+ hasGaps: false,};}@@ -243,12 +250,76 @@ export function parseLiveTranscript(words: parsed.words,vtt: parsed.vtt,updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",+ hasGaps: parsed.hasGaps === true,};} catch {return null;}}+/**+ * Whether the live transcript fully and faithfully covers the recording, so+ * it can be promoted to the canonical transcript instead of paying for a+ * second full transcription pass. Anything short of complete gap-free+ * coverage means the full-pass fallback runs exactly as before.+ */+export function canPromoteLiveTranscript(+ artifact: LiveTranscriptArtifact,+ manifest: Video.SegmentManifestType,+): { ok: true } | { ok: false; reason: string } {+ if (!manifest.is_complete) {+ return { ok: false, reason: "manifest is not complete" };+ }+ if (artifact.hasGaps) {+ return { ok: false, reason: "live transcript has skipped chunks" };+ }++ const plan = planSegmentsAudioExtraction(manifest);+ if (plan.status === "no-audio") {+ return { ok: false, reason: "recording has no audio" };+ }+ if (plan.status !== "ok") {+ return { ok: false, reason: plan.reason };+ }++ const lastIndex = plan.entries[plan.entries.length - 1]?.index;+ if (lastIndex === undefined || artifact.lastAudioSegmentIndex !== lastIndex) {+ return {+ ok: false,+ reason: `covered up to segment ${artifact.lastAudioSegmentIndex} of ${lastIndex}`,+ };+ }++ // A manifest index gap means audio the recording had but we never saw.+ let expected = plan.entries[0]?.index ?? 1;+ for (const entry of plan.entries) {+ if (entry.index !== expected) {+ return { ok: false, reason: `segment gap at index ${expected}` };+ }+ expected++;+ }++ return { ok: true };+}++/**+ * Shape the accumulated live words as a canonical edit transcript (v3). The+ * caption VTT derives from the same words via editTranscriptWordsToCaptionVtt,+ * exactly as the full-pass path does.+ */+export function liveTranscriptToEditTranscript(+ artifact: LiveTranscriptArtifact,+ speechModelUsed: string,+): EditTranscript {+ return {+ version: EDIT_TRANSCRIPT_VERSION,+ speechModelUsed,+ durationMs: Math.max(0, Math.round(artifact.transcribedDurationMs)),+ languageCode: artifact.languageCode,+ words: artifact.words,+ };+}+/*** Merge one transcribed chunk into the artifact. Idempotent per chunk range:* a retried chunk first evicts any words at or after its start.diff --git a/apps/web/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.tsindex 9bfe49303..1fb55caa0 100644--- a/apps/web/workflows/live-transcribe.ts+++ b/apps/web/workflows/live-transcribe.ts@@ -3,35 +3,47 @@ import { promises as fs } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { db } from "@cap/database";-import { organizations, videos } from "@cap/database/schema";+import { organizations, users, videoEdits, videos } from "@cap/database/schema";import { serverEnv } from "@cap/env";import { Storage } from "@cap/web-backend/src/Storage/index";import {type AiGenerationLanguage,parseAiGenerationLanguage,+ type User,Video,} from "@cap/web-domain";import { AssemblyAI } from "assemblyai";-import { eq, sql } from "drizzle-orm";+import { and, eq, isNull, sql } from "drizzle-orm";import { Either, Option, Schema } from "effect";+import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";import {+ ASSEMBLYAI_SPEECH_MODELS,ASSEMBLYAI_SUPPORTED_LANGUAGES,getAssemblyAITranscriptionOptions,} from "@/lib/assemblyai";import { extractAudioFromUrl } from "@/lib/audio-extract";+import {+ getEditTranscriptObjectKey,+ serializeEditTranscript,+} from "@/lib/edit-transcript";+import { encryptEditTranscriptObject } from "@/lib/edit-transcript-storage";+import { startAiGeneration } from "@/lib/generate-ai";import {applyChunkToLiveTranscript,+ canPromoteLiveTranscript,createEmptyLiveTranscript,getLiveTranscriptObjectKey,isNoSpokenAudioError,LIVE_TRANSCRIBE,LIVE_TRANSCRIPT_NO_SEGMENTS,+ liveTranscriptToEditTranscript,type LiveTranscriptState,offsetChunkWords,parseLiveTranscript,planNextLiveChunk,} from "@/lib/live-transcribe-core";import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";+import { transcribeVideo } from "@/lib/transcribe";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -65,12 +77,16 @@ type ChunkStepResult =| { outcome: "gone" };/**- * Provisional live transcription for an instant-mode recording. Polls the- * segment manifest the desktop app continuously re-uploads, transcribes new- * audio in chunks, and maintains `transcription.live.json` for the share- * page. Never touches `videos.transcriptionStatus` or any canonical- * transcription artifact: the post-stop pipeline stays the single source of- * truth and replaces this artifact entirely.+ * Live transcription for an instant-mode recording. Polls the segment+ * manifest the desktop app continuously re-uploads, transcribes new audio in+ * chunks, and maintains `transcription.live.json` for the share page.+ *+ * While recording, this never touches `videos.transcriptionStatus` or any+ * canonical artifact. At completion, IF the chunks cover the whole recording+ * gap-free, promoteLiveTranscript claims the canonical slot atomically and+ * writes the canonical transcript from the accumulated words — skipping the+ * duplicate full transcription pass. Anything less than perfect coverage+ * falls back to the normal full-pass pipeline unchanged.*/export async function liveTranscribeWorkflow(payload: LiveTranscribeWorkflowPayload,@@ -132,6 +148,12 @@ export async function liveTranscribeWorkflow(if (result.outcome === "chunk-failed") {failuresAtIndex++;+ // Skip attempts also count here; if even recording the gap keeps+ // failing, storage is degraded — stop rather than spin.+ if (failuresAtIndex >= LIVE_TRANSCRIBE.MAX_CHUNK_ATTEMPTS * 3) {+ outcome = "chunk-abandoned";+ break;+ }continue;}@@ -154,6 +176,22 @@ export async function liveTranscribeWorkflow(throw error;}+ if (outcome === "done") {+ // Full gap-free coverage: promote the live transcript to canonical and+ // skip the duplicate full transcription pass entirely. On any failure+ // the full-pass fallback is queued so transcription still lands fast.+ const promotion = await promoteLiveTranscript(videoId, userId);+ if (promotion.promoted) {+ return {+ success: true,+ message: "Live transcription promoted to canonical",+ };+ }+ console.warn(+ `[liveTranscribe] Promotion declined for ${videoId}: ${promotion.reason}`,+ );+ }+await finishLiveTranscription(videoId,userId,@@ -323,6 +361,46 @@ async function processNextLiveChunk(options: {console.warn(`[liveTranscribe] Skipping poison chunk ${lastProcessedIndex + 1}..${chunkEndIndex} for ${videoId}`,);+ // The gap MUST be durably recorded before the cursor advances, or a+ // later promotion could ship a transcript that silently misses speech.+ try {+ const artifactKey = getLiveTranscriptObjectKey(video.ownerId, videoId);+ const existing = await bucket+ .getObject(artifactKey)+ .pipe(runWorkflowPromise)+ .catch(() => Option.none<string>());+ const artifact =+ (Option.isSome(existing)+ ? parseLiveTranscript(existing.value)+ : null) ?? createEmptyLiveTranscript(new Date().toISOString());+ await bucket+ .putObject(+ artifactKey,+ JSON.stringify({+ ...artifact,+ hasGaps: true,+ lastAudioSegmentIndex: Math.max(+ artifact.lastAudioSegmentIndex,+ chunkEndIndex,+ ),+ transcribedDurationMs: Math.max(+ artifact.transcribedDurationMs,+ decision.startMs + decision.durationMs,+ ),+ updatedAt: new Date().toISOString(),+ }),+ { contentType: "application/json" },+ )+ .pipe(runWorkflowPromise);+ } catch (error) {+ return {+ outcome: "chunk-failed",+ failedAtIndex: lastProcessedIndex,+ reason: `failed to record chunk gap: ${+ error instanceof Error ? error.message : String(error)+ }`,+ };+ }return {outcome: "chunk",lastAudioSegmentIndex: chunkEndIndex,@@ -448,6 +526,237 @@ async function processNextLiveChunk(options: {}}+type PromotionResult = { promoted: boolean; reason?: string };++/**+ * Promote the completed live transcript to the canonical transcript: write+ * transcription.vtt + the encrypted edit transcript from the accumulated+ * words, claim transcriptionStatus, queue AI generation, and clean up the+ * provisional artifact. Never throws. Any failure releases the claim (if+ * held) and queues the normal full-pass so the video still transcribes.+ */+async function promoteLiveTranscript(+ videoId: string,+ userId: string,+): Promise<PromotionResult> {+ "use step";++ try {+ const [video] = await db()+ .select()+ .from(videos)+ .where(eq(videos.id, videoId as Video.VideoId));++ if (!video || video.ownerId !== userId) {+ return { promoted: false, reason: "video not found" };+ }+ if (video.transcriptionStatus !== null) {+ return {+ promoted: false,+ reason: `canonical status is ${video.transcriptionStatus}`,+ };+ }++ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(video),+ ).pipe(runWorkflowPromise);+ const segSource = new Video.SegmentsSource({+ videoId,+ ownerId: video.ownerId,+ });++ const manifestContent = await bucket+ .getObject(segSource.getManifestKey())+ .pipe(runWorkflowPromise);+ const manifestJson = Option.getOrNull(manifestContent);+ if (!manifestJson) {+ return { promoted: false, reason: "manifest missing" };+ }+ const decoded = Schema.decodeUnknownEither(Video.SegmentManifest)(+ JSON.parse(manifestJson),+ );+ if (Either.isLeft(decoded)) {+ return { promoted: false, reason: "manifest invalid" };+ }++ const artifactKey = getLiveTranscriptObjectKey(video.ownerId, videoId);+ const existing = await bucket+ .getObject(artifactKey)+ .pipe(runWorkflowPromise);+ const artifact = Option.isSome(existing)+ ? parseLiveTranscript(existing.value)+ : null;+ if (!artifact) {+ return { promoted: false, reason: "live artifact missing" };+ }++ const eligible = canPromoteLiveTranscript(artifact, decoded.right);+ if (!eligible.ok) {+ await queueFullPassFallback(videoId, userId);+ return { promoted: false, reason: eligible.reason };+ }++ 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 { promoted: false, reason: "canonical claim held elsewhere" };+ }++ try {+ await bucket+ .putObject(+ `${video.ownerId}/${videoId}/transcription.vtt`,+ artifact.vtt,+ { contentType: "text/vtt" },+ )+ .pipe(runWorkflowPromise);++ // Same rule as the full-pass save: the word transcript must describe+ // the original media, so edited videos keep their own.+ const [edit] = await db()+ .select({ videoId: videoEdits.videoId })+ .from(videoEdits)+ .where(eq(videoEdits.videoId, videoId as Video.VideoId));+ if (!edit) {+ await bucket+ .putObject(+ getEditTranscriptObjectKey(video.ownerId, videoId),+ encryptEditTranscriptObject(+ serializeEditTranscript(+ liveTranscriptToEditTranscript(+ artifact,+ ASSEMBLYAI_SPEECH_MODELS[0],+ ),+ ),+ video.ownerId,+ videoId,+ ),+ { contentType: "application/octet-stream" },+ )+ .pipe(runWorkflowPromise);+ }++ await db()+ .update(videos)+ .set({ transcriptionStatus: "COMPLETE" })+ .where(+ and(+ eq(videos.id, videoId as Video.VideoId),+ eq(videos.transcriptionStatus, "PROCESSING"),+ ),+ );+ } catch (error) {+ // Release the claim so the fallback can transcribe from scratch.+ await db()+ .update(videos)+ .set({ transcriptionStatus: null })+ .where(+ and(+ eq(videos.id, videoId as Video.VideoId),+ eq(videos.transcriptionStatus, "PROCESSING"),+ ),+ );+ await queueFullPassFallback(videoId, userId);+ return {+ promoted: false,+ reason: error instanceof Error ? error.message : String(error),+ };+ }++ // Post-COMPLETE housekeeping: never fatal, never releases the claim.+ try {+ await bucket.deleteObject(artifactKey).pipe(runWorkflowPromise);+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to delete promoted artifact for ${videoId}`,+ error,+ );+ }+ try {+ 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(+ `[liveTranscribe] Failed to clear live flag for ${videoId}`,+ error,+ );+ }+ try {+ const [owner] = await db()+ .select({+ email: users.email,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ })+ .from(users)+ .where(eq(users.id, userId as User.UserId));+ if (isAiGenerationEnabledForUser(owner)) {+ await startAiGeneration(videoId as Video.VideoId, userId);+ }+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to queue AI generation for ${videoId}`,+ error,+ );+ }++ return { promoted: true };+ } catch (error) {+ return {+ promoted: false,+ reason: error instanceof Error ? error.message : String(error),+ };+ }+}++/**+ * When promotion can't happen, immediately queue the normal full+ * transcription (early-from-segments) instead of waiting for the post-mux+ * queue, so a declined promotion costs seconds, not a minute.+ */+async function queueFullPassFallback(+ videoId: string,+ userId: string,+): Promise<void> {+ try {+ const [owner] = await db()+ .select({+ email: users.email,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ })+ .from(users)+ .where(eq(users.id, userId as User.UserId));++ await transcribeVideo(+ videoId as Video.VideoId,+ userId,+ isAiGenerationEnabledForUser(owner),+ { earlyFromSegments: true },+ );+ } catch (error) {+ console.warn(+ `[liveTranscribe] Full-pass fallback queue failed for ${videoId}`,+ error,+ );+ }+}+async function finishLiveTranscription(videoId: string,userId: string,