Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve AI metadata and transcript processing logic

Richie McIlroyd807cd1c283d
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 75320936e..78a94b74e 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -85,7 +85,11 @@
"Bash(if [ -f \"$segment/audio.ogg\" ])",
"Bash(then ffprobe -v error -show_entries format=duration -of default=nw=1 \"$segment/audio.ogg\")",
"Bash(done)",
- "Bash(./target/release/examples/real-device-test-runner:*)"
+ "Bash(./target/release/examples/real-device-test-runner:*)",
+ "Bash(pnpm --dir apps/web exec tsc:*)",
+ "mcp__plugin_greptile_greptile__list_pull_requests",
+ "mcp__plugin_greptile_greptile__search_custom_context",
+ "mcp__plugin_greptile_greptile__list_code_reviews"
],
"deny": [],
"ask": []
diff --git a/apps/web/actions/videos/generate-ai-metadata.ts b/apps/web/actions/videos/generate-ai-metadata.ts
index 9bfa72d69..5fa928adb 100644
--- a/apps/web/actions/videos/generate-ai-metadata.ts
+++ b/apps/web/actions/videos/generate-ai-metadata.ts
@@ -6,7 +6,7 @@ import type { VideoMetadata } from "@cap/database/types";
import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
import type { Video } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { and, eq, sql } from "drizzle-orm";
import { Effect, Option } from "effect";
import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";
import { runPromise } from "@/lib/server";
@@ -52,8 +52,6 @@ export async function generateAiMetadata(
},
})
.where(eq(videos.id, videoId));
-
- metadata.aiProcessing = false;
} else {
return;
}
@@ -89,16 +87,33 @@ export async function generateAiMetadata(
return;
}
+ const lockResult = await db()
+ .update(videos)
+ .set({
+ metadata: {
+ ...metadata,
+ aiProcessing: true,
+ },
+ })
+ .where(
+ and(
+ eq(videos.id, videoId),
+ sql`JSON_EXTRACT(metadata, '$.aiProcessing') IS NULL OR JSON_EXTRACT(metadata, '$.aiProcessing') = false`,
+ ),
+ );
+
+ const affectedRows = (lockResult[0] as { affectedRows?: number })
+ ?.affectedRows;
+ if (typeof affectedRows !== "number") {
+ console.warn(
+ "[generateAiMetadata] Unable to determine lock result, proceeding cautiously",
+ );
+ }
+ if (affectedRows === 0) {
+ return;
+ }
+
try {
- await db()
- .update(videos)
- .set({
- metadata: {
- ...metadata,
- aiProcessing: true,
- },
- })
- .where(eq(videos.id, videoId));
const query = await db()
.select({ video: videos, bucket: s3Buckets })
.from(videos)
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 880af01ce..98d25fd65 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -458,37 +458,35 @@ export const Share = ({
</div>
<div className="hidden mt-4 lg:block">
- {aiLoading &&
- (transcriptionStatus === "PROCESSING" ||
- transcriptionStatus === "COMPLETE") && (
- <div className="p-4 animate-pulse new-card-style">
- <div className="space-y-6">
- <div>
- <div className="mb-3 w-24 h-6 bg-gray-200 rounded"></div>
- <div className="mb-4 w-32 h-3 bg-gray-100 rounded"></div>
- <div className="space-y-3">
- <div className="w-full h-4 bg-gray-200 rounded"></div>
- <div className="w-5/6 h-4 bg-gray-200 rounded"></div>
- <div className="w-4/5 h-4 bg-gray-200 rounded"></div>
- <div className="w-full h-4 bg-gray-200 rounded"></div>
- <div className="w-3/4 h-4 bg-gray-200 rounded"></div>
- </div>
+ {aiLoading && (
+ <div className="p-4 animate-pulse new-card-style">
+ <div className="space-y-6">
+ <div>
+ <div className="mb-3 w-24 h-6 bg-gray-200 rounded"></div>
+ <div className="mb-4 w-32 h-3 bg-gray-100 rounded"></div>
+ <div className="space-y-3">
+ <div className="w-full h-4 bg-gray-200 rounded"></div>
+ <div className="w-5/6 h-4 bg-gray-200 rounded"></div>
+ <div className="w-4/5 h-4 bg-gray-200 rounded"></div>
+ <div className="w-full h-4 bg-gray-200 rounded"></div>
+ <div className="w-3/4 h-4 bg-gray-200 rounded"></div>
</div>
+ </div>
- <div>
- <div className="mb-4 w-24 h-6 bg-gray-200 rounded"></div>
- <div className="space-y-2">
- {[1, 2, 3, 4].map((i) => (
- <div key={i} className="flex items-center p-2">
- <div className="mr-3 w-12 h-4 bg-gray-200 rounded"></div>
- <div className="flex-1 h-4 bg-gray-200 rounded"></div>
- </div>
- ))}
- </div>
+ <div>
+ <div className="mb-4 w-24 h-6 bg-gray-200 rounded"></div>
+ <div className="space-y-2">
+ {[1, 2, 3, 4].map((i) => (
+ <div key={i} className="flex items-center p-2">
+ <div className="mr-3 w-12 h-4 bg-gray-200 rounded"></div>
+ <div className="flex-1 h-4 bg-gray-200 rounded"></div>
+ </div>
+ ))}
</div>
</div>
</div>
- )}
+ </div>
+ )}
<SummaryChapters
isSummaryDisabled={isSummaryDisabled}
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
index cf9e9dca8..66d2cec98 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
@@ -4,7 +4,6 @@ import { Button } from "@cap/ui";
import type { Video } from "@cap/web-domain";
import { faRectangleList } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useEffect, useState } from "react";
interface Chapter {
title: string;
@@ -68,25 +67,12 @@ export const Summary: React.FC<SummaryProps> = ({
aiGenerationEnabled = false,
ownerIsPro,
}) => {
- const [aiData, setAiData] = useState<{
- title?: string | null;
- summary?: string | null;
- chapters?: Chapter[] | null;
- processing?: boolean;
- } | null>(initialAiData || null);
- const [isLoading, setIsLoading] = useState(
+ const aiData = initialAiData || null;
+ const isLoading =
aiGenerationEnabled &&
- (!initialAiData || initialAiData.processing === true),
- );
-
- useEffect(() => {
- if (initialAiData) {
- setAiData(initialAiData);
- setIsLoading(aiGenerationEnabled && initialAiData.processing === true);
- } else {
- setIsLoading(aiGenerationEnabled);
- }
- }, [initialAiData, aiGenerationEnabled]);
+ aiData?.processing === true &&
+ !aiData?.summary &&
+ !aiData?.chapters?.length;
const handleSeek = (time: number) => {
if (onSeek) {
@@ -139,7 +125,7 @@ export const Summary: React.FC<SummaryProps> = ({
if (isSummaryDisabled) return null;
- if (isLoading || aiData?.processing) {
+ if (isLoading) {
return (
<div className="flex flex-col h-full">
<div className="overflow-y-auto flex-1">
@@ -149,7 +135,7 @@ export const Summary: React.FC<SummaryProps> = ({
);
}
- if (!aiData?.summary && (!aiData?.chapters || aiData.chapters.length === 0)) {
+ if (!aiData?.summary && !aiData?.chapters?.length) {
return (
<div className="flex flex-col justify-center items-center p-8 h-full text-center">
<FontAwesomeIcon
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index 3fd774f80..b25290cd4 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -4,7 +4,7 @@ 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";
+import { useEffect, useMemo, useState } from "react";
import { editTranscriptEntry } from "@/actions/videos/edit-transcript";
import { useCurrentUser } from "@/app/Layout/AuthContext";
import type { VideoData } from "../../types";
@@ -122,11 +122,8 @@ const parseVTT = (vttContent: string): TranscriptEntry[] => {
export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
const user = useCurrentUser();
const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
- const [isLoading, setIsLoading] = useState(true);
const [selectedEntry, setSelectedEntry] = useState<number | null>(null);
- const [isTranscriptionProcessing, setIsTranscriptionProcessing] =
- useState(false);
- const [hasTimedOut, setHasTimedOut] = useState(false);
+ const [retryTriggered, setRetryTriggered] = useState(false);
const [editingEntry, setEditingEntry] = useState<number | null>(null);
const [editText, setEditText] = useState<string>("");
const [isSaving, setIsSaving] = useState(false);
@@ -160,8 +157,7 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
return response.json();
},
onSuccess: () => {
- // Reset status - Share.tsx polling will automatically detect the change and trigger transcription
- setIsTranscriptionProcessing(true);
+ setRetryTriggered(true);
invalidateTranscript(data.id);
},
onError: (error) => {
@@ -173,71 +169,32 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
if (transcriptContent) {
const parsed = parseVTT(transcriptContent);
setTranscriptData(parsed);
- setIsTranscriptionProcessing(false);
- setIsLoading(false);
- } else if (transcriptError) {
- console.error(
- "[Transcript] Transcript error from React Query:",
- transcriptError.message,
- );
- if (transcriptError.message === "TRANSCRIPT_NOT_READY") {
- setIsTranscriptionProcessing(true);
- } else {
- setIsTranscriptionProcessing(false);
- }
- setIsLoading(false);
}
- }, [transcriptContent, transcriptError]);
+ }, [transcriptContent]);
- useEffect(() => {
- if (isTranscriptLoading) {
- setIsLoading(true);
+ const isTranscriptionProcessing = useMemo(() => {
+ if (retryTriggered && data.transcriptionStatus !== "COMPLETE") {
+ return true;
}
- }, [isTranscriptLoading]);
+ return (
+ data.transcriptionStatus === "PROCESSING" || !data.transcriptionStatus
+ );
+ }, [data.transcriptionStatus, retryTriggered]);
- useEffect(() => {
+ const isQueryLoading =
+ isTranscriptLoading && data.transcriptionStatus === "COMPLETE";
+
+ const hasTimedOut = useMemo(() => {
const videoCreationTime = new Date(data.createdAt).getTime();
const fiveMinutesInMs = 5 * 60 * 1000;
const isVideoOlderThanFiveMinutes =
Date.now() - videoCreationTime > fiveMinutesInMs;
-
- if (data.transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- setIsLoading(true);
- } else if (data.transcriptionStatus === "ERROR") {
- setIsTranscriptionProcessing(false);
- setIsLoading(false);
- } else if (isVideoOlderThanFiveMinutes && !data.transcriptionStatus) {
- setIsLoading(false);
- setHasTimedOut(true);
- } else if (!data.transcriptionStatus) {
- const startTime = Date.now();
- const maxDuration = 2 * 60 * 1000;
-
- const intervalId = setInterval(() => {
- if (Date.now() - startTime > maxDuration) {
- clearInterval(intervalId);
- setIsLoading(false);
- return;
- }
-
- fetch(`/api/video/transcribe/status?videoId=${data.id}`)
- .then((response) => response.json())
- .then(({ transcriptionStatus }) => {
- if (transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- } else if (transcriptionStatus === "COMPLETE") {
- clearInterval(intervalId);
- } else if (transcriptionStatus === "ERROR") {
- clearInterval(intervalId);
- setIsLoading(false);
- }
- });
- }, 1000);
-
- return () => clearInterval(intervalId);
- }
- }, [data.id, data.transcriptionStatus, data.createdAt]);
+ return (
+ isVideoOlderThanFiveMinutes &&
+ !data.transcriptionStatus &&
+ !retryTriggered
+ );
+ }, [data.createdAt, data.transcriptionStatus, retryTriggered]);
const handleTranscriptClick = (entry: TranscriptEntry) => {
if (editingEntry === entry.id) {
@@ -380,36 +337,7 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
const canEdit = user?.id === data.owner.id;
- if (isLoading) {
- return (
- <div className="flex justify-center items-center h-full">
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="w-8 h-8"
- viewBox="0 0 24 24"
- >
- <style>
- {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
- </style>
- <path
- fill="#4B5563"
- d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
- opacity={0.25}
- />
- <path
- fill="#4B5563"
- d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
- style={{
- transformOrigin: "center",
- animation: "spinner_AtaB .75s infinite linear",
- }}
- />
- </svg>
- </div>
- );
- }
-
- if (isTranscriptionProcessing) {
+ if (isTranscriptionProcessing && !hasTimedOut) {
return (
<div className="flex justify-center items-center h-full text-gray-1">
<div className="text-center">
@@ -443,10 +371,42 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
);
}
+ if (isQueryLoading) {
+ return (
+ <div className="flex justify-center items-center h-full">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="w-8 h-8"
+ viewBox="0 0 24 24"
+ >
+ <style>
+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
+ </style>
+ <path
+ fill="#4B5563"
+ d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
+ opacity={0.25}
+ />
+ <path
+ fill="#4B5563"
+ d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
+ style={{
+ transformOrigin: "center",
+ animation: "spinner_AtaB .75s infinite linear",
+ }}
+ />
+ </svg>
+ </div>
+ );
+ }
+
const showRetryButton =
data.transcriptionStatus === "ERROR" ||
- data.transcriptionStatus === null ||
- (!transcriptData.length && !isTranscriptionProcessing);
+ hasTimedOut ||
+ (data.transcriptionStatus === "COMPLETE" &&
+ !transcriptData.length &&
+ !isQueryLoading &&
+ transcriptError);
if (showRetryButton) {
return (
@@ -458,24 +418,21 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
? "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>
- )}
+ {canEdit && (
+ <Button
+ onClick={() => {
+ retryTranscriptionMutation.mutate();
+ }}
+ disabled={retryTranscriptionMutation.isPending}
+ variant="primary"
+ size="sm"
+ spinner={retryTranscriptionMutation.isPending}
+ >
+ {retryTranscriptionMutation.isPending
+ ? "Retrying..."
+ : "Retry Transcription"}
+ </Button>
+ )}
</div>
</div>
);
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 5814c7d83..ba8c2025d 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -34,7 +34,6 @@ import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import { notFound } from "next/navigation";
-import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import {
getDashboardData,
@@ -528,29 +527,6 @@ async function AuthorizedContent({
};
}
- if (
- video.transcriptionStatus === "COMPLETE" &&
- !currentMetadata.aiProcessing &&
- !currentMetadata.aiGenerationSkipped &&
- !currentMetadata.summary &&
- !currentMetadata.chapters &&
- aiGenerationEnabled
- ) {
- try {
- generateAiMetadata(videoId, video.owner.id).catch((error) => {
- console.error(
- `[ShareVideoPage] Error generating AI metadata for video ${videoId}:`,
- error,
- );
- });
- } catch (error) {
- console.error(
- `[ShareVideoPage] Error starting AI metadata generation for video ${videoId}:`,
- error,
- );
- }
- }
-
const customDomainPromise = (async () => {
if (!user) {
return { customDomain: null, domainVerified: false };
diff --git a/apps/web/hooks/use-transcript.ts b/apps/web/hooks/use-transcript.ts
index c8d6dab95..e43237c0f 100644
--- a/apps/web/hooks/use-transcript.ts
+++ b/apps/web/hooks/use-transcript.ts
@@ -1,11 +1,25 @@
import type { Video } from "@cap/web-domain";
import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useEffect, useRef } from "react";
import { getTranscript } from "@/actions/videos/get-transcript";
export const useTranscript = (
videoId: Video.VideoId,
transcriptionStatus?: string | null,
) => {
+ const queryClient = useQueryClient();
+ const previousStatus = useRef(transcriptionStatus);
+
+ useEffect(() => {
+ if (
+ previousStatus.current !== "COMPLETE" &&
+ transcriptionStatus === "COMPLETE"
+ ) {
+ queryClient.invalidateQueries({ queryKey: ["transcript", videoId] });
+ }
+ previousStatus.current = transcriptionStatus;
+ }, [transcriptionStatus, videoId, queryClient]);
+
return useQuery({
queryKey: ["transcript", videoId],
queryFn: async () => {
@@ -13,16 +27,23 @@ export const useTranscript = (
if (result.success && result.content) {
return result.content;
- } else {
- if (result.message === "Transcript is not ready yet") {
- throw new Error("TRANSCRIPT_NOT_READY");
- }
- throw new Error(result.message);
}
+ if (result.message === "Transcript is not ready yet") {
+ throw new Error("TRANSCRIPT_NOT_READY");
+ }
+ throw new Error(result.message);
},
enabled: transcriptionStatus === "COMPLETE",
- staleTime: 0,
+ staleTime: 30 * 60 * 1000,
+ gcTime: 60 * 60 * 1000,
refetchOnWindowFocus: false,
+ retry: (failureCount, error) => {
+ if (error.message === "TRANSCRIPT_NOT_READY") {
+ return failureCount < 3;
+ }
+ return false;
+ },
+ retryDelay: 1000,
});
};