Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): strict AI response parsing and legacy fallback retry
Richie McIlroy7c4866546723
diff --git a/apps/web/app/api/videos/[videoId]/retry-ai/route.ts b/apps/web/app/api/videos/[videoId]/retry-ai/route.tsindex 56590c105..dad6851b7 100644--- a/apps/web/app/api/videos/[videoId]/retry-ai/route.ts+++ b/apps/web/app/api/videos/[videoId]/retry-ai/route.ts@@ -8,6 +8,9 @@ import { revalidatePath } from "next/cache";import { startAiGeneration } from "@/lib/generate-ai";import { isAiGenerationEnabled } from "@/utils/flags";+const LEGACY_AI_SUMMARY_FALLBACK =+ "The AI was unable to generate a proper summary for this content.";+export async function POST(_request: Request,props: RouteContext<"/api/videos/[videoId]/retry-ai">,@@ -53,7 +56,9 @@ export async function POST(const canRetry =!metadata.aiGenerationStatus ||metadata.aiGenerationStatus === "ERROR" ||- metadata.aiGenerationStatus === "SKIPPED";+ metadata.aiGenerationStatus === "SKIPPED" ||+ (metadata.aiGenerationStatus === "COMPLETE" &&+ metadata.summary === LEGACY_AI_SUMMARY_FALLBACK);if (!canRetry) {return Response.json(diff --git a/apps/web/lib/generate-ai.ts b/apps/web/lib/generate-ai.tsindex 98902d282..f4809c785 100644--- a/apps/web/lib/generate-ai.ts+++ b/apps/web/lib/generate-ai.ts@@ -12,6 +12,9 @@ type GenerateAiResult = {message: string;};+const LEGACY_AI_SUMMARY_FALLBACK =+ "The AI was unable to generate a proper summary for this content.";+const getAffectedRows = (result: unknown) => {if (Array.isArray(result)) {return (@@ -73,6 +76,7 @@ export async function startAiGeneration(if (metadata.aiGenerationStatus === "COMPLETE" &&metadata.summary &&+ metadata.summary !== LEGACY_AI_SUMMARY_FALLBACK &&metadata.chapters) {return {diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.tsindex 63604ee19..0e23f2b7f 100644--- a/apps/web/workflows/generate-ai.ts+++ b/apps/web/workflows/generate-ai.ts@@ -45,6 +45,9 @@ interface AiResult {}const MAX_CHARS_PER_CHUNK = 24000;+const LEGACY_AI_TITLE_FALLBACK = "Generated Title";+const LEGACY_AI_SUMMARY_FALLBACK =+ "The AI was unable to generate a proper summary for this content.";const GENERATED_TITLE_PATTERN =/^(Cap (Recording|Upload) - .+|Cap \d{4}-\d{2}-\d{2} at \d{2}[.:]\d{2}[.:]\d{2}|Untitled|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.+ \((Display|Window|Area|Camera)\) \d{4}-\d{2}-\d{2} \d{2}:\d{2} [AP]M)$/;@@ -69,6 +72,7 @@ export function shouldReplaceVideoTitle({if (!title) return true;if (previousAiTitle?.trim() && title === previousAiTitle.trim()) return true;if (sourceName?.trim() && title === sourceName.trim()) return true;+ if (title === LEGACY_AI_TITLE_FALLBACK) return true;return GENERATED_TITLE_PATTERN.test(title);}@@ -135,15 +139,27 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {throw new FatalError("Transcription not complete");}- if (metadata.summary && metadata.chapters) {+ if (+ metadata.summary &&+ metadata.summary !== LEGACY_AI_SUMMARY_FALLBACK &&+ metadata.chapters+ ) {throw new FatalError("AI metadata already generated");}+ const processingMetadata = { ...metadata };+ if (processingMetadata.aiTitle === LEGACY_AI_TITLE_FALLBACK) {+ delete processingMetadata.aiTitle;+ }+ if (processingMetadata.summary === LEGACY_AI_SUMMARY_FALLBACK) {+ delete processingMetadata.summary;+ }+await db().update(videos).set({metadata: {- ...metadata,+ ...processingMetadata,aiGenerationStatus: "PROCESSING",},})@@ -486,6 +502,7 @@ async function callAiApi(const completion = await groqClient.chat.completions.create({messages: [{ role: "user", content: prompt }],model: GROQ_MODEL,+ response_format: { type: "json_object" },});return completion.choices?.[0]?.message?.content || "{}";} catch (groqError) {@@ -510,6 +527,7 @@ async function callOpenAi(prompt: string): Promise<string> {body: JSON.stringify({model: "gpt-4o-mini",messages: [{ role: "user", content: prompt }],+ response_format: { type: "json_object" },}),});if (!aiRes.ok) {@@ -530,6 +548,44 @@ function cleanJsonResponse(content: string): string {return content;}+function extractJsonObject(content: string): string {+ const cleanedContent = cleanJsonResponse(content).trim();+ const start = cleanedContent.indexOf("{");+ if (start < 0) {+ throw new Error("AI response did not contain a JSON object");+ }++ let depth = 0;+ let inString = false;+ let escaped = false;+ for (let i = start; i < cleanedContent.length; i++) {+ const character = cleanedContent[i];+ if (inString) {+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === '"') {+ inString = false;+ }+ continue;+ }++ if (character === '"') {+ inString = true;+ } else if (character === "{") {+ depth += 1;+ } else if (character === "}") {+ depth -= 1;+ if (depth === 0) {+ return cleanedContent.slice(start, i + 1);+ }+ }+ }++ throw new Error("AI response contained an incomplete JSON object");+}+async function generateSingleChunk(segments: VttSegment[],videoDuration: number,@@ -695,32 +751,36 @@ Return ONLY valid JSON without any markdown formatting or code blocks.`;}}-function parseAiResponse(content: string): AiResult {- try {- const data = JSON.parse(cleanJsonResponse(content).trim());-- const chapters = Array.isArray(data.chapters)- ? data.chapters- .filter(- (ch: { start?: number }) =>- typeof ch.start === "number" && ch.start >= 0,- )- .sort(- (a: { start: number }, b: { start: number }) => a.start - b.start,- )- : [];-- return {- title: data.title,- summary: data.summary,- chapters,- };- } catch {- return {- title: "Generated Title",- summary:- "The AI was unable to generate a proper summary for this content.",- chapters: [],- };+export function parseAiResponse(content: string): AiResult {+ const data = JSON.parse(extractJsonObject(content)) as {+ title?: unknown;+ summary?: unknown;+ chapters?: unknown;+ };+ if (typeof data.title !== "string" || !data.title.trim()) {+ throw new Error("AI response did not contain a valid title");}+ if (typeof data.summary !== "string" || !data.summary.trim()) {+ throw new Error("AI response did not contain a valid summary");+ }++ const chapters = Array.isArray(data.chapters)+ ? data.chapters+ .filter(+ (ch): ch is { start: number; title: string } =>+ typeof ch === "object" &&+ ch !== null &&+ typeof ch.start === "number" &&+ ch.start >= 0 &&+ typeof ch.title === "string" &&+ ch.title.trim().length > 0,+ )+ .sort((a, b) => a.start - b.start)+ : [];++ return {+ title: data.title.trim(),+ summary: data.summary.trim(),+ chapters,+ };}