Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Refactor AI metadata generation to Vercel workflow, and add retry endpoint
Richie McIlroy5b0bb1420bc0
diff --git a/apps/web/actions/videos/generate-ai-metadata.ts b/apps/web/actions/videos/generate-ai-metadata.tsdeleted file mode 100644index ea6ef6e2a..000000000--- a/apps/web/actions/videos/generate-ai-metadata.ts+++ /dev/null@@ -1,581 +0,0 @@-"use server";--import { db } from "@cap/database";-import { s3Buckets, videos } from "@cap/database/schema";-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 { and, eq, sql } from "drizzle-orm";-import { Effect, Option } from "effect";-import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";-import { runPromise } from "@/lib/server";--const MAX_CHARS_PER_CHUNK = 24000;--interface VttSegment {- start: number;- text: string;-}--function parseVttWithTimestamps(vttContent: string): VttSegment[] {- const lines = vttContent.split("\n");- const segments: VttSegment[] = [];- let currentStart = 0;-- for (let i = 0; i < lines.length; i++) {- const line = lines[i]?.trim() ?? "";- if (line.includes("-->")) {- const timeMatch = line.match(/(\d{2}):(\d{2}):(\d{2})[.,](\d{3})/);- if (timeMatch) {- currentStart =- parseInt(timeMatch[1] ?? "0", 10) * 3600 +- parseInt(timeMatch[2] ?? "0", 10) * 60 +- parseInt(timeMatch[3] ?? "0", 10);- }- } else if (- line &&- line !== "WEBVTT" &&- !/^\d+$/.test(line) &&- !line.includes("-->")- ) {- segments.push({ start: currentStart, text: line });- }- }-- return segments;-}--function chunkTranscriptWithTimestamps(- segments: VttSegment[],-): { text: string; startTime: number; endTime: number }[] {- const chunks: { text: string; startTime: number; endTime: number }[] = [];- let currentChunk: VttSegment[] = [];- let currentLength = 0;-- for (const segment of segments) {- if (- currentLength + segment.text.length > MAX_CHARS_PER_CHUNK &&- currentChunk.length > 0- ) {- chunks.push({- text: currentChunk.map((s) => s.text).join(" "),- startTime: currentChunk[0]?.start ?? 0,- endTime: currentChunk[currentChunk.length - 1]?.start ?? 0,- });- currentChunk = [];- currentLength = 0;- }- currentChunk.push(segment);- currentLength += segment.text.length + 1;- }-- if (currentChunk.length > 0) {- chunks.push({- text: currentChunk.map((s) => s.text).join(" "),- startTime: currentChunk[0]?.start ?? 0,- endTime: currentChunk[currentChunk.length - 1]?.start ?? 0,- });- }-- return chunks;-}--async function callAiApi(- prompt: string,- groqClient: ReturnType<typeof getGroqClient>,-): Promise<string> {- if (groqClient) {- try {- const completion = await groqClient.chat.completions.create({- messages: [{ role: "user", content: prompt }],- model: GROQ_MODEL,- });- return completion.choices?.[0]?.message?.content || "{}";- } catch (groqError) {- console.error(- `[generateAiMetadata] Groq API error: ${groqError}, falling back to OpenAI`,- );- if (serverEnv().OPENAI_API_KEY) {- const aiRes = await fetch(- "https://api.openai.com/v1/chat/completions",- {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${serverEnv().OPENAI_API_KEY}`,- },- body: JSON.stringify({- model: "gpt-4o-mini",- messages: [{ role: "user", content: prompt }],- }),- },- );- if (!aiRes.ok) {- const errorText = await aiRes.text();- throw new Error(`OpenAI API error: ${aiRes.status} ${errorText}`);- }- const aiJson = await aiRes.json();- return aiJson.choices?.[0]?.message?.content || "{}";- }- throw groqError;- }- } else if (serverEnv().OPENAI_API_KEY) {- const aiRes = await fetch("https://api.openai.com/v1/chat/completions", {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${serverEnv().OPENAI_API_KEY}`,- },- body: JSON.stringify({- model: "gpt-4o-mini",- messages: [{ role: "user", content: prompt }],- }),- });- if (!aiRes.ok) {- const errorText = await aiRes.text();- throw new Error(`OpenAI API error: ${aiRes.status} ${errorText}`);- }- const aiJson = await aiRes.json();- return aiJson.choices?.[0]?.message?.content || "{}";- }- return "{}";-}--export async function generateAiMetadata(- videoId: Video.VideoId,- userId: string,-) {- const groqClient = getGroqClient();- if (!groqClient && !serverEnv().OPENAI_API_KEY) {- console.error(- "[generateAiMetadata] Missing Groq or OpenAI API key, skipping AI metadata generation",- );- return;- }- const videoQuery = await db()- .select({ video: videos })- .from(videos)- .where(eq(videos.id, videoId));-- if (videoQuery.length === 0 || !videoQuery[0]?.video) {- console.error(- `[generateAiMetadata] Video ${videoId} not found in database`,- );- return;- }-- const videoData = videoQuery[0].video;- const metadata = (videoData.metadata as VideoMetadata) || {};-- if (metadata.aiProcessing === true) {- const updatedAtTime = new Date(videoData.updatedAt).getTime();- const currentTime = Date.now();- const tenMinutesInMs = 10 * 60 * 1000;-- if (currentTime - updatedAtTime > tenMinutesInMs) {- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- },- })- .where(eq(videos.id, videoId));- } else {- return;- }- }-- if (metadata.summary || metadata.chapters) {- if (metadata.aiProcessing) {- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- },- })- .where(eq(videos.id, videoId));- }- return;- }-- if (videoData?.transcriptionStatus !== "COMPLETE") {- if (metadata.aiProcessing) {- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- },- })- .where(eq(videos.id, videoId));- }- 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 {- const query = await db()- .select({ video: videos, bucket: s3Buckets })- .from(videos)- .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))- .where(eq(videos.id, videoId));-- if (query.length === 0 || !query[0]) {- console.error(`[generateAiMetadata] Video data not found for ${videoId}`);- throw new Error(`Video data not found for ${videoId}`);- }-- const row = query[0];- if (!row || !row.video) {- console.error(- `[generateAiMetadata] Video record not found for ${videoId}`,- );- throw new Error(`Video record not found for ${videoId}`);- }-- const { video } = row;-- const vtt = await Effect.gen(function* () {- const [bucket] = yield* S3Buckets.getBucketAccess(- Option.fromNullable(row.bucket?.id),- );-- return yield* bucket.getObject(`${userId}/${videoId}/transcription.vtt`);- }).pipe(runPromise);-- if (Option.isNone(vtt)) {- console.log(- `[generateAiMetadata] Transcript is empty for ${videoId}, skipping AI metadata`,- );- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- aiGenerationSkipped: true,- },- })- .where(eq(videos.id, videoId));- return;- }-- const segments = parseVttWithTimestamps(vtt.value);- const transcriptText = segments- .map((s) => s.text)- .join(" ")- .trim();-- if (transcriptText.length < 10) {- console.log(- `[generateAiMetadata] Transcript content too short for ${videoId} (${transcriptText.length} chars), skipping AI metadata`,- );- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- aiGenerationSkipped: true,- },- })- .where(eq(videos.id, videoId));- return;- }-- const chunks = chunkTranscriptWithTimestamps(segments);- console.log(- `[generateAiMetadata] Processing ${videoId}: ${transcriptText.length} chars, ${chunks.length} chunk(s)`,- );-- let content = "{}";-- if (chunks.length === 1) {- const prompt = `You are Cap AI, an expert at analyzing video content and creating comprehensive summaries.--Analyze this transcript thoroughly and provide a detailed JSON response:-{- "title": "string (concise but descriptive title that captures the main topic)",- "summary": "string (detailed summary that covers ALL key points discussed. For meetings: include decisions made, action items, and key discussion points. For tutorials: cover all steps and concepts explained. For presentations: summarize all main arguments and supporting points. Write from 1st person perspective if the speaker is teaching/presenting, e.g. 'In this video, I walk through...'. Make it comprehensive enough that someone could understand the full content without watching.)",- "chapters": [{"title": "string (descriptive chapter title)", "start": number (seconds from start)}]-}--Guidelines:-- The summary should be detailed and comprehensive, not a brief overview-- Capture ALL important topics, not just the main theme-- For longer content, organize the summary by topic or chronologically-- Include specific details, names, numbers, and conclusions mentioned-- Chapters should mark distinct topic changes or sections--Return ONLY valid JSON without any markdown formatting or code blocks.-Transcript:-${transcriptText}`;- content = await callAiApi(prompt, groqClient);- } else {- const chunkSummaries: {- summary: string;- keyPoints: string[];- chapters: { title: string; start: number }[];- startTime: number;- endTime: number;- }[] = [];-- for (let i = 0; i < chunks.length; i++) {- const chunk = chunks[i];- if (!chunk) continue;- console.log(- `[generateAiMetadata] Processing chunk ${i + 1}/${chunks.length} for ${videoId} (${chunk.startTime}s - ${chunk.endTime}s)`,- );-- const chunkPrompt = `You are Cap AI, an expert at analyzing video content. This is section ${i + 1} of ${chunks.length} from a longer video (timestamp ${Math.floor(chunk.startTime / 60)}:${String(chunk.startTime % 60).padStart(2, "0")} to ${Math.floor(chunk.endTime / 60)}:${String(chunk.endTime % 60).padStart(2, "0")}).--Analyze this section thoroughly and provide JSON:-{- "summary": "string (detailed summary of this section - capture ALL key points, topics discussed, decisions made, or concepts explained. Include specific details like names, numbers, action items, and conclusions. This should be 3-6 sentences minimum.)",- "keyPoints": ["string (specific key point or takeaway)", ...],- "chapters": [{"title": "string (descriptive title for this topic/section)", "start": number (seconds from video start)}]-}--Be thorough - this summary will be combined with other sections to create a comprehensive overview.-Return ONLY valid JSON without any markdown formatting or code blocks.-Transcript section:-${chunk.text}`;-- const chunkContent = await callAiApi(chunkPrompt, groqClient);- try {- let cleanContent = chunkContent;- if (chunkContent.includes("```json")) {- cleanContent = chunkContent- .replace(/```json\s*/g, "")- .replace(/```\s*/g, "");- } else if (chunkContent.includes("```")) {- cleanContent = chunkContent.replace(/```\s*/g, "");- }- const parsed = JSON.parse(cleanContent.trim());- chunkSummaries.push({- summary: parsed.summary || "",- keyPoints: parsed.keyPoints || [],- chapters: parsed.chapters || [],- startTime: chunk.startTime,- endTime: chunk.endTime,- });- } catch {- console.error(- `[generateAiMetadata] Failed to parse chunk ${i + 1} response for ${videoId}`,- );- }- }-- const allChapters = chunkSummaries- .flatMap((c) => c.chapters)- .sort((a, b) => a.start - b.start)- .reduce(- (acc, chapter) => {- const lastChapter = acc[acc.length - 1];- if (- lastChapter &&- Math.abs(chapter.start - lastChapter.start) < 30- ) {- return acc;- }- return [...acc, chapter];- },- [] as { title: string; start: number }[],- );- const allKeyPoints = chunkSummaries.flatMap((c) => c.keyPoints);-- const sectionDetails = chunkSummaries- .map((c, i) => {- const timeRange = `${Math.floor(c.startTime / 60)}:${String(c.startTime % 60).padStart(2, "0")} - ${Math.floor(c.endTime / 60)}:${String(c.endTime % 60).padStart(2, "0")}`;- const keyPointsList =- c.keyPoints.length > 0- ? `\nKey points: ${c.keyPoints.join("; ")}`- : "";- return `Section ${i + 1} (${timeRange}):\n${c.summary}${keyPointsList}`;- })- .join("\n\n");-- const finalPrompt = `You are Cap AI, an expert at synthesizing information into comprehensive, well-organized summaries.--Based on these detailed section analyses of a video, create a thorough final summary that captures EVERYTHING important.--Section analyses:-${sectionDetails}--${allKeyPoints.length > 0 ? `All key points identified:\n${allKeyPoints.map((p, i) => `${i + 1}. ${p}`).join("\n")}\n` : ""}--Provide JSON in the following format:-{- "title": "string (concise but descriptive title that captures the main topic/purpose)",- "summary": "string (COMPREHENSIVE summary that covers the entire video thoroughly. This should be detailed enough that someone could understand all the important content without watching. Include: main topics covered, key decisions or conclusions, important details mentioned, action items if any. Organize it logically - for meetings use topics/agenda items, for tutorials use steps/concepts, for presentations use main arguments. Write from 1st person perspective if appropriate. This should be several paragraphs for longer content.)"-}--The summary must be detailed and comprehensive - not a brief overview. Capture all the important information from every section.-Return ONLY valid JSON without any markdown formatting or code blocks.`;-- const finalContent = await callAiApi(finalPrompt, groqClient);- try {- let cleanContent = finalContent;- if (finalContent.includes("```json")) {- cleanContent = finalContent- .replace(/```json\s*/g, "")- .replace(/```\s*/g, "");- } else if (finalContent.includes("```")) {- cleanContent = finalContent.replace(/```\s*/g, "");- }- const parsed = JSON.parse(cleanContent.trim());- content = JSON.stringify({- title: parsed.title,- summary: parsed.summary,- chapters: allChapters,- });- } catch {- console.error(- `[generateAiMetadata] Failed to parse final summary for ${videoId}`,- );- const fallbackSummary = chunkSummaries- .map((c, i) => `**Part ${i + 1}:** ${c.summary}`)- .join("\n\n");- const keyPointsSummary =- allKeyPoints.length > 0- ? `\n\n**Key Points:**\n${allKeyPoints.map((p) => `- ${p}`).join("\n")}`- : "";- content = JSON.stringify({- title: "Video Summary",- summary: fallbackSummary + keyPointsSummary,- chapters: allChapters,- });- }- }-- let data: {- title?: string;- summary?: string;- chapters?: { title: string; start: number }[];- } = {};- try {- let cleanContent = content;- if (content.includes("```json")) {- cleanContent = content- .replace(/```json\s*/g, "")- .replace(/```\s*/g, "");- } else if (content.includes("```")) {- cleanContent = content.replace(/```\s*/g, "");- }- data = JSON.parse(cleanContent.trim());-- if (data.chapters && data.chapters.length > 0) {- data.chapters = data.chapters- .sort((a, b) => a.start - b.start)- .reduce(- (acc, chapter) => {- const lastChapter = acc[acc.length - 1];- if (- lastChapter &&- Math.abs(chapter.start - lastChapter.start) < 30- ) {- return acc;- }- return [...acc, chapter];- },- [] as { title: string; start: number }[],- );- }- } catch (e) {- console.error(`[generateAiMetadata] Error parsing AI response: ${e}`);- data = {- title: "Generated Title",- summary:- "The AI was unable to generate a proper summary for this content.",- chapters: [],- };- }-- const currentMetadata: VideoMetadata =- (video.metadata as VideoMetadata) || {};- const updatedMetadata: VideoMetadata = {- ...currentMetadata,- aiTitle: data.title || currentMetadata.aiTitle,- summary: data.summary || currentMetadata.summary,- chapters: data.chapters || currentMetadata.chapters,- aiProcessing: false,- };-- await db()- .update(videos)- .set({ metadata: updatedMetadata })- .where(eq(videos.id, videoId));-- const hasDatePattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(- video.name || "",- );-- if (- (video.name?.startsWith("Cap Recording -") || hasDatePattern) &&- data.title- ) {- await db()- .update(videos)- .set({ name: data.title })- .where(eq(videos.id, videoId));- }- } catch (error) {- console.error(`[generateAiMetadata] Error for video ${videoId}:`, error);-- try {- const currentVideo = await db()- .select()- .from(videos)- .where(eq(videos.id, videoId));- if (currentVideo.length > 0 && currentVideo[0]) {- const currentMetadata: VideoMetadata =- (currentVideo[0].metadata as VideoMetadata) || {};- await db()- .update(videos)- .set({- metadata: {- ...currentMetadata,- aiProcessing: false,- },- })- .where(eq(videos.id, videoId));- }- } catch (updateError) {- console.error(- `[generateAiMetadata] Failed to reset processing flag:`,- updateError,- );- }- }-}diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.tsindex 1f499acaf..16edcc978 100644--- a/apps/web/actions/videos/get-status.ts+++ b/apps/web/actions/videos/get-status.ts@@ -1,7 +1,7 @@"use server";import { db } from "@cap/database";-import { users, videos } from "@cap/database/schema";+import { videos } from "@cap/database/schema";import type { VideoMetadata } from "@cap/database/types";import { serverEnv } from "@cap/env";import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";@@ -9,11 +9,7 @@ import { Policy, type Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import { Effect, Exit } from "effect";import * as EffectRuntime from "@/lib/server";-import { isAiGenerationEnabled } from "@/utils/flags";import { transcribeVideo } from "../../lib/transcribe";-import { generateAiMetadata } from "./generate-ai-metadata";--const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000;type TranscriptionStatus =| "PROCESSING"@@ -22,11 +18,17 @@ type TranscriptionStatus =| "SKIPPED"| "NO_AUDIO";+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+export interface VideoStatusResult {transcriptionStatus: TranscriptionStatus | null;+ aiGenerationStatus: AiGenerationStatus | null;aiTitle: string | null;- aiProcessing: boolean;- aiGenerationSkipped: boolean;summary: string | null;chapters: { title: string; start: number }[] | null;error?: string;@@ -66,8 +68,8 @@ export async function getVideoStatus(return {transcriptionStatus: "PROCESSING",- aiProcessing: false,- aiGenerationSkipped: metadata.aiGenerationSkipped || false,+ aiGenerationStatus:+ (metadata.aiGenerationStatus as AiGenerationStatus) || null,aiTitle: metadata.aiTitle || null,summary: metadata.summary || null,chapters: metadata.chapters || null,@@ -79,8 +81,8 @@ export async function getVideoStatus();return {transcriptionStatus: "ERROR",- aiProcessing: false,- aiGenerationSkipped: metadata.aiGenerationSkipped || false,+ aiGenerationStatus:+ (metadata.aiGenerationStatus as AiGenerationStatus) || null,aiTitle: metadata.aiTitle || null,summary: metadata.summary || null,chapters: metadata.chapters || null,@@ -92,8 +94,8 @@ export async function getVideoStatus(if (video.transcriptionStatus === "ERROR") {return {transcriptionStatus: "ERROR",- aiProcessing: false,- aiGenerationSkipped: metadata.aiGenerationSkipped || false,+ aiGenerationStatus:+ (metadata.aiGenerationStatus as AiGenerationStatus) || null,aiTitle: metadata.aiTitle || null,summary: metadata.summary || null,chapters: metadata.chapters || null,@@ -101,146 +103,11 @@ export async function getVideoStatus(};}- if (metadata.aiProcessing) {- const updatedAtTime = new Date(video.updatedAt).getTime();- const currentTime = Date.now();-- if (currentTime - updatedAtTime > MAX_AI_PROCESSING_TIME) {- console.log(- `[Get Status] AI processing appears stuck for video ${videoId} (${Math.round(- (currentTime - updatedAtTime) / 60000,- )} minutes), resetting flag`,- );-- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- // generationError: "AI processing timed out and was reset",- },- })- .where(eq(videos.id, videoId));-- const updatedResult = await db()- .select()- .from(videos)- .where(eq(videos.id, videoId));- if (updatedResult.length > 0 && updatedResult[0]) {- const updatedVideo = updatedResult[0];- const updatedMetadata = (updatedVideo.metadata as VideoMetadata) || {};-- return {- transcriptionStatus:- (updatedVideo.transcriptionStatus as TranscriptionStatus) || null,- aiProcessing: false,- aiGenerationSkipped: updatedMetadata.aiGenerationSkipped || false,- aiTitle: updatedMetadata.aiTitle || null,- summary: updatedMetadata.summary || null,- chapters: updatedMetadata.chapters || null,- error: "AI processing timed out and was reset",- };- }- }- }-- if (- video.transcriptionStatus === "COMPLETE" &&- !metadata.aiProcessing &&- !metadata.aiGenerationSkipped &&- !metadata.summary &&- !metadata.chapters- ) {- console.log(- `[Get Status] Transcription complete but no AI data, checking feature flag for video owner ${video.ownerId}`,- );-- const videoOwnerQuery = await db()- .select({- email: users.email,- stripeSubscriptionStatus: users.stripeSubscriptionStatus,- thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,- })- .from(users)- .where(eq(users.id, video.ownerId))- .limit(1);-- if (- videoOwnerQuery.length > 0 &&- videoOwnerQuery[0] &&- (await isAiGenerationEnabled(videoOwnerQuery[0]))- ) {- console.log(- `[Get Status] Feature flag enabled, triggering AI generation for video ${videoId}`,- );-- (async () => {- try {- console.log(- `[Get Status] Starting AI metadata generation for video ${videoId}`,- );- await generateAiMetadata(videoId, video.ownerId);- console.log(- `[Get Status] AI metadata generation completed for video ${videoId}`,- );- } catch (error) {- console.error(- "[Get Status] Error generating AI metadata for video %s",- videoId,- error,- );-- try {- const currentVideo = await db()- .select()- .from(videos)- .where(eq(videos.id, videoId));- if (currentVideo.length > 0 && currentVideo[0]) {- const currentMetadata =- (currentVideo[0].metadata as VideoMetadata) || {};- await db()- .update(videos)- .set({- metadata: {- ...currentMetadata,- aiProcessing: false,- },- })- .where(eq(videos.id, videoId));- }- } catch (resetError) {- console.error(- `[Get Status] Failed to reset AI processing flag for video %s`,- videoId,- resetError,- );- }- }- })();-- return {- transcriptionStatus:- (video.transcriptionStatus as TranscriptionStatus) || null,- aiProcessing: true,- aiGenerationSkipped: false,- aiTitle: metadata.aiTitle || null,- summary: metadata.summary || null,- chapters: metadata.chapters || null,- };- } else {- const videoOwner = videoOwnerQuery[0];- console.log(- `[Get Status] AI generation feature disabled for video owner ${video.ownerId} (email: ${videoOwner?.email}, pro: ${videoOwner?.stripeSubscriptionStatus})`,- );- }- }-return {transcriptionStatus:(video.transcriptionStatus as TranscriptionStatus) || null,- aiProcessing: metadata.aiProcessing || false,- aiGenerationSkipped: metadata.aiGenerationSkipped || false,+ aiGenerationStatus:+ (metadata.aiGenerationStatus as AiGenerationStatus) || null,aiTitle: metadata.aiTitle || null,summary: metadata.summary || null,chapters: metadata.chapters || null,diff --git a/apps/web/app/api/video/ai/route.ts b/apps/web/app/api/video/ai/route.tsindex bb8d0040b..f1de88201 100644--- a/apps/web/app/api/video/ai/route.ts+++ b/apps/web/app/api/video/ai/route.ts@@ -5,7 +5,7 @@ import type { VideoMetadata } from "@cap/database/types";import type { Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import type { NextRequest } from "next/server";-import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";+import { startAiGeneration } from "@/lib/generate-ai";import { isAiGenerationEnabled } from "@/utils/flags";export const dynamic = "force-dynamic";@@ -41,7 +41,6 @@ export async function GET(request: NextRequest) {const video = result[0];const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {};- // If we have AI data, return itif (metadata.summary || metadata.chapters) {console.log(`[AI API] Returning existing AI metadata for video ${videoId}`,@@ -52,12 +51,16 @@ export async function GET(request: NextRequest) {title: metadata.aiTitle ?? null,summary: metadata.summary ?? null,chapters: metadata.chapters ?? null,+ aiGenerationStatus: metadata.aiGenerationStatus ?? null,},{ status: 200 },);}- if (metadata.aiProcessing) {+ if (+ metadata.aiGenerationStatus === "PROCESSING" ||+ metadata.aiGenerationStatus === "QUEUED"+ ) {console.log(`[AI API] AI processing already in progress for video ${videoId}`,);@@ -65,6 +68,23 @@ export async function GET(request: NextRequest) {{processing: true,message: "AI metadata generation in progress",+ aiGenerationStatus: metadata.aiGenerationStatus,+ },+ { status: 200 },+ );+ }++ const canRetry =+ metadata.aiGenerationStatus === "ERROR" ||+ metadata.aiGenerationStatus === "SKIPPED";++ if (!canRetry) {+ return Response.json(+ {+ processing: false,+ message:+ "AI generation is not available for retry. Generation is triggered automatically when transcription completes.",+ aiGenerationStatus: metadata.aiGenerationStatus ?? null,},{ status: 200 },);@@ -75,6 +95,7 @@ export async function GET(request: NextRequest) {{processing: false,message: `Cannot generate AI metadata - transcription status: ${video.transcriptionStatus || "unknown"}`,+ aiGenerationStatus: metadata.aiGenerationStatus ?? null,},{ status: 200 },);@@ -95,7 +116,6 @@ export async function GET(request: NextRequest) {!videoOwnerQuery[0] ||!(await isAiGenerationEnabled(videoOwnerQuery[0]))) {- const _videoOwner = videoOwnerQuery[0];return Response.json({processing: false,@@ -106,23 +126,32 @@ export async function GET(request: NextRequest) {}try {- generateAiMetadata(videoId, video.ownerId).catch((error) => {- console.error("[AI API] Error generating AI metadata:", error);- });+ const aiResult = await startAiGeneration(videoId, video.ownerId);++ if (!aiResult.success) {+ return Response.json(+ {+ processing: false,+ error: aiResult.message,+ },+ { status: 500 },+ );+ }return Response.json({processing: true,- message: "AI metadata generation started",+ message: aiResult.message,+ aiGenerationStatus: "QUEUED",},{ status: 200 },);} catch (error) {- console.error("[AI API] Error starting AI metadata generation:", error);+ console.error("[AI API] Error starting AI generation workflow:", error);return Response.json({processing: false,- error: "Failed to start AI metadata generation",+ error: "Failed to start AI generation workflow",},{ status: 500 },);diff --git a/apps/web/app/api/video/transcribe/status/route.ts b/apps/web/app/api/video/transcribe/status/route.tsindex 8a31e9079..aff321848 100644--- a/apps/web/app/api/video/transcribe/status/route.ts+++ b/apps/web/app/api/video/transcribe/status/route.ts@@ -1,12 +1,9 @@import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";import { videos } from "@cap/database/schema";-import type { VideoMetadata } from "@cap/database/types";import type { Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import type { NextRequest } from "next/server";-import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";-import { isAiGenerationEnabled } from "@/utils/flags";export const dynamic = "force-dynamic";@@ -35,23 +32,6 @@ export async function GET(request: NextRequest) {);}- if (video[0].transcriptionStatus === "COMPLETE") {- const metadata = (video[0].metadata as VideoMetadata) || {};- const needsAiGeneration =- !metadata.aiProcessing &&- !metadata.aiGenerationSkipped &&- !metadata.summary &&- !metadata.chapters;-- if (needsAiGeneration && (await isAiGenerationEnabled(user))) {- Promise.resolve().then(() => {- generateAiMetadata(videoId, user.id).catch((error) => {- console.error("Error generating AI metadata:", error);- });- });- }- }-return Response.json({ transcriptionStatus: video[0].transcriptionStatus },{ status: 200 },diff --git a/apps/web/app/api/videos/[videoId]/retry-ai/route.ts b/apps/web/app/api/videos/[videoId]/retry-ai/route.tsnew file mode 100644index 000000000..56590c105--- /dev/null+++ b/apps/web/app/api/videos/[videoId]/retry-ai/route.ts@@ -0,0 +1,108 @@+import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";+import { users, videos } from "@cap/database/schema";+import type { VideoMetadata } from "@cap/database/types";+import type { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { revalidatePath } from "next/cache";+import { startAiGeneration } from "@/lib/generate-ai";+import { isAiGenerationEnabled } from "@/utils/flags";++export async function POST(+ _request: Request,+ props: RouteContext<"/api/videos/[videoId]/retry-ai">,+) {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return Response.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { videoId } = (await props.params) as { videoId: Video.VideoId };+ if (!videoId) {+ return Response.json({ error: "Video ID is required" }, { status: 400 });+ }++ const videoQuery = await db()+ .select()+ .from(videos)+ .where(eq(videos.id, videoId))+ .limit(1);++ if (videoQuery.length === 0 || !videoQuery[0]) {+ return Response.json({ error: "Video not found" }, { status: 404 });+ }++ const video = videoQuery[0];+ if (video.ownerId !== user.id) {+ return Response.json({ error: "Unauthorized" }, { status: 403 });+ }++ if (video.transcriptionStatus !== "COMPLETE") {+ return Response.json(+ {+ error: "Cannot generate AI metadata - transcription is not complete",+ transcriptionStatus: video.transcriptionStatus,+ },+ { status: 400 },+ );+ }++ const metadata = (video.metadata as VideoMetadata) || {};++ const canRetry =+ !metadata.aiGenerationStatus ||+ metadata.aiGenerationStatus === "ERROR" ||+ metadata.aiGenerationStatus === "SKIPPED";++ if (!canRetry) {+ return Response.json(+ {+ error:+ "AI generation is already in progress or completed. Cannot retry.",+ aiGenerationStatus: metadata.aiGenerationStatus,+ },+ { status: 400 },+ );+ }++ const videoOwnerQuery = await db()+ .select({+ email: users.email,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ })+ .from(users)+ .where(eq(users.id, video.ownerId))+ .limit(1);++ if (+ videoOwnerQuery.length === 0 ||+ !videoOwnerQuery[0] ||+ !(await isAiGenerationEnabled(videoOwnerQuery[0]))+ ) {+ return Response.json(+ {+ error: "AI generation feature is not available for this user",+ },+ { status: 403 },+ );+ }++ const result = await startAiGeneration(videoId, video.ownerId);++ if (!result.success) {+ return Response.json({ error: result.message }, { status: 500 });+ }++ revalidatePath(`/s/${videoId}`);++ return Response.json({+ success: true,+ message: result.message,+ });+ } catch (error) {+ console.error("Error retrying AI generation:", error);+ return Response.json({ error: "Internal server error" }, { status: 500 });+ }+}diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsxindex 59efc6461..5be00515c 100644--- a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx+++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx@@ -49,21 +49,12 @@ export const EmbedVideo = forwardRef<user: typeof userSelectProps | null;comments: CommentWithAuthor[];chapters?: { title: string; start: number }[];- aiProcessing?: boolean;ownerName?: string | null;autoplay?: boolean;}>((- {- data,- user,- comments,- chapters = [],- aiProcessing = false,- ownerName,- autoplay = false,- },+ { data, user, comments, chapters = [], ownerName, autoplay = false },ref,) => {const videoRef = useRef<HTMLVideoElement>(null);diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsxindex 30ce01f5a..01bc2df2a 100644--- a/apps/web/app/embed/[videoId]/page.tsx+++ b/apps/web/app/embed/[videoId]/page.tsx@@ -270,14 +270,6 @@ async function EmbedContent({title: currentMetadata.aiTitle || null,summary: currentMetadata.summary || null,chapters: currentMetadata.chapters || null,- processing: currentMetadata.aiProcessing || false,- };- } else if (currentMetadata.aiProcessing) {- initialAiData = {- title: null,- summary: null,- chapters: null,- processing: true,};}@@ -320,7 +312,6 @@ async function EmbedContent({user={user}comments={commentsQuery}chapters={initialAiData?.chapters || []}- aiProcessing={initialAiData?.processing || false}ownerName={videoOwner[0]?.name || null}autoplay={autoplay}/>diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex 5475c6e86..614098011 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -131,6 +131,13 @@ const trackVideoView = (payload: {});};+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+interface ShareProps {data: VideoData;comments: MaybePromise<CommentWithAuthor[]>;@@ -144,8 +151,7 @@ interface ShareProps {title?: string | null;summary?: string | null;chapters?: { title: string; start: number }[] | null;- processing?: boolean;- generationSkipped?: boolean;+ aiGenerationStatus?: AiGenerationStatus | null;} | null;aiGenerationEnabled: boolean;}@@ -159,8 +165,7 @@ const useVideoStatus = (title?: string | null;summary?: string | null;chapters?: { title: string; start: number }[] | null;- processing?: boolean;- generationSkipped?: boolean;+ aiGenerationStatus?: AiGenerationStatus | null;} | null;},) => {@@ -181,8 +186,9 @@ const useVideoStatus = (| "SKIPPED"| "NO_AUDIO"| null,- aiProcessing: initialData.aiData?.processing || false,- aiGenerationSkipped: initialData.aiData?.generationSkipped || false,+ aiGenerationStatus:+ (initialData.aiData?.aiGenerationStatus as AiGenerationStatus) ||+ null,aiTitle: initialData.aiData?.title || null,summary: initialData.aiData?.summary || null,chapters: initialData.aiData?.chapters || null,@@ -213,15 +219,22 @@ const useVideoStatus = (return false;}- if (data.aiGenerationSkipped) {+ if (+ data.aiGenerationStatus === "SKIPPED" ||+ data.aiGenerationStatus === "ERROR" ||+ data.aiGenerationStatus === "COMPLETE"+ ) {return false;}- if (data.aiProcessing) {+ if (+ data.aiGenerationStatus === "QUEUED" ||+ data.aiGenerationStatus === "PROCESSING"+ ) {return true;}- if (!data.summary && !data.chapters) {+ if (!data.aiGenerationStatus && !data.summary && !data.chapters) {return true;}@@ -277,8 +290,7 @@ export const Share = ({title: videoStatus?.aiTitle || null,summary: videoStatus?.summary || null,chapters: videoStatus?.chapters || null,- processing: videoStatus?.aiProcessing || false,- generationSkipped: videoStatus?.aiGenerationSkipped || false,+ aiGenerationStatus: videoStatus?.aiGenerationStatus || null,}),[videoStatus],);@@ -313,13 +325,20 @@ export const Share = ({}if (transcriptionStatus === "COMPLETE") {- if (aiData.generationSkipped) {+ if (+ aiData.aiGenerationStatus === "SKIPPED" ||+ aiData.aiGenerationStatus === "ERROR" ||+ aiData.aiGenerationStatus === "COMPLETE"+ ) {return false;}- if (aiData.processing === true) {+ if (+ aiData.aiGenerationStatus === "QUEUED" ||+ aiData.aiGenerationStatus === "PROCESSING"+ ) {return true;}- if (!aiData.summary && !aiData.chapters) {+ if (!aiData.aiGenerationStatus && !aiData.summary && !aiData.chapters) {return true;}}@@ -414,7 +433,7 @@ export const Share = ({areCommentStampsDisabled={areCommentStampsDisabled}areReactionStampsDisabled={areReactionStampsDisabled}chapters={aiData?.chapters || []}- aiProcessing={aiData?.processing || false}+ aiGenerationStatus={aiData?.aiGenerationStatus}ref={playerRef}/></div>diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsxindex 455f185d7..0b2db5dfe 100644--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx@@ -32,6 +32,13 @@ type CommentWithAuthor = typeof commentsSchema.$inferSelect & {authorImage: ImageUpload.ImageUrl | null;};+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+export const ShareVideo = forwardRef<HTMLVideoElement,{@@ -44,7 +51,7 @@ export const ShareVideo = forwardRef<areCaptionsDisabled?: boolean;areCommentStampsDisabled?: boolean;areReactionStampsDisabled?: boolean;- aiProcessing?: boolean;+ aiGenerationStatus?: AiGenerationStatus | null;}>((diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsxindex 11f927778..719b278e7 100644--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx@@ -19,6 +19,13 @@ type CommentType = typeof commentsSchema.$inferSelect & {authorImage?: ImageUpload.ImageUrl | null;};+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+interface SidebarProps {data: VideoData;commentsData: CommentType[];@@ -34,7 +41,7 @@ interface SidebarProps {title?: string | null;summary?: string | null;chapters?: { title: string; start: number }[] | null;- processing?: boolean;+ aiGenerationStatus?: AiGenerationStatus | null;} | null;aiGenerationEnabled?: boolean;}diff --git a/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx b/apps/web/app/s/[videoId]/_components/SummaryChapters.tsxindex e6e33b0f6..52b90061f 100644--- a/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx+++ b/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx@@ -1,6 +1,13 @@import ReactMarkdown from "react-markdown";import { formatTimeMinutes } from "./utils/transcript-utils";+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+interface SummaryChaptersProps {isSummaryDisabled: boolean;areChaptersDisabled: boolean;@@ -14,7 +21,7 @@ interface SummaryChaptersProps {start: number;}[]| null;- processing: boolean;+ aiGenerationStatus: AiGenerationStatus | null;};aiLoading: boolean;}diff --git a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsxindex 5e990d8fd..9a5ca75a6 100644--- a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx+++ b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx@@ -2,10 +2,21 @@import { Button } from "@cap/ui";import type { Video } from "@cap/web-domain";-import { faRectangleList } from "@fortawesome/free-solid-svg-icons";+import {+ faRectangleList,+ faRotateRight,+} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { useState } from "react";import ReactMarkdown from "react-markdown";+type AiGenerationStatus =+ | "QUEUED"+ | "PROCESSING"+ | "COMPLETE"+ | "ERROR"+ | "SKIPPED";+interface Chapter {title: string;start: number;@@ -18,7 +29,7 @@ interface SummaryProps {title?: string | null;summary?: string | null;chapters?: Chapter[] | null;- processing?: boolean;+ aiGenerationStatus?: AiGenerationStatus | null;};aiGenerationEnabled?: boolean;isSummaryDisabled?: boolean;@@ -62,25 +73,60 @@ const SkeletonLoader = () => ();export const Summary: React.FC<SummaryProps> = ({+ videoId,onSeek,initialAiData,isSummaryDisabled = false,aiGenerationEnabled = false,ownerIsPro,}) => {+ const [isRetrying, setIsRetrying] = useState(false);+ const [retryError, setRetryError] = useState<string | null>(null);+const aiData = initialAiData || null;+ const aiGenerationStatus = aiData?.aiGenerationStatus;+const isLoading =aiGenerationEnabled &&- aiData?.processing === true &&+ (aiGenerationStatus === "QUEUED" || aiGenerationStatus === "PROCESSING") &&!aiData?.summary &&!aiData?.chapters?.length;+ const canRetry =+ aiGenerationStatus === "ERROR" || aiGenerationStatus === "SKIPPED";+const handleSeek = (time: number) => {if (onSeek) {onSeek(time);}};+ const handleRetry = async () => {+ setIsRetrying(true);+ setRetryError(null);++ try {+ const response = await fetch(`/api/videos/${videoId}/retry-ai`, {+ method: "POST",+ });++ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || "Failed to retry AI generation");+ }++ window.location.reload();+ } catch (error) {+ setRetryError(+ error instanceof Error+ ? error.message+ : "Failed to retry AI generation",+ );+ } finally {+ setIsRetrying(false);+ }+ };+if (!ownerIsPro) {return (<div className="flex flex-col justify-center items-center p-8 h-full text-center">@@ -145,11 +191,38 @@ export const Summary: React.FC<SummaryProps> = ({/><div className="space-y-1"><h3 className="text-base font-medium text-gray-12">- No summary available+ {aiGenerationStatus === "ERROR"+ ? "AI generation failed"+ : aiGenerationStatus === "SKIPPED"+ ? "AI generation skipped"+ : "No summary available"}</h3><p className="text-sm text-gray-10">- AI summary has not been generated for this video yet.+ {aiGenerationStatus === "ERROR"+ ? "There was an error generating the AI summary."+ : aiGenerationStatus === "SKIPPED"+ ? "The video was too short or had no speech detected."+ : "AI summary has not been generated for this video yet."}</p>+ {canRetry && (+ <div className="pt-4">+ <Button+ variant="gray"+ size="sm"+ onClick={handleRetry}+ disabled={isRetrying}+ >+ <FontAwesomeIcon+ icon={faRotateRight}+ className={`mr-2 ${isRetrying ? "animate-spin" : ""}`}+ />+ {isRetrying ? "Retrying..." : "Retry AI Generation"}+ </Button>+ {retryError && (+ <p className="mt-2 text-sm text-red-500">{retryError}</p>+ )}+ </div>+ )}</div></div>);diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 6e78e8833..bdd1685aa 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -469,33 +469,14 @@ async function AuthorizedContent({const currentMetadata = (video.metadata as VideoMetadata) || {};const metadata = currentMetadata;- let initialAiData = null;-- if (metadata.summary || metadata.chapters || metadata.aiTitle) {- initialAiData = {- title: metadata.aiTitle || null,- summary: metadata.summary || null,- chapters: metadata.chapters || null,- processing: metadata.aiProcessing || false,- generationSkipped: metadata.aiGenerationSkipped || false,- };- } else if (metadata.aiProcessing) {- initialAiData = {- title: null,- summary: null,- chapters: null,- processing: true,- generationSkipped: false,- };- } else if (metadata.aiGenerationSkipped) {- initialAiData = {- title: null,- summary: null,- chapters: null,- processing: false,- generationSkipped: true,- };- }+ const aiGenerationStatus = metadata.aiGenerationStatus || null;++ const initialAiData = {+ title: metadata.aiTitle || null,+ summary: metadata.summary || null,+ chapters: metadata.chapters || null,+ aiGenerationStatus,+ };const customDomainPromise = (async () => {if (!user) {diff --git a/apps/web/lib/generate-ai.ts b/apps/web/lib/generate-ai.tsnew file mode 100644index 000000000..641a6e154--- /dev/null+++ b/apps/web/lib/generate-ai.ts@@ -0,0 +1,107 @@+import { db } from "@cap/database";+import { videos } from "@cap/database/schema";+import type { VideoMetadata } from "@cap/database/types";+import { serverEnv } from "@cap/env";+import type { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { start } from "workflow/api";+import { generateAiWorkflow } from "@/workflows/generate-ai";++type GenerateAiResult = {+ success: boolean;+ message: string;+};++export async function startAiGeneration(+ videoId: Video.VideoId,+ userId: string,+): Promise<GenerateAiResult> {+ if (!serverEnv().GROQ_API_KEY && !serverEnv().OPENAI_API_KEY) {+ return {+ success: false,+ message: "Missing AI API keys (Groq or OpenAI)",+ };+ }++ if (!userId || !videoId) {+ return {+ success: false,+ message: "userId or videoId not supplied",+ };+ }++ const query = await db()+ .select({ video: videos })+ .from(videos)+ .where(eq(videos.id, videoId));++ if (query.length === 0 || !query[0]?.video) {+ return { success: false, message: "Video does not exist" };+ }++ const { video } = query[0];++ if (video.transcriptionStatus !== "COMPLETE") {+ return {+ success: false,+ message: "Transcription not complete",+ };+ }++ const metadata = (video.metadata as VideoMetadata) || {};++ if (+ metadata.aiGenerationStatus === "PROCESSING" ||+ metadata.aiGenerationStatus === "QUEUED"+ ) {+ return {+ success: true,+ message: "AI generation already in progress",+ };+ }++ if (+ metadata.aiGenerationStatus === "COMPLETE" &&+ metadata.summary &&+ metadata.chapters+ ) {+ return {+ success: true,+ message: "AI metadata already generated",+ };+ }++ try {+ await db()+ .update(videos)+ .set({+ metadata: {+ ...metadata,+ aiGenerationStatus: "QUEUED",+ },+ })+ .where(eq(videos.id, videoId));++ await start(generateAiWorkflow, [{ videoId, userId }]);++ return {+ success: true,+ message: "AI generation workflow started",+ };+ } catch {+ await db()+ .update(videos)+ .set({+ metadata: {+ ...metadata,+ aiGenerationStatus: "ERROR",+ },+ })+ .where(eq(videos.id, videoId));++ return {+ success: false,+ message: "Failed to start AI generation workflow",+ };+ }+}diff --git a/apps/web/scripts/reset-ai-processing-flags.ts b/apps/web/scripts/reset-ai-processing-flags.tsdeleted file mode 100644index b3ec48836..000000000--- a/apps/web/scripts/reset-ai-processing-flags.ts+++ /dev/null@@ -1,48 +0,0 @@-import { db } from "@cap/database";-import { videos } from "@cap/database/schema";-import type { VideoMetadata } from "@cap/database/types";-import { sql } from "drizzle-orm";--async function resetStuckAiProcessingFlags() {- console.log("Checking for stuck AI processing flags...");-- const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);-- const stuckVideos = await db()- .select()- .from(videos)- .where(sql`- (metadata->>'aiProcessing')::boolean = true- AND updated_at < ${tenMinutesAgo}- `);-- console.log(- `Found ${stuckVideos.length} videos with stuck AI processing flags`,- );-- for (const video of stuckVideos) {- const metadata = (video.metadata as VideoMetadata) || {};- console.log(- `Resetting AI processing flag for video ${video.id} (updated ${video.updatedAt})`,- );-- await db()- .update(videos)- .set({- metadata: {- ...metadata,- aiProcessing: false,- // generationError: "AI processing was stuck and has been reset",- },- })- .where(sql`id = ${video.id}`);- }-- console.log("Done resetting stuck AI processing flags");- process.exit(0);-}--resetStuckAiProcessingFlags().catch((error) => {- console.error("Error resetting AI processing flags:", error);- process.exit(1);-});diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.tsnew file mode 100644index 000000000..8f0b70734--- /dev/null+++ b/apps/web/workflows/generate-ai.ts@@ -0,0 +1,492 @@+import { db } from "@cap/database";+import { s3Buckets, videos } from "@cap/database/schema";+import type { VideoMetadata } from "@cap/database/types";+import { serverEnv } from "@cap/env";+import { S3Buckets } from "@cap/web-backend";+import type { S3Bucket, Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect, Option } from "effect";+import { FatalError } from "workflow";+import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";+import { runPromise } from "@/lib/server";++interface GenerateAiWorkflowPayload {+ videoId: string;+ userId: string;+}++interface VideoData {+ video: typeof videos.$inferSelect;+ bucketId: S3Bucket.S3BucketId | null;+ metadata: VideoMetadata;+}++interface VttSegment {+ start: number;+ text: string;+}++interface TranscriptData {+ segments: VttSegment[];+ text: string;+}++interface AiResult {+ title?: string;+ summary?: string;+ chapters?: { title: string; start: number }[];+}++const MAX_CHARS_PER_CHUNK = 24000;++export async function generateAiWorkflow(payload: GenerateAiWorkflowPayload) {+ "use workflow";++ const { videoId, userId } = payload;++ const videoData = await validateAndSetProcessing(videoId);++ const transcript = await fetchTranscript(videoId, userId, videoData.bucketId);++ if (!transcript) {+ await markSkipped(videoId, videoData.metadata);+ return {+ success: true,+ message: "Transcript empty or too short - skipped",+ };+ }++ const result = await generateWithAi(transcript);++ await saveResults(videoId, videoData, result);++ return { success: true, message: "AI generation completed successfully" };+}++async function validateAndSetProcessing(videoId: string): Promise<VideoData> {+ "use step";++ const groqClient = getGroqClient();+ if (!groqClient && !serverEnv().OPENAI_API_KEY) {+ throw new FatalError("Missing Groq or OpenAI API key");+ }++ const query = await db()+ .select({ video: videos, bucket: s3Buckets })+ .from(videos)+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))+ .where(eq(videos.id, videoId as Video.VideoId));++ if (query.length === 0 || !query[0]?.video) {+ throw new FatalError("Video does not exist");+ }++ const { video, bucket } = query[0];+ const metadata = (video.metadata as VideoMetadata) || {};++ if (video.transcriptionStatus !== "COMPLETE") {+ throw new FatalError("Transcription not complete");+ }++ if (metadata.summary && metadata.chapters) {+ throw new FatalError("AI metadata already generated");+ }++ await db()+ .update(videos)+ .set({+ metadata: {+ ...metadata,+ aiGenerationStatus: "PROCESSING",+ },+ })+ .where(eq(videos.id, videoId as Video.VideoId));++ return {+ video,+ bucketId: (bucket?.id ?? null) as S3Bucket.S3BucketId | null,+ metadata,+ };+}++async function fetchTranscript(+ videoId: string,+ userId: string,+ bucketId: S3Bucket.S3BucketId | null,+): Promise<TranscriptData | null> {+ "use step";++ const vtt = await Effect.gen(function* () {+ const [bucket] = yield* S3Buckets.getBucketAccess(+ Option.fromNullable(bucketId),+ );+ return yield* bucket.getObject(`${userId}/${videoId}/transcription.vtt`);+ }).pipe(runPromise);++ if (Option.isNone(vtt)) {+ return null;+ }++ const segments = parseVttWithTimestamps(vtt.value);+ const text = segments+ .map((s) => s.text)+ .join(" ")+ .trim();++ if (text.length < 10) {+ return null;+ }++ return { segments, text };+}++async function markSkipped(+ videoId: string,+ metadata: VideoMetadata,+): Promise<void> {+ "use step";++ await db()+ .update(videos)+ .set({+ metadata: {+ ...metadata,+ aiGenerationStatus: "SKIPPED",+ },+ })+ .where(eq(videos.id, videoId as Video.VideoId));+}++async function generateWithAi(transcript: TranscriptData): Promise<AiResult> {+ "use step";++ const groqClient = getGroqClient();+ const chunks = chunkTranscriptWithTimestamps(transcript.segments);++ if (chunks.length === 1) {+ return generateSingleChunk(transcript.text, groqClient);+ }++ return generateMultipleChunks(chunks, groqClient);+}++async function saveResults(+ videoId: string,+ videoData: VideoData,+ result: AiResult,+): Promise<void> {+ "use step";++ const { video, metadata } = videoData;++ const updatedMetadata: VideoMetadata = {+ ...metadata,+ aiTitle: result.title || metadata.aiTitle,+ summary: result.summary || metadata.summary,+ chapters: result.chapters || metadata.chapters,+ aiGenerationStatus: "COMPLETE",+ };++ await db()+ .update(videos)+ .set({ metadata: updatedMetadata })+ .where(eq(videos.id, videoId as Video.VideoId));++ const hasDatePattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(+ video.name || "",+ );++ if (+ (video.name?.startsWith("Cap Recording -") || hasDatePattern) &&+ result.title+ ) {+ await db()+ .update(videos)+ .set({ name: result.title })+ .where(eq(videos.id, videoId as Video.VideoId));+ }+}++function parseVttWithTimestamps(vttContent: string): VttSegment[] {+ const lines = vttContent.split("\n");+ const segments: VttSegment[] = [];+ let currentStart = 0;++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]?.trim() ?? "";+ if (line.includes("-->")) {+ const timeMatch = line.match(/(\d{2}):(\d{2}):(\d{2})[.,](\d{3})/);+ if (timeMatch) {+ currentStart =+ parseInt(timeMatch[1] ?? "0", 10) * 3600 ++ parseInt(timeMatch[2] ?? "0", 10) * 60 ++ parseInt(timeMatch[3] ?? "0", 10);+ }+ } else if (+ line &&+ line !== "WEBVTT" &&+ !/^\d+$/.test(line) &&+ !line.includes("-->")+ ) {+ segments.push({ start: currentStart, text: line });+ }+ }++ return segments;+}++function chunkTranscriptWithTimestamps(+ segments: VttSegment[],+): { text: string; startTime: number; endTime: number }[] {+ const chunks: { text: string; startTime: number; endTime: number }[] = [];+ let currentChunk: VttSegment[] = [];+ let currentLength = 0;++ for (const segment of segments) {+ if (+ currentLength + segment.text.length > MAX_CHARS_PER_CHUNK &&+ currentChunk.length > 0+ ) {+ chunks.push({+ text: currentChunk.map((s) => s.text).join(" "),+ startTime: currentChunk[0]?.start ?? 0,+ endTime: currentChunk[currentChunk.length - 1]?.start ?? 0,+ });+ currentChunk = [];+ currentLength = 0;+ }+ currentChunk.push(segment);+ currentLength += segment.text.length + 1;+ }++ if (currentChunk.length > 0) {+ chunks.push({+ text: currentChunk.map((s) => s.text).join(" "),+ startTime: currentChunk[0]?.start ?? 0,+ endTime: currentChunk[currentChunk.length - 1]?.start ?? 0,+ });+ }++ return chunks;+}++async function callAiApi(+ prompt: string,+ groqClient: ReturnType<typeof getGroqClient>,+): Promise<string> {+ if (groqClient) {+ try {+ const completion = await groqClient.chat.completions.create({+ messages: [{ role: "user", content: prompt }],+ model: GROQ_MODEL,+ });+ return completion.choices?.[0]?.message?.content || "{}";+ } catch (groqError) {+ if (serverEnv().OPENAI_API_KEY) {+ return callOpenAi(prompt);+ }+ throw groqError;+ }+ } else if (serverEnv().OPENAI_API_KEY) {+ return callOpenAi(prompt);+ }+ return "{}";+}++async function callOpenAi(prompt: string): Promise<string> {+ const aiRes = await fetch("https://api.openai.com/v1/chat/completions", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${serverEnv().OPENAI_API_KEY}`,+ },+ body: JSON.stringify({+ model: "gpt-4o-mini",+ messages: [{ role: "user", content: prompt }],+ }),+ });+ if (!aiRes.ok) {+ const errorText = await aiRes.text();+ throw new Error(`OpenAI API error: ${aiRes.status} ${errorText}`);+ }+ const aiJson = await aiRes.json();+ return aiJson.choices?.[0]?.message?.content || "{}";+}++function cleanJsonResponse(content: string): string {+ if (content.includes("```json")) {+ return content.replace(/```json\s*/g, "").replace(/```\s*/g, "");+ }+ if (content.includes("```")) {+ return content.replace(/```\s*/g, "");+ }+ return content;+}++async function generateSingleChunk(+ transcriptText: string,+ groqClient: ReturnType<typeof getGroqClient>,+): Promise<AiResult> {+ const prompt = `You are Cap AI, an expert at analyzing video content and creating comprehensive summaries.++Analyze this transcript thoroughly and provide a detailed JSON response:+{+ "title": "string (concise but descriptive title that captures the main topic)",+ "summary": "string (detailed summary that covers ALL key points discussed. For meetings: include decisions made, action items, and key discussion points. For tutorials: cover all steps and concepts explained. For presentations: summarize all main arguments and supporting points. Write from 1st person perspective if the speaker is teaching/presenting, e.g. 'In this video, I walk through...'. Make it comprehensive enough that someone could understand the full content without watching.)",+ "chapters": [{"title": "string (descriptive chapter title)", "start": number (seconds from start)}]+}++Guidelines:+- The summary should be detailed and comprehensive, not a brief overview+- Capture ALL important topics, not just the main theme+- For longer content, organize the summary by topic or chronologically+- Include specific details, names, numbers, and conclusions mentioned+- Chapters should mark distinct topic changes or sections++Return ONLY valid JSON without any markdown formatting or code blocks.+Transcript:+${transcriptText}`;++ const content = await callAiApi(prompt, groqClient);+ return parseAiResponse(content);+}++async function generateMultipleChunks(+ chunks: { text: string; startTime: number; endTime: number }[],+ groqClient: ReturnType<typeof getGroqClient>,+): Promise<AiResult> {+ const chunkSummaries: {+ summary: string;+ keyPoints: string[];+ chapters: { title: string; start: number }[];+ startTime: number;+ endTime: number;+ }[] = [];++ for (let i = 0; i < chunks.length; i++) {+ const chunk = chunks[i];+ if (!chunk) continue;++ const chunkPrompt = `You are Cap AI, an expert at analyzing video content. This is section ${i + 1} of ${chunks.length} from a longer video (timestamp ${Math.floor(chunk.startTime / 60)}:${String(chunk.startTime % 60).padStart(2, "0")} to ${Math.floor(chunk.endTime / 60)}:${String(chunk.endTime % 60).padStart(2, "0")}).++Analyze this section thoroughly and provide JSON:+{+ "summary": "string (detailed summary of this section - capture ALL key points, topics discussed, decisions made, or concepts explained. Include specific details like names, numbers, action items, and conclusions. This should be 3-6 sentences minimum.)",+ "keyPoints": ["string (specific key point or takeaway)", ...],+ "chapters": [{"title": "string (descriptive title for this topic/section)", "start": number (seconds from video start)}]+}++Be thorough - this summary will be combined with other sections to create a comprehensive overview.+Return ONLY valid JSON without any markdown formatting or code blocks.+Transcript section:+${chunk.text}`;++ const chunkContent = await callAiApi(chunkPrompt, groqClient);+ try {+ const parsed = JSON.parse(cleanJsonResponse(chunkContent).trim());+ chunkSummaries.push({+ summary: parsed.summary || "",+ keyPoints: parsed.keyPoints || [],+ chapters: parsed.chapters || [],+ startTime: chunk.startTime,+ endTime: chunk.endTime,+ });+ } catch {}+ }++ const allChapters: { title: string; start: number }[] = [];+ const sortedChapters = chunkSummaries+ .flatMap((c) => c.chapters)+ .sort((a, b) => a.start - b.start);+ for (const chapter of sortedChapters) {+ const lastChapter = allChapters[allChapters.length - 1];+ if (!lastChapter || Math.abs(chapter.start - lastChapter.start) >= 30) {+ allChapters.push(chapter);+ }+ }++ const allKeyPoints = chunkSummaries.flatMap((c) => c.keyPoints);++ const sectionDetails = chunkSummaries+ .map((c, i) => {+ const timeRange = `${Math.floor(c.startTime / 60)}:${String(c.startTime % 60).padStart(2, "0")} - ${Math.floor(c.endTime / 60)}:${String(c.endTime % 60).padStart(2, "0")}`;+ const keyPointsList =+ c.keyPoints.length > 0 ? `\nKey points: ${c.keyPoints.join("; ")}` : "";+ return `Section ${i + 1} (${timeRange}):\n${c.summary}${keyPointsList}`;+ })+ .join("\n\n");++ const finalPrompt = `You are Cap AI, an expert at synthesizing information into comprehensive, well-organized summaries.++Based on these detailed section analyses of a video, create a thorough final summary that captures EVERYTHING important.++Section analyses:+${sectionDetails}++${allKeyPoints.length > 0 ? `All key points identified:\n${allKeyPoints.map((p, i) => `${i + 1}. ${p}`).join("\n")}\n` : ""}++Provide JSON in the following format:+{+ "title": "string (concise but descriptive title that captures the main topic/purpose)",+ "summary": "string (COMPREHENSIVE summary that covers the entire video thoroughly. This should be detailed enough that someone could understand all the important content without watching. Include: main topics covered, key decisions or conclusions, important details mentioned, action items if any. Organize it logically - for meetings use topics/agenda items, for tutorials use steps/concepts, for presentations use main arguments. Write from 1st person perspective if appropriate. This should be several paragraphs for longer content.)"+}++The summary must be detailed and comprehensive - not a brief overview. Capture all the important information from every section.+Return ONLY valid JSON without any markdown formatting or code blocks.`;++ const finalContent = await callAiApi(finalPrompt, groqClient);+ try {+ const parsed = JSON.parse(cleanJsonResponse(finalContent).trim());+ return {+ title: parsed.title,+ summary: parsed.summary,+ chapters: allChapters,+ };+ } catch {+ const fallbackSummary = chunkSummaries+ .map((c, i) => `**Part ${i + 1}:** ${c.summary}`)+ .join("\n\n");+ const keyPointsSummary =+ allKeyPoints.length > 0+ ? `\n\n**Key Points:**\n${allKeyPoints.map((p) => `- ${p}`).join("\n")}`+ : "";+ return {+ title: "Video Summary",+ summary: fallbackSummary + keyPointsSummary,+ chapters: allChapters,+ };+ }+}++function parseAiResponse(content: string): AiResult {+ try {+ const data = JSON.parse(cleanJsonResponse(content).trim());++ if (data.chapters && data.chapters.length > 0) {+ const sortedChapters = data.chapters.sort(+ (a: { start: number }, b: { start: number }) => a.start - b.start,+ );+ const dedupedChapters: { title: string; start: number }[] = [];+ for (const chapter of sortedChapters) {+ const lastChapter = dedupedChapters[dedupedChapters.length - 1];+ if (!lastChapter || Math.abs(chapter.start - lastChapter.start) >= 30) {+ dedupedChapters.push(chapter);+ }+ }+ data.chapters = dedupedChapters;+ }++ return {+ title: data.title,+ summary: data.summary,+ chapters: data.chapters,+ };+ } catch {+ return {+ title: "Generated Title",+ summary:+ "The AI was unable to generate a proper summary for this content.",+ chapters: [],+ };+ }+}diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.tsindex 3c01ba39d..2db8abc37 100644--- a/apps/web/workflows/transcribe.ts+++ b/apps/web/workflows/transcribe.ts@@ -8,8 +8,8 @@ import { createClient } from "@deepgram/sdk";import { eq } from "drizzle-orm";import { Option } from "effect";import { FatalError } from "workflow";-import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";import { checkHasAudioTrack, extractAudioFromUrl } from "@/lib/audio-extract";+import { startAiGeneration } from "@/lib/generate-ai";import {checkHasAudioTrackViaMediaServer,extractAudioViaMediaServer,@@ -61,7 +61,7 @@ export async function transcribeVideoWorkflow(await cleanupTempAudio(videoId, userId, videoData.bucketId);if (aiGenerationEnabled) {- await generateMetadata(videoId, userId);+ await queueAiGeneration(videoId, userId);}return { success: true, message: "Transcription completed successfully" };@@ -267,11 +267,11 @@ async function cleanupTempAudio(} catch {}}-async function generateMetadata(+async function queueAiGeneration(videoId: string,userId: string,): Promise<void> {"use step";- await generateAiMetadata(videoId as Video.VideoId, userId);+ await startAiGeneration(videoId as Video.VideoId, userId);}