Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): keep workflow-body imports free of Node.js modules
Richie McIlroy88a1d91b44b2
diff --git a/apps/web/__tests__/unit/segments-audio.test.ts b/apps/web/__tests__/unit/segments-audio.test.tsindex 632eb1de2..ab3759184 100644--- a/apps/web/__tests__/unit/segments-audio.test.ts+++ b/apps/web/__tests__/unit/segments-audio.test.ts@@ -2,10 +2,8 @@ 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";+import { planSegmentsAudioExtraction } from "@/lib/segments-audio";+import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";const completeManifest = {version: 5,diff --git a/apps/web/lib/desktop-segments-finalization.ts b/apps/web/lib/desktop-segments-finalization.tsindex 5b610fbe6..3db75ec03 100644--- a/apps/web/lib/desktop-segments-finalization.ts+++ b/apps/web/lib/desktop-segments-finalization.ts@@ -109,12 +109,14 @@ export async function queueDesktopSegmentsFinalization({// 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,- );- });+ 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/live-transcribe-core.ts b/apps/web/lib/live-transcribe-core.tsindex cf22c7e0d..e23096df9 100644--- a/apps/web/lib/live-transcribe-core.ts+++ b/apps/web/lib/live-transcribe-core.ts@@ -64,7 +64,9 @@ export function planNextLiveChunk(options: {const maxTakeSeconds =options.maxTakeSeconds ?? LIVE_TRANSCRIBE.MAX_CHUNK_TAKE_SECONDS;- const plan = planSegmentsAudioExtraction(manifest, { requireComplete: false });+ const plan = planSegmentsAudioExtraction(manifest, {+ requireComplete: false,+ });if (plan.status === "no-audio") {return manifest.is_complete ? { action: "no-audio" } : { action: "wait" };}@@ -150,8 +152,7 @@ export function offsetChunkWords(text,startMs,endMs,- confidence:- typeof word.confidence === "number" ? word.confidence : null,+ confidence: typeof word.confidence === "number" ? word.confidence : null,speaker: typeof word.speaker === "string" ? word.speaker : null,channel: null,});@@ -179,7 +180,9 @@ export function getLiveTranscriptObjectKey(ownerId: string, videoId: string) {return `${ownerId}/${videoId}/transcription.live.json`;}-export function createEmptyLiveTranscript(nowIso: string): LiveTranscriptArtifact {+export function createEmptyLiveTranscript(+ nowIso: string,+): LiveTranscriptArtifact {return {version: LIVE_TRANSCRIPT_VERSION,state: "active",@@ -218,8 +221,7 @@ export function parseLiveTranscript(transcribedDurationMs: parsed.transcribedDurationMs,words: parsed.words,vtt: parsed.vtt,- updatedAt:- typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",};} catch {return null;diff --git a/apps/web/lib/live-transcribe.ts b/apps/web/lib/live-transcribe.tsindex 1958940a5..46c4c739f 100644--- a/apps/web/lib/live-transcribe.ts+++ b/apps/web/lib/live-transcribe.ts@@ -81,10 +81,7 @@ export async function maybeStartLiveTranscription({return "started";} catch (error) {- console.warn(- `[maybeStartLiveTranscription] Failed for ${videoId}`,- error,- );+ console.warn(`[maybeStartLiveTranscription] Failed for ${videoId}`, error);return "skipped";}}diff --git a/apps/web/lib/segments-audio-download.ts b/apps/web/lib/segments-audio-download.tsnew file mode 100644index 000000000..064a310c4--- /dev/null+++ b/apps/web/lib/segments-audio-download.ts@@ -0,0 +1,69 @@+import { createWriteStream } from "node:fs";++/**+ * Byte-level segment assembly. Lives apart from the pure planning helpers in+ * `segments-audio.ts` so workflow bodies (which the workflow compiler bans+ * Node.js modules in) can import the planners; only step code imports this.+ */++/** 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/segments-audio.ts b/apps/web/lib/segments-audio.tsindex f99b6846d..ba0531fec 100644--- a/apps/web/lib/segments-audio.ts+++ b/apps/web/lib/segments-audio.ts@@ -1,4 +1,3 @@-import { createWriteStream } from "node:fs";import { Video } from "@cap/web-domain";/**@@ -68,62 +67,3 @@ export function planSegmentsAudioExtraction(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/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.tsindex 0dfb433f1..6720fdb42 100644--- a/apps/web/workflows/live-transcribe.ts+++ b/apps/web/workflows/live-transcribe.ts@@ -29,7 +29,7 @@ import {parseLiveTranscript,planNextLiveChunk,} from "@/lib/live-transcribe-core";-import { downloadConcatenatedSegments } from "@/lib/segments-audio";+import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -49,7 +49,12 @@ type InitResult =};type ChunkStepResult =- | { outcome: "chunk"; lastAudioSegmentIndex: number; transcribedDurationMs: number; languageCode: string | null }+ | {+ outcome: "chunk";+ lastAudioSegmentIndex: number;+ transcribedDurationMs: number;+ languageCode: string | null;+ }| { outcome: "chunk-failed"; failedAtIndex: number; reason: string }| { outcome: "waiting" }| { outcome: "done" }@@ -75,7 +80,10 @@ export async function liveTranscribeWorkflow(const init = await initLiveTranscription(videoId, userId);if (!init.ok) {await finishLiveTranscription(videoId, userId, "stopped");- return { success: true, message: `Live transcription skipped: ${init.reason}` };+ return {+ success: true,+ message: `Live transcription skipped: ${init.reason}`,+ };}let lastIndex = init.lastAudioSegmentIndex;@@ -86,55 +94,62 @@ export async function liveTranscribeWorkflow(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,- });+ try {+ while (chunkCount < LIVE_TRANSCRIBE.MAX_CHUNKS) {+ if (transcribedMs >= LIVE_TRANSCRIBE.MAX_TRANSCRIBED_SECONDS * 1000) {+ outcome = "budget-exhausted";+ break;+ }- if (result.outcome === "chunk") {- lastIndex = result.lastAudioSegmentIndex;- transcribedMs = result.transcribedDurationMs;- languageCode = languageCode ?? result.languageCode;- chunkCount++;- idleSteps = 0;- failuresAtIndex = 0;- continue;- }+ 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 === "chunk-failed") {+ failuresAtIndex++;+ continue;+ }- if (result.outcome === "waiting") {- idleSteps++;- if (idleSteps >= LIVE_TRANSCRIBE.MAX_IDLE_STEPS) {- outcome = "stalled";- break;+ if (result.outcome === "waiting") {+ idleSteps++;+ if (idleSteps >= LIVE_TRANSCRIBE.MAX_IDLE_STEPS) {+ outcome = "stalled";+ break;+ }+ continue;}- continue;- }- outcome = result.outcome;- break;+ outcome = result.outcome;+ break;+ }+ } catch (error) {+ // A step exhausted its retries; make sure the artifact and metadata+ // never advertise a live transcription that is no longer running.+ await finishLiveTranscription(videoId, userId, "stopped");+ throw error;}await finishLiveTranscription(@@ -210,7 +225,9 @@ async function initLiveTranscription(lastAudioSegmentIndex,transcribedDurationMs,languageCode,- orgLanguage: parseAiGenerationLanguage(row.orgSettings?.aiGenerationLanguage),+ orgLanguage: parseAiGenerationLanguage(+ row.orgSettings?.aiGenerationLanguage,+ ),};}diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.tsindex 313c31288..e975bb096 100644--- a/apps/web/workflows/transcribe.ts+++ b/apps/web/workflows/transcribe.ts@@ -44,10 +44,8 @@ import {probeVideoViaMediaServer,} from "@/lib/media-client";import { getLiveTranscriptObjectKey } from "@/lib/live-transcribe-core";-import {- downloadConcatenatedSegments,- planSegmentsAudioExtraction,-} from "@/lib/segments-audio";+import { planSegmentsAudioExtraction } from "@/lib/segments-audio";+import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";