Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): fall through to the next AI provider on unusable fulfilled responses
Richie McIlroyd0b50eb4b7d9
diff --git a/apps/web/__tests__/unit/generate-ai-fallback.test.ts b/apps/web/__tests__/unit/generate-ai-fallback.test.tsnew file mode 100644index 000000000..25451add9--- /dev/null+++ b/apps/web/__tests__/unit/generate-ai-fallback.test.ts@@ -0,0 +1,122 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AiModelSelection } from "@/lib/ai/provider";++const generateTextMock = vi.hoisted(() => vi.fn());+const getAiProviderChainMock = vi.hoisted(() => vi.fn());++vi.mock("ai", () => ({+ generateText: generateTextMock,+ APICallError: { isInstance: () => false },+}));++vi.mock("@/lib/ai/provider", () => ({+ getAiProviderChain: getAiProviderChainMock,+ isAiConfigured: vi.fn(() => true),+}));++vi.mock("@cap/database", () => ({+ db: vi.fn(),+}));++vi.mock("@cap/env", () => ({+ serverEnv: () => ({}),+}));++vi.mock("@cap/web-backend/src/Storage/index", () => ({+ Storage: {},+}));++vi.mock("@/lib/workflow-runtime", () => ({+ runWorkflowPromise: vi.fn(),+}));++vi.mock("@/lib/video-storage", () => ({+ decodeStorageVideo: vi.fn(),+}));++vi.mock("workflow", () => ({+ FatalError: class FatalError extends Error {},+}));++vi.mock("server-only", () => ({}));++import { AiUnavailableError } from "@/lib/ai/run";+import { callAiApi, parseAiResponse } from "@/workflows/generate-ai";++const makeSelection = (provider: string): AiModelSelection => ({+ provider: provider as AiModelSelection["provider"],+ modelId: `${provider}-model`,+ model: () => ({}) as ReturnType<AiModelSelection["model"]>,+ supportsStreaming: true,+ supportsTemperature: true,+ defaultMaxOutputTokens: 8000,+});++const VALID_JSON =+ '{"title":"Workflow review","summary":"I explain the workflow.","chapters":[]}';++describe("callAiApi provider fallback on invalid output", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, "error").mockImplementation(() => {});+ getAiProviderChainMock.mockReturnValue([+ makeSelection("groq"),+ makeSelection("openai"),+ ]);+ });++ it("falls through to the next provider when a fulfilled response is malformed", async () => {+ generateTextMock+ .mockResolvedValueOnce({ text: "I could not produce JSON" })+ .mockResolvedValueOnce({ text: VALID_JSON });++ await expect(callAiApi("prompt", parseAiResponse)).resolves.toEqual({+ title: "Workflow review",+ summary: "I explain the workflow.",+ chapters: [],+ });+ expect(generateTextMock).toHaveBeenCalledTimes(2);+ });++ it("falls through to the next provider when a fulfilled response is empty or truncated", async () => {+ generateTextMock+ .mockResolvedValueOnce({ text: "" })+ .mockResolvedValueOnce({ text: '{"title":"Cut off","summary":"' })+ .mockResolvedValueOnce({ text: VALID_JSON });+ getAiProviderChainMock.mockReturnValue([+ makeSelection("groq"),+ makeSelection("openai"),+ makeSelection("anthropic"),+ ]);++ await expect(callAiApi("prompt", parseAiResponse)).resolves.toMatchObject({+ title: "Workflow review",+ });+ expect(generateTextMock).toHaveBeenCalledTimes(3);+ });++ it("marks the terminal failure as invalid output when every provider returns unusable text", async () => {+ generateTextMock.mockResolvedValue({ text: "still not JSON" });++ const error = await callAiApi("prompt", parseAiResponse).catch(+ (caught) => caught,+ );++ expect(error).toBeInstanceOf(AiUnavailableError);+ expect((error.cause as Error).name).toBe("InvalidAiOutputError");+ });++ it("keeps request-level chain failures distinguishable from invalid output", async () => {+ const outage = new Error("connect ECONNREFUSED");+ generateTextMock+ .mockResolvedValueOnce({ text: "not JSON" })+ .mockRejectedValueOnce(outage);++ const error = await callAiApi("prompt", parseAiResponse).catch(+ (caught) => caught,+ );++ expect(error).toBeInstanceOf(AiUnavailableError);+ expect(error.cause).toBe(outage);+ });+});diff --git a/apps/web/actions/videos/translate-transcript.ts b/apps/web/actions/videos/translate-transcript.tsindex 012b6dcc3..f3f78d388 100644--- a/apps/web/actions/videos/translate-transcript.ts+++ b/apps/web/actions/videos/translate-transcript.ts@@ -158,21 +158,22 @@ VTT content to translate:${vttContent}`;try {- const response = await runWithAiProviders("generation", (selection) =>- generateText({+ return await runWithAiProviders("generation", async (selection) => {+ const response = await generateText({model: selection.model(),prompt,maxOutputTokens: 8000,...(selection.supportsTemperature ? { temperature: 0.3 } : {}),- }),- );+ });- const content = response.text;- if (content?.includes("WEBVTT")) {- return content.trim();- }+ // Validate inside the provider loop so a fulfilled response that+ // dropped the WEBVTT header falls through to the next provider.+ if (!response.text.includes("WEBVTT")) {+ throw new Error("translation response did not contain WEBVTT");+ }- return null;+ return response.text.trim();+ });} catch (error) {console.error("[translateVttContent] Translation error:", error);return null;diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.tsindex bb2f048e0..f8f749fe5 100644--- a/apps/web/workflows/generate-ai.ts+++ b/apps/web/workflows/generate-ai.ts@@ -14,7 +14,7 @@ import { and, eq, sql } from "drizzle-orm";import { Effect, Option } from "effect";import { FatalError } from "workflow";import { isAiConfigured } from "@/lib/ai/provider";-import { runWithAiProviders } from "@/lib/ai/run";+import { AiUnavailableError, runWithAiProviders } from "@/lib/ai/run";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -490,15 +490,45 @@ function chunkTranscriptWithTimestamps(return chunks;}-async function callAiApi(prompt: string): Promise<string> {- const result = await runWithAiProviders("generation", (selection) =>- generateText({+class InvalidAiOutputError extends Error {+ constructor(message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = "InvalidAiOutputError";+ }+}++/**+ * True when the whole provider chain was exhausted and the terminal failure+ * was a fulfilled-but-unusable response rather than a request-level failure.+ */+function failedOnInvalidOutput(error: unknown): boolean {+ return (+ error instanceof AiUnavailableError &&+ error.cause instanceof InvalidAiOutputError+ );+}++export async function callAiApi<T>(+ prompt: string,+ parse: (text: string) => T,+): Promise<T> {+ return runWithAiProviders("generation", async (selection) => {+ const result = await generateText({model: selection.model({ jsonRepair: true }),prompt,maxOutputTokens: selection.defaultMaxOutputTokens,- }),- );- return result.text;+ });+ // Parse inside the provider loop so an empty, malformed, or truncated+ // fulfilled response falls through to the next provider too.+ try {+ return parse(result.text);+ } catch (error) {+ throw new InvalidAiOutputError(+ error instanceof Error ? error.message : String(error),+ { cause: error },+ );+ }+ });}function cleanJsonResponse(content: string): string {@@ -587,8 +617,7 @@ Return ONLY valid JSON without any markdown formatting or code blocks.Transcript:${transcriptWithTimestamps}`;- const content = await callAiApi(prompt);- return parseAiResponse(content);+ return callAiApi(prompt, parseAiResponse);}async function generateMultipleChunks(@@ -629,9 +658,10 @@ Return ONLY valid JSON without any markdown formatting or code blocks.Transcript section:${chunk.text}`;- const chunkContent = await callAiApi(chunkPrompt);try {- const parsed = JSON.parse(extractJsonObject(chunkContent));+ const parsed = await callAiApi(chunkPrompt, (text) =>+ JSON.parse(extractJsonObject(text)),+ );chunkSummaries.push({summary: parsed.summary || "",keyPoints: parsed.keyPoints || [],@@ -639,7 +669,11 @@ ${chunk.text}`;startTime: chunk.startTime,endTime: chunk.endTime,});- } catch {}+ } catch (error) {+ // A chunk is skipped only when every provider returned unusable+ // JSON; a request-level chain failure still fails the workflow.+ if (!failedOnInvalidOutput(error)) throw error;+ }}const allChapters: { title: string; start: number }[] = [];@@ -688,15 +722,17 @@ Additional requirements:- Keep JSON property names exactly as shown.Return ONLY valid JSON without any markdown formatting or code blocks.`;- const finalContent = await callAiApi(finalPrompt);try {- const parsed = JSON.parse(extractJsonObject(finalContent));+ const parsed = await callAiApi(finalPrompt, (text) =>+ JSON.parse(extractJsonObject(text)),+ );return {title: parsed.title,summary: parsed.summary,chapters: allChapters,};- } catch {+ } catch (error) {+ if (!failedOnInvalidOutput(error)) throw error;const fallbackSummary = chunkSummaries.map((c, i) => `**Part ${i + 1}:** ${c.summary}`).join("\n\n");