Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): transcribe instant recordings from segment audio at stop
Richie McIlroy20fcb9e77d76
diff --git a/apps/web/__tests__/integration/transcribe-early-segments.test.ts b/apps/web/__tests__/integration/transcribe-early-segments.test.tsnew file mode 100644index 000000000..bf2e62043--- /dev/null+++ b/apps/web/__tests__/integration/transcribe-early-segments.test.ts@@ -0,0 +1,354 @@+import { randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Option } from "effect";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { assemblyAIEditResponse } from "../fixtures/assemblyai-edit-response";++const mocks = vi.hoisted(() => ({+ transcribe: vi.fn(),+ putObject: vi.fn(),+ deleteObject: vi.fn(),+ getObject: vi.fn(),+ getInternalSignedObjectUrl: vi.fn(),+ startAiGeneration: vi.fn(),+ updates: [] as Record<string, unknown>[],+}));++const schemaMocks = vi.hoisted(() => ({+ videos: {+ id: "videos.id",+ metadata: "videos.metadata",+ transcriptionStatus: "videos.transcriptionStatus",+ updatedAt: "videos.updatedAt",+ },+ organizations: { id: "organizations.id" },+ videoUploads: {+ videoId: "videoUploads.videoId",+ rawFileKey: "videoUploads.rawFileKey",+ },+ videoEdits: {+ videoId: "videoEdits.videoId",+ editSpec: "videoEdits.editSpec",+ },+}));++const videoRow = vi.hoisted(() => ({+ id: "video-123",+ ownerId: "user-456",+ duration: null as number | null,+ settings: null,+ source: { type: "desktopSegments" },+ isScreenshot: false,+ transcriptionStatus: null,+ updatedAt: new Date("2026-08-01T00:00:00.000Z"),+ metadata: {},+}));++const state = vi.hoisted(() => ({+ editRows: [] as unknown[],+ fakeAudioPath: "",+}));++vi.mock("@cap/env", () => ({+ serverEnv: () => ({+ ASSEMBLY_API_KEY: "test-assembly-api-key",+ NEXTAUTH_SECRET: "test-secret-with-enough-entropy",+ }),+}));++vi.mock("@cap/database/schema", () => schemaMocks);++vi.mock("@cap/database", () => ({+ db: () => ({+ select: () => ({+ from: (table: unknown) => {+ if (table === schemaMocks.videoUploads) {+ return { where: () => ({ limit: async () => [] }) };+ }+ if (table === schemaMocks.videoEdits) {+ return { where: async () => state.editRows };+ }+ return {+ leftJoin: () => ({+ where: async () => [{ video: videoRow, orgSettings: null }],+ }),+ where: async () => [videoRow],+ };+ },+ }),+ update: () => ({+ set: (values: Record<string, unknown>) => {+ mocks.updates.push(values);+ return { where: async () => [{ affectedRows: 1 }] };+ },+ }),+ }),+}));++vi.mock("drizzle-orm", () => ({+ and: (...conditions: unknown[]) => ({ conditions }),+ eq: (field: unknown, value: unknown) => ({ field, value }),+ sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({+ strings,+ values,+ }),+}));++vi.mock("server-only", () => ({}));++vi.mock("workflow", () => ({+ FatalError: class FatalError extends Error {},+}));++vi.mock("assemblyai", () => ({+ AssemblyAI: class {+ transcripts = { transcribe: mocks.transcribe };+ },+}));++vi.mock("@cap/web-backend/src/Storage/index", () => ({+ Storage: {+ getAccessForVideo: () => ({+ pipe: (runner: (value: unknown) => unknown) =>+ runner([+ {+ putObject: mocks.putObject,+ deleteObject: mocks.deleteObject,+ getObject: mocks.getObject,+ getInternalSignedObjectUrl: mocks.getInternalSignedObjectUrl,+ },+ ]),+ }),+ },+}));++vi.mock("@/lib/workflow-runtime", () => ({+ runWorkflowPromise: (value: unknown) => Promise.resolve(value),+}));++vi.mock("@/lib/video-storage", () => ({+ decodeStorageVideo: (video: unknown) => video,+}));++vi.mock("@/lib/media-client", () => ({+ isMediaServerConfigured: () => true,+ probeVideoViaMediaServer: async () => ({+ audioCodec: "aac",+ videoCodec: "h264",+ duration: 4,+ audioChannels: 2,+ sampleRate: 48_000,+ }),+ extractAudioViaMediaServer: async () => Buffer.from("audio"),+ checkHasAudioTrackViaMediaServer: async () => true,+}));++vi.mock("@/lib/audio-extract", () => ({+ checkHasAudioTrack: async () => true,+ extractAudioFromUrl: async () => ({+ filePath: state.fakeAudioPath,+ cleanup: async () => {},+ }),+}));++vi.mock("@/lib/audio-enhance", () => ({+ ENHANCED_AUDIO_CONTENT_TYPE: "audio/mpeg",+ ENHANCED_AUDIO_EXTENSION: "mp3",+ enhanceAudioFromUrl: async () => Buffer.from(""),+}));++vi.mock("@/lib/generate-ai", () => ({+ startAiGeneration: mocks.startAiGeneration,+}));++function pipeValue(value: unknown) {+ return { pipe: (runner: (input: unknown) => unknown) => runner(value) };+}++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 }],+ is_complete: true,+};++describe("transcribeVideoWorkflow earlyFromSegments", () => {+ beforeEach(async () => {+ mocks.updates.length = 0;+ state.editRows = [];+ videoRow.duration = null;+ videoRow.source = { type: "desktopSegments" };+ mocks.transcribe.mockReset();+ mocks.transcribe.mockResolvedValue({+ ...assemblyAIEditResponse,+ audio_duration: 4,+ });+ mocks.putObject.mockImplementation(() => pipeValue(undefined));+ mocks.deleteObject.mockImplementation(() => pipeValue(undefined));+ mocks.getObject.mockImplementation(() =>+ pipeValue(Option.some(JSON.stringify(manifest))),+ );+ mocks.getInternalSignedObjectUrl.mockImplementation((key: string) =>+ pipeValue(`https://storage.test/${key}`),+ );+ mocks.startAiGeneration.mockResolvedValue({ success: true, message: "ok" });++ state.fakeAudioPath = join(tmpdir(), `fake-audio-${randomUUID()}.mp3`);+ await fs.writeFile(state.fakeAudioPath, "mp3-bytes");++ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("result.mp4") || url.includes("rawFileKey")) {+ return { ok: false, status: 404, statusText: "Not Found" };+ }+ return {+ ok: true,+ status: 200,+ statusText: "OK",+ arrayBuffer: async () => new TextEncoder().encode("seg").buffer,+ };+ }),+ );+ });++ it("transcribes straight from segment audio before any mux exists", async () => {+ const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");++ const result = await transcribeVideoWorkflow({+ videoId: "video-123",+ userId: "user-456",+ aiGenerationEnabled: false,+ earlyFromSegments: true,+ });++ expect(result.success).toBe(true);+ expect(mocks.transcribe).toHaveBeenCalledTimes(1);++ 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/segment_001.m4s",+ );+ expect(signedKeys).toContain(+ "user-456/video-123/segments/audio/segment_002.m4s",+ );+ // never touches the video track+ expect(signedKeys.join()).not.toContain("segments/video");++ const writtenKeys = mocks.putObject.mock.calls.map((call) => call[0]);+ expect(writtenKeys).toContain("user-456/video-123/audio-temp.mp3");+ expect(writtenKeys).toContain("user-456/video-123/transcription.vtt");+ expect(writtenKeys).toContain(+ "user-456/video-123/transcription.edit.v3.json",+ );++ // duration falls back to the manifest sum (2s + 2.5s) when the video row+ // has no duration yet (it is only set by the post-mux webhook)+ const { parseEditTranscript } = await import("@/lib/edit-transcript");+ const { decryptEditTranscriptObject } = await import(+ "@/lib/edit-transcript-storage"+ );+ const write = mocks.putObject.mock.calls.find(+ (call) => call[0] === "user-456/video-123/transcription.edit.v3.json",+ );+ const stored = parseEditTranscript(+ decryptEditTranscriptObject(write?.[1] as string, "user-456", "video-123") ??+ "",+ );+ expect(stored?.durationMs).toBe(4500);++ expect(mocks.updates.at(-1)).toEqual({ transcriptionStatus: "COMPLETE" });+ });++ it("defers back to the post-mux queue when the manifest is missing", async () => {+ mocks.getObject.mockImplementation(() => pipeValue(Option.none()));++ const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");+ const result = await transcribeVideoWorkflow({+ videoId: "video-123",+ userId: "user-456",+ aiGenerationEnabled: false,+ earlyFromSegments: true,+ });++ expect(result.success).toBe(true);+ expect(result.message).toContain("deferred");+ expect(mocks.transcribe).not.toHaveBeenCalled();+ // the claim is released (PROCESSING -> null), never marked ERROR+ expect(mocks.updates).toContainEqual({ transcriptionStatus: null });+ expect(mocks.updates).not.toContainEqual({ transcriptionStatus: "ERROR" });+ expect(mocks.updates).not.toContainEqual({+ transcriptionStatus: "COMPLETE",+ });+ });++ it("defers when the manifest exists but is not complete", async () => {+ mocks.getObject.mockImplementation(() =>+ pipeValue(Option.some(JSON.stringify({ ...manifest, is_complete: false }))),+ );++ const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");+ const result = await transcribeVideoWorkflow({+ videoId: "video-123",+ userId: "user-456",+ aiGenerationEnabled: false,+ earlyFromSegments: true,+ });++ expect(result.message).toContain("deferred");+ expect(mocks.transcribe).not.toHaveBeenCalled();+ expect(mocks.updates).toContainEqual({ transcriptionStatus: null });+ });++ it("marks NO_AUDIO when the completed manifest has no audio track", async () => {+ mocks.getObject.mockImplementation(() =>+ pipeValue(+ Option.some(+ JSON.stringify({+ ...manifest,+ audio_init_uploaded: false,+ audio_segments: [],+ }),+ ),+ ),+ );++ const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");+ const result = await transcribeVideoWorkflow({+ videoId: "video-123",+ userId: "user-456",+ aiGenerationEnabled: false,+ earlyFromSegments: true,+ });++ expect(result.success).toBe(true);+ expect(mocks.transcribe).not.toHaveBeenCalled();+ expect(mocks.updates.at(-1)).toEqual({ transcriptionStatus: "NO_AUDIO" });+ });++ it("falls back to segment audio in the normal path when no muxed source exists", async () => {+ const { transcribeVideoWorkflow } = await import("@/workflows/transcribe");++ const result = await transcribeVideoWorkflow({+ videoId: "video-123",+ userId: "user-456",+ aiGenerationEnabled: false,+ });++ expect(result.success).toBe(true);+ expect(mocks.transcribe).toHaveBeenCalledTimes(1);+ const writtenKeys = mocks.putObject.mock.calls.map((call) => call[0]);+ expect(writtenKeys).toContain("user-456/video-123/transcription.vtt");+ expect(mocks.updates.at(-1)).toEqual({ transcriptionStatus: "COMPLETE" });+ });+});diff --git a/apps/web/__tests__/unit/segments-audio.test.ts b/apps/web/__tests__/unit/segments-audio.test.tsnew file mode 100644index 000000000..632eb1de2--- /dev/null+++ b/apps/web/__tests__/unit/segments-audio.test.ts@@ -0,0 +1,138 @@+import { promises as fs } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import {+ downloadConcatenatedSegments,+ planSegmentsAudioExtraction,+} from "@/lib/segments-audio";++const completeManifest = {+ version: 5,+ video_init_uploaded: true,+ audio_init_uploaded: true,+ video_segments: [1, 2, 3],+ audio_segments: [1, 2, 3],+ is_complete: true,+};++describe("planSegmentsAudioExtraction", () => {+ it("refuses an incomplete manifest so partial recordings are never transcribed", () => {+ const plan = planSegmentsAudioExtraction({+ ...completeManifest,+ is_complete: false,+ });+ expect(plan).toEqual({+ status: "unavailable",+ reason: "manifest is not complete",+ });+ });++ it("allows an incomplete manifest when completeness is not required", () => {+ const plan = planSegmentsAudioExtraction(+ { ...completeManifest, is_complete: false },+ { requireComplete: false },+ );+ expect(plan.status).toBe("ok");+ });++ it("reports no-audio when the audio track was never uploaded", () => {+ expect(+ planSegmentsAudioExtraction({+ ...completeManifest,+ audio_init_uploaded: false,+ }),+ ).toEqual({ status: "no-audio" });+ expect(+ planSegmentsAudioExtraction({+ ...completeManifest,+ audio_segments: [],+ }),+ ).toEqual({ status: "no-audio" });+ });++ it("normalizes, sorts and dedupes segment entries and sums their durations", () => {+ 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],+ });++ expect(plan).toEqual({+ status: "ok",+ entries: [+ { index: 1, duration: 3.0 },+ { index: 2, duration: 1.5 },+ { index: 3, duration: 3.0 },+ ],+ totalDurationMs: 7500,+ });+ });++ it("rejects manifests with invalid entries", () => {+ const plan = planSegmentsAudioExtraction({+ ...completeManifest,+ audio_segments: [{ index: -1, duration: 2 }],+ });+ expect(plan.status).toBe("unavailable");+ });+});++describe("downloadConcatenatedSegments", () => {+ const outputs: string[] = [];++ const makeOutputPath = () => {+ const path = join(tmpdir(), `segments-audio-test-${Math.random()}.bin`);+ outputs.push(path);+ return path;+ };++ afterEach(async () => {+ await Promise.all(outputs.map((path) => fs.unlink(path).catch(() => {})));+ outputs.length = 0;+ });++ const fetchFromMap =+ (objects: Record<string, string>, delays: Record<string, number> = {}) =>+ async (input: string | URL | Request) => {+ const url = String(input);+ await new Promise((resolve) => setTimeout(resolve, delays[url] ?? 0));+ const body = objects[url];+ if (body === undefined) {+ return { ok: false, status: 404 } as Response;+ }+ return {+ ok: true,+ status: 200,+ arrayBuffer: async () => new TextEncoder().encode(body).buffer,+ } as unknown as Response;+ };++ it("concatenates objects in order even when later fetches resolve first", async () => {+ const outputPath = makeOutputPath();+ const bytes = await downloadConcatenatedSegments(+ ["u/init", "u/1", "u/2", "u/3"],+ outputPath,+ {+ fetchImpl: fetchFromMap(+ { "u/init": "INIT", "u/1": "AAA", "u/2": "BBB", "u/3": "CCC" },+ { "u/init": 30, "u/1": 20, "u/2": 10, "u/3": 0 },+ ),+ concurrency: 4,+ },+ );++ expect(bytes).toBe(13);+ expect(await fs.readFile(outputPath, "utf8")).toBe("INITAAABBBCCC");+ });++ it("throws with the failing segment position when an object is missing", async () => {+ const outputPath = makeOutputPath();+ await expect(+ downloadConcatenatedSegments(["u/init", "u/1", "u/gone"], outputPath, {+ fetchImpl: fetchFromMap({ "u/init": "INIT", "u/1": "AAA" }),+ concurrency: 2,+ }),+ ).rejects.toThrow("Segment 2 not accessible: 404");+ });+});diff --git a/apps/web/lib/desktop-segments-finalization.ts b/apps/web/lib/desktop-segments-finalization.tsindex af586637c..5b610fbe6 100644--- a/apps/web/lib/desktop-segments-finalization.ts+++ b/apps/web/lib/desktop-segments-finalization.ts@@ -1,8 +1,10 @@import { db } from "@cap/database";-import { videoUploads } from "@cap/database/schema";+import { users, 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";+import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";+import { transcribeVideo } from "@/lib/transcribe";import { finalizeDesktopRecordingWorkflow } from "@/workflows/finalize-desktop-recording";export { isRetryableDesktopSegmentsFinalizationError } from "@/lib/desktop-segments-retryable-errors";@@ -21,6 +23,36 @@ const getAffectedRows = (result: unknown) => {return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;};+async function queueEarlySegmentsTranscription({+ videoId,+ userId,+}: {+ videoId: Video.VideoId;+ userId: User.UserId;+}): Promise<void> {+ const [owner] = await db()+ .select({+ email: users.email,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ })+ .from(users)+ .where(eq(users.id, userId));++ const result = await transcribeVideo(+ videoId,+ userId,+ isAiGenerationEnabledForUser(owner),+ { earlyFromSegments: true },+ );++ if (!result.success) {+ console.warn(+ `[queueEarlySegmentsTranscription] Not queued for ${videoId}: ${result.message}`,+ );+ }+}+export async function queueDesktopSegmentsFinalization({videoId,userId,@@ -73,6 +105,16 @@ export async function queueDesktopSegmentsFinalization({userId,},]);+ // The segments are fully uploaded at this point, so transcription can+ // start right away from the segment audio instead of waiting for the mux+ // into result.mp4. Failures here never block finalization: the workflow+ // re-queues transcription after the mux exactly as before.+ await queueEarlySegmentsTranscription({ videoId, userId }).catch((error) => {+ console.warn(+ `[queueDesktopSegmentsFinalization] Early transcription queue failed for ${videoId}`,+ error,+ );+ });return "queued";} catch (error) {await db()diff --git a/apps/web/lib/segments-audio.ts b/apps/web/lib/segments-audio.tsnew file mode 100644index 000000000..f99b6846d--- /dev/null+++ b/apps/web/lib/segments-audio.ts@@ -0,0 +1,129 @@+import { createWriteStream } from "node:fs";+import { Video } from "@cap/web-domain";++/**+ * Helpers for turning a desktop instant-mode recording's uploaded audio+ * segments (fMP4 init + .m4s fragments) into a single audio file the+ * transcription pipeline can consume, without waiting for the media server+ * to mux `result.mp4`.+ */++export interface NormalizedSegmentEntry {+ index: number;+ duration: number;+}++export type SegmentsAudioPlan =+ | { status: "unavailable"; reason: string }+ | { status: "no-audio" }+ | {+ status: "ok";+ entries: NormalizedSegmentEntry[];+ totalDurationMs: number;+ };++/**+ * Decide whether a segment manifest can back an audio extraction. The manifest+ * must be finalized (`is_complete`) so we never transcribe a partial+ * recording; a complete manifest without audio segments means the recording+ * genuinely has no audio track.+ */+export function planSegmentsAudioExtraction(+ manifest: Video.SegmentManifestType,+ options: { requireComplete?: boolean } = {},+): SegmentsAudioPlan {+ const requireComplete = options.requireComplete ?? true;++ if (requireComplete && !manifest.is_complete) {+ return { status: "unavailable", reason: "manifest is not complete" };+ }++ if (!manifest.audio_init_uploaded || manifest.audio_segments.length === 0) {+ return { status: "no-audio" };+ }++ const byIndex = new Map<number, NormalizedSegmentEntry>();+ for (const raw of manifest.audio_segments) {+ const entry = Video.normalizeSegmentEntry(raw);+ if (+ !Number.isFinite(entry.index) ||+ entry.index < 0 ||+ !Number.isFinite(entry.duration) ||+ entry.duration < 0+ ) {+ return {+ status: "unavailable",+ reason: `invalid audio segment entry (index=${entry.index})`,+ };+ }+ if (!byIndex.has(entry.index)) {+ byIndex.set(entry.index, entry);+ }+ }++ const entries = [...byIndex.values()].sort((a, b) => a.index - b.index);+ const totalDurationMs = Math.round(+ entries.reduce((sum, entry) => sum + entry.duration, 0) * 1000,+ );++ return { status: "ok", entries, totalDurationMs };+}++/** Segment fetches beyond this are almost certainly a bug, not a recording. */+const MAX_SEGMENTS_AUDIO_BYTES = 1_536 * 1024 * 1024;++const DEFAULT_DOWNLOAD_CONCURRENCY = 8;++/**+ * Download objects and byte-concatenate them, in order, into `outputPath`.+ * An fMP4 init segment followed by its fragments concatenates into a valid+ * fragmented MP4, so the output is directly consumable by ffmpeg.+ * Returns total bytes written; throws if any object is inaccessible.+ */+export async function downloadConcatenatedSegments(+ urls: string[],+ outputPath: string,+ options: { concurrency?: number; fetchImpl?: typeof fetch } = {},+): Promise<number> {+ const concurrency = Math.max(1, options.concurrency ?? DEFAULT_DOWNLOAD_CONCURRENCY);+ const fetchImpl = options.fetchImpl ?? fetch;++ const stream = createWriteStream(outputPath);+ let totalBytes = 0;++ const write = (chunk: Buffer) =>+ new Promise<void>((resolve, reject) => {+ stream.write(chunk, (error) => (error ? reject(error) : resolve()));+ });++ try {+ for (let start = 0; start < urls.length; start += concurrency) {+ const batch = urls.slice(start, start + concurrency);+ const buffers = await Promise.all(+ batch.map(async (url, offset) => {+ const response = await fetchImpl(url);+ if (!response.ok) {+ throw new Error(+ `Segment ${start + offset} not accessible: ${response.status}`,+ );+ }+ return Buffer.from(await response.arrayBuffer());+ }),+ );++ for (const buffer of buffers) {+ totalBytes += buffer.length;+ if (totalBytes > MAX_SEGMENTS_AUDIO_BYTES) {+ throw new Error(+ `Segment audio exceeds ${MAX_SEGMENTS_AUDIO_BYTES} bytes`,+ );+ }+ await write(buffer);+ }+ }+ } finally {+ await new Promise<void>((resolve) => stream.end(() => resolve()));+ }++ return totalBytes;+}diff --git a/apps/web/lib/transcribe.ts b/apps/web/lib/transcribe.tsindex 05611e8ad..94ecde9cd 100644--- a/apps/web/lib/transcribe.ts+++ b/apps/web/lib/transcribe.ts@@ -11,6 +11,17 @@ type TranscribeResult = {message: string;};+export type TranscribeVideoOptions = {+ /**+ * The recording's segments are fully uploaded but post-processing (the mux+ * into result.mp4) has not finished. Skips the active-upload guard — the+ * upload row is in "processing" during the mux — and makes the workflow+ * transcribe straight from the segment audio, deferring back to the normal+ * post-mux queue if that isn't possible.+ */+ earlyFromSegments?: boolean;+};+const TRANSCRIPTION_ALREADY_HANDLED_MESSAGE ="Transcription already completed, in progress, or awaiting manual retry";@@ -28,6 +39,7 @@ export async function transcribeVideo(videoId: Video.VideoId,userId: string,aiGenerationEnabled = false,+ options: TranscribeVideoOptions = {},): Promise<TranscribeResult> {if (!serverEnv().ASSEMBLY_API_KEY) {return {@@ -106,21 +118,23 @@ export async function transcribeVideo(};}- const upload = await db()- .select({ phase: videoUploads.phase })- .from(videoUploads)- .where(eq(videoUploads.videoId, videoId))- .limit(1);-- if (- upload[0]?.phase === "uploading" ||- upload[0]?.phase === "processing" ||- upload[0]?.phase === "generating_thumbnail"- ) {- return {- success: true,- message: "Video upload is still in progress",- };+ if (!options.earlyFromSegments) {+ const upload = await db()+ .select({ phase: videoUploads.phase })+ .from(videoUploads)+ .where(eq(videoUploads.videoId, videoId))+ .limit(1);++ if (+ upload[0]?.phase === "uploading" ||+ upload[0]?.phase === "processing" ||+ upload[0]?.phase === "generating_thumbnail"+ ) {+ return {+ success: true,+ message: "Video upload is still in progress",+ };+ }}try {@@ -145,6 +159,7 @@ export async function transcribeVideo(videoId,userId,aiGenerationEnabled,+ ...(options.earlyFromSegments ? { earlyFromSegments: true } : {}),},]);diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.tsindex 761860cd6..b005e316d 100644--- a/apps/web/workflows/transcribe.ts+++ b/apps/web/workflows/transcribe.ts@@ -1,4 +1,7 @@+import { randomUUID } from "node:crypto";import { promises as fs } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { db } from "@cap/database";import {organizations,@@ -12,10 +15,11 @@ import { Storage } from "@cap/web-backend/src/Storage/index";import {type AiGenerationLanguage,parseAiGenerationLanguage,- type Video,+ Video,} from "@cap/web-domain";import { AssemblyAI } from "assemblyai";import { and, eq, sql } from "drizzle-orm";+import { Either, Option, Schema } from "effect";import { FatalError } from "workflow";import { getAssemblyAITranscriptionOptions } from "@/lib/assemblyai";import {@@ -39,6 +43,10 @@ import {isMediaServerConfigured,probeVideoViaMediaServer,} from "@/lib/media-client";+import {+ downloadConcatenatedSegments,+ planSegmentsAudioExtraction,+} from "@/lib/segments-audio";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -46,6 +54,12 @@ interface TranscribeWorkflowPayload {videoId: string;userId: string;aiGenerationEnabled: boolean;+ /**+ * The recording's segments are fully uploaded but the mux into result.mp4+ * has not finished; transcribe directly from the segment audio and defer+ * back to the normal post-mux queue if that isn't possible.+ */+ earlyFromSegments?: boolean;}interface VideoData {@@ -88,7 +102,44 @@ export async function transcribeVideoWorkflow(}try {- const audioUrl = await extractAudio(videoId, userId, videoData.video);+ let audioUrl: string | null;+ let videoDurationMs = Math.max(0, (videoData.video.duration ?? 0) * 1000);++ if (payload.earlyFromSegments) {+ const segments = await extractAudioFromSegmentsStep(+ videoId,+ userId,+ videoData.video,+ );++ if (segments.status === "no-audio") {+ await markNoAudio(videoId);+ return {+ success: true,+ message: "Video has no audio track - skipped transcription",+ };+ }++ 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);+ await cleanupTempAudio(videoId, userId, videoData.video);+ return {+ success: true,+ message: `Early transcription deferred: ${+ segments.status === "unavailable" ? segments.reason : "no audio URL"+ }`,+ };+ }++ audioUrl = segments.audioUrl;+ if (videoDurationMs <= 0 && (segments.durationMs ?? 0) > 0) {+ videoDurationMs = segments.durationMs ?? 0;+ }+ } else {+ audioUrl = await extractAudio(videoId, userId, videoData.video);+ }if (!audioUrl) {await markNoAudio(videoId);@@ -101,7 +152,7 @@ export async function transcribeVideoWorkflow(const transcription = await transcribeWithAssemblyAI(audioUrl,videoData.aiGenerationLanguage,- Math.max(0, (videoData.video.duration ?? 0) * 1000),+ videoDurationMs,);await saveTranscription(videoId, userId, videoData.video, transcription);@@ -320,6 +371,20 @@ async function markError(videoId: string): Promise<void> {);}+async function deferEarlyTranscription(videoId: string): Promise<void> {+ "use step";++ await db()+ .update(videos)+ .set({ transcriptionStatus: null })+ .where(+ and(+ eq(videos.id, videoId as Video.VideoId),+ eq(videos.transcriptionStatus, "PROCESSING"),+ ),+ );+}+async function extractAudio(videoId: string,userId: string,@@ -333,12 +398,37 @@ async function extractAudio(decodeStorageVideo(video),).pipe(runWorkflowPromise);- const videoUrl = await resolveVideoSourceUrl(- videoId,- userId,- video,- sourceKeyOverride,- );+ let videoUrl: string;+ try {+ videoUrl = await resolveVideoSourceUrl(+ videoId,+ userId,+ video,+ sourceKeyOverride,+ );+ } catch (error) {+ // Instant-mode recordings can be transcribed straight from their uploaded+ // audio segments when no muxed source exists (self-hosted deployments+ // without a media server never produce a result.mp4 at all).+ if (+ !sourceKeyOverride &&+ (video.source.type === "desktopSegments" ||+ video.source.type === "desktopMP4")+ ) {+ const segments = await extractAudioFromSegmentsImpl(+ videoId,+ userId,+ video,+ tempAudioFilename,+ );+ if (segments.status === "ok") return segments.audioUrl;+ if (segments.status === "no-audio") return null;+ console.warn(+ `[transcribe] Segments audio fallback unavailable for ${videoId}: ${segments.reason}`,+ );+ }+ throw error;+ }const useMediaServer = isMediaServerConfigured();console.log(@@ -454,6 +544,126 @@ async function resolveVideoSourceUrl(throw new Error("Video file not accessible");}+type SegmentsAudioExtraction =+ | { status: "ok"; audioUrl: string; durationMs: number }+ | { status: "no-audio" }+ | { status: "unavailable"; reason: string };++async function extractAudioFromSegmentsStep(+ videoId: string,+ userId: string,+ video: typeof videos.$inferSelect,+): Promise<SegmentsAudioExtraction> {+ "use step";++ return extractAudioFromSegmentsImpl(videoId, userId, video);+}++/**+ * Build the transcription audio input straight from the recording's uploaded+ * fMP4 audio segments (init.mp4 + segment_*.m4s byte-concatenate into a valid+ * fragmented MP4). Never throws: any failure reports "unavailable" so callers+ * can fall back to the muxed result.mp4 path instead of erroring the video.+ */+async function extractAudioFromSegmentsImpl(+ videoId: string,+ userId: string,+ video: typeof videos.$inferSelect,+ tempAudioFilename = "audio-temp.mp3",+): Promise<SegmentsAudioExtraction> {+ try {+ 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 { status: "unavailable", reason: "segment manifest not found" };+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(manifestJson);+ } catch {+ return { status: "unavailable", reason: "invalid segment manifest JSON" };+ }++ const decoded = Schema.decodeUnknownEither(Video.SegmentManifest)(parsed);+ if (Either.isLeft(decoded)) {+ return {+ status: "unavailable",+ reason: "invalid segment manifest format",+ };+ }+ const manifest = decoded.right;++ const plan = planSegmentsAudioExtraction(manifest);+ if (plan.status !== "ok") return plan;++ const segmentUrls = await Promise.all([+ bucket+ .getInternalSignedObjectUrl(segSource.getAudioInitKey())+ .pipe(runWorkflowPromise),+ ...plan.entries.map((entry) =>+ bucket+ .getInternalSignedObjectUrl(segSource.getAudioSegmentKey(entry.index))+ .pipe(runWorkflowPromise),+ ),+ ]);++ const concatPath = join(tmpdir(), `segments-audio-${randomUUID()}.mp4`);+ try {+ const totalBytes = await downloadConcatenatedSegments(+ segmentUrls,+ concatPath,+ );+ console.log(+ `[transcribe] Assembled ${plan.entries.length} audio segments (${totalBytes} bytes) for ${videoId}`,+ );++ const result = await extractAudioFromUrl(concatPath);+ let audioBuffer: Buffer;+ try {+ audioBuffer = await fs.readFile(result.filePath);+ } finally {+ await result.cleanup();+ }++ const audioKey = `${userId}/${videoId}/${tempAudioFilename}`;+ await bucket+ .putObject(audioKey, audioBuffer, {+ contentType: "audio/mpeg",+ })+ .pipe(runWorkflowPromise);++ const audioSignedUrl = await bucket+ .getInternalSignedObjectUrl(audioKey)+ .pipe(runWorkflowPromise);++ return {+ status: "ok",+ audioUrl: audioSignedUrl,+ durationMs: plan.totalDurationMs,+ };+ } finally {+ await fs.unlink(concatPath).catch(() => {});+ }+ } catch (error) {+ return {+ status: "unavailable",+ reason: error instanceof Error ? error.message : String(error),+ };+ }+}+async function transcribeWithAssemblyAI(audioUrl: string,language: AiGenerationLanguage,