Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: transcript race condition (#999)
Ameer Al Ashhabd9c496124829
diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.tsindex 87b24caef..eb4a0d8cd 100644--- a/apps/web/actions/videos/get-status.ts+++ b/apps/web/actions/videos/get-status.ts@@ -16,11 +16,10 @@ const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000;export interface VideoStatusResult {transcriptionStatus: "PROCESSING" | "COMPLETE" | "ERROR" | null;- aiProcessing: boolean;aiTitle: string | null;+ aiProcessing: boolean;summary: string | null;chapters: { title: string; start: number }[] | null;- // generationError: string | null;error?: string;}diff --git a/apps/web/app/api/videos/[videoId]/retry-transcription/route.ts b/apps/web/app/api/videos/[videoId]/retry-transcription/route.tsnew file mode 100644index 000000000..8f84a0af6--- /dev/null+++ b/apps/web/app/api/videos/[videoId]/retry-transcription/route.ts@@ -0,0 +1,55 @@+import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";+import { videos } from "@cap/database/schema";+import { eq } from "drizzle-orm";+import { revalidatePath } from "next/cache";++export async function POST(+ _request: Request,+ { params }: { params: { videoId: string } },+) {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return Response.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { videoId } = params;+ if (!videoId) {+ return Response.json({ error: "Video ID is required" }, { status: 400 });+ }++ // Verify user owns the video+ const videoQuery = await db()+ .select()+ .from(videos)+ .where(eq(videos.id, videoId))+ .limit(1);++ if (videoQuery.length === 0) {+ return Response.json({ error: "Video not found" }, { status: 404 });+ }++ const video = videoQuery[0];+ if (!video || video.ownerId !== user.id) {+ return Response.json({ error: "Unauthorized" }, { status: 403 });+ }++ // Reset status to null - this will trigger automatic retry via get-status.ts+ await db()+ .update(videos)+ .set({ transcriptionStatus: null })+ .where(eq(videos.id, videoId));++ // Revalidate the video page to ensure UI updates with fresh data+ revalidatePath(`/s/${videoId}`);++ return Response.json({+ success: true,+ message: "Transcription retry triggered",+ });+ } catch (error) {+ console.error("Error resetting transcription status:", error);+ return Response.json({ error: "Internal server error" }, { status: 500 });+ }+}diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsxindex 54e1c147f..64cc7ae3d 100644--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx@@ -2,6 +2,7 @@import type { videos } from "@cap/database/schema";import { Button } from "@cap/ui";+import { useMutation } from "@tanstack/react-query";import { useInvalidateTranscript, useTranscript } from "hooks/use-transcript";import { Check, Copy, Download, Edit3, MessageSquare, X } from "lucide-react";import { useEffect, useState } from "react";@@ -142,6 +143,33 @@ export const Transcript: React.FC<TranscriptProps> = ({const invalidateTranscript = useInvalidateTranscript();+ const retryTranscriptionMutation = useMutation({+ mutationFn: async () => {+ const response = await fetch(+ `/api/videos/${data.id}/retry-transcription`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ },+ );++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to retry transcription: ${errorText}`);+ }++ return response.json();+ },+ onSuccess: () => {+ // Reset status - Share.tsx polling will automatically detect the change and trigger transcription+ setIsTranscriptionProcessing(true);+ invalidateTranscript(data.id);+ },+ onError: (error) => {+ console.error("Failed to retry transcription:", error);+ },+ });+useEffect(() => {if (transcriptContent) {const parsed = parseVTT(transcriptContent);@@ -212,11 +240,6 @@ export const Transcript: React.FC<TranscriptProps> = ({}}, [data.id, data.transcriptionStatus, data.createdAt]);- const handleReset = () => {- setIsLoading(true);- invalidateTranscript(data.id);- };-const handleTranscriptClick = (entry: TranscriptEntry) => {if (editingEntry === entry.id) {return;@@ -421,14 +444,39 @@ export const Transcript: React.FC<TranscriptProps> = ({);}- if (hasTimedOut || (!transcriptData.length && !isTranscriptionProcessing)) {+ const showRetryButton =+ data.transcriptionStatus === "ERROR" ||+ data.transcriptionStatus === null ||+ (!transcriptData.length && !isTranscriptionProcessing);++ if (showRetryButton) {return (<div className="flex justify-center items-center h-full text-gray-1"><div className="text-center"><MessageSquare className="mx-auto mb-2 w-8 h-8 text-gray-300" />- <p className="text-sm font-medium text-gray-12">- No transcript available+ <p className="mb-4 text-sm font-medium text-gray-12">+ {data.transcriptionStatus === "ERROR"+ ? "Transcript not available"+ : "No transcript available"}</p>+ {canEdit &&+ (data.transcriptionStatus === "ERROR" ||+ data.transcriptionStatus === null ||+ hasTimedOut) && (+ <Button+ onClick={() => {+ retryTranscriptionMutation.mutate();+ }}+ disabled={retryTranscriptionMutation.isPending}+ variant="primary"+ size="sm"+ spinner={retryTranscriptionMutation.isPending}+ >+ {retryTranscriptionMutation.isPending+ ? "Retrying..."+ : "Retry Transcription"}+ </Button>+ )}</div></div>);@@ -518,6 +566,7 @@ export const Transcript: React.FC<TranscriptProps> = ({e.stopPropagation();startEditing(entry);}}+ type="button"className="opacity-0 group-hover:opacity-100 p-1.5 hover:bg-gray-3 rounded-md transition-all duration-200"title="Edit transcript">diff --git a/apps/web/hooks/use-transcript.ts b/apps/web/hooks/use-transcript.tsindex ad35c7d44..e5731f98f 100644--- a/apps/web/hooks/use-transcript.ts+++ b/apps/web/hooks/use-transcript.ts@@ -13,10 +13,6 @@ export const useTranscript = (if (result.success && result.content) {return result.content;} else {- console.error(- "[useTranscript] Failed to fetch transcript:",- result.message,- );if (result.message === "Transcript is not ready yet") {throw new Error("TRANSCRIPT_NOT_READY");}diff --git a/apps/web/lib/transcribe.ts b/apps/web/lib/transcribe.tsindex 138f819ae..8fdc660de 100644--- a/apps/web/lib/transcribe.ts+++ b/apps/web/lib/transcribe.ts@@ -16,6 +16,7 @@ export async function transcribeVideo(videoId: Video.VideoId,userId: string,aiGenerationEnabled = false,+ isRetry = false,): Promise<TranscribeResult> {if (!serverEnv().DEEPGRAM_API_KEY) {return {@@ -77,8 +78,39 @@ export async function transcribeVideo(const videoUrl = await bucket.getSignedObjectUrl(videoKey);+ // Check if video file actually exists before transcribing+ try {+ const headResponse = await fetch(videoUrl, { method: "HEAD" });+ if (!headResponse.ok) {+ // Video not ready yet - reset to null for retry+ await db()+ .update(videos)+ .set({ transcriptionStatus: null })+ .where(eq(videos.id, videoId));++ return {+ success: false,+ message: "Video file not ready yet - will retry automatically",+ };+ }+ } catch {+ console.log(+ `[transcribeVideo] Video file not accessible yet for ${videoId}, will retry later`,+ );+ await db()+ .update(videos)+ .set({ transcriptionStatus: null })+ .where(eq(videos.id, videoId));++ return {+ success: false,+ message: "Video file not ready yet - will retry automatically",+ };+ }+const transcription = await transcribeAudio(videoUrl);+ // Note: Empty transcription is valid for silent videos (just contains "WEBVTT\n\n")if (transcription === "") {throw new Error("Failed to transcribe audio");}@@ -127,12 +159,28 @@ export async function transcribeVideo(};} catch (error) {console.error("Error transcribing video:", error);++ // Determine if this is a temporary or permanent error+ const errorMessage = error instanceof Error ? error.message : String(error);+ const isTemporaryError =+ errorMessage.includes("not found") ||+ errorMessage.includes("access denied") ||+ errorMessage.includes("network") ||+ !isRetry; // First attempt failures are often temporary++ const newStatus = isTemporaryError ? null : "ERROR";+await db().update(videos)- .set({ transcriptionStatus: "ERROR" })+ .set({ transcriptionStatus: newStatus }).where(eq(videos.id, videoId));- return { success: false, message: "Error processing video file" };+ return {+ success: false,+ message: isTemporaryError+ ? "Video not ready - will retry"+ : "Transcription failed permanently",+ };}}@@ -140,6 +188,14 @@ function formatToWebVTT(result: any): string {let output = "WEBVTT\n\n";let captionIndex = 1;+ // Handle case where there are no utterances (silent video)+ if (!result.results.utterances || result.results.utterances.length === 0) {+ console.log(+ "[formatToWebVTT] No utterances found - video appears to be silent",+ );+ return output; // Return valid but empty VTT file+ }+result.results.utterances.forEach((utterance: any) => {const words = utterance.words;let group = [];