Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
refactor(web): migrate AI generation, translation, docs Ask AI, and messenger to the provider layer
Richie McIlroydfcdb7ad3313
diff --git a/apps/web/__tests__/unit/docs-ask-route.test.ts b/apps/web/__tests__/unit/docs-ask-route.test.tsnew file mode 100644index 000000000..faee2d67a--- /dev/null+++ b/apps/web/__tests__/unit/docs-ask-route.test.ts@@ -0,0 +1,176 @@+import { convertArrayToReadableStream, MockLanguageModelV4 } from "ai/test";+import type { NextRequest } from "next/server";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AiModelSelection } from "@/lib/ai/provider";++const getAiProviderChainMock = vi.hoisted(() => vi.fn());+const isAiConfiguredMock = vi.hoisted(() => vi.fn());+const isRateLimitedMock = vi.hoisted(() => vi.fn());+const getAllDocsMock = vi.hoisted(() => vi.fn());+const buildDocsAskContextMock = vi.hoisted(() => vi.fn());+const buildDocsAskSystemPromptMock = vi.hoisted(() => vi.fn());++vi.mock("@/lib/ai/provider", () => ({+ getAiProviderChain: getAiProviderChainMock,+ isAiConfigured: isAiConfiguredMock,+}));++vi.mock("@/lib/rate-limit", () => ({+ isRateLimited: isRateLimitedMock,+ RATE_LIMIT_IDS: { DOCS_ASK: "docs-ask" },+}));++vi.mock("@/utils/docs", () => ({+ getAllDocs: getAllDocsMock,+}));++vi.mock("@/lib/docs-ask", () => ({+ buildDocsAskContext: buildDocsAskContextMock,+ buildDocsAskSystemPrompt: buildDocsAskSystemPromptMock,+}));++const testUsage = {+ inputTokens: {+ total: 1,+ noCache: 1,+ cacheRead: undefined,+ cacheWrite: undefined,+ },+ outputTokens: {+ total: 1,+ text: 1,+ reasoning: undefined,+ },+};++const streamFromDeltas = (deltas: string[]) =>+ convertArrayToReadableStream([+ { type: "stream-start" as const, warnings: [] },+ { type: "text-start" as const, id: "1" },+ ...deltas.map((delta) => ({+ type: "text-delta" as const,+ id: "1",+ delta,+ })),+ { type: "text-end" as const, id: "1" },+ {+ type: "finish" as const,+ finishReason: { unified: "stop" as const, raw: undefined },+ usage: testUsage,+ },+ ]);++const makeSelection = (+ model: MockLanguageModelV4,+ overrides: Partial<AiModelSelection> = {},+): AiModelSelection => ({+ provider: "groq",+ modelId: "test-model",+ model: () => model,+ supportsStreaming: true,+ supportsTemperature: true,+ defaultMaxOutputTokens: 2000,+ ...overrides,+});++const makeRequest = (body: unknown) =>+ new Request("http://localhost/api/docs/ask", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ }) as unknown as NextRequest;++describe("docs ask route", () => {+ beforeEach(() => {+ isAiConfiguredMock.mockReturnValue(true);+ isRateLimitedMock.mockResolvedValue(false);+ getAllDocsMock.mockReturnValue([]);+ buildDocsAskContextMock.mockReturnValue({ context: "" });+ buildDocsAskSystemPromptMock.mockReturnValue("system prompt");+ vi.spyOn(console, "error").mockImplementation(() => {});+ });++ it("streams the model output as plain text", async () => {+ const model = new MockLanguageModelV4({+ doStream: { stream: streamFromDeltas(["Hello ", "world!"]) },+ });+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);++ const { POST } = await import("@/app/api/docs/ask/route");+ const response = await POST(+ makeRequest({ question: "How do I record my screen?" }),+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe(+ "text/plain; charset=utf-8",+ );+ expect(response.headers.get("cache-control")).toBe("no-store");+ await expect(response.text()).resolves.toBe("Hello world!");+ });++ it("falls through to the next provider when streaming setup fails", async () => {+ const failingModel = new MockLanguageModelV4({+ doStream: async () => {+ throw new Error("primary provider down");+ },+ });+ const workingModel = new MockLanguageModelV4({+ doStream: { stream: streamFromDeltas(["Hello ", "world!"]) },+ });+ getAiProviderChainMock.mockReturnValue([+ makeSelection(failingModel),+ makeSelection(workingModel, { provider: "openai" }),+ ]);++ const { POST } = await import("@/app/api/docs/ask/route");+ const response = await POST(+ makeRequest({ question: "How do I record my screen?" }),+ );++ expect(response.status).toBe(200);+ await expect(response.text()).resolves.toBe("Hello world!");+ });++ it("returns 503 when no AI provider is configured", async () => {+ isAiConfiguredMock.mockReturnValue(false);++ const { POST } = await import("@/app/api/docs/ask/route");+ const response = await POST(+ makeRequest({ question: "How do I record my screen?" }),+ );++ expect(response.status).toBe(503);+ await expect(response.json()).resolves.toEqual({+ error: "Ask AI is not available right now. Try searching instead.",+ });+ });++ it("returns 502 when every provider fails", async () => {+ const failingModel = new MockLanguageModelV4({+ doStream: async () => {+ throw new Error("provider down");+ },+ });+ getAiProviderChainMock.mockReturnValue([makeSelection(failingModel)]);++ const { POST } = await import("@/app/api/docs/ask/route");+ const response = await POST(+ makeRequest({ question: "How do I record my screen?" }),+ );++ expect(response.status).toBe(502);+ await expect(response.json()).resolves.toEqual({+ error: "Ask AI is having trouble right now. Try again shortly.",+ });+ });++ it("rejects questions that are too short", async () => {+ getAiProviderChainMock.mockReturnValue([]);++ const { POST } = await import("@/app/api/docs/ask/route");+ const response = await POST(makeRequest({ question: "hi" }));++ expect(response.status).toBe(400);+ });+});diff --git a/apps/web/__tests__/unit/generate-ai-start.test.ts b/apps/web/__tests__/unit/generate-ai-start.test.tsindex 323908e8f..da945bd12 100644--- a/apps/web/__tests__/unit/generate-ai-start.test.ts+++ b/apps/web/__tests__/unit/generate-ai-start.test.ts@@ -2,6 +2,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mockDb = vi.fn();const mockStart = vi.fn();+const serverEnvMock = vi.hoisted(() =>+ vi.fn<() => Record<string, string | undefined>>(() => ({+ GROQ_API_KEY: "test-key",+ })),+);vi.mock("@cap/database", () => ({db: mockDb,@@ -17,7 +22,7 @@ vi.mock("@cap/database/schema", () => ({}));vi.mock("@cap/env", () => ({- serverEnv: () => ({ GROQ_API_KEY: "test-key" }),+ serverEnv: serverEnvMock,}));vi.mock("drizzle-orm", () => ({@@ -70,10 +75,25 @@ const video = {beforeEach(() => {vi.clearAllMocks();+ serverEnvMock.mockReturnValue({ GROQ_API_KEY: "test-key" });mockStart.mockResolvedValue({ runId: "run-1" });});describe("startAiGeneration", () => {+ it("fails fast when no AI provider is configured", async () => {+ serverEnvMock.mockReturnValue({});++ const { startAiGeneration } = await import("@/lib/generate-ai");+ const result = await startAiGeneration("video-1" as never, "user-1");++ expect(result).toEqual({+ success: false,+ message: "No AI provider configured",+ });+ expect(mockDb).not.toHaveBeenCalled();+ expect(mockStart).not.toHaveBeenCalled();+ });+it("starts after atomically claiming the current video version", async () => {mockDb.mockReturnValueOnce(makeSelectChain(video))diff --git a/apps/web/__tests__/unit/generate-ai-title.test.ts b/apps/web/__tests__/unit/generate-ai-title.test.tsindex 7ebbbd04f..a34b826f2 100644--- a/apps/web/__tests__/unit/generate-ai-title.test.ts+++ b/apps/web/__tests__/unit/generate-ai-title.test.ts@@ -12,9 +12,12 @@ vi.mock("@cap/web-backend/src/Storage/index", () => ({Storage: {},}));-vi.mock("@/lib/groq-client", () => ({- GROQ_MODEL: "test-model",- getGroqClient: vi.fn(() => null),+vi.mock("@/lib/ai/provider", () => ({+ isAiConfigured: vi.fn(() => true),+}));++vi.mock("@/lib/ai/run", () => ({+ runWithAiProviders: vi.fn(),}));vi.mock("@/lib/workflow-runtime", () => ({diff --git a/apps/web/__tests__/unit/messenger-agent.test.ts b/apps/web/__tests__/unit/messenger-agent.test.tsindex 396fc00a6..46ef5c491 100644--- a/apps/web/__tests__/unit/messenger-agent.test.ts+++ b/apps/web/__tests__/unit/messenger-agent.test.ts@@ -1,34 +1,18 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--type ServerEnvMockValue = {- ANTHROPIC_API_KEY: string | undefined;- OPENAI_API_KEY: string | undefined;- GROQ_API_KEY: string | undefined;- SUPERMEMORY_API_KEY: string | undefined;- SUPERMEMORY_KNOWLEDGE_TAG: string | undefined;-};+import { MockLanguageModelV4 } from "ai/test";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AiModelSelection } from "@/lib/ai/provider";++type LanguageModelV4GenerateResult = Awaited<+ ReturnType<MockLanguageModelV4["doGenerate"]>+>;-const serverEnvMock = vi.hoisted(() =>- vi.fn<() => ServerEnvMockValue>(() => ({- ANTHROPIC_API_KEY: "anthropic-key",- OPENAI_API_KEY: undefined,- GROQ_API_KEY: undefined,- SUPERMEMORY_API_KEY: undefined,- SUPERMEMORY_KNOWLEDGE_TAG: undefined,- })),-);+const getAiProviderChainMock = vi.hoisted(() => vi.fn());const searchSupermemoryMock = vi.hoisted(() => vi.fn());-const getGroqClientMock = vi.hoisted(() => vi.fn());vi.mock("server-only", () => ({}));-vi.mock("@cap/env", () => ({- serverEnv: serverEnvMock,-}));--vi.mock("@/lib/groq-client", () => ({- GROQ_MODEL: "groq-model",- getGroqClient: getGroqClientMock,+vi.mock("@/lib/ai/provider", () => ({+ getAiProviderChain: getAiProviderChainMock,}));vi.mock("@/lib/messenger/supermemory", () => ({@@ -36,91 +20,90 @@ vi.mock("@/lib/messenger/supermemory", () => ({searchSupermemory: searchSupermemoryMock,}));-const readFetchBody = (call: unknown[]) => {- const init = call[1] as { body?: unknown };- if (typeof init.body !== "string") {- throw new Error("Expected fetch body");- }- return JSON.parse(init.body) as {- model?: string;- max_tokens?: number;- tool_choice?: string;- parallel_tool_calls?: boolean;- tools?: Array<{- name?: string;- input_schema?: {- properties?: Record<string, unknown>;- };- function?: {- name?: string;- parameters?: {- properties?: Record<string, unknown>;- };- };- }>;- messages?: Array<{- role?: string;- content?: unknown;- tool_calls?: unknown;- tool_call_id?: string;- }>;- };+const testUsage = {+ inputTokens: {+ total: 1,+ noCache: 1,+ cacheRead: undefined,+ cacheWrite: undefined,+ },+ outputTokens: {+ total: 1,+ text: 1,+ reasoning: undefined,+ },+};++const textResult = (text: string): LanguageModelV4GenerateResult => ({+ content: text ? [{ type: "text", text }] : [],+ finishReason: { unified: "stop", raw: undefined },+ usage: testUsage,+ warnings: [],+});++const toolCallPart = (input: Record<string, unknown>, id: string) => ({+ type: "tool-call" as const,+ toolCallId: id,+ toolName: "send_support_email",+ input: JSON.stringify(input),+});++const toolCallResult = (+ inputs: Record<string, unknown>[],+): LanguageModelV4GenerateResult => ({+ content: inputs.map((input, index) =>+ toolCallPart(input, `tool-${index + 1}`),+ ),+ finishReason: { unified: "tool-calls", raw: undefined },+ usage: testUsage,+ warnings: [],+});++const makeSelection = (+ model: MockLanguageModelV4,+ overrides: Partial<AiModelSelection> = {},+): AiModelSelection => ({+ provider: "groq",+ modelId: "test-model",+ model: () => model,+ supportsStreaming: true,+ supportsTemperature: true,+ defaultMaxOutputTokens: 512,+ providerOptions: { groq: { parallelToolCalls: false } },+ ...overrides,+});++const baseArgs = {+ userIdentity: "Test User <[email protected]>",+ identityTag: "user:user-123",+ query: "Please send this to support",+ history: [+ {+ role: "user" as const,+ content: "Uploads keep failing. Please send this to support.",+ },+ ],+};++const supportEmailInput = {+ subject: "Upload issue",+ message: "The user cannot upload their recording.",};describe("generateMessengerAgentReply", () => {beforeEach(() => {- vi.clearAllMocks();- serverEnvMock.mockReturnValue({- ANTHROPIC_API_KEY: "anthropic-key",- OPENAI_API_KEY: undefined,- GROQ_API_KEY: undefined,- SUPERMEMORY_API_KEY: undefined,- SUPERMEMORY_KNOWLEDGE_TAG: undefined,- });searchSupermemoryMock.mockResolvedValue([]);- getGroqClientMock.mockReturnValue(null);- });-- afterEach(() => {- vi.unstubAllGlobals();+ vi.spyOn(console, "error").mockImplementation(() => {});});- it("uses Sonnet 5 and executes the constrained support email tool", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- new Response(- JSON.stringify({- content: [- {- type: "tool_use",- id: "tool-1",- name: "send_support_email",- input: {- subject: "Upload issue",- message: "The user cannot upload their recording.",- email: "[email protected]",- },- },- ],- }),- { status: 200 },- ),- )- .mockResolvedValueOnce(- new Response(- JSON.stringify({- content: [- {- type: "text",- text: "Done, I sent that to the team from your account email.",- },- ],- }),- { status: 200 },- ),- );- vi.stubGlobal("fetch", fetchMock);+ it("executes the constrained support email tool and strips spoofed fields", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [+ toolCallResult([{ ...supportEmailInput, email: "[email protected]" }]),+ textResult("Done, I sent that to the team from your account email."),+ ],+ });+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);const execute = vi.fn().mockResolvedValue({status: "sent" as const,@@ -131,85 +114,51 @@ describe("generateMessengerAgentReply", () => {);const result = await generateMessengerAgentReply({- userIdentity: "Test User <[email protected]>",- identityTag: "user:user-123",- query: "Please send this to support",- history: [- {- role: "user",- content: "Uploads keep failing. Please send this to support.",- },- ],- supportEmailTool: {- execute,- },+ ...baseArgs,+ supportEmailTool: { execute },});expect(result).toBe("Done, I sent that to the team from your account email.",);- expect(fetchMock).toHaveBeenCalledTimes(2);- const firstBody = readFetchBody(fetchMock.mock.calls[0] ?? []);- expect(firstBody.model).toBe("claude-sonnet-5");- expect(firstBody.max_tokens).toBe(512);- expect(firstBody.tools?.[0]?.name).toBe("send_support_email");- expect(firstBody.tools?.[0]?.input_schema?.properties?.email).toBe(- undefined,- );- expect(execute).toHaveBeenCalledWith({- subject: "Upload issue",- message: "The user cannot upload their recording.",+ expect(execute).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledWith(supportEmailInput);++ expect(model.doGenerateCalls).toHaveLength(2);+ const firstCall = model.doGenerateCalls[0];+ expect(firstCall?.maxOutputTokens).toBe(512);+ expect(firstCall?.temperature).toBe(0.65);+ expect(firstCall?.providerOptions).toEqual({+ groq: { parallelToolCalls: false },});- const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);- expect(secondBody.max_tokens).toBe(350);- const toolResultMessage = secondBody.messages?.at(-1);- expect(toolResultMessage?.role).toBe("user");- expect(toolResultMessage?.content).toEqual([- {- type: "tool_result",- tool_use_id: "tool-1",- content:- "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",- },- ]);+ const toolDefinition = firstCall?.tools?.[0] as+ | {+ name?: string;+ inputSchema?: { properties?: Record<string, unknown> };+ }+ | undefined;+ expect(toolDefinition?.name).toBe("send_support_email");+ expect(toolDefinition?.inputSchema?.properties?.subject).toBeDefined();+ expect(toolDefinition?.inputSchema?.properties?.message).toBeDefined();+ expect(toolDefinition?.inputSchema?.properties?.email).toBeUndefined();++ expect(JSON.stringify(firstCall?.prompt)).toContain("Support email tool");+ expect(JSON.stringify(model.doGenerateCalls[1]?.prompt)).toContain(+ "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",+ );});- it("returns a tool error result when the support email tool fails", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- new Response(- JSON.stringify({- content: [- {- type: "tool_use",- id: "tool-1",- name: "send_support_email",- input: {- subject: "Upload issue",- message: "The user cannot upload their recording.",- },- },- ],- }),- { status: 200 },- ),- )- .mockResolvedValueOnce(- new Response(- JSON.stringify({- content: [- {- type: "text",- text: "I couldn't send that to the team right now. Please email [email protected] directly.",- },- ],- }),- { status: 200 },+ it("reports a tool error result when the support email tool fails", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [+ toolCallResult([supportEmailInput]),+ textResult(+ "I couldn't send that to the team right now. Please email [email protected] directly.",),- );- vi.stubGlobal("fetch", fetchMock);+ ],+ });+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);const execute = vi.fn().mockRejectedValue(new Error("provider failed"));const { generateMessengerAgentReply } = await import(@@ -217,91 +166,29 @@ describe("generateMessengerAgentReply", () => {);const result = await generateMessengerAgentReply({- userIdentity: "Test User <[email protected]>",- identityTag: "user:user-123",- query: "Please send this to support",- history: [- {- role: "user",- content: "Uploads keep failing. Please send this to support.",- },- ],- supportEmailTool: {- execute,- },+ ...baseArgs,+ supportEmailTool: { execute },});expect(result).toBe("I couldn't send that to the team right now. Please email [email protected] directly.",);-- const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);- const toolResultMessage = secondBody.messages?.at(-1);- expect(toolResultMessage?.content).toEqual([- {- type: "tool_result",- tool_use_id: "tool-1",- content: "Failed to send support email.",- is_error: true,- },- ]);+ expect(JSON.stringify(model.doGenerateCalls[1]?.prompt)).toContain(+ "Failed to send support email.",+ );});- it("executes the support email tool through OpenAI fallback", async () => {- serverEnvMock.mockReturnValue({- ANTHROPIC_API_KEY: undefined,- OPENAI_API_KEY: "openai-key",- GROQ_API_KEY: undefined,- SUPERMEMORY_API_KEY: undefined,- SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ it("sends at most one support email per assistant response", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [+ toolCallResult([+ supportEmailInput,+ { subject: "Second email", message: "Should be rejected." },+ ]),+ textResult("Done, I sent that to the team from your account email."),+ ],});- const toolCalls = [- {- id: "call-1",- type: "function",- function: {- name: "send_support_email",- arguments: JSON.stringify({- subject: "Upload issue",- message: "The user cannot upload their recording.",- email: "[email protected]",- }),- },- },- ];- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- new Response(- JSON.stringify({- choices: [- {- message: {- content: null,- tool_calls: toolCalls,- },- },- ],- }),- { status: 200 },- ),- )- .mockResolvedValueOnce(- new Response(- JSON.stringify({- choices: [- {- message: {- content:- "Done, I sent that to the team from your account email.",- },- },- ],- }),- { status: 200 },- ),- );- vi.stubGlobal("fetch", fetchMock);+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);const execute = vi.fn().mockResolvedValue({status: "sent" as const,@@ -312,103 +199,65 @@ describe("generateMessengerAgentReply", () => {);const result = await generateMessengerAgentReply({- userIdentity: "Test User <[email protected]>",- identityTag: "user:user-123",- query: "Please send this to support",- history: [- {- role: "user",- content: "Uploads keep failing. Please send this to support.",- },- ],- supportEmailTool: {- execute,- },+ ...baseArgs,+ supportEmailTool: { execute },});expect(result).toBe("Done, I sent that to the team from your account email.",);- expect(fetchMock).toHaveBeenCalledTimes(2);- const firstBody = readFetchBody(fetchMock.mock.calls[0] ?? []);- expect(firstBody.model).toBe("gpt-4o-mini");- expect(firstBody.max_tokens).toBe(512);- expect(firstBody.tool_choice).toBe("auto");- expect(firstBody.parallel_tool_calls).toBe(false);- expect(firstBody.tools?.[0]?.function?.name).toBe("send_support_email");- expect(firstBody.tools?.[0]?.function?.parameters?.properties?.email).toBe(- undefined,- );- expect(firstBody.messages?.[0]?.content).toContain("Support email tool");- expect(firstBody.messages?.[0]?.content).not.toContain(- "You cannot send support email",+ expect(execute).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledWith(supportEmailInput);+ expect(JSON.stringify(model.doGenerateCalls[1]?.prompt)).toContain(+ "Only one support email can be sent per assistant response.",);- expect(execute).toHaveBeenCalledWith({- subject: "Upload issue",- message: "The user cannot upload their recording.",- });+ });- const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);- expect(secondBody.max_tokens).toBe(350);- expect(secondBody.tools).toBeUndefined();- expect(secondBody.messages?.at(-2)?.role).toBe("assistant");- expect(secondBody.messages?.at(-2)?.tool_calls).toEqual(toolCalls);- expect(secondBody.messages?.at(-1)).toEqual({- role: "tool",- tool_call_id: "call-1",- content:- "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",+ it("falls back to the next provider in the chain when the first fails", async () => {+ const failingModel = new MockLanguageModelV4({+ doGenerate: async () => {+ throw new Error("primary provider down");+ },+ });+ const workingModel = new MockLanguageModelV4({+ doGenerate: [textResult("Hey there!")],});+ getAiProviderChainMock.mockReturnValue([+ makeSelection(failingModel, {+ provider: "anthropic",+ providerOptions: { anthropic: { disableParallelToolUse: true } },+ }),+ makeSelection(workingModel),+ ]);++ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply(baseArgs);++ expect(result).toBe("Hey there!");+ expect(workingModel.doGenerateCalls).toHaveLength(1);});- it("executes the support email tool through Groq fallback", async () => {- serverEnvMock.mockReturnValue({- ANTHROPIC_API_KEY: undefined,- OPENAI_API_KEY: undefined,- GROQ_API_KEY: "groq-key",- SUPERMEMORY_API_KEY: undefined,- SUPERMEMORY_KNOWLEDGE_TAG: undefined,- });- const create = vi- .fn()- .mockResolvedValueOnce({- choices: [- {- message: {- content: null,- tool_calls: [- {- id: "call-1",- type: "function",- function: {- name: "send_support_email",- arguments: JSON.stringify({- subject: "Upload issue",- message: "The user cannot upload their recording.",- }),- },- },- ],- },- },- ],- })- .mockResolvedValueOnce({- choices: [- {- message: {- content: "Done, I sent that to the team from your account email.",- },- },- ],- });- getGroqClientMock.mockReturnValue({- chat: {- completions: {- create,- },+ it("does not retry another provider after the support email was sent", async () => {+ let calls = 0;+ const failingAfterToolModel = new MockLanguageModelV4({+ doGenerate: async () => {+ calls += 1;+ if (calls > 1) {+ throw new Error("provider failed mid-turn");+ }+ return toolCallResult([supportEmailInput]);},});+ const secondaryModel = new MockLanguageModelV4({+ doGenerate: [textResult("Should never be used.")],+ });+ getAiProviderChainMock.mockReturnValue([+ makeSelection(failingAfterToolModel),+ makeSelection(secondaryModel, { provider: "openai" }),+ ]);const execute = vi.fn().mockResolvedValue({status: "sent" as const,@@ -419,131 +268,106 @@ describe("generateMessengerAgentReply", () => {);const result = await generateMessengerAgentReply({- userIdentity: "Test User <[email protected]>",- identityTag: "user:user-123",- query: "Please send this to support",- history: [- {- role: "user",- content: "Uploads keep failing. Please send this to support.",- },- ],- supportEmailTool: {- execute,- },+ ...baseArgs,+ supportEmailTool: { execute },});expect(result).toBe(- "Done, I sent that to the team from your account email.",+ "Done, I sent that to the team from your account email. We'll follow up with you there.",);- expect(create).toHaveBeenCalledTimes(2);- expect(create.mock.calls[0]?.[0]).toMatchObject({- model: "groq-model",- max_tokens: 512,- tool_choice: "auto",- parallel_tool_calls: false,- tools: [- {- type: "function",- function: {- name: "send_support_email",- },- },- ],+ expect(execute).toHaveBeenCalledTimes(1);+ expect(secondaryModel.doGenerateCalls).toHaveLength(0);+ });++ it("uses the rate limited fallback reply when the model gives no closing text", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [toolCallResult([supportEmailInput]), textResult("")],});- expect(create.mock.calls[1]?.[0]).toMatchObject({- max_tokens: 350,- messages: expect.arrayContaining([- {- role: "tool",- tool_call_id: "call-1",- content:- "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",- },- ]),+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);++ const execute = vi.fn().mockResolvedValue({+ status: "rate_limited" as const,+ remainingToday: 0 as const,});- expect(execute).toHaveBeenCalledWith({- subject: "Upload issue",- message: "The user cannot upload their recording.",+ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply({+ ...baseArgs,+ supportEmailTool: { execute },});++ expect(result).toBe(+ "I couldn't send another support email from your account today. You're limited to 2 per day, but you can still email [email protected] directly.",+ );});- it("does not retry another provider after a fallback provider sends support email", async () => {- serverEnvMock.mockReturnValue({- ANTHROPIC_API_KEY: undefined,- OPENAI_API_KEY: "openai-key",- GROQ_API_KEY: "groq-key",- SUPERMEMORY_API_KEY: undefined,- SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ it("returns the apology when every provider fails", async () => {+ const firstModel = new MockLanguageModelV4({+ doGenerate: async () => {+ throw new Error("first provider down");+ },});- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- new Response(- JSON.stringify({- choices: [- {- message: {- content: null,- tool_calls: [- {- id: "call-1",- type: "function",- function: {- name: "send_support_email",- arguments: JSON.stringify({- subject: "Upload issue",- message: "The user cannot upload their recording.",- }),- },- },- ],- },- },- ],- }),- { status: 200 },- ),- )- .mockResolvedValueOnce(new Response("provider failed", { status: 500 }));- vi.stubGlobal("fetch", fetchMock);-- const create = vi.fn();- getGroqClientMock.mockReturnValue({- chat: {- completions: {- create,- },+ const secondModel = new MockLanguageModelV4({+ doGenerate: async () => {+ throw new Error("second provider down");},});- const execute = vi.fn().mockResolvedValue({- status: "sent" as const,- remainingToday: 1,+ getAiProviderChainMock.mockReturnValue([+ makeSelection(firstModel),+ makeSelection(secondModel, { provider: "openai" }),+ ]);++ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply(baseArgs);++ expect(result).toBe(+ "Oh no, I'm so sorry about this! I'm having a little technical hiccup on my end. Someone from the team will jump in here shortly to help you out though!",+ );+ });++ it("uses 350 max output tokens and no tools without the support email tool", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [textResult("Happy to help!")],});+ getAiProviderChainMock.mockReturnValue([makeSelection(model)]);+const { generateMessengerAgentReply } = await import("@/lib/messenger/agent");- const result = await generateMessengerAgentReply({- userIdentity: "Test User <[email protected]>",- identityTag: "user:user-123",- query: "Please send this to support",- history: [- {- role: "user",- content: "Uploads keep failing. Please send this to support.",- },- ],- supportEmailTool: {- execute,- },+ const result = await generateMessengerAgentReply(baseArgs);++ expect(result).toBe("Happy to help!");+ const call = model.doGenerateCalls[0];+ expect(call?.maxOutputTokens).toBe(350);+ expect(call?.tools ?? []).toEqual([]);+ expect(JSON.stringify(call?.prompt)).toContain(+ "You cannot send support email",+ );+ });++ it("omits temperature for anthropic like the previous implementation", async () => {+ const model = new MockLanguageModelV4({+ doGenerate: [textResult("Hello!")],});+ getAiProviderChainMock.mockReturnValue([+ makeSelection(model, {+ provider: "anthropic",+ providerOptions: { anthropic: { disableParallelToolUse: true } },+ }),+ ]);- expect(result).toBe(- "Done, I sent that to the team from your account email. We'll follow up with you there.",+ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent");- expect(fetchMock).toHaveBeenCalledTimes(2);- expect(create).not.toHaveBeenCalled();- expect(execute).toHaveBeenCalledTimes(1);++ await generateMessengerAgentReply(baseArgs);++ expect(model.doGenerateCalls[0]?.temperature).toBeUndefined();});});diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.tsindex 7a4b62266..282ad7488 100644--- a/apps/web/actions/videos/get-status.ts+++ b/apps/web/actions/videos/get-status.ts@@ -8,6 +8,7 @@ import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";import { Policy, type Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import { Effect, Exit } from "effect";+import { isAiConfigured } from "@/lib/ai/provider";import {isRetryableDesktopSegmentsFinalizationError,queueDesktopSegmentsFinalization,@@ -156,7 +157,7 @@ export async function getVideoStatus(video.transcriptionStatus === "COMPLETE" &&!metadata.aiGenerationStatus &&!metadata.summary &&- (serverEnv().GROQ_API_KEY || serverEnv().OPENAI_API_KEY);+ isAiConfigured();if (shouldTriggerAiGeneration) {try {diff --git a/apps/web/actions/videos/translate-transcript.ts b/apps/web/actions/videos/translate-transcript.tsindex 0dfdfdaf3..012b6dcc3 100644--- a/apps/web/actions/videos/translate-transcript.ts+++ b/apps/web/actions/videos/translate-transcript.ts@@ -4,9 +4,11 @@ import { db } from "@cap/database";import { videos } from "@cap/database/schema";import { provideOptionalAuth, Storage, VideosPolicy } from "@cap/web-backend";import { Policy, type Video } from "@cap/web-domain";+import { generateText } from "ai";import { eq } from "drizzle-orm";import { Effect, Exit, Option } from "effect";-import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";+import { isAiConfigured } from "@/lib/ai/provider";+import { runWithAiProviders } from "@/lib/ai/run";import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";import * as EffectRuntime from "@/lib/server";import { runPromise } from "@/lib/server";@@ -40,8 +42,7 @@ export async function translateTranscript(};}- const groq = getGroqClient();- if (!groq) {+ if (!isAiConfigured()) {return {success: false,message: "Translation service not configured",@@ -109,7 +110,6 @@ export async function translateTranscript(const translatedVtt = await translateVttContent(originalVtt.value,targetLanguage,- groq,);if (!translatedVtt) {@@ -139,7 +139,6 @@ export async function translateTranscript(async function translateVttContent(vttContent: string,targetLanguage: LanguageCode,- groq: NonNullable<ReturnType<typeof getGroqClient>>,): Promise<string | null> {const targetLanguageName = SUPPORTED_LANGUAGES[targetLanguage];@@ -159,14 +158,16 @@ VTT content to translate:${vttContent}`;try {- const response = await groq.chat.completions.create({- model: GROQ_MODEL,- messages: [{ role: "user", content: prompt }],- temperature: 0.3,- max_tokens: 8000,- });-- const content = response.choices[0]?.message?.content;+ const response = await runWithAiProviders("generation", (selection) =>+ generateText({+ model: selection.model(),+ prompt,+ maxOutputTokens: 8000,+ ...(selection.supportsTemperature ? { temperature: 0.3 } : {}),+ }),+ );++ const content = response.text;if (content?.includes("WEBVTT")) {return content.trim();}diff --git a/apps/web/app/api/docs/ask/route.ts b/apps/web/app/api/docs/ask/route.tsindex e4f9d69f3..d632d87cb 100644--- a/apps/web/app/api/docs/ask/route.ts+++ b/apps/web/app/api/docs/ask/route.ts@@ -1,13 +1,13 @@-import { serverEnv } from "@cap/env";+import { streamText } from "ai";import type { NextRequest } from "next/server";+import { isAiConfigured } from "@/lib/ai/provider";+import { runWithAiProviders } from "@/lib/ai/run";import { buildDocsAskContext, buildDocsAskSystemPrompt } from "@/lib/docs-ask";import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";import { getAllDocs } from "@/utils/docs";export const dynamic = "force-dynamic";-const ASK_MODEL = "claude-sonnet-5";-const ASK_MAX_TOKENS = 800;const MAX_QUESTION_LENGTH = 500;const MAX_HISTORY_TURNS = 6;const MAX_HISTORY_CONTENT_LENGTH = 4000;@@ -56,28 +56,12 @@ function parseHistory(value: unknown): HistoryTurn[] {.slice(-MAX_HISTORY_TURNS * 2);}-function extractDeltaText(data: string): string | null {- try {- const event = JSON.parse(data) as {- type?: unknown;- delta?: { type?: unknown; text?: unknown };- };- if (- event.type === "content_block_delta" &&- event.delta?.type === "text_delta" &&- typeof event.delta.text === "string"- ) {- return event.delta.text;- }- } catch {- return null;- }- return null;+function toStreamError(error: unknown): Error {+ return error instanceof Error ? error : new Error(String(error));}export async function POST(request: NextRequest) {- const key = serverEnv().ANTHROPIC_API_KEY;- if (!key) {+ if (!isAiConfigured()) {return Response.json({ error: "Ask AI is not available right now. Try searching instead." },{ status: 503 },@@ -139,63 +123,78 @@ export async function POST(request: NextRequest) {context,});- const upstream = await fetch("https://api.anthropic.com/v1/messages", {- method: "POST",- headers: {- "x-api-key": key,- "anthropic-version": "2023-06-01",- "Content-Type": "application/json",- },- body: JSON.stringify({- model: ASK_MODEL,- max_tokens: ASK_MAX_TOKENS,- stream: true,+ const upstream = await runWithAiProviders("chat-streaming", (selection) => {+ const result = streamText({+ model: selection.model(),system,messages: [...history, { role: "user", content: trimmedQuestion }],- }),- signal: AbortSignal.timeout(60_000),+ maxOutputTokens: selection.defaultMaxOutputTokens,+ abortSignal: AbortSignal.timeout(60_000),+ });++ const reader = result.fullStream.getReader();+ const buffered: string[] = [];++ // Read ahead to the first text delta so provider setup failures fall+ // through to the next provider before any bytes reach the client.+ // Once streaming has started, mid-stream breaks behave as before.+ const readAhead = async () => {+ while (buffered.length === 0) {+ const { done, value } = await reader.read();+ if (done) break;+ if (value.type === "error") throw toStreamError(value.error);+ if (value.type === "abort")+ throw new Error(value.reason ?? "docs-ask stream aborted");+ if (value.type === "text-delta" && value.text)+ buffered.push(value.text);+ }+ if (buffered.length === 0) {+ // A completion with no visible text (eg. thinking consumed the+ // whole token budget) is a failure — let the chain try the next+ // provider rather than streaming an empty answer.+ throw new Error("docs-ask stream produced no text");+ }+ return { reader, buffered };+ };++ return readAhead();}).catch((error) => {- console.error("docs-ask upstream fetch failed", error);+ console.error("docs-ask upstream error", error);return null;});- if (!upstream || !upstream.ok || !upstream.body) {- const detail = upstream ? await upstream.text().catch(() => "") : "fetch";- console.error("docs-ask upstream error", upstream?.status, detail);+ if (!upstream) {return Response.json({ error: "Ask AI is having trouble right now. Try again shortly." },{ status: 502 },);}- const upstreamBody = upstream.body;const encoder = new TextEncoder();- const decoder = new TextDecoder();- let buffer = "";const stream = new ReadableStream<Uint8Array>({start(controller) {- const reader = upstreamBody.getReader();+ for (const text of upstream.buffered) {+ controller.enqueue(encoder.encode(text));+ }const pump = (): Promise<void> =>- reader.read().then(({ done, value }) => {+ upstream.reader.read().then(({ done, value }) => {if (done) {controller.close();return;}- buffer += decoder.decode(value, { stream: true });- const lines = buffer.split("\n");- buffer = lines.pop() ?? "";- for (const line of lines) {- if (!line.startsWith("data:")) continue;- const text = extractDeltaText(line.slice(5).trim());- if (text) controller.enqueue(encoder.encode(text));+ if (value.type === "error") throw toStreamError(value.error);+ if (value.type === "abort")+ throw new Error(value.reason ?? "docs-ask stream aborted");+ if (value.type === "text-delta" && value.text) {+ controller.enqueue(encoder.encode(value.text));}return pump();});return pump().catch((error) => controller.error(error));},cancel(reason) {- upstreamBody.cancel(reason).catch(() => undefined);+ upstream.reader.cancel(reason).catch(() => undefined);},});diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 954e55cfe..3c7251377 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -43,6 +43,7 @@ import {getDashboardData,type OrganizationSettings,} from "@/app/(org)/dashboard/dashboard-data";+import { isAiConfigured } from "@/lib/ai/provider";import { completeDesktopSegmentsManifestAndQueue } from "@/lib/desktop-segments-recovery";import { createNotification } from "@/lib/Notification";import {@@ -774,7 +775,7 @@ async function AuthorizedContent({!video.isScreenshot &&Boolean(env.ASSEMBLY_API_KEY) &&!rules.settings.disableTranscript;- const aiProviderAvailable = Boolean(env.GROQ_API_KEY || env.OPENAI_API_KEY);+ const aiProviderAvailable = isAiConfigured();if (transcriptionGenerationAvailable &&diff --git a/apps/web/lib/generate-ai.ts b/apps/web/lib/generate-ai.tsindex f4809c785..12ac36abf 100644--- a/apps/web/lib/generate-ai.ts+++ b/apps/web/lib/generate-ai.ts@@ -1,10 +1,10 @@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 { and, eq, sql } from "drizzle-orm";import { start } from "workflow/api";+import { isAiConfigured } from "@/lib/ai/provider";import { generateAiWorkflow } from "@/workflows/generate-ai";type GenerateAiResult = {@@ -29,10 +29,10 @@ export async function startAiGeneration(videoId: Video.VideoId,userId: string,): Promise<GenerateAiResult> {- if (!serverEnv().GROQ_API_KEY && !serverEnv().OPENAI_API_KEY) {+ if (!isAiConfigured()) {return {success: false,- message: "Missing AI API keys (Groq or OpenAI)",+ message: "No AI provider configured",};}diff --git a/apps/web/lib/groq-client.ts b/apps/web/lib/groq-client.tsdeleted file mode 100644index f22ee9c45..000000000--- a/apps/web/lib/groq-client.ts+++ /dev/null@@ -1,20 +0,0 @@-import { serverEnv } from "@cap/env";-import Groq from "groq-sdk";--let groqClient: Groq | null = null;--export function getGroqClient(): Groq | null {- if (!serverEnv().GROQ_API_KEY) {- return null;- }-- if (!groqClient) {- groqClient = new Groq({- apiKey: serverEnv().GROQ_API_KEY,- });- }-- return groqClient;-}--export const GROQ_MODEL = "openai/gpt-oss-120b";diff --git a/apps/web/lib/messenger/agent.ts b/apps/web/lib/messenger/agent.tsindex cac71fb5e..264267859 100644--- a/apps/web/lib/messenger/agent.ts+++ b/apps/web/lib/messenger/agent.ts@@ -1,14 +1,9 @@import "server-only";import type { MessengerMessageRole } from "@cap/database/schema";-import { serverEnv } from "@cap/env";-import type {- ChatCompletionAssistantMessageParam,- ChatCompletionMessageParam,- ChatCompletionMessageToolCall,- ChatCompletionTool,-} from "groq-sdk/resources/chat";-import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";+import { generateText, stepCountIs, tool } from "ai";+import { z } from "zod";+import { runWithAiProviders } from "@/lib/ai/run";import { CAP_REFERENCE_GUIDE, MESSENGER_AGENT_PROMPT } from "./constants";import { getKnowledgeTag, searchSupermemory } from "./supermemory";@@ -36,36 +31,17 @@ type SupportEmailTool = {execute: (input: SupportEmailToolInput) => Promise<SupportEmailToolResult>;};-type AnthropicTextBlock = {- type: "text";- text: string;-};--type AnthropicToolUseBlock = {- type: "tool_use";- id: string;- name: string;- input: unknown;-};--type AnthropicResponseBlock = AnthropicTextBlock | AnthropicToolUseBlock;--type AnthropicToolResultBlock = {- type: "tool_result";- tool_use_id: string;- content: string;- is_error?: boolean;-};-type SupportEmailExecutionResult = {content: string;isError?: boolean;};-const MESSENGER_ANTHROPIC_MODEL = "claude-sonnet-5";const MESSENGER_MAX_TOKENS = 350;const MESSENGER_TOOL_DISPATCH_MAX_TOKENS = 512;+const MESSENGER_APOLOGY_REPLY =+ "Oh no, I'm so sorry about this! I'm having a little technical hiccup on my end. Someone from the team will jump in here shortly to help you out though!";+const normalizeContext = (sections: string[]) =>sections.map((entry) => entry.trim())@@ -74,36 +50,20 @@ const normalizeContext = (sections: string[]) =>.join("\n\n").slice(0, 7000);-const supportEmailToolDefinition = {- name: "send_support_email",- description:- "Send a concise support email to the Cap team after the signed-in user explicitly asks or agrees. The server controls the recipient, sender, reply-to address, account email, conversation id, and rate limit.",- input_schema: {- type: "object",- properties: {- subject: {- type: "string",- description: "A concise support email subject.",- },- message: {- type: "string",- description:- "A concise support email body summarizing the user's issue and relevant context from the chat.",- },- },- required: ["subject", "message"],- additionalProperties: false,- },-} as const;+// zod strips unknown keys (like a spoofed `email`) before `execute` runs;+// the server alone controls sender, recipient, and reply-to.+const supportEmailInputSchema = z.object({+ subject: z.string().describe("A concise support email subject."),+ message: z+ .string()+ .describe(+ "A concise support email body summarizing the user's issue and relevant context from the chat.",+ ),+});-const openAiCompatibleSupportEmailToolDefinition = {- type: "function",- function: {- name: supportEmailToolDefinition.name,- description: supportEmailToolDefinition.description,- parameters: supportEmailToolDefinition.input_schema,- },-} satisfies ChatCompletionTool;+const SUPPORT_EMAIL_TOOL_NAME = "send_support_email";+const SUPPORT_EMAIL_TOOL_DESCRIPTION =+ "Send a concise support email to the Cap team after the signed-in user explicitly asks or agrees. The server controls the recipient, sender, reply-to address, account email, conversation id, and rate limit.";const buildSystemPrompt = ({userIdentity,@@ -157,46 +117,6 @@ const mapHistoryForLlm = (history: ConversationMessage[]) =>content: message.content.slice(0, 6000),}));-const parseAnthropicMessage = (payload: unknown) => {- if (!payload || typeof payload !== "object") return null;- const content = (payload as { content?: unknown }).content;- if (!Array.isArray(content)) return null;-- const blocks = content.flatMap((block): AnthropicResponseBlock[] => {- if (!block || typeof block !== "object") return [];- const type = (block as { type?: unknown }).type;- if (type === "text") {- const text = (block as { text?: unknown }).text;- return typeof text === "string" ? [{ type, text }] : [];- }- if (type === "tool_use") {- const id = (block as { id?: unknown }).id;- const name = (block as { name?: unknown }).name;- if (typeof id !== "string" || typeof name !== "string") return [];- return [- {- type,- id,- name,- input: (block as { input?: unknown }).input,- },- ];- }- return [];- });- if (!blocks.length) return null;-- const text = blocks- .map((block) => (block.type === "text" ? block.text : ""))- .join("\n")- .trim();-- return {- content: blocks,- text: text.length > 0 ? text : null,- };-};-const readToolString = (input: unknown, key: keyof SupportEmailToolInput) => {if (!input || typeof input !== "object") return null;const value = (input as Record<string, unknown>)[key];@@ -236,21 +156,12 @@ const fallbackReplyFromSupportEmailToolResults = (};const executeSupportEmailTool = async ({- name,input,supportEmailTool,}: {- name: string;input: unknown;supportEmailTool: SupportEmailTool;}): Promise<SupportEmailExecutionResult> => {- if (name !== supportEmailToolDefinition.name) {- return {- content: "Unknown tool.",- isError: true,- };- }-const parsedInput = readSupportEmailInput(input);if (!parsedInput) {return {@@ -272,385 +183,6 @@ const executeSupportEmailTool = async ({}};-const executeSupportEmailToolUse = async ({- toolUse,- supportEmailTool,-}: {- toolUse: AnthropicToolUseBlock;- supportEmailTool: SupportEmailTool;-}): Promise<AnthropicToolResultBlock> => {- const result = await executeSupportEmailTool({- name: toolUse.name,- input: toolUse.input,- supportEmailTool,- });- return {- type: "tool_result",- tool_use_id: toolUse.id,- content: result.content,- ...(result.isError ? { is_error: true } : {}),- };-};--const postAnthropicMessages = async ({- key,- systemPrompt,- messages,- tools,- maxTokens = MESSENGER_MAX_TOKENS,-}: {- key: string;- systemPrompt: string;- messages: Array<{- role: "user" | "assistant";- content: string | AnthropicResponseBlock[] | AnthropicToolResultBlock[];- }>;- tools?: [typeof supportEmailToolDefinition];- maxTokens?: number;-}) => {- const response = await fetch("https://api.anthropic.com/v1/messages", {- method: "POST",- headers: {- "x-api-key": key,- "anthropic-version": "2023-06-01",- "Content-Type": "application/json",- },- body: JSON.stringify({- model: MESSENGER_ANTHROPIC_MODEL,- max_tokens: maxTokens,- system: systemPrompt,- messages,- tools,- }),- signal: AbortSignal.timeout(35000),- });-- if (!response.ok) {- const text = await response.text();- throw new Error(`Anthropic chat failed: ${response.status} ${text}`);- }-- const payload = await response.json();- return parseAnthropicMessage(payload);-};--const callAnthropic = async ({- systemPrompt,- history,- supportEmailTool,-}: {- systemPrompt: string;- history: ConversationMessage[];- supportEmailTool: SupportEmailTool | null;-}) => {- const key = serverEnv().ANTHROPIC_API_KEY;- if (!key) return null;-- const initial = await postAnthropicMessages({- key,- systemPrompt,- messages: mapHistoryForLlm(history),- tools: supportEmailTool ? [supportEmailToolDefinition] : undefined,- maxTokens: supportEmailTool- ? MESSENGER_TOOL_DISPATCH_MAX_TOKENS- : MESSENGER_MAX_TOKENS,- });-- if (!initial) return null;- const toolUses = supportEmailTool- ? initial.content.filter(- (block): block is AnthropicToolUseBlock => block.type === "tool_use",- )- : [];-- if (!supportEmailTool || toolUses.length === 0) {- return initial.text;- }-- const toolResults: AnthropicToolResultBlock[] = [];- let sentEmailToolResult = false;- for (const toolUse of toolUses) {- if (sentEmailToolResult) {- toolResults.push({- type: "tool_result",- tool_use_id: toolUse.id,- content: "Only one support email can be sent per assistant response.",- is_error: true,- });- continue;- }- toolResults.push(- await executeSupportEmailToolUse({ toolUse, supportEmailTool }),- );- sentEmailToolResult = true;- }-- const final = await postAnthropicMessages({- key,- systemPrompt,- messages: [- ...mapHistoryForLlm(history),- {- role: "assistant",- content: initial.content,- },- {- role: "user",- content: toolResults,- },- ],- }).catch(() => null);-- if (final?.text) return final.text;- return fallbackReplyFromSupportEmailToolResults(- toolResults.map((result) => ({- content: result.content,- isError: result.is_error,- })),- );-};--const parseOpenAiCompatibleToolCalls = (message: { tool_calls?: unknown }) => {- if (!Array.isArray(message.tool_calls)) return [];-- return message.tool_calls.flatMap(- (toolCall): ChatCompletionMessageToolCall[] => {- if (!toolCall || typeof toolCall !== "object") return [];- const id = (toolCall as { id?: unknown }).id;- const type = (toolCall as { type?: unknown }).type;- const fn = (toolCall as { function?: unknown }).function;- if (typeof id !== "string" || type !== "function") return [];- if (!fn || typeof fn !== "object") return [];- const name = (fn as { name?: unknown }).name;- const args = (fn as { arguments?: unknown }).arguments;- if (typeof name !== "string" || typeof args !== "string") return [];- return [- {- id,- type,- function: {- name,- arguments: args,- },- },- ];- },- );-};--const parseOpenAiCompatibleMessage = (payload: unknown) => {- if (!payload || typeof payload !== "object") return null;- const choices = (payload as { choices?: unknown }).choices;- if (!Array.isArray(choices) || choices.length === 0) return null;- const first = choices[0] as {- message?: {- content?: unknown;- tool_calls?: unknown;- };- };- const message = first.message;- if (!message) return null;- const content =- typeof message.content === "string" ? message.content.trim() : "";- const toolCalls = parseOpenAiCompatibleToolCalls(message);- if (!content && toolCalls.length === 0) return null;- return {- text: content.length > 0 ? content : null,- toolCalls,- };-};--const parseOpenAiToolInput = (args: string) => {- try {- return JSON.parse(args) as unknown;- } catch {- return null;- }-};--const executeOpenAiCompatibleToolCalls = async ({- toolCalls,- supportEmailTool,-}: {- toolCalls: ChatCompletionMessageToolCall[];- supportEmailTool: SupportEmailTool;-}) => {- const toolResults: Array<- SupportEmailExecutionResult & { toolCall: ChatCompletionMessageToolCall }- > = [];- let sentEmailToolResult = false;-- for (const toolCall of toolCalls) {- if (sentEmailToolResult) {- toolResults.push({- toolCall,- content: "Only one support email can be sent per assistant response.",- isError: true,- });- continue;- }-- toolResults.push({- toolCall,- ...(await executeSupportEmailTool({- name: toolCall.function.name,- input: parseOpenAiToolInput(toolCall.function.arguments),- supportEmailTool,- })),- });- sentEmailToolResult = true;- }-- return toolResults;-};--const runOpenAiCompatibleToolLoop = async ({- systemPrompt,- history,- supportEmailTool,- createCompletion,-}: {- systemPrompt: string;- history: ConversationMessage[];- supportEmailTool: SupportEmailTool | null;- createCompletion: ({- messages,- tools,- maxTokens,- }: {- messages: ChatCompletionMessageParam[];- tools?: ChatCompletionTool[];- maxTokens: number;- }) => Promise<ReturnType<typeof parseOpenAiCompatibleMessage>>;-}) => {- const messages: ChatCompletionMessageParam[] = [- { role: "system", content: systemPrompt },- ...mapHistoryForLlm(history),- ];-- const initial = await createCompletion({- messages,- tools: supportEmailTool- ? [openAiCompatibleSupportEmailToolDefinition]- : undefined,- maxTokens: supportEmailTool- ? MESSENGER_TOOL_DISPATCH_MAX_TOKENS- : MESSENGER_MAX_TOKENS,- });-- if (!initial) return null;- if (!supportEmailTool || initial.toolCalls.length === 0) {- return initial.text;- }-- const toolResults = await executeOpenAiCompatibleToolCalls({- toolCalls: initial.toolCalls,- supportEmailTool,- });- const assistantMessage: ChatCompletionAssistantMessageParam = {- role: "assistant",- content: initial.text,- tool_calls: initial.toolCalls,- };- const final = await createCompletion({- messages: [- ...messages,- assistantMessage,- ...toolResults.map(- (result): ChatCompletionMessageParam => ({- role: "tool",- tool_call_id: result.toolCall.id,- content: result.content,- }),- ),- ],- maxTokens: MESSENGER_MAX_TOKENS,- }).catch(() => null);-- if (final?.text) return final.text;- return fallbackReplyFromSupportEmailToolResults(toolResults);-};--const callOpenAi = async ({- systemPrompt,- history,- supportEmailTool,-}: {- systemPrompt: string;- history: ConversationMessage[];- supportEmailTool: SupportEmailTool | null;-}) => {- const key = serverEnv().OPENAI_API_KEY;- if (!key) return null;-- return runOpenAiCompatibleToolLoop({- systemPrompt,- history,- supportEmailTool,- createCompletion: async ({ messages, tools, maxTokens }) => {- const response = await fetch(- "https://api.openai.com/v1/chat/completions",- {- method: "POST",- headers: {- Authorization: `Bearer ${key}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- model: "gpt-4o-mini",- temperature: 0.65,- max_tokens: maxTokens,- messages,- tools,- tool_choice: tools ? "auto" : undefined,- parallel_tool_calls: tools ? false : undefined,- }),- signal: AbortSignal.timeout(35000),- },- );-- if (!response.ok) {- const text = await response.text();- throw new Error(`OpenAI chat failed: ${response.status} ${text}`);- }-- const payload = await response.json();- return parseOpenAiCompatibleMessage(payload);- },- });-};--const callGroq = async ({- systemPrompt,- history,- supportEmailTool,-}: {- systemPrompt: string;- history: ConversationMessage[];- supportEmailTool: SupportEmailTool | null;-}) => {- const client = getGroqClient();- if (!client) return null;-- return runOpenAiCompatibleToolLoop({- systemPrompt,- history,- supportEmailTool,- createCompletion: async ({ messages, tools, maxTokens }) => {- const completion = await client.chat.completions.create({- model: GROQ_MODEL,- temperature: 0.65,- max_tokens: maxTokens,- messages,- tools,- tool_choice: tools ? "auto" : undefined,- parallel_tool_calls: tools ? false : undefined,- });- return parseOpenAiCompatibleMessage(completion);- },- });-};-export const generateMessengerAgentReply = async ({userIdentity,identityTag,@@ -681,26 +213,86 @@ export const generateMessengerAgentReply = async ({supportEmailAvailable: Boolean(supportEmailTool),});- const fromAnthropic = await callAnthropic({- systemPrompt,- history,- supportEmailTool,- }).catch(() => null);- if (fromAnthropic) return fromAnthropic;-- const fromOpenAi = await callOpenAi({- systemPrompt,- history,- supportEmailTool,- }).catch(() => null);- if (fromOpenAi) return fromOpenAi;-- const fromGroq = await callGroq({- systemPrompt,- history,- supportEmailTool,- }).catch(() => null);- if (fromGroq) return fromGroq;+ // Shared across providers on purpose: once a support email attempt has+ // happened, no other provider may retry the turn (`stopOnError` below).+ const state: {+ sent: boolean;+ toolResults: SupportEmailExecutionResult[];+ } = { sent: false, toolResults: [] };++ const tools = supportEmailTool+ ? {+ [SUPPORT_EMAIL_TOOL_NAME]: tool({+ description: SUPPORT_EMAIL_TOOL_DESCRIPTION,+ inputSchema: supportEmailInputSchema,+ execute: async (input) => {+ // In-execute latch: providers without a parallel-tool-call+ // switch (eg. the AssemblyAI gateway) can emit several tool+ // calls in one step; only the first may send an email.+ if (state.sent) {+ const result: SupportEmailExecutionResult = {+ content:+ "Only one support email can be sent per assistant response.",+ isError: true,+ };+ state.toolResults.push(result);+ return result.content;+ }+ state.sent = true;++ const result = await executeSupportEmailTool({+ input,+ supportEmailTool,+ });+ state.toolResults.push(result);+ return result.content;+ },+ }),+ }+ : undefined;- return "Oh no, I'm so sorry about this! I'm having a little technical hiccup on my end. Someone from the team will jump in here shortly to help you out though!";+ try {+ return await runWithAiProviders(+ "chat",+ async (selection) => {+ const result = await generateText({+ model: selection.model(),+ system: systemPrompt,+ messages: mapHistoryForLlm(history),+ maxOutputTokens: supportEmailTool+ ? MESSENGER_TOOL_DISPATCH_MAX_TOKENS+ : MESSENGER_MAX_TOKENS,+ // Parity with the previous per-provider implementations: the+ // raw Anthropic calls never sent temperature.+ ...(selection.supportsTemperature &&+ selection.provider !== "anthropic"+ ? { temperature: 0.65 }+ : {}),+ abortSignal: AbortSignal.timeout(35000),+ ...(tools+ ? {+ tools,+ stopWhen: stepCountIs(2),+ ...(selection.providerOptions+ ? { providerOptions: selection.providerOptions }+ : {}),+ }+ : {}),+ });++ const text = result.text.trim();+ if (text) return text;+ if (state.toolResults.length > 0) {+ return fallbackReplyFromSupportEmailToolResults(state.toolResults);+ }+ throw new Error("Messenger agent returned an empty reply");+ },+ { stopOnError: () => state.sent },+ );+ } catch {+ if (state.toolResults.length > 0) {+ return fallbackReplyFromSupportEmailToolResults(state.toolResults);+ }+ return MESSENGER_APOLOGY_REPLY;+ }};diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.tsindex 0e23f2b7f..bb2f048e0 100644--- a/apps/web/workflows/generate-ai.ts+++ b/apps/web/workflows/generate-ai.ts@@ -1,7 +1,6 @@import { db } from "@cap/database";import { organizations, videos } from "@cap/database/schema";import type { VideoMetadata } from "@cap/database/types";-import { serverEnv } from "@cap/env";import { Storage } from "@cap/web-backend/src/Storage/index";import {AI_GENERATION_LANGUAGE_AUTO,@@ -10,10 +9,12 @@ import {parseAiGenerationLanguage,type Video,} from "@cap/web-domain";+import { generateText } from "ai";import { and, eq, sql } from "drizzle-orm";import { Effect, Option } from "effect";import { FatalError } from "workflow";-import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";+import { isAiConfigured } from "@/lib/ai/provider";+import { runWithAiProviders } from "@/lib/ai/run";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -117,9 +118,8 @@ export async function generateAiWorkflow(payload: GenerateAiWorkflowPayload) {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");+ if (!isAiConfigured()) {+ throw new FatalError("No AI provider configured");}const query = await db()@@ -250,7 +250,6 @@ async function generateWithAi(): Promise<AiResult> {"use step";- const groqClient = getGroqClient();const chunks = chunkTranscriptWithTimestamps(transcript.segments);const videoDuration = getVideoDuration(transcript.segments);@@ -261,14 +260,12 @@ async function generateWithAi(result = await generateSingleChunk(transcript.segments,videoDuration,- groqClient,languageInstruction,);} else {result = await generateMultipleChunks(chunks,videoDuration,- groqClient,languageInstruction,);}@@ -493,49 +490,15 @@ function chunkTranscriptWithTimestamps(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,- response_format: { type: "json_object" },- });- 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 }],- response_format: { type: "json_object" },+async function callAiApi(prompt: string): Promise<string> {+ const result = await runWithAiProviders("generation", (selection) =>+ generateText({+ model: selection.model({ jsonRepair: true }),+ prompt,+ maxOutputTokens: selection.defaultMaxOutputTokens,}),- });- 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 result.text;}function cleanJsonResponse(content: string): string {@@ -589,7 +552,6 @@ function extractJsonObject(content: string): string {async function generateSingleChunk(segments: VttSegment[],videoDuration: number,- groqClient: ReturnType<typeof getGroqClient>,languageInstruction: string,): Promise<AiResult> {const transcriptWithTimestamps = segments@@ -625,14 +587,13 @@ Return ONLY valid JSON without any markdown formatting or code blocks.Transcript:${transcriptWithTimestamps}`;- const content = await callAiApi(prompt, groqClient);+ const content = await callAiApi(prompt);return parseAiResponse(content);}async function generateMultipleChunks(chunks: { text: string; startTime: number; endTime: number }[],videoDuration: number,- groqClient: ReturnType<typeof getGroqClient>,languageInstruction: string,): Promise<AiResult> {const chunkSummaries: {@@ -668,9 +629,9 @@ Return ONLY valid JSON without any markdown formatting or code blocks.Transcript section:${chunk.text}`;- const chunkContent = await callAiApi(chunkPrompt, groqClient);+ const chunkContent = await callAiApi(chunkPrompt);try {- const parsed = JSON.parse(cleanJsonResponse(chunkContent).trim());+ const parsed = JSON.parse(extractJsonObject(chunkContent));chunkSummaries.push({summary: parsed.summary || "",keyPoints: parsed.keyPoints || [],@@ -727,9 +688,9 @@ 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, groqClient);+ const finalContent = await callAiApi(finalPrompt);try {- const parsed = JSON.parse(cleanJsonResponse(finalContent).trim());+ const parsed = JSON.parse(extractJsonObject(finalContent));return {title: parsed.title,summary: parsed.summary,