Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(settings): add OpenAI, Gemini, Azure OpenAI and OpenRouter keys for Chat (#1210)
Cihanb2ff68f53900
diff --git a/supabase/migrations/00188_organization_ai_keys.sql b/supabase/migrations/00188_organization_ai_keys.sqlnew file mode 100644index 000000000..b90c0a8d4--- /dev/null+++ b/supabase/migrations/00188_organization_ai_keys.sql@@ -0,0 +1,137 @@+-- AI Providers (Settings): an organization's own keys for Chat, one per+-- provider — Anthropic, OpenAI, Google Gemini, Microsoft Azure OpenAI and+-- OpenRouter — and which one Chat uses (`active`, at most one per org).+--+-- Each key is the AES-256-GCM envelope from web/src/lib/agent/key-encryption.ts,+-- as the Anthropic key on `organizations` was (00010); `last4` is display-only.+-- `settings` holds what a provider needs besides the key: Azure's endpoint+-- and deployment, OpenRouter's model.+--+-- RLS on with no policies: only the service role reads and writes it (the web+-- app's /api/settings/ai-providers route and Chat).++create table public.organization_ai_keys (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ provider text not null+ check (provider in ('anthropic', 'openai', 'google', 'azure', 'openrouter')),+ key_encrypted text not null,+ key_last4 text not null,+ settings jsonb not null default '{}'::jsonb,+ active boolean not null default false,+ set_at timestamptz not null default now(),+ set_by uuid references public.profiles(id) on delete set null,+ primary key (organization_id, provider)+);++create unique index organization_ai_keys_one_active+ on public.organization_ai_keys (organization_id)+ where active;++alter table public.organization_ai_keys enable row level security;++comment on table public.organization_ai_keys is+ 'Organization-level AI provider keys for Chat (BYOK, cloud). Service role only.';+comment on column public.organization_ai_keys.active is+ 'The provider Chat uses; at most one per organization.';++-- Existing Anthropic keys carry over as the provider Chat uses. The old+-- organizations.anthropic_api_key_* columns stay until a later migration.+insert into public.organization_ai_keys+ (organization_id, provider, key_encrypted, key_last4, active, set_at, set_by)+select id, 'anthropic', anthropic_api_key_encrypted, coalesce(anthropic_api_key_last4, ''),+ true, coalesce(anthropic_api_key_set_at, now()), anthropic_api_key_set_by+from public.organizations+where anthropic_api_key_encrypted is not null+on conflict (organization_id, provider) do nothing;++-- Makes one saved provider the one Chat uses; with p_only_if_none, only when+-- none is yet (a first key saved). The organization's rows are locked first,+-- so two switches at once queue rather than both setting `active` and one+-- failing the unique index. Others off first: that index is checked row by+-- row. False when the organization has no key for that provider.+create or replace function public.set_active_ai_provider(+ p_organization_id uuid,+ p_provider text,+ p_only_if_none boolean default false+) returns boolean+language plpgsql+set search_path = public+as $$+begin+ perform 1 from organization_ai_keys+ where organization_id = p_organization_id+ for update;++ if not exists (+ select 1 from organization_ai_keys+ where organization_id = p_organization_id and provider = p_provider+ ) then+ return false;+ end if;+ if p_only_if_none and exists (+ select 1 from organization_ai_keys+ where organization_id = p_organization_id and active+ ) then+ return true;+ end if;+ update organization_ai_keys set active = false+ where organization_id = p_organization_id and active and provider <> p_provider;+ update organization_ai_keys set active = true+ where organization_id = p_organization_id and provider = p_provider and not active;+ return true;+end;+$$;++revoke execute on function public.set_active_ai_provider(uuid, text, boolean)+ from public, anon, authenticated;+grant execute on function public.set_active_ai_provider(uuid, text, boolean)+ to service_role;++-- Removes a provider's key. When it was the one Chat used, the most recently+-- saved other key takes over, in the same transaction and under the same+-- lock as a switch. Returns the provider Chat uses afterwards, or null.+create or replace function public.remove_ai_provider_key(+ p_organization_id uuid,+ p_provider text+) returns text+language plpgsql+set search_path = public+as $$+declare+ v_was_active boolean;+ v_next text;+begin+ perform 1 from organization_ai_keys+ where organization_id = p_organization_id+ for update;++ delete from organization_ai_keys+ where organization_id = p_organization_id and provider = p_provider+ returning active into v_was_active;++ if coalesce(v_was_active, false) then+ select provider into v_next+ from organization_ai_keys+ where organization_id = p_organization_id+ order by set_at desc+ limit 1;+ if v_next is not null then+ update organization_ai_keys set active = true+ where organization_id = p_organization_id and provider = v_next;+ end if;+ return v_next;+ end if;++ select provider into v_next+ from organization_ai_keys+ where organization_id = p_organization_id and active;+ return v_next;+end;+$$;++revoke execute on function public.remove_ai_provider_key(uuid, text)+ from public, anon, authenticated;+grant execute on function public.remove_ai_provider_key(uuid, text)+ to service_role;++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 15637edac..f46a48f91 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -26786,6 +26786,147 @@ create policy "ai_traffic_digests: member select" on public.ai_traffic_digestscomment on table public.ai_traffic_digests is'AI Traffic weekly digests sent (AT-013): one per brand and week, claimed before sending so a week is never mailed twice.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00188_organization_ai_keys.sql+-- ─────────────────────────────────────────────────────────────────────────+-- AI Providers (Settings): an organization's own keys for Chat, one per+-- provider — Anthropic, OpenAI, Google Gemini, Microsoft Azure OpenAI and+-- OpenRouter — and which one Chat uses (`active`, at most one per org).+--+-- Each key is the AES-256-GCM envelope from web/src/lib/agent/key-encryption.ts,+-- as the Anthropic key on `organizations` was (00010); `last4` is display-only.+-- `settings` holds what a provider needs besides the key: Azure's endpoint+-- and deployment, OpenRouter's model.+--+-- RLS on with no policies: only the service role reads and writes it (the web+-- app's /api/settings/ai-providers route and Chat).++create table public.organization_ai_keys (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ provider text not null+ check (provider in ('anthropic', 'openai', 'google', 'azure', 'openrouter')),+ key_encrypted text not null,+ key_last4 text not null,+ settings jsonb not null default '{}'::jsonb,+ active boolean not null default false,+ set_at timestamptz not null default now(),+ set_by uuid references public.profiles(id) on delete set null,+ primary key (organization_id, provider)+);++create unique index organization_ai_keys_one_active+ on public.organization_ai_keys (organization_id)+ where active;++alter table public.organization_ai_keys enable row level security;++comment on table public.organization_ai_keys is+ 'Organization-level AI provider keys for Chat (BYOK, cloud). Service role only.';+comment on column public.organization_ai_keys.active is+ 'The provider Chat uses; at most one per organization.';++-- Existing Anthropic keys carry over as the provider Chat uses. The old+-- organizations.anthropic_api_key_* columns stay until a later migration.+insert into public.organization_ai_keys+ (organization_id, provider, key_encrypted, key_last4, active, set_at, set_by)+select id, 'anthropic', anthropic_api_key_encrypted, coalesce(anthropic_api_key_last4, ''),+ true, coalesce(anthropic_api_key_set_at, now()), anthropic_api_key_set_by+from public.organizations+where anthropic_api_key_encrypted is not null+on conflict (organization_id, provider) do nothing;++-- Makes one saved provider the one Chat uses; with p_only_if_none, only when+-- none is yet (a first key saved). The organization's rows are locked first,+-- so two switches at once queue rather than both setting `active` and one+-- failing the unique index. Others off first: that index is checked row by+-- row. False when the organization has no key for that provider.+create or replace function public.set_active_ai_provider(+ p_organization_id uuid,+ p_provider text,+ p_only_if_none boolean default false+) returns boolean+language plpgsql+set search_path = public+as $$+begin+ perform 1 from organization_ai_keys+ where organization_id = p_organization_id+ for update;++ if not exists (+ select 1 from organization_ai_keys+ where organization_id = p_organization_id and provider = p_provider+ ) then+ return false;+ end if;+ if p_only_if_none and exists (+ select 1 from organization_ai_keys+ where organization_id = p_organization_id and active+ ) then+ return true;+ end if;+ update organization_ai_keys set active = false+ where organization_id = p_organization_id and active and provider <> p_provider;+ update organization_ai_keys set active = true+ where organization_id = p_organization_id and provider = p_provider and not active;+ return true;+end;+$$;++revoke execute on function public.set_active_ai_provider(uuid, text, boolean)+ from public, anon, authenticated;+grant execute on function public.set_active_ai_provider(uuid, text, boolean)+ to service_role;++-- Removes a provider's key. When it was the one Chat used, the most recently+-- saved other key takes over, in the same transaction and under the same+-- lock as a switch. Returns the provider Chat uses afterwards, or null.+create or replace function public.remove_ai_provider_key(+ p_organization_id uuid,+ p_provider text+) returns text+language plpgsql+set search_path = public+as $$+declare+ v_was_active boolean;+ v_next text;+begin+ perform 1 from organization_ai_keys+ where organization_id = p_organization_id+ for update;++ delete from organization_ai_keys+ where organization_id = p_organization_id and provider = p_provider+ returning active into v_was_active;++ if coalesce(v_was_active, false) then+ select provider into v_next+ from organization_ai_keys+ where organization_id = p_organization_id+ order by set_at desc+ limit 1;+ if v_next is not null then+ update organization_ai_keys set active = true+ where organization_id = p_organization_id and provider = v_next;+ end if;+ return v_next;+ end if;++ select provider into v_next+ from organization_ai_keys+ where organization_id = p_organization_id and active;+ return v_next;+end;+$$;++revoke execute on function public.remove_ai_provider_key(uuid, text)+ from public, anon, authenticated;+grant execute on function public.remove_ai_provider_key(uuid, text)+ to service_role;++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00189_ai_bot_ingest_file.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/.env.example b/web/.env.exampleindex 55e182ac1..1297175c6 100644--- a/web/.env.example+++ b/web/.env.example@@ -20,8 +20,8 @@ ANTHROPIC_API_KEY=sk-ant-...# -----------------------------------------------------------------------------# Agent (in-product BYOK)# ------------------------------------------------------------------------------# Cloud customers paste their own Anthropic key in Settings → Agent. We-# encrypt it at rest with AES-256-GCM; this is the master key. Must be a+# Cloud customers paste their own AI provider keys in Settings › AI+# Providers. We encrypt them at rest with AES-256-GCM; this is the master key. Must be a# 32-byte (256-bit) value, base64-encoded.# Generate one: `openssl rand -base64 32`# Self-host instances can skip this — they use ANTHROPIC_API_KEY directly.diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2319640e3..be0ea0e1b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2457,8 +2457,8 @@"emptyExample1": "“how is my brand doing?”","emptyBodyOr": "or","emptyExample2": "“who's gaining share of voice this month?”",- "keyMissingTitle": "Add your Anthropic API key",- "keyMissingBody": "The agent uses your own Anthropic key to call Claude directly — usage is billed to your Anthropic account, not to Ansvisor. Paste a key in Settings to unlock the chat.",+ "keyMissingTitle": "Add an AI provider key",+ "keyMissingBody": "Chat uses your own key for Anthropic, OpenAI, Google Gemini, Microsoft Azure OpenAI or OpenRouter — usage is billed to that account, not to Ansvisor. Add a key in Settings to unlock the chat.","goToSettings": "Go to Settings","planGateTitle": "Agent is a {plan} feature","planGateBody": "Upgrade your plan to chat with your dashboard about visibility, competitors, citations, and content gaps."@@ -5865,7 +5865,7 @@"revokeApiKey": "Revoke API key","revokeApiKeyConfirm": "Revoke this API key? Clients using it will lose access immediately.","revoke": "Revoke",- "agent_removeKeyConfirm": "Remove the Anthropic API key? Team members will lose access to the agent until a new key is saved.",+ "agent_removeKeyConfirm": "Remove the {provider} API key? If Chat uses it, Chat switches to the most recently saved other key, or stays locked until a new one is saved.","remove": "Remove","apiKeys_description": "Long-lived tokens for the Ansvisor MCP server and other external clients. Keys are shown once at creation — store them somewhere safe.","apiKeys_mcpEndpoint": "MCP endpoint",@@ -5897,19 +5897,67 @@"zed": "Add to your Zed settings.json."},"apiKeys_name": "Name",- "agent_description": "Ansvisor's Chat answers with an AI model on your own account with its provider. Add your Anthropic API key: Chat calls Claude with it, the usage is billed to your Anthropic account rather than to Ansvisor, and the key is stored encrypted.",- "agent_keyConfigured": "Key configured",+ "agent_description": "Ansvisor's Chat answers with an AI model on your own account with its provider, so the usage is billed to that account rather than to Ansvisor. Add a key for one or more providers and choose the one Chat uses. Keys are stored encrypted; Ansvisor support cannot read them.",+ "agent_usedByChat": "Used by Chat",+ "agent_keySaved": "Key saved","agent_savedAt": "Saved {date}","agent_savedBy": "by {email}",- "agent_noKey": "No key configured. The agent will be locked for everyone in this organization until a key is saved.",- "agent_replaceKey": "Replace key",- "agent_anthropicKeyLabel": "Anthropic API key",- "agent_keyPlaceholder": "sk-ant-…",+ "agent_modelInUse": "Model {model}",+ "agent_noKey": "No key yet. Chat stays locked for everyone in this organization until a key is saved.",+ "agent_addKey": "Add key","agent_replace": "Replace",- "agent_keyHint": "Get a key from <link>console.anthropic.com</link>. The key is encrypted at rest; Ansvisor support cannot read it.",+ "agent_useForChat": "Use for Chat",+ "agent_apiKeyLabel": "API key",+ "agent_endpointLabel": "Endpoint",+ "agent_endpointPlaceholder": "https://your-resource.openai.azure.com",+ "agent_deploymentLabel": "Deployment name",+ "agent_deploymentPlaceholder": "gpt-5-chat",+ "agent_modelLabel": "Model",+ "agent_modelOptional": "Optional. Leave empty to use {model}.",+ "agent_openrouterModelHint": "The model's OpenRouter id, for example {model}.",+ "agent_invalid": {+ "endpoint": "Enter your resource's endpoint, for example https://your-resource.openai.azure.com.",+ "deployment": "Enter the deployment's name: letters, digits, dots, dashes or underscores.",+ "model": "Enter a model id."+ },+ "agent_saved": "{provider} key saved",+ "agent_switched": "Chat now uses {provider}",+ "agent_removed": "Key removed","agent_removeKey": "Remove key","agent_adminOnly": "Admin-only setting",- "agent_adminOnlyHint": "Only org admins can add, replace, or remove the Anthropic API key. Ask an admin if you need it changed.",+ "agent_adminOnlyHint": "Only org admins can add, replace, or remove AI provider keys. Ask an admin if you need one changed.",+ "agent_providers": {+ "anthropic": {+ "name": "Anthropic",+ "about": "Claude models, billed to your Anthropic account.",+ "keyPlaceholder": "sk-ant-…",+ "keyHint": "Get a key from <link>console.anthropic.com</link>."+ },+ "openai": {+ "name": "OpenAI",+ "about": "GPT models, billed to your OpenAI account.",+ "keyPlaceholder": "sk-…",+ "keyHint": "Get a key from <link>platform.openai.com</link>."+ },+ "google": {+ "name": "Google Gemini",+ "about": "Gemini models, billed to your Google AI Studio account.",+ "keyPlaceholder": "AIza…",+ "keyHint": "Get a key from <link>aistudio.google.com</link>."+ },+ "azure": {+ "name": "Microsoft Azure OpenAI",+ "about": "OpenAI models deployed in your own Azure subscription.",+ "keyPlaceholder": "Key 1 or Key 2",+ "keyHint": "Find the key and the endpoint under your resource's Keys and Endpoint in the <link>Azure portal</link>."+ },+ "openrouter": {+ "name": "OpenRouter",+ "about": "One key for models from many providers, billed to your OpenRouter account.",+ "keyPlaceholder": "sk-or-…",+ "keyHint": "Get a key from <link>openrouter.ai</link>."+ }+ },"integrations_cancel": "Cancel","integrations_connecting": "Connecting…","integrations_connect": "Connect",diff --git a/web/package.json b/web/package.jsonindex c6fe81d6f..84ceb2e62 100644--- a/web/package.json+++ b/web/package.json@@ -22,6 +22,9 @@},"dependencies": {"@ai-sdk/anthropic": "^3.0.58",+ "@ai-sdk/azure": "^3.0.141",+ "@ai-sdk/google": "^3.0.135",+ "@ai-sdk/openai": "^3.0.130","@ai-sdk/react": "^3.0.81","@base-ui/react": "^1.2.0","@modelcontextprotocol/sdk": "^1.29.0",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsxindex 9152eed3a..78bfb5e61 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx@@ -80,8 +80,8 @@ export default function AgentPage() {return <PlanGate requiredPlan={requiredPlanFor('ai_agent')} />;}- // BYOK gate — on cloud the real gate is "has the org saved an Anthropic- // key?". We probe the same endpoint Settings → Agent uses; if it's not+ // BYOK gate — on cloud the real gate is "has the org saved a provider key+ // for Chat?". We probe the same endpoint Settings › AI Providers uses; if it's not// configured, send the user to Settings instead of letting them type a// message that would 403 on submit. Self-host bypasses (key is in env).if (isCloud) {@@ -727,7 +727,7 @@ function EmptyState() {}/**- * Cloud wrapper: probes /api/settings/anthropic-key once on mount and+ * Cloud wrapper: probes /api/settings/ai-providers once on mount and* either renders the chat (key configured) or a Settings CTA (no key).* Self-host renders AgentChat directly — its key check is environmental.*/@@ -738,7 +738,7 @@ function KeyGatedAgentChat(props: React.ComponentProps<typeof AgentChat>) {let cancelled = false;(async () => {try {- const res = await fetch('/api/settings/anthropic-key');+ const res = await fetch('/api/settings/ai-providers');if (!res.ok) {if (!cancelled) setStatus('missing');return;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsxindex 94f4c9a8f..d0bc166da 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx@@ -14,7 +14,7 @@ import { usePlanContext } from '@/components/providers/plan-provider';import { BillingSection } from '@/components/settings/billing-section';import { TeamSection } from '@/components/settings/team-section';import { ApiKeysSection } from '@/components/settings/api-keys-section';-import { AgentSection } from '@/components/settings/agent-section';+import { AiProvidersSection } from '@/components/settings/ai-providers-section';import { NotificationsSection } from '@/components/settings/notifications-section';import { IntegrationsSection } from '@/components/settings/integrations-section';import { OrganizationSection } from '@/components/settings/organization-section';@@ -179,7 +179,7 @@ export function SettingsView({ section }: { section: SettingsSection }) {{active === 'api-keys' && <ApiKeysSection />}{/* AI Providers (cloud BYOK) */}- {active === 'ai-providers' && isCloud && <AgentSection />}+ {active === 'ai-providers' && isCloud && <AiProvidersSection />}{/* Billing */}{active === 'billing' && isCloud && <BillingSection />}diff --git a/web/src/app/api/agent/chat/route.ts b/web/src/app/api/agent/chat/route.tsindex 21348d375..1e00b4c21 100644--- a/web/src/app/api/agent/chat/route.ts+++ b/web/src/app/api/agent/chat/route.ts@@ -4,8 +4,8 @@ import { supabaseAdmin } from '@/lib/supabase/admin';import { resolveAgentAuth } from '@/lib/agent/auth';import { buildAgentTools } from '@/lib/agent/tools';import { buildAgentSystemPrompt } from '@/lib/agent/system-prompt';-import { buildAgentModel } from '@/lib/agent/model';-import { resolveAnthropicKey } from '@/lib/agent/key';+import { AGENT_PROVIDER_OPTIONS, buildAgentModel } from '@/lib/agent/model';+import { resolveAgentModelConfig } from '@/lib/agent/key';import { recordAgentTokenUsage } from '@/lib/agent/token-quota';import { getPlan, hasFeature, type PlanId } from '@/config/plans';@@ -80,7 +80,7 @@ export async function POST(req: Request) {// Plan gate. On cloud the gate is intentionally loose — `ai_agent` is in// every paid plan's feature list; the *real* gate is whether the org has- // pasted an Anthropic key in Settings → Agent (BYOK). Self-host bypasses+ // pasted a provider key in Settings › AI Providers (BYOK). Self-host bypasses// both checks because the operator's env supplies everything.const { data: org } = await supabaseAdmin.from('organizations')@@ -92,23 +92,24 @@ export async function POST(req: Request) {return NextResponse.json({ error: 'ai_agent is not enabled for this plan' }, { status: 403 });}- // BYOK gate. Cloud customers paste their Anthropic key in- // Settings → Agent and the agent uses *that* key — Ansvisor never pays- // for the customer's tokens. Missing key = 403 with a code the UI can- // intercept to render the "add your key" CTA instead of a generic error.- const anthropicKey = await resolveAnthropicKey(organizationId);- if (!anthropicKey) {+ // BYOK gate. Cloud customers paste a provider key in Settings › AI+ // Providers and the agent uses *that* key, with the provider they picked —+ // Ansvisor never pays for the customer's tokens. Missing key = 403 with a+ // code the UI can intercept to render the "add your key" CTA instead of a+ // generic error.+ const modelConfig = await resolveAgentModelConfig(organizationId);+ if (!modelConfig) {return NextResponse.json({- error: 'Anthropic API key required',- code: 'missing_anthropic_key',+ error: 'AI provider key required',+ code: 'missing_ai_key',},{ status: 403 },);}const result = streamText({- model: buildAgentModel(anthropicKey),+ model: buildAgentModel(modelConfig),maxOutputTokens: 16000,system: buildAgentSystemPrompt(new Date(), defaultBrand),messages: await convertToModelMessages(messages),@@ -122,11 +123,13 @@ export async function POST(req: Request) {// get_visibility_summary → answer" chain without burning tokens// forever on a pathological loop.stopWhen: stepCountIs(20),- onFinish: async ({ usage }) => {- // Bill the turn. inputTokens / outputTokens are the counts from the- // provider; default to 0 if a step finished without billable usage.- const promptTokens = usage?.inputTokens ?? 0;- const completionTokens = usage?.outputTokens ?? 0;+ providerOptions: AGENT_PROVIDER_OPTIONS,+ onFinish: async ({ totalUsage }) => {+ // Bill the turn: every step's tokens (totalUsage), not only the last+ // step's (usage), which leaves out a turn's tool calls. Default to 0 if+ // nothing was billable.+ const promptTokens = totalUsage?.inputTokens ?? 0;+ const completionTokens = totalUsage?.outputTokens ?? 0;try {await recordAgentTokenUsage(auth.userId, organizationId, promptTokens, completionTokens);} catch (err) {diff --git a/web/src/app/api/agent/conversations/route.ts b/web/src/app/api/agent/conversations/route.tsindex f7555596b..330a3de92 100644--- a/web/src/app/api/agent/conversations/route.ts+++ b/web/src/app/api/agent/conversations/route.ts@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server';import { supabaseAdmin } from '@/lib/supabase/admin';import { resolveAgentAuth } from '@/lib/agent/auth';import { getPlan, hasFeature, type PlanId } from '@/config/plans';-import { isAnthropicKeyConfigured } from '@/lib/agent/key';+import { isAgentKeyConfigured } from '@/lib/agent/key';/*** GET /api/agent/conversations@@ -60,11 +60,11 @@ export async function POST(req: Request) {// BYOK gate — match the chat endpoint so "+ new chat" can't create a row// the user can never send a message to. UI uses the same code to route- // to the Settings → Agent CTA.- const hasKey = await isAnthropicKeyConfigured(organizationId);+ // to the Settings › AI Providers CTA.+ const hasKey = await isAgentKeyConfigured(organizationId);if (!hasKey) {return NextResponse.json(- { error: 'Anthropic API key required', code: 'missing_anthropic_key' },+ { error: 'AI provider key required', code: 'missing_ai_key' },{ status: 403 },);}diff --git a/web/src/app/api/settings/ai-providers/route.test.ts b/web/src/app/api/settings/ai-providers/route.test.tsnew file mode 100644index 000000000..289e5ead5--- /dev/null+++ b/web/src/app/api/settings/ai-providers/route.test.ts@@ -0,0 +1,258 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * /api/settings/ai-providers: an organization's own keys for Chat, one per+ * provider, and the one Chat uses. Members read; admins save, switch and remove.+ */++let user: { id: string } | null;+let profile: { id: string; role: string; organization_id: string } | null;++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user } }) },+ from: () => ({+ select: () => ({ eq: () => ({ single: async () => ({ data: profile }) }) }),+ }),+ }),+}));++/** Each query on the admin client: its table and the calls made on it. */+const queries: { table: string; calls: [string, ...unknown[]][] }[] = [];+/** What each query resolves to, in order. */+let results: { data?: unknown; error?: { message: string } | null }[];+const rpc = vi.fn();++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const query = { table, calls: [] as [string, ...unknown[]][] };+ queries.push(query);+ const settle = () => Promise.resolve(results.shift() ?? { data: null, error: null });+ const chain: Record<string, unknown> = {};+ for (const op of ['select', 'eq', 'upsert', 'update', 'delete', 'order', 'limit']) {+ chain[op] = (...args: unknown[]) => {+ query.calls.push([op, ...args]);+ return chain;+ };+ }+ chain.maybeSingle = settle;+ chain.then = (resolve: (v: unknown) => unknown, reject: (e: unknown) => unknown) =>+ settle().then(resolve, reject);+ return chain;+ },+ rpc: (...args: unknown[]) => rpc(...args),+ auth: {+ admin: {+ getUserById: async (id: string) => ({ data: { user: { email: `${id}@acme.test` } } }),+ },+ },+ },+}));++vi.mock('@/lib/agent/key-encryption', () => ({+ encryptApiKey: (key: string) => `enc(${key})`,+ last4: (key: string) => key.slice(-4),+}));++const { GET, PUT, PATCH, DELETE } = await import('./route');++const KEY = 'sk-test-0123456789abcdef';+const send = (method: string, body?: unknown) =>+ new Request('http://localhost/api/settings/ai-providers', {+ method,+ body: body === undefined ? undefined : JSON.stringify(body),+ });++beforeEach(() => {+ user = { id: 'u1' };+ profile = { id: 'u1', role: 'admin', organization_id: 'org1' };+ queries.length = 0;+ results = [];+ rpc.mockReset().mockResolvedValue({ data: true, error: null });+});++describe('GET', () => {+ it('lists the saved providers with who saved them, and whether Chat has one', async () => {+ profile!.role = 'member';+ results = [+ {+ data: [+ {+ provider: 'openai',+ key_last4: 'abcd',+ settings: {},+ active: true,+ set_at: '2026-10-19T08:00:00Z',+ set_by: 'u2',+ },+ {+ provider: 'azure',+ key_last4: 'wxyz',+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'd1' },+ active: false,+ set_at: '2026-10-18T08:00:00Z',+ set_by: null,+ },+ ],+ error: null,+ },+ ];+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ configured: true,+ providers: [+ {+ provider: 'openai',+ last4: 'abcd',+ settings: {},+ active: true,+ setAt: '2026-10-19T08:00:00Z',+ setByEmail: '[email protected]',+ },+ {+ provider: 'azure',+ last4: 'wxyz',+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'd1' },+ active: false,+ setAt: '2026-10-18T08:00:00Z',+ setByEmail: null,+ },+ ],+ });+ expect(queries[0].calls).toContainEqual(['eq', 'organization_id', 'org1']);+ });++ it('needs a signed-in user', async () => {+ user = null;+ expect((await GET()).status).toBe(401);+ });+});++describe('PUT', () => {+ it('lets admins only change the keys', async () => {+ profile!.role = 'manager';+ const res = await PUT(send('PUT', { provider: 'openai', apiKey: KEY }));+ expect(res.status).toBe(403);+ expect(queries).toHaveLength(0);+ });++ it("refuses an unknown provider, a short key, and names the setting that's wrong", async () => {+ expect((await PUT(send('PUT', { provider: 'copilot', apiKey: KEY }))).status).toBe(400);+ expect((await PUT(send('PUT', { provider: 'openai', apiKey: 'short' }))).status).toBe(400);+ const res = await PUT(+ send('PUT', {+ provider: 'azure',+ apiKey: KEY,+ settings: { endpoint: 'https://evil.example', deployment: 'd1' },+ }),+ );+ expect(res.status).toBe(400);+ expect(await res.json()).toMatchObject({ field: 'endpoint' });+ expect(queries).toHaveLength(0);+ });++ it('saves the key encrypted, and makes the first one the one Chat uses', async () => {+ results = [{ error: null }];+ const res = await PUT(+ send('PUT', {+ provider: 'azure',+ apiKey: ` ${KEY} `,+ settings: { endpoint: 'https://acme.openai.azure.com/', deployment: 'd1' },+ }),+ );+ expect(res.status).toBe(200);+ const [upsert] = queries[0].calls;+ expect(upsert[0]).toBe('upsert');+ expect(upsert[1]).toMatchObject({+ organization_id: 'org1',+ provider: 'azure',+ key_encrypted: `enc(${KEY})`,+ key_last4: 'cdef',+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'd1' },+ set_by: 'u1',+ });+ // A replaced key keeps whether Chat uses it.+ expect(upsert[1]).not.toHaveProperty('active');+ // Only while no key is Chat's, decided under the lock (00188).+ expect(rpc).toHaveBeenCalledWith('set_active_ai_provider', {+ p_organization_id: 'org1',+ p_provider: 'azure',+ p_only_if_none: true,+ });+ // Only an Anthropic key has an old copy to clear.+ expect(queries.map((q) => q.table)).toEqual(['organization_ai_keys']);+ });++ it("clears the Anthropic key's old copy on organizations when it is replaced", async () => {+ results = [{ error: null }, { error: null }];+ expect((await PUT(send('PUT', { provider: 'anthropic', apiKey: KEY }))).status).toBe(200);+ expect(queries[1].table).toBe('organizations');+ expect(queries[1].calls).toEqual([+ [+ 'update',+ {+ anthropic_api_key_encrypted: null,+ anthropic_api_key_last4: null,+ anthropic_api_key_set_at: null,+ anthropic_api_key_set_by: null,+ },+ ],+ ['eq', 'id', 'org1'],+ ]);+ });+});++describe('PATCH', () => {+ it('switches Chat to a saved provider', async () => {+ const res = await PATCH(send('PATCH', { provider: 'google' }));+ expect(res.status).toBe(200);+ expect(rpc).toHaveBeenCalledWith('set_active_ai_provider', {+ p_organization_id: 'org1',+ p_provider: 'google',+ p_only_if_none: false,+ });+ });++ it('answers 404 for a provider without a key', async () => {+ rpc.mockResolvedValue({ data: false, error: null });+ expect((await PATCH(send('PATCH', { provider: 'google' }))).status).toBe(404);+ });+});++describe('DELETE', () => {+ const remove = (provider: string) =>+ DELETE(+ new Request(`http://localhost/api/settings/ai-providers?provider=${provider}`, {+ method: 'DELETE',+ }),+ );++ it('removes the key in one locked step that also hands Chat to another key', async () => {+ rpc.mockResolvedValue({ data: 'google', error: null });+ expect((await remove('openai')).status).toBe(200);+ expect(rpc).toHaveBeenCalledWith('remove_ai_provider_key', {+ p_organization_id: 'org1',+ p_provider: 'openai',+ });+ expect(queries).toHaveLength(0);+ });++ it("clears the Anthropic key's old copy too", async () => {+ rpc.mockResolvedValue({ data: null, error: null });+ results = [{ error: null }];+ expect((await remove('anthropic')).status).toBe(200);+ expect(queries[0].table).toBe('organizations');+ expect(queries[0].calls[0][0]).toBe('update');+ });++ it('answers 500 when the removal fails', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } });+ expect((await remove('openai')).status).toBe(500);+ });++ it('refuses an unknown provider', async () => {+ expect((await remove('copilot')).status).toBe(400);+ });+});diff --git a/web/src/app/api/settings/ai-providers/route.ts b/web/src/app/api/settings/ai-providers/route.tsnew file mode 100644index 000000000..a78df7377--- /dev/null+++ b/web/src/app/api/settings/ai-providers/route.ts@@ -0,0 +1,256 @@+import { NextResponse } from 'next/server';+import { createClient } from '@/lib/supabase/server';+import { supabaseAdmin } from '@/lib/supabase/admin';+import { encryptApiKey, last4 } from '@/lib/agent/key-encryption';+import { isAiProvider, parseProviderSettings, type AiProvider } from '@/lib/agent/providers';++/**+ * GET / PUT / PATCH / DELETE /api/settings/ai-providers+ *+ * Manages the org-level AI provider keys the in-product agent uses on+ * cloud — one per provider, and the one Chat uses (`active`). We never+ * return the plaintext — GET surfaces only the metadata the Settings UI+ * needs to render each provider (last4, set_at, who saved it, its settings).+ *+ * - GET: the saved providers, and whether Chat has one to use.+ * - PUT { provider, apiKey, settings }: saves (or replaces) a provider's key;+ * the first one saved becomes the one Chat uses.+ * - PATCH { provider }: makes a saved provider the one Chat uses.+ * - DELETE ?provider=: removes a key; when it was Chat's, the most recently+ * saved other one takes over.+ *+ * Auth model:+ * - GET: any signed-in org member can see which keys are configured.+ * The chat endpoint already gates, so leaking "we have a key" is fine.+ * - PUT / PATCH / DELETE: admins only. Same role bar as team management —+ * adding a payment instrument (which is effectively what a provider key+ * is) shouldn't be a non-admin action.+ */++async function getCallerAndOrg() {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return { error: 'Unauthorized' as const };++ const { data: profile } = await supabase+ .from('profiles')+ .select('id, role, organization_id')+ .eq('id', user.id)+ .single();++ if (!profile?.organization_id) return { error: 'No organization' as const };++ return {+ user,+ profile: profile as { id: string; role: string; organization_id: string },+ };+}++type Caller = Exclude<Awaited<ReturnType<typeof getCallerAndOrg>>, { error: string }>;++/** The caller when they may change the keys, or the response that says why not. */+async function getAdmin(): Promise<Caller | NextResponse> {+ const ctx = await getCallerAndOrg();+ if ('error' in ctx) {+ return NextResponse.json(+ { error: ctx.error },+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },+ );+ }+ if (ctx.profile.role !== 'admin') {+ return NextResponse.json({ error: 'Only admins can manage AI provider keys' }, { status: 403 });+ }+ return ctx;+}++/** Under a lock on the org's keys (00188); with onlyIfNone, only while none is Chat's. */+async function setActive(organizationId: string, provider: AiProvider, onlyIfNone = false) {+ return supabaseAdmin.rpc('set_active_ai_provider', {+ p_organization_id: organizationId,+ p_provider: provider,+ p_only_if_none: onlyIfNone,+ });+}++/**+ * The Anthropic key's copy on `organizations` (00010), which only the old+ * settings route wrote: cleared when the key is replaced or removed here, so+ * a removed key doesn't stay stored, or come back on a rollback.+ */+async function clearLegacyAnthropicKey(organizationId: string) {+ return supabaseAdmin+ .from('organizations')+ .update({+ anthropic_api_key_encrypted: null,+ anthropic_api_key_last4: null,+ anthropic_api_key_set_at: null,+ anthropic_api_key_set_by: null,+ })+ .eq('id', organizationId);+}++export async function GET() {+ const ctx = await getCallerAndOrg();+ if ('error' in ctx) {+ return NextResponse.json(+ { error: ctx.error },+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },+ );+ }++ const { data, error } = await supabaseAdmin+ .from('organization_ai_keys')+ .select('provider, key_last4, settings, active, set_at, set_by')+ .eq('organization_id', ctx.profile.organization_id);++ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }++ // Savers' e-mails, one lookup each — the FK is to `profiles(id)`, which+ // the auth user model mirrors.+ const setters = [...new Set((data ?? []).map((row) => row.set_by).filter(Boolean))];+ const emails = new Map(+ await Promise.all(+ setters.map(async (id) => {+ const { data: setter } = await supabaseAdmin.auth.admin.getUserById(id);+ return [id, setter?.user?.email ?? null] as const;+ }),+ ),+ );++ const rows = (data ?? []).filter((row) => isAiProvider(row.provider));+ return NextResponse.json({+ // Whether Chat has a key to use — what the sidebar badge and Chat ask.+ configured: rows.some((row) => row.active),+ providers: rows.map((row) => ({+ provider: row.provider,+ last4: row.key_last4,+ settings: row.settings ?? {},+ active: row.active,+ setAt: row.set_at,+ setByEmail: row.set_by ? (emails.get(row.set_by) ?? null) : null,+ })),+ });+}++export async function PUT(req: Request) {+ const ctx = await getAdmin();+ if (ctx instanceof NextResponse) return ctx;++ const body = (await req.json().catch(() => ({}))) as {+ provider?: unknown;+ apiKey?: unknown;+ settings?: unknown;+ };+ if (!isAiProvider(body.provider)) {+ return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });+ }+ const provider = body.provider;+ const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';+ if (!apiKey) {+ return NextResponse.json({ error: 'apiKey is required' }, { status: 400 });+ }+ // A soft length check rather than each provider's prefix — prefixes have+ // changed before, and the first chat turn surfaces a bad key as a 401+ // immediately anyway.+ if (apiKey.length < 20 || apiKey.length > 300) {+ return NextResponse.json({ error: 'apiKey looks malformed' }, { status: 400 });+ }+ const parsed = parseProviderSettings(provider, body.settings);+ if ('error' in parsed) {+ return NextResponse.json(+ { error: `${parsed.error} is missing or malformed`, field: parsed.error },+ { status: 400 },+ );+ }++ let encrypted: string;+ try {+ encrypted = encryptApiKey(apiKey);+ } catch (err) {+ // Misconfigured server env — surface a clear 500 instead of writing+ // unrecoverable data.+ console.error('[ai-providers] encryption failed:', err);+ return NextResponse.json({ error: 'Server encryption is not configured' }, { status: 500 });+ }++ const organizationId = ctx.profile.organization_id;+ // `active` is left out: a replaced key keeps whether Chat uses it.+ const { error } = await supabaseAdmin.from('organization_ai_keys').upsert(+ {+ organization_id: organizationId,+ provider,+ key_encrypted: encrypted,+ key_last4: last4(apiKey),+ settings: parsed.settings,+ set_at: new Date().toISOString(),+ set_by: ctx.profile.id,+ },+ { onConflict: 'organization_id,provider' },+ );+ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }++ // The first key saved is the one Chat uses: decided under the lock, so a+ // switch at the same time can't be overridden.+ const { error: activeError } = await setActive(organizationId, provider, true);+ if (activeError) {+ return NextResponse.json({ error: activeError.message }, { status: 500 });+ }+ if (provider === 'anthropic') {+ const { error: legacyError } = await clearLegacyAnthropicKey(organizationId);+ if (legacyError) {+ return NextResponse.json({ error: legacyError.message }, { status: 500 });+ }+ }+ return NextResponse.json({ ok: true });+}++export async function PATCH(req: Request) {+ const ctx = await getAdmin();+ if (ctx instanceof NextResponse) return ctx;++ const body = (await req.json().catch(() => ({}))) as { provider?: unknown };+ if (!isAiProvider(body.provider)) {+ return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });+ }+ const { data, error } = await setActive(ctx.profile.organization_id, body.provider);+ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }+ if (!data) {+ return NextResponse.json({ error: 'No key is saved for this provider' }, { status: 404 });+ }+ return NextResponse.json({ ok: true });+}++export async function DELETE(req: Request) {+ const ctx = await getAdmin();+ if (ctx instanceof NextResponse) return ctx;++ const provider = new URL(req.url).searchParams.get('provider');+ if (!isAiProvider(provider)) {+ return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });+ }+ const organizationId = ctx.profile.organization_id;+ // Removed, and when it was Chat's key the most recently saved other one+ // takes over, in one transaction under a lock on the org's keys (00188).+ const { error } = await supabaseAdmin.rpc('remove_ai_provider_key', {+ p_organization_id: organizationId,+ p_provider: provider,+ });+ if (error) {+ return NextResponse.json({ error: error.message }, { status: 500 });+ }+ if (provider === 'anthropic') {+ const { error: legacyError } = await clearLegacyAnthropicKey(organizationId);+ if (legacyError) {+ return NextResponse.json({ error: legacyError.message }, { status: 500 });+ }+ }+ return NextResponse.json({ ok: true });+}diff --git a/web/src/app/api/settings/anthropic-key/route.ts b/web/src/app/api/settings/anthropic-key/route.tsdeleted file mode 100644index 5a7cd2d34..000000000--- a/web/src/app/api/settings/anthropic-key/route.ts+++ /dev/null@@ -1,168 +0,0 @@-import { NextResponse } from 'next/server';-import { createClient } from '@/lib/supabase/server';-import { supabaseAdmin } from '@/lib/supabase/admin';-import { encryptApiKey, last4 } from '@/lib/agent/key-encryption';--/**- * GET / PUT / DELETE /api/settings/anthropic-key- *- * Manages the org-level Anthropic API key the in-product agent uses on- * cloud. We never return the plaintext — GET surfaces only the metadata- * the Settings UI needs to render the "configured" state (last4, set_at,- * who saved it).- *- * Auth model:- * - GET: any signed-in org member can see whether a key is configured.- * The chat endpoint already gates, so leaking "we have a key" is fine.- * - PUT / DELETE: admins only. Same role bar as team management — adding- * a payment instrument (which is effectively what an Anthropic key is)- * shouldn't be a non-admin action.- */--async function getCallerAndOrg() {- const supabase = await createClient();- const {- data: { user },- } = await supabase.auth.getUser();- if (!user) return { error: 'Unauthorized' as const };-- const { data: profile } = await supabase- .from('profiles')- .select('id, role, organization_id')- .eq('id', user.id)- .single();-- if (!profile?.organization_id) return { error: 'No organization' as const };-- return {- user,- profile: profile as { id: string; role: string; organization_id: string },- };-}--export async function GET() {- const ctx = await getCallerAndOrg();- if ('error' in ctx) {- return NextResponse.json(- { error: ctx.error },- { status: ctx.error === 'Unauthorized' ? 401 : 400 },- );- }-- const { data, error } = await supabaseAdmin- .from('organizations')- .select(- 'anthropic_api_key_last4, anthropic_api_key_set_at, anthropic_api_key_set_by, anthropic_api_key_encrypted',- )- .eq('id', ctx.profile.organization_id)- .single();-- if (error) {- return NextResponse.json({ error: error.message }, { status: 500 });- }-- // Fetch the saver's name separately — the FK we declared is to- // `profiles(id)`, which the auth user model already mirrors, so a quick- // second query is simpler than a join through PostgREST.- let setByEmail: string | null = null;- if (data?.anthropic_api_key_set_by) {- const { data: setter } = await supabaseAdmin.auth.admin.getUserById(- data.anthropic_api_key_set_by,- );- setByEmail = setter?.user?.email ?? null;- }-- return NextResponse.json({- configured: !!data?.anthropic_api_key_encrypted,- last4: data?.anthropic_api_key_last4 ?? null,- setAt: data?.anthropic_api_key_set_at ?? null,- setByEmail,- });-}--export async function PUT(req: Request) {- const ctx = await getCallerAndOrg();- if ('error' in ctx) {- return NextResponse.json(- { error: ctx.error },- { status: ctx.error === 'Unauthorized' ? 401 : 400 },- );- }- if (ctx.profile.role !== 'admin') {- return NextResponse.json(- { error: 'Only admins can manage the Anthropic API key' },- { status: 403 },- );- }-- const body = (await req.json().catch(() => ({}))) as { apiKey?: string };- const apiKey = (body.apiKey ?? '').trim();- if (!apiKey) {- return NextResponse.json({ error: 'apiKey is required' }, { status: 400 });- }- // Anthropic keys are `sk-ant-…`. We do a soft format check rather than a- // hard one — the prefix has changed before and we don't want to lock- // users out over a future format bump. A network validation against- // /v1/messages would be more rigorous but doubles save latency for- // little gain; the first chat turn will surface a bad key as a 401- // immediately anyway.- if (apiKey.length < 20 || apiKey.length > 200) {- return NextResponse.json({ error: 'apiKey looks malformed' }, { status: 400 });- }-- let encrypted: string;- try {- encrypted = encryptApiKey(apiKey);- } catch (err) {- // Misconfigured server env — surface a clear 500 instead of writing- // unrecoverable data.- console.error('[anthropic-key] encryption failed:', err);- return NextResponse.json({ error: 'Server encryption is not configured' }, { status: 500 });- }-- const { error } = await supabaseAdmin- .from('organizations')- .update({- anthropic_api_key_encrypted: encrypted,- anthropic_api_key_last4: last4(apiKey),- anthropic_api_key_set_at: new Date().toISOString(),- anthropic_api_key_set_by: ctx.profile.id,- })- .eq('id', ctx.profile.organization_id);-- if (error) {- return NextResponse.json({ error: error.message }, { status: 500 });- }- return NextResponse.json({ ok: true });-}--export async function DELETE() {- const ctx = await getCallerAndOrg();- if ('error' in ctx) {- return NextResponse.json(- { error: ctx.error },- { status: ctx.error === 'Unauthorized' ? 401 : 400 },- );- }- if (ctx.profile.role !== 'admin') {- return NextResponse.json(- { error: 'Only admins can manage the Anthropic API key' },- { status: 403 },- );- }-- const { error } = await supabaseAdmin- .from('organizations')- .update({- anthropic_api_key_encrypted: null,- anthropic_api_key_last4: null,- anthropic_api_key_set_at: null,- anthropic_api_key_set_by: null,- })- .eq('id', ctx.profile.organization_id);-- if (error) {- return NextResponse.json({ error: error.message }, { status: 500 });- }- return NextResponse.json({ ok: true });-}diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsxindex 8a61cdc1b..af1cf9363 100644--- a/web/src/components/layout/mobile-nav.tsx+++ b/web/src/components/layout/mobile-nav.tsx@@ -105,7 +105,7 @@ export function MobileNav() {const label = getDashboardNavLabel(item.title, t, tBrands);// Dynamic badge override: show "Set up" on the Agent item- // when the org has no Anthropic key saved (cloud only).+ // when the org has no provider key for Chat (cloud only).const effectiveBadge =item.href === '/dashboard/agent' && agentKeyMissing ? 'Set up' : item.badge;diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsxindex 4e15edaaa..33d5143f8 100644--- a/web/src/components/layout/sidebar.tsx+++ b/web/src/components/layout/sidebar.tsx@@ -138,7 +138,7 @@ export function Sidebar() {const t = useTranslations('nav');const tBrands = useTranslations('brands');const { canUse, requiredPlanFor, isCloud } = useFeatureGate();- // Probe once per session whether the org has saved an Anthropic key.+ // Probe once per session whether the org has a provider key for Chat.// Returns 'configured' immediately on self-host (no network call).const agentKeyStatus = useAgentKeyStatus(isCloud);const agentKeyMissing = isCloud && agentKeyStatus === 'missing';@@ -358,7 +358,7 @@ export function Sidebar() {const label = getDashboardNavLabel(item.title, t, tBrands);// Dynamic badge override: show "Set up" on the Agent item- // when the org has no Anthropic key saved (cloud only).+ // when the org has no provider key for Chat (cloud only).const effectiveBadge =item.href === '/dashboard/agent' && agentKeyMissing ? 'Set up' : item.badge;diff --git a/web/src/components/settings/agent-section.tsx b/web/src/components/settings/agent-section.tsxdeleted file mode 100644index 4c48ae5d4..000000000--- a/web/src/components/settings/agent-section.tsx+++ /dev/null@@ -1,251 +0,0 @@-'use client';--import { useCallback, useEffect, useState } from 'react';-import { toast } from 'sonner';-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Badge } from '@/components/ui/badge';-import { Skeleton } from '@/components/ui/skeleton';-import { Loader2, Lock, Sparkles, Trash2, CheckCircle2 } from 'lucide-react';-import { useTranslations } from 'next-intl';-import { useUserRole } from '@/hooks/use-user-role';-import { formatDate } from '@/lib/format';-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';--interface KeyState {- configured: boolean;- last4: string | null;- setAt: string | null;- setByEmail: string | null;-}--/**- * Settings → Agent.- *- * Bring-your-own-key UI for the in-product agent on cloud. Customers paste- * an Anthropic API key here and the chat endpoint reads it back per turn- * (encrypted at rest, see web/src/lib/agent/key-encryption.ts).- *- * The plaintext is never returned from the server — `configured` + `last4`- * are enough to render the "sk-…abcd" chip without a decrypt round-trip.- * On save / clear we just refetch.- */-export function AgentSection() {- const t = useTranslations('settings');- const tCommon = useTranslations('common');- const [state, setState] = useState<KeyState | null>(null);- const [loading, setLoading] = useState(true);- const [input, setInput] = useState('');- const [saving, setSaving] = useState(false);- const [clearing, setClearing] = useState(false);- const { canAdmin } = useUserRole();- const [confirmClear, setConfirmClear] = useState(false);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await fetch('/api/settings/anthropic-key');- const body = (await res.json()) as Partial<KeyState> & { error?: string };- if (!res.ok) throw new Error(body.error || 'Failed to load');- setState({- configured: !!body.configured,- last4: body.last4 ?? null,- setAt: body.setAt ?? null,- setByEmail: body.setByEmail ?? null,- });- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to load');- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- void load();- }, [load]);-- const handleSave = async () => {- const apiKey = input.trim();- if (!apiKey) return;- setSaving(true);- try {- const res = await fetch('/api/settings/anthropic-key', {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ apiKey }),- });- const body = (await res.json().catch(() => ({}))) as { error?: string };- if (!res.ok) throw new Error(body.error || 'Failed to save');- toast.success('Anthropic API key saved');- setInput('');- await load();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to save');- } finally {- setSaving(false);- }- };-- const handleClear = async () => {- setClearing(true);- try {- const res = await fetch('/api/settings/anthropic-key', { method: 'DELETE' });- const body = (await res.json().catch(() => ({}))) as { error?: string };- if (!res.ok) throw new Error(body.error || 'Failed to clear');- toast.success('Key removed');- await load();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to clear');- } finally {- setClearing(false);- setConfirmClear(false);- }- };-- const configured = state?.configured ?? false;- const isReplacing = configured && input.length > 0;-- return (- <Card>- <CardHeader>- <CardTitle className="flex items-center gap-2">- <Sparkles className="h-4 w-4" />- {t('aiProviders')}- </CardTitle>- <CardDescription>{t('agent_description')}</CardDescription>- </CardHeader>- <CardContent className="space-y-4">- {loading ? (- <Skeleton className="h-20 w-full" />- ) : configured && state ? (- <div className="rounded-md border bg-muted/40 p-3 space-y-2">- <div className="flex items-center gap-2">- <Badge variant="secondary" className="gap-1">- <CheckCircle2 className="h-3 w-3" />- {t('agent_keyConfigured')}- </Badge>- {state.last4 && (- <code className="text-xs font-mono text-muted-foreground">sk-…{state.last4}</code>- )}- </div>- <p className="text-xs text-muted-foreground">- {t('agent_savedAt', { date: formatDate(state.setAt) })}- {state.setByEmail && ` ${t('agent_savedBy', { email: state.setByEmail })}`}.- </p>- </div>- ) : (- <p className="text-sm text-muted-foreground">{t('agent_noKey')}</p>- )}-- {canAdmin ? (- <>- <div className="space-y-2">- <Label htmlFor="anthropic-key">- {configured ? t('agent_replaceKey') : t('agent_anthropicKeyLabel')}- </Label>- <div className="flex gap-2">- <Input- id="anthropic-key"- type="password"- autoComplete="off"- spellCheck={false}- placeholder={t('agent_keyPlaceholder')}- value={input}- onChange={(e) => setInput(e.target.value)}- disabled={saving}- className="font-mono"- />- <Button onClick={handleSave} disabled={saving || !input.trim()}>- {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {isReplacing ? t('agent_replace') : tCommon('save')}- </Button>- </div>- <p className="text-xs text-muted-foreground">- {t.rich('agent_keyHint', {- link: (chunks) => (- <a- href="https://console.anthropic.com/settings/keys"- target="_blank"- rel="noreferrer"- className="underline"- >- {chunks}- </a>- ),- })}- </p>- </div>-- {configured && (- <div className="pt-2 border-t">- <Button- variant="outline"- size="sm"- onClick={() => setConfirmClear(true)}- disabled={clearing}- className="text-destructive hover:text-destructive"- >- {clearing ? (- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- ) : (- <Trash2 className="mr-2 h-4 w-4" />- )}- {t('agent_removeKey')}- </Button>- <Dialog open={confirmClear} onOpenChange={setConfirmClear}>- <DialogContent className="sm:max-w-sm">- <DialogHeader>- <DialogTitle>{t('agent_removeKey')}</DialogTitle>- <DialogDescription>{t('agent_removeKeyConfirm')}</DialogDescription>- </DialogHeader>-- <DialogFooter>- <DialogClose render={<Button variant="outline" />}>- {tCommon('cancel')}- </DialogClose>-- <Button- type="button"- variant="destructive"- disabled={clearing}- onClick={(e) => {- e.stopPropagation();- void handleClear();- }}- >- {clearing && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {t('remove')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>- )}- </>- ) : (- // Server-side, `/api/settings/anthropic-key` PUT/DELETE already- // refuses non-admin role with a 403. The form here used to render- // anyway and any click ended in an unhelpful toast — replace it- // with an explicit read-only message so non-admins know why.- <div className="flex items-start gap-3 rounded-md border bg-muted/40 p-3 text-sm">- <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />- <div>- <p className="font-medium">{t('agent_adminOnly')}</p>- <p className="mt-1 text-muted-foreground">{t('agent_adminOnlyHint')}</p>- </div>- </div>- )}- </CardContent>- </Card>- );-}diff --git a/web/src/components/settings/ai-providers-section.test.tsx b/web/src/components/settings/ai-providers-section.test.tsxnew file mode 100644index 000000000..2a315bdfa--- /dev/null+++ b/web/src/components/settings/ai-providers-section.test.tsx@@ -0,0 +1,174 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';++/**+ * Settings › AI Providers: a row per provider with its saved key, the one+ * Chat uses, and — for admins — adding, replacing, switching and removing.+ */++const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++let canAdmin = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canAdmin ? 'admin' : 'member', canManage: canAdmin, canAdmin }),+}));++const { AiProvidersSection } = await import('./ai-providers-section');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const fetchMock = vi.fn();+let saved: unknown[];++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });++beforeEach(() => {+ vi.clearAllMocks();+ canAdmin = true;+ saved = [+ {+ provider: 'anthropic',+ last4: 'abcd',+ settings: {},+ active: true,+ setAt: '2026-10-19T08:00:00Z',+ setByEmail: '[email protected]',+ },+ {+ provider: 'openai',+ last4: 'wxyz',+ settings: { model: 'gpt-5.4' },+ active: false,+ setAt: '2026-10-18T08:00:00Z',+ setByEmail: null,+ },+ ];+ fetchMock.mockImplementation(async (_url: string, init?: RequestInit) =>+ !init?.method ? json({ configured: true, providers: saved }) : json({ ok: true }),+ );+ vi.stubGlobal('fetch', fetchMock);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.innerHTML = '';+ vi.unstubAllGlobals();+});++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <AiProvidersSection />+ </NextIntlClientProvider>,+ );+ });+}++const row = (provider: string) =>+ container.querySelector(`[data-provider="${provider}"]`) as HTMLElement;+const button = (scope: HTMLElement, label: string) =>+ [...scope.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLElement;++function type(input: HTMLInputElement, value: string) {+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('AiProvidersSection', () => {+ it('shows each provider, the one Chat uses, and the model each calls', async () => {+ await render();+ expect(row('anthropic').textContent).toContain('Used by Chat');+ expect(row('anthropic').textContent).toContain('Model claude-sonnet-5');+ expect(row('anthropic').textContent).toContain('by [email protected]');+ expect(row('openai').textContent).toContain('Key saved');+ expect(row('openai').textContent).toContain('Model gpt-5.4');+ expect(row('azure').textContent).toContain('OpenAI models deployed in your own Azure');+ expect(button(row('azure'), 'Add key')).toBeTruthy();+ expect(button(row('anthropic'), 'Use for Chat')).toBeUndefined();+ expect(container.textContent).not.toContain('No key yet');+ });++ it('switches Chat to another saved provider', async () => {+ await render();+ await act(async () => button(row('openai'), 'Use for Chat').click());+ expect(fetchMock).toHaveBeenCalledWith('/api/settings/ai-providers', {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ provider: 'openai' }),+ });+ expect(toast.success).toHaveBeenCalledWith('Chat now uses OpenAI');+ });++ it("checks Azure's endpoint before saving, then saves the key with its settings", async () => {+ await render();+ act(() => button(row('azure'), 'Add key').click());+ const form = row('azure').querySelector('form') as HTMLFormElement;+ type(+ form.querySelector('#ai-provider-azure-key') as HTMLInputElement,+ 'azure-key-0123456789abc',+ );+ type(+ form.querySelector('#ai-provider-azure-endpoint') as HTMLInputElement,+ 'https://x.example',+ );+ type(form.querySelector('#ai-provider-azure-deployment') as HTMLInputElement, 'gpt-5-chat');+ await act(async () => button(form, 'Save').click());+ expect(form.textContent).toContain("Enter your resource's endpoint");+ expect(fetchMock).toHaveBeenCalledTimes(1);++ type(+ form.querySelector('#ai-provider-azure-endpoint') as HTMLInputElement,+ 'https://acme.openai.azure.com/',+ );+ await act(async () => button(form, 'Save').click());+ expect(fetchMock).toHaveBeenCalledWith('/api/settings/ai-providers', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ provider: 'azure',+ apiKey: 'azure-key-0123456789abc',+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'gpt-5-chat' },+ }),+ });+ expect(toast.success).toHaveBeenCalledWith('Microsoft Azure OpenAI key saved');+ expect(row('azure').querySelector('form')).toBeNull();+ });++ it('removes a key after asking', async () => {+ await render();+ act(() =>+ (+ row('openai').querySelector('button[aria-label="Remove key: OpenAI"]') as HTMLElement+ ).click(),+ );+ expect(document.body.textContent).toContain('Remove the OpenAI API key?');+ await act(async () => button(document.body, 'Remove').click());+ expect(fetchMock).toHaveBeenCalledWith('/api/settings/ai-providers?provider=openai', {+ method: 'DELETE',+ });+ });++ it('shows members the keys without the buttons that change them', async () => {+ canAdmin = false;+ saved = [];+ await render();+ expect(container.textContent).toContain('No key yet');+ expect(container.textContent).toContain('Admin-only setting');+ expect(button(row('anthropic'), 'Add key')).toBeUndefined();+ });+});diff --git a/web/src/components/settings/ai-providers-section.tsx b/web/src/components/settings/ai-providers-section.tsxnew file mode 100644index 000000000..3eb3c6e46--- /dev/null+++ b/web/src/components/settings/ai-providers-section.tsx@@ -0,0 +1,463 @@+'use client';++import { useCallback, useEffect, useState } from 'react';+import { toast } from 'sonner';+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Badge } from '@/components/ui/badge';+import { Skeleton } from '@/components/ui/skeleton';+import { CheckCircle2, Cloud, Loader2, Lock, Route, Sparkles, Trash2 } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { AIProviderAvatar } from '@/components/ai-provider-avatar';+import { useUserRole } from '@/hooks/use-user-role';+import { formatDate } from '@/lib/format';+import {+ AI_PROVIDERS,+ DEFAULT_MODELS,+ OPENROUTER_MODEL_EXAMPLE,+ chatModelId,+ parseProviderSettings,+ type AiProvider,+ type AiProviderSettings,+ type SettingsError,+} from '@/lib/agent/providers';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';++interface SavedProvider {+ provider: AiProvider;+ last4: string | null;+ settings: AiProviderSettings;+ active: boolean;+ setAt: string | null;+ setByEmail: string | null;+}++/** Where each provider hands out keys. */+const KEY_LINKS: Record<AiProvider, string> = {+ anthropic: 'https://console.anthropic.com/settings/keys',+ openai: 'https://platform.openai.com/api-keys',+ google: 'https://aistudio.google.com/apikey',+ azure: 'https://portal.azure.com/',+ openrouter: 'https://openrouter.ai/settings/keys',+};++function ProviderIcon({ provider }: { provider: AiProvider }) {+ if (provider === 'azure') return <Cloud className="h-5 w-5 text-muted-foreground" />;+ if (provider === 'openrouter') return <Route className="h-5 w-5 text-muted-foreground" />;+ // The same logos as the platforms' (OpenAI's drawn black on a light card).+ return <AIProviderAvatar provider={provider} plain />;+}++/**+ * Settings › AI Providers.+ *+ * Bring-your-own-key UI for the in-product agent on cloud. Customers add a+ * key for one or more providers — Anthropic, OpenAI, Google Gemini,+ * Microsoft Azure OpenAI, OpenRouter — and pick the one Chat uses; the chat+ * endpoint reads it back per turn (encrypted at rest, see+ * web/src/lib/agent/key-encryption.ts).+ *+ * The plaintext is never returned from the server — `last4` is enough to+ * render the "…abcd" chip without a decrypt round-trip. On every change we+ * just refetch.+ */+export function AiProvidersSection() {+ const t = useTranslations('settings');+ const tCommon = useTranslations('common');+ const { canAdmin } = useUserRole();+ const [saved, setSaved] = useState<SavedProvider[] | null>(null);+ const [editing, setEditing] = useState<AiProvider | null>(null);+ const [switching, setSwitching] = useState<AiProvider | null>(null);+ // The key the remove dialog asks about; kept while the dialog fades out.+ const [confirmRemove, setConfirmRemove] = useState<AiProvider | null>(null);+ const [removeOpen, setRemoveOpen] = useState(false);+ const [removing, setRemoving] = useState(false);++ const name = (provider: AiProvider) => t(`agent_providers.${provider}.name`);++ const load = useCallback(async () => {+ try {+ const res = await fetch('/api/settings/ai-providers');+ const body = (await res.json()) as { providers?: SavedProvider[]; error?: string };+ if (!res.ok) throw new Error(body.error || 'Failed to load');+ setSaved(body.providers ?? []);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to load');+ setSaved((current) => current ?? []);+ }+ }, []);++ useEffect(() => {+ void load();+ }, [load]);++ const handleUse = async (provider: AiProvider) => {+ setSwitching(provider);+ try {+ const res = await fetch('/api/settings/ai-providers', {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ provider }),+ });+ const body = (await res.json().catch(() => ({}))) as { error?: string };+ if (!res.ok) throw new Error(body.error || 'Failed to save');+ toast.success(t('agent_switched', { provider: name(provider) }));+ await load();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to save');+ } finally {+ setSwitching(null);+ }+ };++ const handleRemove = async (provider: AiProvider) => {+ setRemoving(true);+ try {+ const res = await fetch(`/api/settings/ai-providers?provider=${provider}`, {+ method: 'DELETE',+ });+ const body = (await res.json().catch(() => ({}))) as { error?: string };+ if (!res.ok) throw new Error(body.error || 'Failed to clear');+ toast.success(t('agent_removed'));+ await load();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to clear');+ } finally {+ setRemoving(false);+ setRemoveOpen(false);+ }+ };++ const byProvider = new Map((saved ?? []).map((row) => [row.provider, row]));++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Sparkles className="h-4 w-4" />+ {t('aiProviders')}+ </CardTitle>+ <CardDescription>{t('agent_description')}</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ {saved === null ? (+ <Skeleton className="h-64 w-full" />+ ) : (+ <>+ {!saved.some((row) => row.active) && (+ <p className="text-sm text-muted-foreground">{t('agent_noKey')}</p>+ )}+ <div className="divide-y rounded-lg border">+ {AI_PROVIDERS.map((provider) => {+ const row = byProvider.get(provider);+ return (+ <div key={provider} className="@container space-y-4 p-4" data-provider={provider}>+ <div className="flex flex-col gap-3 @lg:flex-row @lg:items-center @lg:justify-between">+ <div className="flex min-w-0 items-center gap-3">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted/50">+ <ProviderIcon provider={provider} />+ </div>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <p className="text-sm font-medium">{name(provider)}</p>+ {row?.active ? (+ <Badge+ variant="outline"+ className="gap-1 border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ >+ <CheckCircle2 className="h-3 w-3" />+ {t('agent_usedByChat')}+ </Badge>+ ) : (+ row && <Badge variant="secondary">{t('agent_keySaved')}</Badge>+ )}+ </div>+ {row ? (+ <p className="text-xs text-muted-foreground">+ {row.last4 && <code className="font-mono">…{row.last4}</code>}+ {' · '}+ {t('agent_modelInUse', {+ model: chatModelId(provider, row.settings),+ })}+ {' · '}+ {t('agent_savedAt', { date: formatDate(row.setAt) })}+ {row.setByEmail &&+ ` ${t('agent_savedBy', { email: row.setByEmail })}`}+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">+ {t(`agent_providers.${provider}.about`)}+ </p>+ )}+ </div>+ </div>++ {canAdmin && editing !== provider && (+ <div className="flex shrink-0 items-center gap-2 pl-13 @lg:pl-0">+ {row && !row.active && (+ <Button+ variant="outline"+ size="sm"+ disabled={switching !== null}+ onClick={() => void handleUse(provider)}+ >+ {switching === provider && (+ <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />+ )}+ {t('agent_useForChat')}+ </Button>+ )}+ <Button variant="outline" size="sm" onClick={() => setEditing(provider)}>+ {row ? t('agent_replace') : t('agent_addKey')}+ </Button>+ {row && (+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={`${t('agent_removeKey')}: ${name(provider)}`}+ className="text-muted-foreground hover:text-destructive"+ onClick={() => {+ setConfirmRemove(provider);+ setRemoveOpen(true);+ }}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}+ </div>+ )}+ </div>++ {canAdmin && editing === provider && (+ <ProviderKeyForm+ provider={provider}+ saved={row?.settings ?? {}}+ onCancel={() => setEditing(null)}+ onSaved={async () => {+ // Closed once the row shows the new key, not before.+ await load();+ setEditing(null);+ }}+ />+ )}+ </div>+ );+ })}+ </div>+ </>+ )}++ {!canAdmin && (+ // Server-side, `/api/settings/ai-providers` PUT/PATCH/DELETE+ // already refuse a non-admin role with a 403 — say so up front+ // instead of offering buttons that end in an unhelpful toast.+ <div className="flex items-start gap-3 rounded-md border bg-muted/40 p-3 text-sm">+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <div>+ <p className="font-medium">{t('agent_adminOnly')}</p>+ <p className="mt-1 text-muted-foreground">{t('agent_adminOnlyHint')}</p>+ </div>+ </div>+ )}++ <Dialog open={removeOpen} onOpenChange={setRemoveOpen}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('agent_removeKey')}</DialogTitle>+ <DialogDescription>+ {confirmRemove && t('agent_removeKeyConfirm', { provider: name(confirmRemove) })}+ </DialogDescription>+ </DialogHeader>++ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{tCommon('cancel')}</DialogClose>++ <Button+ type="button"+ variant="destructive"+ disabled={removing}+ onClick={(e) => {+ e.stopPropagation();+ if (confirmRemove) void handleRemove(confirmRemove);+ }}+ >+ {removing && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {t('remove')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </CardContent>+ </Card>+ );+}++/** A provider's key, and the settings it needs besides, saved together. */+function ProviderKeyForm({+ provider,+ saved,+ onCancel,+ onSaved,+}: {+ provider: AiProvider;+ saved: AiProviderSettings;+ onCancel: () => void;+ onSaved: () => Promise<void>;+}) {+ const t = useTranslations('settings');+ const tCommon = useTranslations('common');+ const [apiKey, setApiKey] = useState('');+ const [endpoint, setEndpoint] = useState(saved.endpoint ?? '');+ const [deployment, setDeployment] = useState(saved.deployment ?? '');+ const [model, setModel] = useState(saved.model ?? '');+ const [invalid, setInvalid] = useState<SettingsError | null>(null);+ const [saving, setSaving] = useState(false);+ const id = (field: string) => `ai-provider-${provider}-${field}`;++ const handleSave = async () => {+ const settings = provider === 'azure' ? { endpoint, deployment } : { model };+ const parsed = parseProviderSettings(provider, settings);+ if ('error' in parsed) {+ setInvalid(parsed.error);+ return;+ }+ setInvalid(null);+ setSaving(true);+ try {+ const res = await fetch('/api/settings/ai-providers', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ provider, apiKey: apiKey.trim(), settings: parsed.settings }),+ });+ const body = (await res.json().catch(() => ({}))) as {+ error?: string;+ field?: SettingsError;+ };+ if (body.field) {+ setInvalid(body.field);+ return;+ }+ if (!res.ok) throw new Error(body.error || 'Failed to save');+ toast.success(t('agent_saved', { provider: t(`agent_providers.${provider}.name`) }));+ await onSaved();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to save');+ } finally {+ setSaving(false);+ }+ };++ const fieldError = (field: SettingsError) =>+ invalid === field && <p className="text-xs text-destructive">{t(`agent_invalid.${field}`)}</p>;++ return (+ <form+ className="space-y-3 rounded-md border bg-muted/40 p-3"+ onSubmit={(e) => {+ e.preventDefault();+ void handleSave();+ }}+ >+ <div className="space-y-2">+ <Label htmlFor={id('key')}>{t('agent_apiKeyLabel')}</Label>+ <Input+ id={id('key')}+ type="password"+ autoComplete="off"+ spellCheck={false}+ placeholder={t(`agent_providers.${provider}.keyPlaceholder`)}+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ disabled={saving}+ className="bg-card font-mono"+ autoFocus+ />+ <p className="text-xs text-muted-foreground">+ {t.rich(`agent_providers.${provider}.keyHint`, {+ link: (chunks) => (+ <a href={KEY_LINKS[provider]} target="_blank" rel="noreferrer" className="underline">+ {chunks}+ </a>+ ),+ })}+ </p>+ </div>++ {provider === 'azure' ? (+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="space-y-2">+ <Label htmlFor={id('endpoint')}>{t('agent_endpointLabel')}</Label>+ <Input+ id={id('endpoint')}+ spellCheck={false}+ placeholder={t('agent_endpointPlaceholder')}+ value={endpoint}+ onChange={(e) => setEndpoint(e.target.value)}+ disabled={saving}+ aria-invalid={invalid === 'endpoint'}+ className="bg-card"+ />+ {fieldError('endpoint')}+ </div>+ <div className="space-y-2">+ <Label htmlFor={id('deployment')}>{t('agent_deploymentLabel')}</Label>+ <Input+ id={id('deployment')}+ spellCheck={false}+ placeholder={t('agent_deploymentPlaceholder')}+ value={deployment}+ onChange={(e) => setDeployment(e.target.value)}+ disabled={saving}+ aria-invalid={invalid === 'deployment'}+ className="bg-card"+ />+ {fieldError('deployment')}+ </div>+ </div>+ ) : (+ <div className="space-y-2">+ <Label htmlFor={id('model')}>{t('agent_modelLabel')}</Label>+ <Input+ id={id('model')}+ spellCheck={false}+ placeholder={+ provider === 'openrouter' ? OPENROUTER_MODEL_EXAMPLE : DEFAULT_MODELS[provider]+ }+ value={model}+ onChange={(e) => setModel(e.target.value)}+ disabled={saving}+ aria-invalid={invalid === 'model'}+ className="bg-card font-mono"+ />+ {fieldError('model') || (+ <p className="text-xs text-muted-foreground">+ {provider === 'openrouter'+ ? t('agent_openrouterModelHint', { model: OPENROUTER_MODEL_EXAMPLE })+ : t('agent_modelOptional', { model: DEFAULT_MODELS[provider] })}+ </p>+ )}+ </div>+ )}++ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" size="sm" onClick={onCancel} disabled={saving}>+ {tCommon('cancel')}+ </Button>+ <Button type="submit" size="sm" disabled={saving || !apiKey.trim()}>+ {saving && <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />}+ {tCommon('save')}+ </Button>+ </div>+ </form>+ );+}diff --git a/web/src/components/settings/organization-section.tsx b/web/src/components/settings/organization-section.tsxindex 5887bd21e..caf7bc6ab 100644--- a/web/src/components/settings/organization-section.tsx+++ b/web/src/components/settings/organization-section.tsx@@ -25,7 +25,7 @@ import {* not exposed for editing — it is used in external integrations and must* remain stable.*- * Follows the TeamSection / AgentSection pattern exactly:+ * Follows the TeamSection / AiProvidersSection pattern exactly:* - load via useEffect / useCallback* - Skeleton while loading* - admin-gate via useUserRole().canAdmindiff --git a/web/src/config/plans.ts b/web/src/config/plans.tsindex 26f0786fd..1e22b2d07 100644--- a/web/src/config/plans.ts+++ b/web/src/config/plans.ts@@ -192,7 +192,7 @@ export const PLANS: Record<PlanId, Plan> = {'custom_reports','api_access',// Cloud is BYOK across the board: the customer pastes their own- // Anthropic key in Settings → Agent and we just use it. Plan no+ // provider key in Settings › AI Providers and we just use it. Plan no// longer gates the feature — only "did you paste a key?" does.// Self-host gets the feature unconditionally via env.'ai_agent',diff --git a/web/src/hooks/use-agent-key-status.ts b/web/src/hooks/use-agent-key-status.tsindex f228f1f57..0d3fa58bd 100644--- a/web/src/hooks/use-agent-key-status.ts+++ b/web/src/hooks/use-agent-key-status.ts@@ -3,7 +3,7 @@import { useEffect, useState } from 'react';/**- * Module-level cache so we only hit /api/settings/anthropic-key once per+ * Module-level cache so we only hit /api/settings/ai-providers once per* page-load session — not on every navigation. The sidebar and mobile nav* both consume this hook; sharing the cache means a single inflight request* even when both components mount simultaneously (e.g. on a resize boundary).@@ -19,7 +19,7 @@ export function fetchKeyStatus(): Promise<void> {if (fetchPromise) return fetchPromise;fetchPromise = (async () => {try {- const res = await fetch('/api/settings/anthropic-key');+ const res = await fetch('/api/settings/ai-providers');if (!res.ok) {cachedStatus = 'missing';return;@@ -39,7 +39,7 @@ export function getCachedStatus() {}/**- * Returns whether the org has saved an Anthropic API key.+ * Returns whether the org has a provider key for Chat to use.** On self-host (`isCloud === false`) this is a no-op — the key lives in the* server env and no network call is made. Only cloud instances probe thediff --git a/web/src/hooks/use-user-role.ts b/web/src/hooks/use-user-role.tsindex c7a914b96..8bd27812d 100644--- a/web/src/hooks/use-user-role.ts+++ b/web/src/hooks/use-user-role.ts@@ -7,7 +7,7 @@ export interface UserRoleInfo {role: TeamRole;/** admin or manager — can write to prompts, brands, topics, etc. */canManage: boolean;- /** admin only — can manage team members, API keys, billing, the Anthropic key. */+ /** admin only — can manage team members, API keys, billing, AI provider keys. */canAdmin: boolean;}@@ -17,7 +17,7 @@ export interface UserRoleInfo {* matches the admin-or-manager RLS gate used across `prompts`,* `prompt_sets`, `brand_domains`, `content_opportunities`, etc.;* `canAdmin` is the stricter admin-only gate used by team management- * and the Settings → Agent API key.+ * and Settings › AI Providers' keys.** The plan-gating equivalent is [`useFeatureGate`](./use-feature-gate.ts).* They compose cleanly: feature gate decides "is this product surfacediff --git a/web/src/lib/agent/key-encryption.ts b/web/src/lib/agent/key-encryption.tsindex 23a52f77b..bbd446a84 100644--- a/web/src/lib/agent/key-encryption.ts+++ b/web/src/lib/agent/key-encryption.ts@@ -1,7 +1,7 @@import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';/**- * App-level encryption for Anthropic API keys stored on `organizations`.+ * App-level encryption for the AI provider keys in `organization_ai_keys`.** Tradeoff vs. Supabase Vault / pgsodium: doing this at the app layer keeps* the only thing that can decrypt the key out of the database entirely —@@ -96,8 +96,8 @@ export function decryptApiKey(envelopeJson: string | null | undefined): string |/*** Last 4 chars of the plaintext, returned to the UI for "sk-…abcd" display.- * Mirrored into `organizations.anthropic_api_key_last4` so reading it back- * doesn't require decrypt.+ * Mirrored into `organization_ai_keys.key_last4` so reading it back doesn't+ * require decrypt.*/export function last4(plaintext: string): string {return plaintext.slice(-4);diff --git a/web/src/lib/agent/key.test.ts b/web/src/lib/agent/key.test.tsnew file mode 100644index 000000000..cc2400e04--- /dev/null+++ b/web/src/lib/agent/key.test.ts@@ -0,0 +1,85 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The provider and key Chat uses: the organization's active key on cloud,+ * the operator's Anthropic key on self-host.+ */++let row: unknown;+const eqs: [string, unknown][] = [];++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => {+ const chain = {+ select: () => chain,+ eq: (col: string, val: unknown) => {+ eqs.push([col, val]);+ return chain;+ },+ maybeSingle: async () => ({ data: row, error: null }),+ };+ return chain;+ },+ },+}));++vi.mock('@/lib/agent/key-encryption', () => ({+ decryptApiKey: (envelope: string) => (envelope === 'bad' ? null : `plain(${envelope})`),+}));++const { isAgentKeyConfigured, resolveAgentModelConfig } = await import('./key');++beforeEach(() => {+ row = null;+ eqs.length = 0;+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('resolveAgentModelConfig', () => {+ it("uses the organization's active key, with its provider and settings, on cloud", async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ vi.stubEnv('ANTHROPIC_API_KEY', 'operator-key');+ row = { provider: 'openrouter', key_encrypted: 'env1', settings: { model: 'openai/gpt-5.5' } };+ expect(await resolveAgentModelConfig('org1')).toEqual({+ provider: 'openrouter',+ apiKey: 'plain(env1)',+ settings: { model: 'openai/gpt-5.5' },+ });+ expect(eqs).toEqual([+ ['organization_id', 'org1'],+ ['active', true],+ ]);+ });++ it('is null on cloud without an active key, or with one that no longer decrypts', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ vi.stubEnv('ANTHROPIC_API_KEY', 'operator-key');+ expect(await resolveAgentModelConfig('org1')).toBeNull();+ row = { provider: 'openai', key_encrypted: 'bad', settings: {} };+ expect(await resolveAgentModelConfig('org1')).toBeNull();+ });++ it("uses the operator's Anthropic key on self-host", async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ vi.stubEnv('ANTHROPIC_API_KEY', 'operator-key');+ expect(await resolveAgentModelConfig('org1')).toEqual({+ provider: 'anthropic',+ apiKey: 'operator-key',+ settings: {},+ });+ expect(eqs).toHaveLength(0);+ });+});++describe('isAgentKeyConfigured', () => {+ it('asks whether the organization has an active key on cloud', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ expect(await isAgentKeyConfigured('org1')).toBe(false);+ row = { provider: 'google' };+ expect(await isAgentKeyConfigured('org1')).toBe(true);+ });+});diff --git a/web/src/lib/agent/key.ts b/web/src/lib/agent/key.tsindex 04e1c862e..1054fcac2 100644--- a/web/src/lib/agent/key.ts+++ b/web/src/lib/agent/key.ts@@ -1,35 +1,48 @@import { supabaseAdmin } from '@/lib/supabase/admin';import { isCloud } from '@/config/plans';import { decryptApiKey } from '@/lib/agent/key-encryption';+import type { AgentModelConfig } from '@/lib/agent/model';+import { isAiProvider, type AiProviderSettings } from '@/lib/agent/providers';/**- * Resolve the Anthropic API key that the agent should use for this org.+ * Resolve the provider and API key that the agent should use for this org.** - **Self-host** (`isCloud() === false`): falls back to the operator's- * own `ANTHROPIC_API_KEY` env var. The org table is ignored — self-host+ * own `ANTHROPIC_API_KEY` env var. The org's keys are ignored — self-host* instances belong to one customer who configures the model centrally.- * - **Cloud**: reads `organizations.anthropic_api_key_encrypted`, decrypts- * via `decryptApiKey`, and returns the plaintext. Returns `null` if the- * org hasn't set a key yet or if the envelope can't be decrypted (master- * key rotated without re-saving, malformed row, etc.) — callers turn- * that into a 403 + "set a key in Settings" CTA.+ * - **Cloud**: reads the org's active row in `organization_ai_keys` (the+ * provider picked in Settings › AI Providers), decrypts its key via+ * `decryptApiKey`, and returns it with the provider's settings. Returns+ * `null` if the org hasn't set a key yet or if the envelope can't be+ * decrypted (master key rotated without re-saving, malformed row, etc.) —+ * callers turn that into a 403 + "set a key in Settings" CTA.** Never logs the plaintext. Never returns the env key on cloud (avoid the* footgun of one customer falling back to Ansvisor's own quota).*/-export async function resolveAnthropicKey(organizationId: string): Promise<string | null> {+export async function resolveAgentModelConfig(+ organizationId: string,+): Promise<AgentModelConfig | null> {if (!isCloud()) {- return process.env.ANTHROPIC_API_KEY ?? null;+ const apiKey = process.env.ANTHROPIC_API_KEY;+ return apiKey ? { provider: 'anthropic', apiKey, settings: {} } : null;}const { data } = await supabaseAdmin- .from('organizations')- .select('anthropic_api_key_encrypted')- .eq('id', organizationId)+ .from('organization_ai_keys')+ .select('provider, key_encrypted, settings')+ .eq('organization_id', organizationId)+ .eq('active', true).maybeSingle();- if (!data?.anthropic_api_key_encrypted) return null;- return decryptApiKey(data.anthropic_api_key_encrypted);+ if (!data?.key_encrypted || !isAiProvider(data.provider)) return null;+ const apiKey = decryptApiKey(data.key_encrypted);+ if (!apiKey) return null;+ return {+ provider: data.provider,+ apiKey,+ settings: (data.settings ?? {}) as AiProviderSettings,+ };}/**@@ -37,14 +50,15 @@ export async function resolveAnthropicKey(organizationId: string): Promise<strin* page-load gating where we only need to know whether to render the chat* UI vs the "set a key" empty state.*/-export async function isAnthropicKeyConfigured(organizationId: string): Promise<boolean> {+export async function isAgentKeyConfigured(organizationId: string): Promise<boolean> {if (!isCloud()) {return !!process.env.ANTHROPIC_API_KEY;}const { data } = await supabaseAdmin- .from('organizations')- .select('anthropic_api_key_encrypted')- .eq('id', organizationId)+ .from('organization_ai_keys')+ .select('provider')+ .eq('organization_id', organizationId)+ .eq('active', true).maybeSingle();- return !!data?.anthropic_api_key_encrypted;+ return !!data;}diff --git a/web/src/lib/agent/model.test.ts b/web/src/lib/agent/model.test.tsnew file mode 100644index 000000000..af7352040--- /dev/null+++ b/web/src/lib/agent/model.test.ts@@ -0,0 +1,73 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AGENT_PROVIDER_OPTIONS, buildAgentModel, type AgentModel } from './model';++/** Chat's model for each AI provider, called with the organization's own key. */++const KEY = 'test-key-0123456789abcdef';++/** The request a model sends, caught before it leaves. */+async function firstRequest(model: AgentModel) {+ const fetch = vi.fn(async () => new Response('{}', { status: 418 }));+ vi.stubGlobal('fetch', fetch);+ await Promise.resolve(+ model.doGenerate({+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],+ providerOptions: AGENT_PROVIDER_OPTIONS,+ }),+ ).catch(() => {});+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];+ return { url, headers: new Headers(init.headers), body: JSON.parse(String(init.body)) };+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('buildAgentModel', () => {+ it("calls each first-party provider's default model, or the one named", async () => {+ const anthropic = buildAgentModel({ provider: 'anthropic', apiKey: KEY, settings: {} });+ expect([anthropic.provider, anthropic.modelId]).toEqual([+ 'anthropic.messages',+ 'claude-sonnet-5',+ ]);+ const openai = buildAgentModel({ provider: 'openai', apiKey: KEY, settings: {} });+ expect([openai.provider, openai.modelId]).toEqual(['openai.responses', 'gpt-5.5']);+ expect((await firstRequest(openai)).body.store).toBe(false);+ const google = buildAgentModel({+ provider: 'google',+ apiKey: KEY,+ settings: { model: 'gemini-3.1-pro-preview' },+ });+ expect([google.provider, google.modelId]).toEqual([+ 'google.generative-ai',+ 'gemini-3.1-pro-preview',+ ]);+ });++ it("calls an Azure deployment on the resource's own endpoint", async () => {+ const model = buildAgentModel({+ provider: 'azure',+ apiKey: KEY,+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'gpt-5-chat' },+ });+ expect(model.modelId).toBe('gpt-5-chat');+ const { url, headers, body } = await firstRequest(model);+ expect(url).toBe('https://acme.openai.azure.com/openai/v1/responses?api-version=v1');+ expect(headers.get('api-key')).toBe(KEY);+ // Chat keeps its history: nothing stored for it to refer back to.+ expect(body.store).toBe(false);+ });++ it("calls OpenRouter's Chat Completions with the model named", async () => {+ const model = buildAgentModel({+ provider: 'openrouter',+ apiKey: KEY,+ settings: { model: 'openai/gpt-5.5' },+ });+ expect([model.provider, model.modelId]).toEqual(['openai.chat', 'openai/gpt-5.5']);+ const { url, headers } = await firstRequest(model);+ expect(url).toBe('https://openrouter.ai/api/v1/chat/completions');+ expect(headers.get('authorization')).toBe(`Bearer ${KEY}`);+ expect(headers.get('x-title')).toBe('Ansvisor');+ });+});diff --git a/web/src/lib/agent/model.ts b/web/src/lib/agent/model.tsindex 4db8a68d0..111b28450 100644--- a/web/src/lib/agent/model.ts+++ b/web/src/lib/agent/model.ts@@ -1,17 +1,61 @@-import { createAnthropic, type AnthropicProvider } from '@ai-sdk/anthropic';+import { createAnthropic } from '@ai-sdk/anthropic';+import { createAzure } from '@ai-sdk/azure';+import { createGoogleGenerativeAI } from '@ai-sdk/google';+import { createOpenAI } from '@ai-sdk/openai';+import { chatModelId, type AiProvider, type AiProviderSettings } from './providers';++/** A provider SDK's language model — each of them builds the same kind. */+export type AgentModel = ReturnType<ReturnType<typeof createOpenAI>>;++/**+ * OpenAI's Responses API (and Azure's) stores each response by default, and+ * saved turns would then go back as references to those stored items rather+ * than as text: a key from another project, an expired item or zero data+ * retention fails the thread with "item not found". The app keeps the whole+ * history itself.+ */+export const AGENT_PROVIDER_OPTIONS = {+ openai: { store: false },+ azure: { store: false },+};++/** The provider, key and settings Chat calls a model with. */+export interface AgentModelConfig {+ provider: AiProvider;+ apiKey: string;+ settings: AiProviderSettings;+}/*** Builds the in-product agent's LLM with the caller-supplied API key.*- * We can't export a singleton model anymore — on cloud each org brings its- * own Anthropic key (Settings → Agent), so the key is request-scoped. The- * chat route resolves the key per turn via `resolveAnthropicKey(orgId)`- * and hands it to this builder; self-host passes the operator's env key.+ * The key is request-scoped: on cloud each org brings its own key for the+ * provider it picked in Settings › AI Providers, and the chat route resolves+ * it per turn via `resolveAgentModelConfig(orgId)`; self-host passes the+ * operator's env Anthropic key.*- * Model choice (claude-sonnet-5) matches the tracking flow's Claude+ * Anthropic's default (claude-sonnet-5) matches the tracking flow's Claude* option so behavior + cost shape stay consistent across the product.*/-export function buildAgentModel(apiKey: string): ReturnType<AnthropicProvider> {- const anthropic = createAnthropic({ apiKey });- return anthropic('claude-sonnet-5');+export function buildAgentModel({ provider, apiKey, settings }: AgentModelConfig): AgentModel {+ const model = chatModelId(provider, settings);+ switch (provider) {+ case 'anthropic':+ return createAnthropic({ apiKey })(model);+ case 'openai':+ return createOpenAI({ apiKey })(model);+ case 'google':+ return createGoogleGenerativeAI({ apiKey })(model);+ case 'azure':+ // The resource's own endpoint (checked against Azure's hosts when it+ // was saved); the SDK adds /v1 and calls the deployment by name.+ return createAzure({ apiKey, baseURL: `${settings.endpoint}/openai` })(model);+ case 'openrouter':+ // OpenRouter speaks Chat Completions, not OpenAI's default Responses API.+ return createOpenAI({+ apiKey,+ baseURL: 'https://openrouter.ai/api/v1',+ headers: { 'HTTP-Referer': 'https://ansvisor.com', 'X-Title': 'Ansvisor' },+ }).chat(model);+ }}diff --git a/web/src/lib/agent/providers.test.ts b/web/src/lib/agent/providers.test.tsnew file mode 100644index 000000000..b6bc2ab21--- /dev/null+++ b/web/src/lib/agent/providers.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';+import { azureEndpoint, chatModelId, isAiProvider, parseProviderSettings } from './providers';++/** What each AI provider keeps besides its key, and the model Chat calls with it. */++describe('isAiProvider', () => {+ it('knows the five providers only', () => {+ expect(['anthropic', 'openai', 'google', 'azure', 'openrouter'].every(isAiProvider)).toBe(true);+ expect(isAiProvider('copilot')).toBe(false);+ expect(isAiProvider(null)).toBe(false);+ });+});++describe('azureEndpoint', () => {+ it("keeps an Azure resource's https origin", () => {+ expect(azureEndpoint(' https://acme.openai.azure.com/openai/v1/ ')).toBe(+ 'https://acme.openai.azure.com',+ );+ expect(azureEndpoint('https://acme.cognitiveservices.azure.com')).toBe(+ 'https://acme.cognitiveservices.azure.com',+ );+ expect(azureEndpoint('https://acme.services.ai.azure.com/models')).toBe(+ 'https://acme.services.ai.azure.com',+ );+ });++ it('refuses other hosts, plain http, ports and credentials', () => {+ expect(azureEndpoint('https://openai.azure.com.evil.example')).toBeNull();+ expect(azureEndpoint('https://localhost')).toBeNull();+ expect(azureEndpoint('http://acme.openai.azure.com')).toBeNull();+ expect(azureEndpoint('https://acme.openai.azure.com:8443')).toBeNull();+ expect(azureEndpoint('https://u:[email protected]')).toBeNull();+ expect(azureEndpoint('acme')).toBeNull();+ });+});++describe('parseProviderSettings', () => {+ it("keeps Azure's endpoint and deployment, and names the one that's wrong", () => {+ expect(+ parseProviderSettings('azure', {+ endpoint: 'https://acme.openai.azure.com/',+ deployment: ' gpt-5-chat ',+ model: 'ignored',+ }),+ ).toEqual({+ settings: { endpoint: 'https://acme.openai.azure.com', deployment: 'gpt-5-chat' },+ });+ expect(+ parseProviderSettings('azure', { endpoint: 'https://x.example', deployment: 'a' }),+ ).toEqual({ error: 'endpoint' });+ expect(+ parseProviderSettings('azure', { endpoint: 'https://acme.openai.azure.com', deployment: '' }),+ ).toEqual({ error: 'deployment' });+ });++ it('needs an OpenRouter model with its maker in the id', () => {+ expect(parseProviderSettings('openrouter', { model: 'openai/gpt-5.5' })).toEqual({+ settings: { model: 'openai/gpt-5.5' },+ });+ expect(parseProviderSettings('openrouter', { model: 'gpt-5.5' })).toEqual({ error: 'model' });+ expect(parseProviderSettings('openrouter', {})).toEqual({ error: 'model' });+ });++ it('lets the first-party providers keep their default model, or name another', () => {+ expect(parseProviderSettings('openai', { model: ' ' })).toEqual({ settings: {} });+ expect(parseProviderSettings('google', undefined)).toEqual({ settings: {} });+ expect(parseProviderSettings('anthropic', { model: 'claude-opus-4-8' })).toEqual({+ settings: { model: 'claude-opus-4-8' },+ });+ expect(parseProviderSettings('openai', { model: 'gpt 5' })).toEqual({ error: 'model' });+ // The id can land in a URL path: no `..`, and `/` only on OpenRouter.+ expect(parseProviderSettings('google', { model: '../v1/files' })).toEqual({ error: 'model' });+ expect(parseProviderSettings('openai', { model: 'org/gpt-5.5' })).toEqual({ error: 'model' });+ expect(parseProviderSettings('openrouter', { model: 'openai/../x' })).toEqual({+ error: 'model',+ });+ });+});++describe('chatModelId', () => {+ it("is the named model, the provider's default, or Azure's deployment", () => {+ expect(chatModelId('anthropic', {})).toBe('claude-sonnet-5');+ expect(chatModelId('openai', {})).toBe('gpt-5.5');+ expect(chatModelId('google', { model: 'gemini-3.1-pro-preview' })).toBe(+ 'gemini-3.1-pro-preview',+ );+ expect(chatModelId('azure', { endpoint: 'https://a.openai.azure.com', deployment: 'd1' })).toBe(+ 'd1',+ );+ expect(chatModelId('openrouter', { model: 'openai/gpt-5.5' })).toBe('openai/gpt-5.5');+ });+});diff --git a/web/src/lib/agent/providers.ts b/web/src/lib/agent/providers.tsnew file mode 100644index 000000000..f3562f5a1--- /dev/null+++ b/web/src/lib/agent/providers.ts@@ -0,0 +1,86 @@+/**+ * The AI providers an organization can add a key for in Settings › AI+ * Providers, and what each needs besides the key. Shared by the settings+ * route, Chat and the settings form — no SDK imports here.+ */++export const AI_PROVIDERS = ['anthropic', 'openai', 'google', 'azure', 'openrouter'] as const;+export type AiProvider = (typeof AI_PROVIDERS)[number];++/** What a provider keeps besides the key: Azure's endpoint and deployment, a model. */+export interface AiProviderSettings {+ endpoint?: string;+ deployment?: string;+ model?: string;+}++/** The model Chat uses when the settings name none (Azure uses its deployment). */+export const DEFAULT_MODELS: Record<Exclude<AiProvider, 'azure' | 'openrouter'>, string> = {+ anthropic: 'claude-sonnet-5',+ openai: 'gpt-5.5',+ google: 'gemini-3.5-flash',+};++/** An OpenRouter model id, shown as the example: they name the model's maker. */+export const OPENROUTER_MODEL_EXAMPLE = 'openai/gpt-5.5';++/** Hosts an Azure OpenAI endpoint may be on — the ones @ai-sdk/azure treats as Azure. */+const AZURE_HOSTS = ['.openai.azure.com', '.services.ai.azure.com', '.cognitiveservices.azure.com'];++const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;+const DEPLOYMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;++export function isAiProvider(value: unknown): value is AiProvider {+ return typeof value === 'string' && (AI_PROVIDERS as readonly string[]).includes(value);+}++/** An Azure OpenAI endpoint as its https origin, or null when it isn't one. */+export function azureEndpoint(value: string): string | null {+ let url: URL;+ try {+ url = new URL(value.trim());+ } catch {+ return null;+ }+ if (url.protocol !== 'https:' || url.port || url.username || url.password) return null;+ return AZURE_HOSTS.some((host) => url.hostname.endsWith(host)) ? url.origin : null;+}++export type SettingsError = 'endpoint' | 'deployment' | 'model';++/**+ * The settings a provider keeps, read from a request body: only its own+ * fields, trimmed. An error names the field that is missing or malformed.+ */+export function parseProviderSettings(+ provider: AiProvider,+ raw: unknown,+): { settings: AiProviderSettings } | { error: SettingsError } {+ const input = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;+ const text = (key: string) => (typeof input[key] === 'string' ? input[key].trim() : '');++ if (provider === 'azure') {+ const endpoint = azureEndpoint(text('endpoint'));+ if (!endpoint) return { error: 'endpoint' };+ const deployment = text('deployment');+ if (!DEPLOYMENT.test(deployment)) return { error: 'deployment' };+ return { settings: { endpoint, deployment } };+ }++ const model = text('model');+ // OpenRouter has no default: its ids name the model's maker.+ if (provider === 'openrouter' && !model.includes('/')) return { error: 'model' };+ if (!model) return { settings: {} };+ // Some SDKs put the id in the URL's path (Gemini): no `..`, and a `/` only+ // where OpenRouter's ids need one.+ if (!MODEL_ID.test(model) || model.includes('..')) return { error: 'model' };+ if (provider !== 'openrouter' && model.includes('/')) return { error: 'model' };+ return { settings: { model } };+}++/** The model Chat calls for a provider and its settings. */+export function chatModelId(provider: AiProvider, settings: AiProviderSettings): string {+ if (provider === 'azure') return settings.deployment ?? '';+ if (provider === 'openrouter') return settings.model ?? '';+ return settings.model || DEFAULT_MODELS[provider];+}diff --git a/web/src/lib/agent/tools.ts b/web/src/lib/agent/tools.tsindex be0b22f41..d939e2054 100644--- a/web/src/lib/agent/tools.ts+++ b/web/src/lib/agent/tools.ts@@ -291,7 +291,21 @@ export function buildAgentTools(auth: McpAuthContext) {categoryScores: z.record(z.string(), z.unknown()).describe('Per-category audit scores.'),- recommendations: z.array(z.unknown()).describe('AI-generated audit recommendations.'),+ // Typed items, not z.unknown(): an untyped `items: {}` is a schema+ // Gemini may refuse, and that fails every Chat turn on it.+ recommendations: z+ .array(+ z.object({+ signalKey: z.string().optional(),+ label: z.string().optional(),+ category: z.string().nullable().optional(),+ priority: z.enum(['high', 'medium', 'low']).optional(),+ recommendation: z.string(),+ draft: z.string().nullable().optional(),+ code: z.string().nullable().optional(),+ }),+ )+ .describe('AI-generated audit recommendations, as get_site_audit returns them.'),signalsEvaluated: z.number().nullable().describe('Number of audit signals evaluated.'),diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 31752933c..45b99407a 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1965,6 +1965,54 @@ export type Database = {},]}+ organization_ai_keys: {+ Row: {+ active: boolean+ key_encrypted: string+ key_last4: string+ organization_id: string+ provider: string+ set_at: string+ set_by: string | null+ settings: Json+ }+ Insert: {+ active?: boolean+ key_encrypted: string+ key_last4: string+ organization_id: string+ provider: string+ set_at?: string+ set_by?: string | null+ settings?: Json+ }+ Update: {+ active?: boolean+ key_encrypted?: string+ key_last4?: string+ organization_id?: string+ provider?: string+ set_at?: string+ set_by?: string | null+ settings?: Json+ }+ Relationships: [+ {+ foreignKeyName: "organization_ai_keys_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "organization_ai_keys_set_by_fkey"+ columns: ["set_by"]+ isOneToOne: false+ referencedRelation: "profiles"+ referencedColumns: ["id"]+ },+ ]+ }organizations: {Row: {anthropic_api_key_encrypted: string | null@@ -4194,6 +4242,10 @@ export type Database = {Args: { p_brand_id: string; p_day_from: string; p_day_to: string }Returns: undefined}+ remove_ai_provider_key: {+ Args: { p_organization_id: string; p_provider: string }+ Returns: string+ }report_citation_evidence: {Args: {p_brand_id: string@@ -4275,6 +4327,14 @@ export type Database = {Args: { p_brand_id: string; p_kpis: Json }Returns: boolean}+ set_active_ai_provider: {+ Args: {+ p_only_if_none?: boolean+ p_organization_id: string+ p_provider: string+ }+ Returns: boolean+ }share_of_voice_aggregates: {Args: {p_brand_id: stringdiff --git a/web/yarn.lock b/web/yarn.lockindex d835066ec..de29a54f1 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -10,6 +10,24 @@"@ai-sdk/provider" "3.0.10""@ai-sdk/provider-utils" "4.0.27"+"@ai-sdk/azure@^3.0.141":+ version "3.0.141"+ resolved "https://registry.yarnpkg.com/@ai-sdk/azure/-/azure-3.0.141.tgz#64a84e4449716f55068af024424699c33355a188"+ integrity sha512-1lG0C9njLmI33YEN/O17EozJ3xV/p1nItt7vnAZyetwf847C1m1YesU2ExcIf/pMwlJII9sRWAmie+kJusyQBA==+ dependencies:+ "@ai-sdk/deepseek" "2.0.76"+ "@ai-sdk/openai" "3.0.130"+ "@ai-sdk/provider" "3.0.19"+ "@ai-sdk/provider-utils" "4.0.61"++"@ai-sdk/[email protected]":+ version "2.0.76"+ resolved "https://registry.yarnpkg.com/@ai-sdk/deepseek/-/deepseek-2.0.76.tgz#92dd9c6d77ef7b2ab5d3c8602dd1f5043174a351"+ integrity sha512-nXndej2BhgAtEk4P43IcXTrg6+X/6C/xIC9hp+vS6ayCi0+YrTRRu6YcX8E8p3OA/TNmpExhWuyOD5HRnEJJZg==+ dependencies:+ "@ai-sdk/provider" "3.0.19"+ "@ai-sdk/provider-utils" "4.0.61"+"@ai-sdk/[email protected]":version "3.0.121"resolved "https://registry.yarnpkg.com/@ai-sdk/gateway/-/gateway-3.0.121.tgz#14cd9daa48516ad5a8023c8889d8a63e254fe77e"@@ -19,6 +37,22 @@"@ai-sdk/provider-utils" "4.0.27""@vercel/oidc" "3.2.0"+"@ai-sdk/google@^3.0.135":+ version "3.0.135"+ resolved "https://registry.yarnpkg.com/@ai-sdk/google/-/google-3.0.135.tgz#b03663e4490f581e42a4f3d2fc8780f82a82a4a3"+ integrity sha512-iz75FLJNBzWKhP7ToildSmrblH+0wuoSXMZiuX+A3+kCBZaGEfVdDre97HAEQ68BLKuJB0ucaCvZZUD5UeH9CA==+ dependencies:+ "@ai-sdk/provider" "3.0.19"+ "@ai-sdk/provider-utils" "4.0.61"++"@ai-sdk/[email protected]", "@ai-sdk/openai@^3.0.130":+ version "3.0.130"+ resolved "https://registry.yarnpkg.com/@ai-sdk/openai/-/openai-3.0.130.tgz#3687061824c6faafe119cb158ed5a23d2b442551"+ integrity sha512-4v0HiJBv2Y/e3HBuKKbcXVCMQHJLVcO4BUMs019+vGOIMCLSwDrugMIM3CWmMkGHwhqyHWvPUUMSdlJciSH6Eg==+ dependencies:+ "@ai-sdk/provider" "3.0.19"+ "@ai-sdk/provider-utils" "4.0.61"+"@ai-sdk/[email protected]":version "4.0.27"resolved "https://registry.yarnpkg.com/@ai-sdk/provider-utils/-/provider-utils-4.0.27.tgz#d2183685768626bcf1c968b7d73ea2b974da59b9"@@ -28,6 +62,16 @@"@standard-schema/spec" "^1.1.0"eventsource-parser "^3.0.8"+"@ai-sdk/[email protected]":+ version "4.0.61"+ resolved "https://registry.yarnpkg.com/@ai-sdk/provider-utils/-/provider-utils-4.0.61.tgz#8ff7e3d4295af997e25659b3792349e540ea0c69"+ integrity sha512-spROQutwsgm9ezXdoKP5PUPuHnNqMnuFqjioihmYDMJaaJnknYiEXYctH9hL4NJjaHuQBIl4ageCNsIZrQ+yCg==+ dependencies:+ "@ai-sdk/provider" "3.0.19"+ "@standard-schema/spec" "^1.1.0"+ eventsource-parser "^3.0.8"+ undici "^6.28.0"+"@ai-sdk/[email protected]":version "3.0.10"resolved "https://registry.yarnpkg.com/@ai-sdk/provider/-/provider-3.0.10.tgz#abfb6776f699951f9b8ac20cf1d42a3fc7d79752"@@ -35,6 +79,13 @@dependencies:json-schema "^0.4.0"+"@ai-sdk/[email protected]":+ version "3.0.19"+ resolved "https://registry.yarnpkg.com/@ai-sdk/provider/-/provider-3.0.19.tgz#9adebbcb183f41d6f726f00efd528485b58d56d3"+ integrity sha512-5lWq7zSfRaU5ylDESn3sDQjgGl2AI1vjZKO/6JY3aFW70ct4zcP1kN+ZUYOuTXr28fVsYbyu2YFhddLdIgQFZQ==+ dependencies:+ json-schema "^0.4.0"+"@ai-sdk/react@^3.0.81":version "3.0.195"resolved "https://registry.yarnpkg.com/@ai-sdk/react/-/react-3.0.195.tgz#dc74b0b27cddbc316433119edb9aaba161b4aa49"@@ -8364,6 +8415,11 @@ undici-types@~7.21.0:resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.21.0.tgz#433f7dd1b5daa9ab4dacb721a5e11a8de51eadda"integrity sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==+undici@^6.28.0:+ version "6.29.1"+ resolved "https://registry.yarnpkg.com/undici/-/undici-6.29.1.tgz#a3317c5df0236e0633727d9a7bd4f7ed195d8575"+ integrity sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==+unicode-properties@^1.4.0, unicode-properties@^1.4.1:version "1.4.1"resolved "https://registry.yarnpkg.com/unicode-properties/-/unicode-properties-1.4.1.tgz#96a9cffb7e619a0dc7368c28da27e05fc8f9be5f"