Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): live incremental transcription for instant recordings
Richie McIlroy4714151c0d20
diff --git a/apps/web/__tests__/integration/transcribe-early-segments.test.ts b/apps/web/__tests__/integration/transcribe-early-segments.test.tsindex bf2e62043..d5a2e4ea5 100644--- a/apps/web/__tests__/integration/transcribe-early-segments.test.ts+++ b/apps/web/__tests__/integration/transcribe-early-segments.test.ts@@ -267,7 +267,12 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {);expect(stored?.durationMs).toBe(4500);- expect(mocks.updates.at(-1)).toEqual({ transcriptionStatus: "COMPLETE" });+ expect(mocks.updates).toContainEqual({ transcriptionStatus: "COMPLETE" });+ expect(mocks.updates).not.toContainEqual({ transcriptionStatus: "ERROR" });+ // the provisional live transcript is superseded by the canonical one+ expect(mocks.deleteObject.mock.calls.map((call) => call[0])).toContain(+ "user-456/video-123/transcription.live.json",+ );});it("defers back to the post-mux queue when the manifest is missing", async () => {@@ -349,6 +354,7 @@ describe("transcribeVideoWorkflow earlyFromSegments", () => {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" });+ expect(mocks.updates).toContainEqual({ transcriptionStatus: "COMPLETE" });+ expect(mocks.updates).not.toContainEqual({ transcriptionStatus: "ERROR" });});});diff --git a/apps/web/__tests__/unit/live-transcribe-core.test.ts b/apps/web/__tests__/unit/live-transcribe-core.test.tsnew file mode 100644index 000000000..76967bc58--- /dev/null+++ b/apps/web/__tests__/unit/live-transcribe-core.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it } from "vitest";+import {+ applyChunkToLiveTranscript,+ createEmptyLiveTranscript,+ offsetChunkWords,+ parseLiveTranscript,+ planNextLiveChunk,+} from "@/lib/live-transcribe-core";++const baseManifest = {+ version: 5,+ video_init_uploaded: true,+ audio_init_uploaded: true,+ video_segments: [] as unknown[],+ audio_segments: [] as unknown[],+ is_complete: false,+};++const seg = (index: number, duration = 2) => ({ index, duration });++describe("planNextLiveChunk", () => {+ it("waits while there is not enough new audio for a chunk", () => {+ const decision = planNextLiveChunk({+ manifest: {+ ...baseManifest,+ audio_segments: [seg(1), seg(2), seg(3)],+ },+ lastProcessedIndex: 0,+ targetSeconds: 15,+ });+ expect(decision).toEqual({ action: "wait" });+ });++ it("emits a chunk once the window target is reached, with the right offset", () => {+ const decision = planNextLiveChunk({+ manifest: {+ ...baseManifest,+ audio_segments: [1, 2, 3, 4, 5, 6, 7, 8].map((i) => seg(i)),+ },+ lastProcessedIndex: 2,+ targetSeconds: 10,+ });++ expect(decision).toMatchObject({+ action: "chunk",+ startMs: 4000,+ durationMs: 12000,+ });+ if (decision.action === "chunk") {+ expect(decision.entries.map((entry) => entry.index)).toEqual([+ 3, 4, 5, 6, 7, 8,+ ]);+ }+ });++ it("emits the remainder immediately once the manifest is complete", () => {+ const decision = planNextLiveChunk({+ manifest: {+ ...baseManifest,+ audio_segments: [seg(1), seg(2), seg(3)],+ is_complete: true,+ },+ lastProcessedIndex: 2,+ targetSeconds: 15,+ });+ expect(decision).toMatchObject({+ action: "chunk",+ startMs: 4000,+ durationMs: 2000,+ });+ });++ it("caps how much audio one chunk may take when catching up", () => {+ const decision = planNextLiveChunk({+ manifest: {+ ...baseManifest,+ audio_segments: Array.from({ length: 60 }, (_, i) => seg(i + 1)),+ },+ lastProcessedIndex: 0,+ targetSeconds: 15,+ maxTakeSeconds: 20,+ });+ expect(decision).toMatchObject({ action: "chunk", durationMs: 20000 });+ });++ it("never reads past a segment index gap", () => {+ const decision = 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)],+ is_complete: true,+ },+ lastProcessedIndex: 0,+ targetSeconds: 2,+ });+ expect(decision).toMatchObject({+ action: "chunk",+ startMs: 0,+ durationMs: 4000,+ });+ if (decision.action === "chunk") {+ expect(decision.entries.map((entry) => entry.index)).toEqual([1, 2]);+ }+ });++ it("finishes when a completed manifest has nothing contiguous left", () => {+ expect(+ planNextLiveChunk({+ manifest: {+ ...baseManifest,+ audio_segments: [seg(1), seg(2), seg(4)],+ is_complete: true,+ },+ lastProcessedIndex: 2,+ targetSeconds: 15,+ }),+ ).toEqual({ action: "done" });+ });++ it("reports no-audio only for completed manifests", () => {+ expect(+ planNextLiveChunk({+ manifest: { ...baseManifest, is_complete: true },+ lastProcessedIndex: 0,+ targetSeconds: 15,+ }),+ ).toEqual({ action: "no-audio" });+ expect(+ planNextLiveChunk({+ manifest: baseManifest,+ lastProcessedIndex: 0,+ targetSeconds: 15,+ }),+ ).toEqual({ action: "wait" });+ });+});++describe("offsetChunkWords", () => {+ it("offsets, clamps and filters words onto the recording timeline", () => {+ const words = offsetChunkWords(+ [+ { text: "hello", start: 100, end: 500, confidence: 0.9 },+ { text: "world", start: 500, end: 99999, speaker: "A" },+ { text: "", start: 0, end: 100 },+ { text: "bad", start: null as unknown as number, end: 100 },+ ],+ 10_000,+ 4_000,+ );++ expect(words).toHaveLength(2);+ expect(words[0]).toMatchObject({+ text: "hello",+ startMs: 10_100,+ endMs: 10_500,+ confidence: 0.9,+ });+ // end clamped to the chunk bound+ expect(words[1]).toMatchObject({+ text: "world",+ startMs: 10_500,+ endMs: 14_000,+ speaker: "A",+ });+ });+});++describe("live transcript artifact", () => {+ it("applies chunks idempotently and renders captions", () => {+ const empty = createEmptyLiveTranscript("2026-08-03T00:00:00.000Z");++ const chunk1 = applyChunkToLiveTranscript(empty, {+ startMs: 0,+ durationMs: 4000,+ lastAudioSegmentIndex: 2,+ words: offsetChunkWords(+ [{ text: "First", start: 0, end: 900 }],+ 0,+ 4000,+ ),+ languageCode: "en",+ nowIso: "2026-08-03T00:00:05.000Z",+ });++ const chunk2 = {+ startMs: 4000,+ durationMs: 4000,+ lastAudioSegmentIndex: 4,+ words: offsetChunkWords(+ [{ text: "second", start: 200, end: 1000 }],+ 4000,+ 4000,+ ),+ languageCode: "en" as const,+ nowIso: "2026-08-03T00:00:09.000Z",+ };++ const applied = applyChunkToLiveTranscript(chunk1, chunk2);+ // retrying the same chunk must not duplicate words+ const reapplied = applyChunkToLiveTranscript(applied, chunk2);++ expect(reapplied.words.map((word) => word.text)).toEqual([+ "First",+ "second",+ ]);+ expect(reapplied.lastAudioSegmentIndex).toBe(4);+ expect(reapplied.transcribedDurationMs).toBe(8000);+ expect(reapplied.languageCode).toBe("en");+ expect(reapplied.vtt.startsWith("WEBVTT")).toBe(true);+ expect(reapplied.vtt).toContain("First");+ expect(reapplied.vtt).toContain("second");++ const roundTripped = parseLiveTranscript(JSON.stringify(reapplied));+ expect(roundTripped).toEqual(reapplied);+ });++ it("rejects malformed artifacts", () => {+ expect(parseLiveTranscript("not json")).toBeNull();+ expect(parseLiveTranscript(JSON.stringify({ version: 99 }))).toBeNull();+ });+});diff --git a/apps/web/actions/videos/get-live-transcript.ts b/apps/web/actions/videos/get-live-transcript.tsnew file mode 100644index 000000000..493d76e50--- /dev/null+++ b/apps/web/actions/videos/get-live-transcript.ts@@ -0,0 +1,95 @@+"use server";++import { db } from "@cap/database";+import { videos } from "@cap/database/schema";+import { provideOptionalAuth, Storage, VideosPolicy } from "@cap/web-backend";+import { Policy, type Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect, Exit, Option } from "effect";+import {+ getLiveTranscriptObjectKey,+ type LiveTranscriptState,+ parseLiveTranscript,+} from "@/lib/live-transcribe-core";+import * as EffectRuntime from "@/lib/server";+import { runPromise } from "@/lib/server";+import { decodeStorageVideo } from "@/lib/video-storage";++export type GetLiveTranscriptResult = {+ success: boolean;+ message: string;+ content?: string;+ state?: LiveTranscriptState;+ updatedAt?: string;+};++/**+ * Provisional transcript of an instant-mode recording that is still being+ * (or was just) recorded. Only meaningful before the canonical transcription+ * completes; auth mirrors getTranscript exactly.+ */+export async function getLiveTranscript(+ videoId: Video.VideoId,+): Promise<GetLiveTranscriptResult> {+ if (!videoId) {+ return { success: false, message: "Missing video id" };+ }++ const exit = await Effect.gen(function* () {+ const videosPolicy = yield* VideosPolicy;++ return yield* Effect.promise(() =>+ db().select({ video: videos }).from(videos).where(eq(videos.id, videoId)),+ ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId)));+ }).pipe(provideOptionalAuth, EffectRuntime.runPromiseExit);++ if (Exit.isFailure(exit)) {+ return { success: false, message: "Video not found" };+ }++ const video = exit.value[0]?.video;+ if (!video) {+ return { success: false, message: "Video not found" };+ }++ // Once the canonical transcript exists the live one is superseded (and+ // normally already deleted); send clients to getTranscript instead.+ if (video.transcriptionStatus === "COMPLETE") {+ return { success: false, message: "Transcript is ready" };+ }++ try {+ const content = await Effect.gen(function* () {+ const [bucket] = yield* Storage.getAccessForVideo(+ decodeStorageVideo(video),+ );++ return yield* bucket.getObject(+ getLiveTranscriptObjectKey(video.ownerId, videoId),+ );+ }).pipe(runPromise);++ if (Option.isNone(content)) {+ return { success: false, message: "Live transcript not available" };+ }++ const artifact = parseLiveTranscript(content.value);+ if (!artifact) {+ return { success: false, message: "Live transcript not available" };+ }++ return {+ success: true,+ message: "Live transcript retrieved successfully",+ content: artifact.vtt,+ state: artifact.state,+ updatedAt: artifact.updatedAt,+ };+ } catch (error) {+ console.error("[getLiveTranscript] Error fetching live transcript:", {+ error: error instanceof Error ? error.message : error,+ videoId,+ });+ return { success: false, message: "Failed to fetch live transcript" };+ }+}diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.tsindex 63008fac5..ec2223bd2 100644--- a/apps/web/app/api/desktop/[...route]/video.ts+++ b/apps/web/app/api/desktop/[...route]/video.ts@@ -21,6 +21,7 @@ import { Effect, Option } from "effect";import { Hono } from "hono";import { z } from "zod";import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";+import { maybeStartLiveTranscription } from "@/lib/live-transcribe";import { runPromise } from "@/lib/server";import { decodeStorageVideo } from "@/lib/video-storage";import {@@ -147,6 +148,18 @@ app.get(});}+ if (+ video.source?.type === "desktopSegments" &&+ !video.isScreenshot &&+ !isScreenshot+ ) {+ await maybeStartLiveTranscription({+ videoId: video.id,+ ownerId: user.id,+ orgId: video.orgId,+ });+ }+return c.json({id: video.id,// All deprecated@@ -312,6 +325,14 @@ app.get(mode: "singlepart",});+ if (recordingMode === "desktopSegments" && !isScreenshot) {+ await maybeStartLiveTranscription({+ videoId: idToUse,+ ownerId: user.id,+ orgId: videoOrgId,+ });+ }+try {const videoCount = await db().select({ count: count() })diff --git a/apps/web/lib/live-transcribe-core.ts b/apps/web/lib/live-transcribe-core.tsnew file mode 100644index 000000000..cf22c7e0d--- /dev/null+++ b/apps/web/lib/live-transcribe-core.ts@@ -0,0 +1,264 @@+import type { Video } from "@cap/web-domain";+import {+ type EditTranscriptWord,+ editTranscriptWordsToCaptionVtt,+} from "@/lib/edit-transcript";+import type { NormalizedSegmentEntry } from "@/lib/segments-audio";+import { planSegmentsAudioExtraction } from "@/lib/segments-audio";++/**+ * Pure logic for the provisional live transcription of instant-mode+ * recordings: which audio segments form the next chunk, how chunk words are+ * placed on the recording timeline, and the `transcription.live.json`+ * artifact that the share page reads while the canonical transcription+ * doesn't exist yet.+ */++export const LIVE_TRANSCRIBE = {+ /** Chunk window while the recording is young — favors low latency. */+ INITIAL_CHUNK_SECONDS: 15,+ /** Chunk window after GROW_AFTER_CHUNKS — favors fewer, cheaper calls. */+ MAX_CHUNK_SECONDS: 30,+ GROW_AFTER_CHUNKS: 6,+ /** Catch-up bound: one chunk never covers more audio than this. */+ MAX_CHUNK_TAKE_SECONDS: 60,+ /** Hard cost cap: stop live-transcribing after this much audio; the+ * canonical post-stop transcription covers the full recording anyway. */+ MAX_TRANSCRIBED_SECONDS: 60 * 60,+ /** Hard backstop on chunk count (MAX_TRANSCRIBED / INITIAL implies ~240). */+ MAX_CHUNKS: 300,+ POLL_INTERVAL_MS: 3_000,+ /** One waiting step holds its invocation at most this long. */+ MAX_POLL_MS_PER_STEP: 120_000,+ /** Consecutive empty waiting steps before giving up (~8 minutes). */+ MAX_IDLE_STEPS: 4,+ /** Attempts per chunk before it is skipped so one poison chunk can never+ * wedge the loop or burn retries forever. */+ MAX_CHUNK_ATTEMPTS: 2,+} as const;++export type LiveChunkDecision =+ | { action: "wait" }+ | { action: "no-audio" }+ | { action: "done" }+ | {+ action: "chunk";+ entries: NormalizedSegmentEntry[];+ startMs: number;+ durationMs: number;+ };++/**+ * Choose the next contiguous run of unprocessed audio segments. Segments+ * after an index gap are never taken (a missing upload would silently shift+ * every later word), so a mid-recording gap pauses live transcription and a+ * gap in a completed manifest ends it.+ */+export function planNextLiveChunk(options: {+ manifest: Video.SegmentManifestType;+ lastProcessedIndex: number;+ targetSeconds: number;+ maxTakeSeconds?: number;+}): LiveChunkDecision {+ const { manifest, lastProcessedIndex, targetSeconds } = options;+ const maxTakeSeconds =+ options.maxTakeSeconds ?? LIVE_TRANSCRIBE.MAX_CHUNK_TAKE_SECONDS;++ const plan = planSegmentsAudioExtraction(manifest, { requireComplete: false });+ if (plan.status === "no-audio") {+ return manifest.is_complete ? { action: "no-audio" } : { action: "wait" };+ }+ if (plan.status !== "ok") {+ return { action: "wait" };+ }++ let startMs = 0;+ const pending: NormalizedSegmentEntry[] = [];+ let expectedIndex = plan.entries[0]?.index === 0 ? 0 : 1;++ for (const entry of plan.entries) {+ if (entry.index !== expectedIndex) break;+ expectedIndex++;++ if (entry.index <= lastProcessedIndex) {+ startMs += entry.duration * 1000;+ } else {+ pending.push(entry);+ }+ }++ if (pending.length === 0) {+ return manifest.is_complete ? { action: "done" } : { action: "wait" };+ }++ const taken: NormalizedSegmentEntry[] = [];+ let takenSeconds = 0;+ for (const entry of pending) {+ if (taken.length > 0 && takenSeconds + entry.duration > maxTakeSeconds) {+ break;+ }+ taken.push(entry);+ takenSeconds += entry.duration;+ if (takenSeconds >= maxTakeSeconds) break;+ }++ const tookEverything = taken.length === pending.length;+ if (!manifest.is_complete && tookEverything && takenSeconds < targetSeconds) {+ return { action: "wait" };+ }++ return {+ action: "chunk",+ entries: taken,+ startMs: Math.round(startMs),+ durationMs: Math.round(takenSeconds * 1000),+ };+}++export interface LiveChunkWordInput {+ text?: unknown;+ start?: unknown;+ end?: unknown;+ confidence?: unknown;+ speaker?: unknown;+}++/** Place a chunk's AssemblyAI words (chunk-relative ms) on the recording+ * timeline. Words outside the chunk bounds are clamped, invalid ones dropped. */+export function offsetChunkWords(+ words: readonly LiveChunkWordInput[] | null | undefined,+ chunkStartMs: number,+ chunkDurationMs: number,+): EditTranscriptWord[] {+ const result: EditTranscriptWord[] = [];++ for (const [index, word] of (words ?? []).entries()) {+ const text = typeof word.text === "string" ? word.text.trim() : "";+ const start = typeof word.start === "number" ? word.start : null;+ const end = typeof word.end === "number" ? word.end : null;+ if (!text || start === null || end === null || !Number.isFinite(start)) {+ continue;+ }++ const clamp = (value: number) =>+ Math.min(Math.max(Math.round(value), 0), chunkDurationMs);+ const startMs = chunkStartMs + clamp(start);+ const endMs = chunkStartMs + Math.max(clamp(end), clamp(start));++ result.push({+ id: `live-${chunkStartMs}-${index}`,+ text,+ startMs,+ endMs,+ confidence:+ typeof word.confidence === "number" ? word.confidence : null,+ speaker: typeof word.speaker === "string" ? word.speaker : null,+ channel: null,+ });+ }++ return result;+}++export const LIVE_TRANSCRIPT_VERSION = 1;++export type LiveTranscriptState = "active" | "complete" | "stopped";++export interface LiveTranscriptArtifact {+ version: typeof LIVE_TRANSCRIPT_VERSION;+ state: LiveTranscriptState;+ languageCode: string | null;+ lastAudioSegmentIndex: number;+ transcribedDurationMs: number;+ words: EditTranscriptWord[];+ vtt: string;+ updatedAt: string;+}++export function getLiveTranscriptObjectKey(ownerId: string, videoId: string) {+ return `${ownerId}/${videoId}/transcription.live.json`;+}++export function createEmptyLiveTranscript(nowIso: string): LiveTranscriptArtifact {+ return {+ version: LIVE_TRANSCRIPT_VERSION,+ state: "active",+ languageCode: null,+ lastAudioSegmentIndex: 0,+ transcribedDurationMs: 0,+ words: [],+ vtt: editTranscriptWordsToCaptionVtt([]),+ updatedAt: nowIso,+ };+}++export function parseLiveTranscript(+ value: string,+): LiveTranscriptArtifact | null {+ try {+ const parsed = JSON.parse(value) as Partial<LiveTranscriptArtifact>;+ if (+ parsed?.version !== LIVE_TRANSCRIPT_VERSION ||+ !Array.isArray(parsed.words) ||+ typeof parsed.vtt !== "string" ||+ typeof parsed.lastAudioSegmentIndex !== "number" ||+ typeof parsed.transcribedDurationMs !== "number"+ ) {+ return null;+ }+ return {+ version: LIVE_TRANSCRIPT_VERSION,+ state:+ parsed.state === "complete" || parsed.state === "stopped"+ ? parsed.state+ : "active",+ languageCode:+ typeof parsed.languageCode === "string" ? parsed.languageCode : null,+ lastAudioSegmentIndex: parsed.lastAudioSegmentIndex,+ transcribedDurationMs: parsed.transcribedDurationMs,+ words: parsed.words,+ vtt: parsed.vtt,+ updatedAt:+ typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",+ };+ } catch {+ return null;+ }+}++/**+ * Merge one transcribed chunk into the artifact. Idempotent per chunk range:+ * a retried chunk first evicts any words at or after its start.+ */+export function applyChunkToLiveTranscript(+ artifact: LiveTranscriptArtifact,+ chunk: {+ startMs: number;+ durationMs: number;+ lastAudioSegmentIndex: number;+ words: EditTranscriptWord[];+ languageCode: string | null;+ nowIso: string;+ },+): LiveTranscriptArtifact {+ const words = [+ ...artifact.words.filter((word) => word.startMs < chunk.startMs),+ ...chunk.words,+ ];++ return {+ ...artifact,+ languageCode: artifact.languageCode ?? chunk.languageCode,+ lastAudioSegmentIndex: Math.max(+ artifact.lastAudioSegmentIndex,+ chunk.lastAudioSegmentIndex,+ ),+ transcribedDurationMs: Math.max(+ artifact.transcribedDurationMs,+ chunk.startMs + chunk.durationMs,+ ),+ words,+ vtt: editTranscriptWordsToCaptionVtt(words),+ updatedAt: chunk.nowIso,+ };+}diff --git a/apps/web/lib/live-transcribe.ts b/apps/web/lib/live-transcribe.tsnew file mode 100644index 000000000..1958940a5--- /dev/null+++ b/apps/web/lib/live-transcribe.ts@@ -0,0 +1,90 @@+import { db } from "@cap/database";+import { organizations, videos } from "@cap/database/schema";+import { serverEnv } from "@cap/env";+import type { Organisation, User, Video } from "@cap/web-domain";+import { and, eq, sql } from "drizzle-orm";+import { start } from "workflow/api";+import { liveTranscribeWorkflow } from "@/workflows/live-transcribe";++const getAffectedRows = (result: unknown) => {+ if (Array.isArray(result)) {+ return (+ (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0+ );+ }++ return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;+};++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.+ */+export async function maybeStartLiveTranscription({+ videoId,+ ownerId,+ orgId,+}: {+ videoId: Video.VideoId;+ ownerId: User.UserId;+ orgId: Organisation.OrganisationId;+}): Promise<LiveTranscriptionStart> {+ try {+ const env = serverEnv();+ if (!env.CAP_LIVE_TRANSCRIPTION || !env.ASSEMBLY_API_KEY) {+ return "skipped";+ }++ const [org] = await db()+ .select({ settings: organizations.settings })+ .from(organizations)+ .where(eq(organizations.id, orgId));+ if (org?.settings?.disableTranscript) {+ return "skipped";+ }++ const claim = await db()+ .update(videos)+ .set({+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript', JSON_OBJECT('status', 'active', 'updatedAt', ${new Date().toISOString()}))`,+ updatedAt: sql`${videos.updatedAt}`,+ })+ .where(+ and(+ eq(videos.id, videoId),+ eq(videos.ownerId, ownerId),+ sql`JSON_EXTRACT(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript') IS NULL`,+ ),+ );++ if (getAffectedRows(claim) === 0) {+ return "skipped";+ }++ try {+ await start(liveTranscribeWorkflow, [{ videoId, userId: ownerId }]);+ } catch (error) {+ // Release the claim so a retried create can start the workflow.+ await db()+ .update(videos)+ .set({+ metadata: sql`JSON_REMOVE(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript')`,+ updatedAt: sql`${videos.updatedAt}`,+ })+ .where(eq(videos.id, videoId));+ throw error;+ }++ return "started";+ } catch (error) {+ console.warn(+ `[maybeStartLiveTranscription] Failed for ${videoId}`,+ error,+ );+ return "skipped";+ }+}diff --git a/apps/web/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.tsnew file mode 100644index 000000000..0dfb433f1--- /dev/null+++ b/apps/web/workflows/live-transcribe.ts@@ -0,0 +1,473 @@+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, videos } from "@cap/database/schema";+import { serverEnv } from "@cap/env";+import { Storage } from "@cap/web-backend/src/Storage/index";+import {+ type AiGenerationLanguage,+ parseAiGenerationLanguage,+ Video,+} from "@cap/web-domain";+import { AssemblyAI } from "assemblyai";+import { eq, sql } from "drizzle-orm";+import { Either, Option, Schema } from "effect";+import {+ ASSEMBLYAI_SUPPORTED_LANGUAGES,+ getAssemblyAITranscriptionOptions,+} from "@/lib/assemblyai";+import { extractAudioFromUrl } from "@/lib/audio-extract";+import {+ applyChunkToLiveTranscript,+ createEmptyLiveTranscript,+ getLiveTranscriptObjectKey,+ LIVE_TRANSCRIBE,+ type LiveTranscriptState,+ offsetChunkWords,+ parseLiveTranscript,+ planNextLiveChunk,+} from "@/lib/live-transcribe-core";+import { downloadConcatenatedSegments } from "@/lib/segments-audio";+import { decodeStorageVideo } from "@/lib/video-storage";+import { runWorkflowPromise } from "@/lib/workflow-runtime";++interface LiveTranscribeWorkflowPayload {+ videoId: string;+ userId: string;+}++type InitResult =+ | { ok: false; reason: string }+ | {+ ok: true;+ lastAudioSegmentIndex: number;+ transcribedDurationMs: number;+ languageCode: string | null;+ orgLanguage: AiGenerationLanguage;+ };++type ChunkStepResult =+ | { outcome: "chunk"; lastAudioSegmentIndex: number; transcribedDurationMs: number; languageCode: string | null }+ | { outcome: "chunk-failed"; failedAtIndex: number; reason: string }+ | { outcome: "waiting" }+ | { outcome: "done" }+ | { outcome: "no-audio" }+ | { outcome: "canonical-done" }+ | { 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.+ */+export async function liveTranscribeWorkflow(+ payload: LiveTranscribeWorkflowPayload,+) {+ "use workflow";++ const { videoId, userId } = payload;++ const init = await initLiveTranscription(videoId, userId);+ if (!init.ok) {+ await finishLiveTranscription(videoId, userId, "stopped");+ return { success: true, message: `Live transcription skipped: ${init.reason}` };+ }++ let lastIndex = init.lastAudioSegmentIndex;+ let transcribedMs = init.transcribedDurationMs;+ let languageCode = init.languageCode;+ let chunkCount = 0;+ let idleSteps = 0;+ let failuresAtIndex = 0;+ let outcome = "chunk-limit";++ while (chunkCount < LIVE_TRANSCRIBE.MAX_CHUNKS) {+ if (transcribedMs >= LIVE_TRANSCRIBE.MAX_TRANSCRIBED_SECONDS * 1000) {+ outcome = "budget-exhausted";+ break;+ }++ const targetSeconds =+ chunkCount < LIVE_TRANSCRIBE.GROW_AFTER_CHUNKS+ ? LIVE_TRANSCRIBE.INITIAL_CHUNK_SECONDS+ : LIVE_TRANSCRIBE.MAX_CHUNK_SECONDS;++ const result = await processNextLiveChunk({+ videoId,+ userId,+ lastProcessedIndex: lastIndex,+ targetSeconds,+ language: languageCode ?? init.orgLanguage,+ // After repeated failures the chunk is skipped: advance past it and+ // leave a gap for the canonical transcription to fill.+ skipPastFailedChunk:+ failuresAtIndex >= LIVE_TRANSCRIBE.MAX_CHUNK_ATTEMPTS,+ });++ if (result.outcome === "chunk") {+ lastIndex = result.lastAudioSegmentIndex;+ transcribedMs = result.transcribedDurationMs;+ languageCode = languageCode ?? result.languageCode;+ chunkCount++;+ idleSteps = 0;+ failuresAtIndex = 0;+ continue;+ }++ if (result.outcome === "chunk-failed") {+ failuresAtIndex++;+ continue;+ }++ if (result.outcome === "waiting") {+ idleSteps++;+ if (idleSteps >= LIVE_TRANSCRIBE.MAX_IDLE_STEPS) {+ outcome = "stalled";+ break;+ }+ continue;+ }++ outcome = result.outcome;+ break;+ }++ await finishLiveTranscription(+ videoId,+ userId,+ outcome === "done" ? "complete" : "stopped",+ );++ return { success: true, message: `Live transcription ${outcome}` };+}++async function initLiveTranscription(+ videoId: string,+ userId: string,+): Promise<InitResult> {+ "use step";++ if (!serverEnv().ASSEMBLY_API_KEY) {+ return { ok: false, reason: "missing ASSEMBLY_API_KEY" };+ }++ const [row] = await db()+ .select({ video: videos, orgSettings: organizations.settings })+ .from(videos)+ .leftJoin(organizations, eq(videos.orgId, organizations.id))+ .where(eq(videos.id, videoId as Video.VideoId));++ if (!row?.video || row.video.ownerId !== userId) {+ return { ok: false, reason: "video not found" };+ }+ if (row.video.source.type !== "desktopSegments") {+ return { ok: false, reason: "not a segmented recording" };+ }+ if (+ row.video.settings?.disableTranscript ??+ row.orgSettings?.disableTranscript+ ) {+ return { ok: false, reason: "transcription disabled" };+ }+ if (row.video.transcriptionStatus === "COMPLETE") {+ return { ok: false, reason: "canonical transcript already exists" };+ }++ // Resume from a previous run's artifact after a crash/redeploy so already+ // paid-for chunks are never re-transcribed.+ let lastAudioSegmentIndex = 0;+ let transcribedDurationMs = 0;+ let languageCode: string | null = null;+ try {+ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(row.video),+ ).pipe(runWorkflowPromise);+ const existing = await bucket+ .getObject(getLiveTranscriptObjectKey(row.video.ownerId, videoId))+ .pipe(runWorkflowPromise);+ const artifact = Option.isSome(existing)+ ? parseLiveTranscript(existing.value)+ : null;+ if (artifact) {+ lastAudioSegmentIndex = artifact.lastAudioSegmentIndex;+ transcribedDurationMs = artifact.transcribedDurationMs;+ languageCode = artifact.languageCode;+ }+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to read existing artifact for ${videoId}`,+ error,+ );+ }++ return {+ ok: true,+ lastAudioSegmentIndex,+ transcribedDurationMs,+ languageCode,+ orgLanguage: parseAiGenerationLanguage(row.orgSettings?.aiGenerationLanguage),+ };+}++async function processNextLiveChunk(options: {+ videoId: string;+ userId: string;+ lastProcessedIndex: number;+ targetSeconds: number;+ language: string;+ skipPastFailedChunk: boolean;+}): Promise<ChunkStepResult> {+ "use step";++ const { videoId, userId, lastProcessedIndex, targetSeconds } = options;++ const [video] = await db()+ .select()+ .from(videos)+ .where(eq(videos.id, videoId as Video.VideoId));++ if (!video) return { outcome: "gone" };+ if (+ video.transcriptionStatus === "COMPLETE" ||+ video.transcriptionStatus === "SKIPPED" ||+ video.transcriptionStatus === "NO_AUDIO"+ ) {+ // The canonical pipeline finished (or decided) while we were running;+ // everything from here on would be wasted spend.+ return { outcome: "canonical-done" };+ }+ if (video.settings?.disableTranscript) {+ return { outcome: "canonical-done" };+ }++ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(video),+ ).pipe(runWorkflowPromise);+ const segSource = new Video.SegmentsSource({+ videoId,+ ownerId: video.ownerId,+ });++ // Poll inside the step (same pattern as the mux-completion wait) so idle+ // 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;++ while (Date.now() < pollDeadline) {+ const manifestContent = await bucket+ .getObject(segSource.getManifestKey())+ .pipe(runWorkflowPromise)+ .catch(() => Option.none<string>());+ const manifestJson = Option.getOrNull(manifestContent);++ if (manifestJson) {+ let parsed: unknown = null;+ try {+ parsed = JSON.parse(manifestJson);+ } catch {}+ const decoded = parsed+ ? Schema.decodeUnknownEither(Video.SegmentManifest)(parsed)+ : null;++ if (decoded && Either.isRight(decoded)) {+ const next = planNextLiveChunk({+ manifest: decoded.right,+ lastProcessedIndex,+ targetSeconds,+ });+ if (next.action !== "wait") {+ decision = next;+ break;+ }+ }+ }++ await new Promise((resolve) =>+ setTimeout(resolve, LIVE_TRANSCRIBE.POLL_INTERVAL_MS),+ );+ }++ if (!decision) return { outcome: "waiting" };+ if (decision.action === "done") return { outcome: "done" };+ if (decision.action === "no-audio") return { outcome: "no-audio" };+ if (decision.action !== "chunk") return { outcome: "waiting" };++ const chunkEndIndex =+ decision.entries[decision.entries.length - 1]?.index ?? lastProcessedIndex;++ if (options.skipPastFailedChunk) {+ console.warn(+ `[liveTranscribe] Skipping poison chunk ${lastProcessedIndex + 1}..${chunkEndIndex} for ${videoId}`,+ );+ return {+ outcome: "chunk",+ lastAudioSegmentIndex: chunkEndIndex,+ transcribedDurationMs: decision.startMs + decision.durationMs,+ languageCode: null,+ };+ }++ try {+ const segmentUrls = await Promise.all([+ bucket+ .getInternalSignedObjectUrl(segSource.getAudioInitKey())+ .pipe(runWorkflowPromise),+ ...decision.entries.map((entry) =>+ bucket+ .getInternalSignedObjectUrl(segSource.getAudioSegmentKey(entry.index))+ .pipe(runWorkflowPromise),+ ),+ ]);++ const concatPath = join(tmpdir(), `live-chunk-${randomUUID()}.mp4`);+ let audioBuffer: Buffer;+ try {+ await downloadConcatenatedSegments(segmentUrls, concatPath);+ const extracted = await extractAudioFromUrl(concatPath);+ try {+ audioBuffer = await fs.readFile(extracted.filePath);+ } finally {+ await extracted.cleanup();+ }+ } finally {+ await fs.unlink(concatPath).catch(() => {});+ }++ const client = new AssemblyAI({+ apiKey: serverEnv().ASSEMBLY_API_KEY as string,+ });+ const language = (+ ASSEMBLYAI_SUPPORTED_LANGUAGES as readonly string[]+ ).includes(options.language)+ ? (options.language as AiGenerationLanguage)+ : ("auto" as AiGenerationLanguage);+ const transcript = await client.transcripts.transcribe({+ audio: audioBuffer,+ ...getAssemblyAITranscriptionOptions(language),+ disfluencies: true,+ });++ if (transcript.status === "error") {+ throw new Error(transcript.error ?? "AssemblyAI chunk failed");+ }++ const words = offsetChunkWords(+ transcript.words,+ decision.startMs,+ decision.durationMs,+ );++ 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());++ const updated = applyChunkToLiveTranscript(artifact, {+ startMs: decision.startMs,+ durationMs: decision.durationMs,+ lastAudioSegmentIndex: chunkEndIndex,+ words,+ languageCode:+ typeof transcript.language_code === "string"+ ? transcript.language_code+ : null,+ nowIso: new Date().toISOString(),+ });++ const body = JSON.stringify(updated);+ await bucket+ .putObject(artifactKey, body, { contentType: "application/json" })+ .pipe(runWorkflowPromise);++ console.log(+ `[liveTranscribe] ${videoId} chunk ${lastProcessedIndex + 1}..${chunkEndIndex} (${decision.durationMs}ms, ${words.length} words)`,+ );++ return {+ outcome: "chunk",+ lastAudioSegmentIndex: chunkEndIndex,+ transcribedDurationMs: updated.transcribedDurationMs,+ languageCode: updated.languageCode,+ };+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ console.warn(+ `[liveTranscribe] Chunk ${lastProcessedIndex + 1}..${chunkEndIndex} failed for ${videoId}: ${reason}`,+ );+ return {+ outcome: "chunk-failed",+ failedAtIndex: lastProcessedIndex,+ reason,+ };+ }+}++async function finishLiveTranscription(+ videoId: string,+ userId: string,+ state: LiveTranscriptState,+): Promise<void> {+ "use step";++ try {+ await db()+ .update(videos)+ .set({+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.liveTranscript.status', ${state}, '$.liveTranscript.updatedAt', ${new Date().toISOString()})`,+ updatedAt: sql`${videos.updatedAt}`,+ })+ .where(eq(videos.id, videoId as Video.VideoId));+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to update metadata for ${videoId}`,+ error,+ );+ }++ try {+ const [video] = await db()+ .select()+ .from(videos)+ .where(eq(videos.id, videoId as Video.VideoId));+ if (!video || video.ownerId !== userId) return;++ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(video),+ ).pipe(runWorkflowPromise);+ const artifactKey = getLiveTranscriptObjectKey(video.ownerId, videoId);+ const existing = await bucket+ .getObject(artifactKey)+ .pipe(runWorkflowPromise)+ .catch(() => Option.none<string>());+ if (Option.isNone(existing)) return;++ const artifact = parseLiveTranscript(existing.value);+ if (!artifact || artifact.state === state) return;++ await bucket+ .putObject(+ artifactKey,+ JSON.stringify({+ ...artifact,+ state,+ updatedAt: new Date().toISOString(),+ }),+ { contentType: "application/json" },+ )+ .pipe(runWorkflowPromise);+ } catch (error) {+ console.warn(+ `[liveTranscribe] Failed to finalize artifact for ${videoId}`,+ error,+ );+ }+}diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.tsindex b005e316d..313c31288 100644--- a/apps/web/workflows/transcribe.ts+++ b/apps/web/workflows/transcribe.ts@@ -43,6 +43,7 @@ import {isMediaServerConfigured,probeVideoViaMediaServer,} from "@/lib/media-client";+import { getLiveTranscriptObjectKey } from "@/lib/live-transcribe-core";import {downloadConcatenatedSegments,planSegmentsAudioExtraction,@@ -801,6 +802,32 @@ async function saveTranscription(.update(videos).set({ transcriptionStatus: "COMPLETE" }).where(eq(videos.id, videoId as Video.VideoId));++ // The canonical transcript supersedes the provisional live transcript, so+ // drop the artifact and its metadata flag. Never fatal: a leftover live+ // artifact is unused once transcriptionStatus is COMPLETE.+ if (+ video.source.type === "desktopSegments" ||+ video.source.type === "desktopMP4"+ ) {+ try {+ 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,+ );+ }+ }}async function saveEditTranscriptBackfill(diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.tsindex 86a5e5010..27f8396ae 100644--- a/packages/database/types/metadata.ts+++ b/packages/database/types/metadata.ts@@ -34,6 +34,16 @@ export interface VideoMetadata {| "COMPLETE"| "ERROR"| "SKIPPED";+ /**+ * Progress of the provisional live transcription that runs while an+ * instant-mode recording is still uploading. The transcript content lives+ * in `transcription.live.json` next to the video; this only gates UI/queue+ * behavior. Cleared when the canonical transcription completes.+ */+ liveTranscript?: {+ status: "active" | "complete" | "stopped";+ updatedAt?: string;+ };enhancedAudioStatus?: "PROCESSING" | "COMPLETE" | "ERROR" | "SKIPPED";agentUpload?: {state: "pending" | "accepted" | "rejected";diff --git a/packages/env/server.ts b/packages/env/server.tsindex 0c1da1a92..d029b1122 100644--- a/packages/env/server.ts+++ b/packages/env/server.ts@@ -90,6 +90,9 @@ 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"),