Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): always-on live transcription + real-recording e2e harness
Richie McIlroy3147af376410
diff --git a/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.ts b/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.tsnew file mode 100644index 000000000..4c521b950--- /dev/null+++ b/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.ts@@ -0,0 +1,249 @@+/**+ * Local end-to-end test of the segments transcription pipeline against a REAL+ * instant-mode recording and the REAL AssemblyAI API. Gated because it needs+ * local S3-compatible storage holding an uploaded recording, an AssemblyAI+ * key, and spends (a trivial amount of) transcription credit.+ *+ * Run:+ * CAP_TRANSCRIBE_E2E=1 CAP_TRANSCRIBE_E2E_PREFIX=<userId>/<videoId> \+ * pnpm exec dotenv -e ../../.env -- vitest run __tests__/e2e/live-transcribe-local-e2e.test.ts+ *+ * where <userId>/<videoId> has `segments/manifest.json` + audio segments in+ * the CAP_AWS_BUCKET of CAP_AWS_ENDPOINT.+ */+import { randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";+import { Video } from "@cap/web-domain";+import { AssemblyAI } from "assemblyai";+import { Either, Schema } from "effect";+import { describe, expect, it } from "vitest";+import { getAssemblyAITranscriptionOptions } from "@/lib/assemblyai";+import { extractAudioFromUrl } from "@/lib/audio-extract";+import {+ createEditTranscript,+ editTranscriptWordsToCaptionVtt,+} from "@/lib/edit-transcript";+import {+ applyChunkToLiveTranscript,+ createEmptyLiveTranscript,+ LIVE_TRANSCRIPT_NO_SEGMENTS,+ offsetChunkWords,+ planNextLiveChunk,+} from "@/lib/live-transcribe-core";+import { planSegmentsAudioExtraction } from "@/lib/segments-audio";+import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";++const enabled =+ process.env.CAP_TRANSCRIBE_E2E === "1" &&+ !!process.env.CAP_TRANSCRIBE_E2E_PREFIX &&+ !!process.env.ASSEMBLY_API_KEY &&+ !!process.env.CAP_AWS_ENDPOINT;++const prefix = process.env.CAP_TRANSCRIBE_E2E_PREFIX ?? "";+const bucket = process.env.CAP_AWS_BUCKET ?? "capso";++function s3() {+ return new S3Client({+ endpoint: process.env.CAP_AWS_ENDPOINT,+ region: process.env.CAP_AWS_REGION ?? "us-east-1",+ forcePathStyle: true,+ credentials: {+ accessKeyId: process.env.CAP_AWS_ACCESS_KEY ?? "",+ secretAccessKey: process.env.CAP_AWS_SECRET_KEY ?? "",+ },+ });+}++async function getObjectText(client: S3Client, key: string) {+ const result = await client.send(+ new GetObjectCommand({ Bucket: bucket, Key: key }),+ );+ return result.Body?.transformToString() ?? "";+}++const presign = (client: S3Client, key: string) =>+ getSignedUrl(client, new GetObjectCommand({ Bucket: bucket, Key: key }), {+ expiresIn: 3600,+ });++async function extractMp3(concatPath: string): Promise<Buffer> {+ const extracted = await extractAudioFromUrl(concatPath);+ try {+ return await fs.readFile(extracted.filePath);+ } finally {+ await extracted.cleanup();+ }+}++async function transcribeBuffer(+ audio: Buffer,+ language: Parameters<typeof getAssemblyAITranscriptionOptions>[0],+) {+ const client = new AssemblyAI({+ apiKey: process.env.ASSEMBLY_API_KEY as string,+ });+ const transcript = await client.transcripts.transcribe({+ audio,+ ...getAssemblyAITranscriptionOptions(language),+ disfluencies: true,+ });+ expect(transcript.status).toBe("completed");+ return transcript;+}++describe.skipIf(!enabled)("segments transcription local e2e", () => {+ it(+ "transcribes a real instant recording end to end, full-pass and chunked",+ { timeout: 300_000 },+ async () => {+ const client = s3();++ // 1. Real manifest decodes with the production schema+ const manifestJson = await getObjectText(+ client,+ `${prefix}/segments/manifest.json`,+ );+ const decoded = Schema.decodeUnknownEither(Video.SegmentManifest)(+ JSON.parse(manifestJson),+ );+ expect(Either.isRight(decoded)).toBe(true);+ if (!Either.isRight(decoded)) return;+ const manifest = decoded.right;+ console.log(+ `[e2e] manifest: ${manifest.audio_segments.length} audio segments, complete=${manifest.is_complete}, version=${manifest.version}`,+ );++ // 2. Phase 0: full concat -> ffmpeg -> AssemblyAI -> VTT+ const plan = planSegmentsAudioExtraction(manifest);+ expect(plan.status).toBe("ok");+ if (plan.status !== "ok") return;++ const urls = await Promise.all([+ presign(client, `${prefix}/segments/audio/init.mp4`),+ ...plan.entries.map((entry) =>+ presign(+ client,+ `${prefix}/segments/audio/segment_${String(entry.index).padStart(3, "0")}.m4s`,+ ),+ ),+ ]);++ const concatPath = join(tmpdir(), `e2e-full-${randomUUID()}.mp4`);+ try {+ const bytes = await downloadConcatenatedSegments(urls, concatPath);+ console.log(+ `[e2e] concatenated ${plan.entries.length} segments: ${bytes} bytes, expected ~${Math.round(plan.totalDurationMs / 1000)}s audio`,+ );++ const mp3 = await extractMp3(concatPath);+ expect(mp3.length).toBeGreaterThan(10_000);++ const full = await transcribeBuffer(mp3, "auto");+ const audioDurationMs = (full.audio_duration ?? 0) * 1000;+ // ffmpeg-decoded duration must match the manifest's segment sum+ expect(+ Math.abs(audioDurationMs - plan.totalDurationMs),+ ).toBeLessThan(3000);++ const edit = createEditTranscript(full, plan.totalDurationMs);+ const vtt = editTranscriptWordsToCaptionVtt(edit.words);+ expect(vtt.startsWith("WEBVTT")).toBe(true);+ console.log(+ `[e2e] FULL PASS: ${edit.words.length} words, language=${full.language_code}\n--- full text ---\n${full.text}\n--- vtt head ---\n${vtt.slice(0, 400)}`,+ );++ // 3. Phase 1: same audio through the live chunked path+ const artifactChunks: string[] = [];+ let artifact = createEmptyLiveTranscript(new Date().toISOString());+ let lastIndex = LIVE_TRANSCRIPT_NO_SEGMENTS;+ let language: Parameters<+ typeof getAssemblyAITranscriptionOptions+ >[0] = "auto";++ for (let i = 0; i < 20; i++) {+ const decision = planNextLiveChunk({+ manifest,+ lastProcessedIndex: lastIndex,+ targetSeconds: 15,+ maxTakeSeconds: Math.ceil(plan.totalDurationMs / 2000) + 2,+ });+ if (decision.action !== "chunk") {+ expect(decision.action).toBe("done");+ break;+ }++ const chunkUrls = await Promise.all([+ presign(client, `${prefix}/segments/audio/init.mp4`),+ ...decision.entries.map((entry) =>+ presign(+ client,+ `${prefix}/segments/audio/segment_${String(entry.index).padStart(3, "0")}.m4s`,+ ),+ ),+ ]);+ const chunkPath = join(tmpdir(), `e2e-chunk-${randomUUID()}.mp4`);+ try {+ await downloadConcatenatedSegments(chunkUrls, chunkPath);+ const chunkMp3 = await extractMp3(chunkPath);+ const chunkTranscript = await transcribeBuffer(chunkMp3, language);++ const words = offsetChunkWords(+ chunkTranscript.words,+ decision.startMs,+ decision.durationMs,+ );+ artifact = applyChunkToLiveTranscript(artifact, {+ startMs: decision.startMs,+ durationMs: decision.durationMs,+ lastAudioSegmentIndex:+ decision.entries[decision.entries.length - 1]?.index ??+ lastIndex,+ words,+ languageCode: chunkTranscript.language_code ?? null,+ nowIso: new Date().toISOString(),+ });+ artifactChunks.push(chunkTranscript.text ?? "");+ lastIndex = artifact.lastAudioSegmentIndex;+ if (+ language === "auto" &&+ typeof chunkTranscript.language_code === "string"+ ) {+ language = chunkTranscript.language_code as typeof language;+ }+ console.log(+ `[e2e] CHUNK ${artifactChunks.length}: segments ..${lastIndex}, +${words.length} words @ ${decision.startMs}ms`,+ );+ } finally {+ await fs.unlink(chunkPath).catch(() => {});+ }+ }++ expect(artifactChunks.length).toBeGreaterThanOrEqual(2);+ expect(artifact.vtt.startsWith("WEBVTT")).toBe(true);+ // timestamps must be strictly ordered across chunk boundaries+ for (let i = 1; i < artifact.words.length; i++) {+ const prev = artifact.words[i - 1];+ const curr = artifact.words[i];+ if (prev && curr) {+ expect(curr.startMs).toBeGreaterThanOrEqual(prev.startMs);+ }+ }+ // chunked word volume should be in the same ballpark as the full pass+ if (edit.words.length > 20) {+ const ratio = artifact.words.length / edit.words.length;+ console.log(+ `[e2e] LIVE PATH: ${artifact.words.length} words vs full ${edit.words.length} (ratio ${ratio.toFixed(2)})\n--- live vtt head ---\n${artifact.vtt.slice(0, 400)}`,+ );+ expect(ratio).toBeGreaterThan(0.6);+ expect(ratio).toBeLessThan(1.4);+ }+ } finally {+ await fs.unlink(concatPath).catch(() => {});+ }+ },+ );+});diff --git a/apps/web/__tests__/unit/segments-audio.test.ts b/apps/web/__tests__/unit/segments-audio.test.tsindex e7e9f51fe..d0a358e0a 100644--- a/apps/web/__tests__/unit/segments-audio.test.ts+++ b/apps/web/__tests__/unit/segments-audio.test.ts@@ -34,13 +34,7 @@ describe("planSegmentsAudioExtraction", () => {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" });+ it("reports no-audio only when no audio segments are listed", () => {expect(planSegmentsAudioExtraction({...completeManifest,@@ -49,6 +43,36 @@ describe("planSegmentsAudioExtraction", () => {).toEqual({ status: "no-audio" });});+ it("trusts listed segments over the init flag on completed manifests (v1 reality)", () => {+ // Real version-1 manifests list uploaded audio segments while+ // audio_init_uploaded stays false; absence must be proven by the object+ // store, not the flag.+ const plan = planSegmentsAudioExtraction({+ version: 1,+ video_init_uploaded: true,+ audio_init_uploaded: false,+ video_segments: [1, 2, 3],+ audio_segments: [1, 2, 3],+ is_complete: true,+ });+ expect(plan.status).toBe("ok");+ });++ it("waits for the audio init while the recording is still uploading", () => {+ const plan = planSegmentsAudioExtraction(+ {+ ...completeManifest,+ audio_init_uploaded: false,+ is_complete: false,+ },+ { requireComplete: false },+ );+ expect(plan).toEqual({+ status: "unavailable",+ reason: "audio init not uploaded yet",+ });+ });+it("normalizes, sorts and dedupes segment entries and sums their durations", () => {const plan = planSegmentsAudioExtraction({...completeManifest,diff --git a/apps/web/lib/live-transcribe.ts b/apps/web/lib/live-transcribe.tsindex 46c4c739f..5759d3941 100644--- a/apps/web/lib/live-transcribe.ts+++ b/apps/web/lib/live-transcribe.ts@@ -20,9 +20,9 @@ export type LiveTranscriptionStart = "started" | "skipped";/*** Kick off provisional live transcription for a just-created instant-mode- * recording. Feature-flagged, idempotent (an atomic metadata claim allows- * exactly one live workflow per video) and never throws: any failure means- * the video simply behaves exactly as it does today.+ * recording. Idempotent (an atomic metadata claim allows exactly one live+ * workflow per video) and never throws: any failure means the video simply+ * behaves exactly as it does today.*/export async function maybeStartLiveTranscription({videoId,@@ -34,8 +34,7 @@ export async function maybeStartLiveTranscription({orgId: Organisation.OrganisationId;}): Promise<LiveTranscriptionStart> {try {- const env = serverEnv();- if (!env.CAP_LIVE_TRANSCRIPTION || !env.ASSEMBLY_API_KEY) {+ if (!serverEnv().ASSEMBLY_API_KEY) {return "skipped";}diff --git a/apps/web/lib/segments-audio.ts b/apps/web/lib/segments-audio.tsindex ba0531fec..f6bf0a2ed 100644--- a/apps/web/lib/segments-audio.ts+++ b/apps/web/lib/segments-audio.ts@@ -37,10 +37,20 @@ export function planSegmentsAudioExtraction(return { status: "unavailable", reason: "manifest is not complete" };}- if (!manifest.audio_init_uploaded || manifest.audio_segments.length === 0) {+ if (manifest.audio_segments.length === 0) {return { status: "no-audio" };}+ // The init flag can't prove absence when segments are listed: version 1+ // manifests uploaded audio segments while never setting it (seen in real+ // data). Mid-recording it only means the init may not have arrived yet;+ // for completed manifests the object store is the truth — a genuinely+ // missing init fails the fetch downstream as "unavailable", never as a+ // false NO_AUDIO.+ if (!manifest.is_complete && !manifest.audio_init_uploaded) {+ return { status: "unavailable", reason: "audio init not uploaded yet" };+ }+const byIndex = new Map<number, NormalizedSegmentEntry>();for (const raw of manifest.audio_segments) {const entry = Video.normalizeSegmentEntry(raw);diff --git a/packages/env/server.ts b/packages/env/server.tsindex d029b1122..0c1da1a92 100644--- a/packages/env/server.ts+++ b/packages/env/server.ts@@ -90,9 +90,6 @@ function createServerEnv() {/// AI providersASSEMBLY_API_KEY: z.string().optional().describe("Audio transcription"),- CAP_LIVE_TRANSCRIPTION: boolString(false).describe(- "Transcribe instant-mode recordings live while they upload (needs ASSEMBLY_API_KEY)",- ),ANTHROPIC_API_KEY: z.string().optional().describe("AI chat"),OPENAI_API_KEY: z.string().optional().describe("AI summaries"),GROQ_API_KEY: z.string().optional().describe("AI summaries"),