The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: redesign AI settings (#72041)
Maksym Yakubychb395d978686e
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 91f8a7e84a5..f9bd1d9ba24 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -155,14 +155,17 @@agent-api{:team "Metabot"- :api #{metabase.agent-api.api}+ :api #{metabase.agent-api.api+ metabase.agent-api.init}:uses #{apiauth-identitylib+ llmmetabotquery-processorrequestserver+ settingsutil}:model-imports #{:model/User}}@@ -1152,6 +1155,7 @@apiapi-scopeconfig+ llmoauth-serverrequestserver@@ -1488,6 +1492,7 @@configeventsinternal-stats+ llmsettingsstartuptaskdiff --git a/docs/ai/settings.md b/docs/ai/settings.mdindex 256ed4587a5..a3369a26a6a 100644--- a/docs/ai/settings.md+++ b/docs/ai/settings.md@@ -69,7 +69,15 @@ Toggle [Metabot](./metabot.md) on or off for your Metabase. Metabot is enabled bWhen enabled, Metabot is available to help people create questions, analyze data, and answer questions about your data. When disabled, the Metabot icon and keyboard shortcuts are hidden. Currently, Metabot is available to everyone who uses your Metabase. There's no way to scope Metabot usage per person.-Toggling off Metabot only turns off in-app Metabot features. People can still use the [MCP server](./mcp.md) and [Agent API](./agent-api.md). To turn off the MCP server and Agent API, you'll need to disconnect from the provider in **Admin > AI > Connection settings**.+Toggling off Metabot only turns off in-app Metabot features. People can still use the [MCP server](./mcp.md) and [Agent API](./agent-api.md).++### Enable MCP server++Use the **MCP server** toggle to turn external access to the [MCP server](./mcp.md) on or off.++### Enable Agent API++Use the **Agent API** toggle to turn external access to the [Agent API](./agent-api.md) on or off.### Embedded Metabotdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsxindex 82202bc5df4..493ad1ad334 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx@@ -1,13 +1,13 @@import { PLUGIN_AI_CONTROLS } from "metabase/plugins";import { hasPremiumFeature } from "metabase-enterprise/settings";-import { getAiControlsNavItems } from "./nav";+import { AiControlsNavItems } from "./nav";import { getAiControlsRoutes } from "./routes";export function initializePlugin() {if (hasPremiumFeature("ai_controls")) {PLUGIN_AI_CONTROLS.isEnabled = true;PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsRoutes;- PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsNavItems;+ PLUGIN_AI_CONTROLS.AiControlsNavItems = AiControlsNavItems;}}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsxindex 6d3c92b1536..9ead9d06554 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx@@ -1,19 +1,29 @@import { t } from "ttag";import { AdminNavItem } from "metabase/admin/components/AdminNav";+import { useSetting } from "metabase/common/hooks";import { FIXED_METABOT_IDS } from "metabase/metabot/constants";-export function getAiControlsNavItems() {+export function AiControlsNavItems() {+ const isConfigured = useSetting("llm-metabot-configured?");+ const areAiFeaturesEnabled = useSetting("ai-features-enabled?");++ if (!areAiFeaturesEnabled) {+ return null;+ }+return (<><AdminNavItemicon="lock"label={t`Usage controls`}folderPattern="usage-controls"+ disabled={!isConfigured}><AdminNavItemlabel={t`AI feature access`}path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/usage-controls/ai-feature-access`}+ disabled={!isConfigured}/><AdminNavItemlabel={t`AI usage limits`}@@ -24,23 +34,28 @@ export function getAiControlsNavItems() {icon="palette"label={t`Customization`}path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/customization`}+ disabled={!isConfigured}/><AdminNavItemicon="document"label={t`System prompts`}folderPattern="system-prompts"+ disabled={!isConfigured}><AdminNavItemlabel={t`Metabot chat`}path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/metabot-chat`}+ disabled={!isConfigured}/><AdminNavItemlabel={t`Natural language queries`}path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/natural-language-queries`}+ disabled={!isConfigured}/><AdminNavItemlabel={t`SQL generation`}path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/sql-generation`}+ disabled={!isConfigured}/></AdminNavItem></>diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsxindex f10cef20afb..b06f921216a 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx@@ -1,14 +1,15 @@-import { useState } from "react";+import { useCallback, useState } from "react";import { match } from "ts-pattern";import { jt, t } from "ttag";+import { useUpdateMetabotSettingsMutation } from "metabase/api";import { getErrorMessage } from "metabase/api/utils";import { useSetting } from "metabase/common/hooks";+import { useMetabotSetupContext } from "metabase/metabot/components/MetabotAdmin/MetabotSetup";import { getStoreUsers } from "metabase/selectors/store-users";import {Anchor,Box,- Button,Checkbox,Flex,Group,@@ -38,23 +39,22 @@ import { usePurchaseMetabaseManagedAi } from "../../usePurchaseMetabaseManagedAiimport { MetabotSettingUpModal } from "./MetabotSettingUpModal";-type MetabaseAIProviderSetupProps = {- isMetabaseProviderConnected: boolean;- isSavingMetabaseConnection: boolean;- onConnect: () => Promise<void>;-};--export function MetabaseAIProviderSetup({- isMetabaseProviderConnected,- isSavingMetabaseConnection,- onConnect,-}: MetabaseAIProviderSetupProps) {+export function MetabaseAIProviderSetup() {const llmProxyConfigured = useSetting("llm-proxy-configured?");const hasMetabaseManagedAiProviderFeature = !!hasPremiumFeature(METABASE_MANAGED_AI_FEATURE,);const { isStoreUser, anyStoreUserEmailAddress } = useSelector(getStoreUsers);+ const isConfigured = useSetting("llm-metabot-configured?");++ const [updateMetabotSettings, updateMetabotSettingsResult] =+ useUpdateMetabotSettingsMutation();++ const handleConnect = useCallback(async () => {+ await updateMetabotSettings({ provider: "metabase", model: "" }).unwrap();+ }, [updateMetabotSettings]);+const {pricing: metabaseManagedAiPricing,isLoading: isLoadingMetabaseManagedAiPricing,@@ -65,14 +65,7 @@ export function MetabaseAIProviderSetup({const [hasAcceptedTerms, setHasAcceptedTerms] = useState(false);const [isSettingUpModalOpen, setIsSettingUpModalOpen] = useState(false);- const metabaseManagedAiPurchaseError = metabaseManagedAiPurchase.error- ? getErrorMessage(- metabaseManagedAiPurchase.error,- t`Unable to connect to this AI provider.`,- )- : undefined;-- const handleMetabasePurchase = async () => {+ const handleMetabasePurchase = useCallback(async () => {setIsSettingUpModalOpen(true);try {@@ -82,11 +75,42 @@ export function MetabaseAIProviderSetup({} catch {setIsSettingUpModalOpen(false);}- };+ }, [hasAcceptedTerms, metabaseManagedAiPurchase]);++ const onConnect = match({+ hasAcceptedTerms,+ hasMetabaseManagedAiProviderFeature,+ isConfigured,+ isStoreUser,+ })+ .with(+ { hasMetabaseManagedAiProviderFeature: false, hasAcceptedTerms: false },+ () => null,+ )+ .with({ isConfigured: true }, () => null)+ .with({ hasMetabaseManagedAiProviderFeature: true }, () => handleConnect)+ .with({ isStoreUser: false }, () => null)+ .otherwise(() => handleMetabasePurchase);++ const { isLoading } = useMetabotSetupContext(onConnect);++ const metabaseManagedAiPurchaseError = metabaseManagedAiPurchase.error+ ? getErrorMessage(+ metabaseManagedAiPurchase.error,+ t`Unable to connect to this AI provider.`,+ )+ : undefined;++ const updateMetabotSettingsError = updateMetabotSettingsResult.error+ ? getErrorMessage(+ updateMetabotSettingsResult.error,+ t`Unable to connect to this AI provider.`,+ )+ : undefined;return (<>- {isMetabaseProviderConnected ? (+ {isConfigured ? (<MetabaseManagedProviderCardisLoadingPricing={isLoadingMetabaseManagedAiPricing}pricing={metabaseManagedAiPricing}@@ -116,12 +140,7 @@ export function MetabaseAIProviderSetup({hasMetabaseManagedAiProviderFeature,isStoreUser,})- .with({ hasMetabaseManagedAiProviderFeature: true }, () => (- <Button- loading={isSavingMetabaseConnection}- onClick={onConnect}- >{t`Connect`}</Button>- ))+ .with({ hasMetabaseManagedAiProviderFeature: true }, () => null).with({ isStoreUser: false }, () => (<Text fw="bold">{/* eslint-disable-next-line metabase/no-literal-metabase-strings -- This string only shows for admins. */}@@ -129,31 +148,23 @@ export function MetabaseAIProviderSetup({</Text>)).otherwise(() => (- <Stack gap="sm">- <Checkbox- checked={hasAcceptedTerms}- onChange={(event) =>- setHasAcceptedTerms(event.currentTarget.checked)- }- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Metabase AI service- label={jt`I agree with the Metabase AI add-on ${(- <Anchor- key="metabase-ai-terms-link"- href={METABASE_MANAGED_AI_TERMS_URL}- target="_blank"- >- {t`Terms of Service`}- </Anchor>- )}`}- />- <Button- disabled={!hasAcceptedTerms}- loading={- metabaseManagedAiPurchase.isLoading || isSettingUpModalOpen- }- onClick={handleMetabasePurchase}- >{t`Connect`}</Button>- </Stack>+ <Checkbox+ checked={hasAcceptedTerms}+ disabled={isLoading}+ onChange={(event) =>+ setHasAcceptedTerms(event.currentTarget.checked)+ }+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Metabase AI service+ label={jt`I agree with the Metabase AI Service ${(+ <Anchor+ key="metabase-ai-terms-link"+ href={METABASE_MANAGED_AI_TERMS_URL}+ target="_blank"+ >+ {t`Terms of Service`}+ </Anchor>+ )}`}+ />))}</>)}@@ -164,11 +175,17 @@ export function MetabaseAIProviderSetup({</Text>)}+ {updateMetabotSettingsError && (+ <Text size="sm" c="error">+ {updateMetabotSettingsError}+ </Text>+ )}+<MetabotSettingUpModalisSavingConfiguration={- isSettingUpModalOpen && isSavingMetabaseConnection+ isSettingUpModalOpen && updateMetabotSettingsResult.isLoading}- onActivated={onConnect}+ onActivated={handleConnect}opened={isSettingUpModalOpen}onClose={() => setIsSettingUpModalOpen(false)}/>@@ -187,37 +204,28 @@ function MetabaseManagedProviderCard({const totalCost = getMetabaseUsageCost(metabotUsage?.tokens, pricing);return (- <Stack gap="lg">- <Group align="flex-start" gap="md" wrap="nowrap">- <Title order={4}>{- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Metabase AI service- t`Connected to Metabase AI service`- }</Title>- </Group>+ <Stack gap="md">+ <Text c="text-secondary" lh="1">{t`Current billing cycle`}</Text>- <Stack gap="md">- <Text c="text-secondary" lh="1">{t`Current billing cycle`}</Text>-- <MetabaseUsageRow- label={t`Total tokens`}- value={formatNumber(metabotUsage?.tokens ?? 0)}- />+ <MetabaseUsageRow+ label={t`Total tokens`}+ value={formatNumber(metabotUsage?.tokens ?? 0)}+ />- {isLoadingPricing ? (- <Flex align="center" justify="space-between" gap="md">- <Skeleton h="1rem" w="7rem" />- <Box flex={1} h={1} bg="border" />- <Skeleton h="1rem" w="8rem" />- </Flex>- ) : pricing ? (- <MetabasePricingRow pricing={pricing} />- ) : null}+ {isLoadingPricing ? (+ <Flex align="center" justify="space-between" gap="md">+ <Skeleton h="1rem" w="7rem" />+ <Box flex={1} h={1} bg="border" />+ <Skeleton h="1rem" w="8rem" />+ </Flex>+ ) : pricing ? (+ <MetabasePricingRow pricing={pricing} />+ ) : null}- <MetabaseUsageRow- label={t`Total cost`}- value={formatMetabaseCost(totalCost)}- />- </Stack>+ <MetabaseUsageRow+ label={t`Total cost`}+ value={formatMetabaseCost(totalCost)}+ /></Stack>);}diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.ts b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsindex 9ad51a50cbf..4a6443dc7ae 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.ts@@ -4,7 +4,10 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";import { MetabaseAIProviderSetup } from "./components/MetabotAdmin/MetabaseAIProviderSetup";export function initializePlugin() {- if (hasPremiumFeature("offer-metabase-ai-managed")) {+ if (+ hasPremiumFeature("offer-metabase-ai-managed") ||+ hasPremiumFeature("metabase-ai-managed")+ ) {PLUGIN_METABOT.isEnabled = true;PLUGIN_METABOT.MetabaseAIProviderSetup = MetabaseAIProviderSetup;}diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 7c8ca6af22a..f2635871e46 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -317,6 +317,7 @@ export const createMockSettings = ("ldap-group-membership-filter": "(member={dn})","loading-message": "doing-science","llm-anthropic-api-key-configured?": false,+ "mcp-enabled?": true,"map-tile-server-url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png","native-query-autocomplete-match-style": "substring","openai-api-key": null,@@ -371,6 +372,8 @@ export const createMockSettings = ("show-homepage-data": false,"show-homepage-pin-message": false,"show-homepage-xrays": false,+ "ai-features-enabled?": true,+ "agent-api-enabled?": true,"metabot-enabled?": true,"metabot-name": "Metabot","metabot-icon": "metabot",diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex a9b7e6ad96f..74b9d6bd837 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -534,6 +534,8 @@ type PrivilegedSettings = AdminSettings & SettingsManagerSettings;interface PublicSettings {"allowed-iframe-hosts": string;+ "ai-features-enabled?": boolean;+ "agent-api-enabled?": boolean;"analytics-uuid": string;"anon-tracking-enabled": boolean;"application-font": string;@@ -588,6 +590,7 @@ interface PublicSettings {"ldap-user-provisioning-enabled?": boolean;"oidc-user-provisioning-enabled?": boolean;"loading-message": LoadingMessage;+ "mcp-enabled?": boolean;"map-tile-server-url": string;"native-query-autocomplete-match-style": AutocompleteMatchStyle;"other-sso-enabled?": boolean | null; // TODO: FIXME! This is an enterprise-only setting!diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsxindex 2d54ab7822e..d87c0e752b0 100644--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx@@ -17,6 +17,7 @@ export function SettingsSection({titleProps,description,children,+ id,stackProps,...boxProps}: {@@ -24,10 +25,11 @@ export function SettingsSection({titleProps?: TitleProps;description?: React.ReactNode;children?: React.ReactNode;+ id?: string;stackProps?: StackProps;} & BoxProps) {return (- <Box {...boxProps}>+ <Box id={id} {...boxProps}>{children && (<Stack gap="lg" className={S.SettingsSection} {...stackProps}>{(title || description) && (diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.tsxnew file mode 100644index 00000000000..5493346dfdd--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.tsx@@ -0,0 +1,268 @@+import type { ReactNode } from "react";+import { jt, t } from "ttag";++import {+ SettingsPageWrapper,+ SettingsSection,+} from "metabase/admin/components/SettingsSection";+import { useAdminSetting } from "metabase/api/utils";+import { ExternalLink } from "metabase/common/components/ExternalLink";+import { Link } from "metabase/common/components/Link";+import { useDocsUrl, useSetting } from "metabase/common/hooks";+import {+ FIXED_METABOT_ENTITY_IDS,+ FIXED_METABOT_IDS,+} from "metabase/metabot/constants";+import {+ PLUGIN_EMBEDDING_IFRAME_SDK,+ PLUGIN_EMBEDDING_SDK,+} from "metabase/plugins";+import { useRouter } from "metabase/router/useRouter";+import { Flex, Stack, Switch, Tabs } from "metabase/ui";+import type { MetabotInfo } from "metabase-types/api";++import { McpAppsSettings } from "./McpAppsSettings";+import { MetabotSettingsPanel } from "./MetabotSettingsPanel";+import { MetabotSetup } from "./MetabotSetup";++type MetabotTabValue = "embedded" | "internal";++const SETUP_SECTION_ID = "setup";+const METABOT_SECTION_ID = "metabot";+const MCP_SECTION_ID = "mcp";+const AGENT_API_SECTION_ID = "agent-api";+const AI_FEATURES_ENABLED_SECTION_ID = "ai-features-enabled";++const DEFAULT_METABOT_PATH = `/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}`;+const EMBEDDED_METABOT_PATH = `/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}`;++const INTERNAL_METABOT = {+ id: FIXED_METABOT_IDS.DEFAULT,+ entity_id: FIXED_METABOT_ENTITY_IDS.DEFAULT,+ name: "Metabot",+} as MetabotInfo;++const EMBEDDED_METABOT = {+ id: FIXED_METABOT_IDS.EMBEDDED,+ entity_id: FIXED_METABOT_ENTITY_IDS.EMBEDDED,+ name: "Embedded Metabot",+} as MetabotInfo;++export function AISettingsPage() {+ const {+ location: { pathname },+ params,+ } = useRouter();++ const isConfigured = !!useSetting("llm-metabot-configured?");+ const hasEmbedding =+ PLUGIN_EMBEDDING_SDK.isEnabled() || PLUGIN_EMBEDDING_IFRAME_SDK.isEnabled();++ const {+ value: aiFeaturesEnabledValue,+ updateSetting: updateAiSetting,+ isLoading: isUpdatingAiFeatures,+ } = useAdminSetting("ai-features-enabled?");+ const areAiFeaturesEnabled = aiFeaturesEnabledValue !== false;++ const {+ value: agentApiEnabledValue,+ updateSetting: updateAgentApiSetting,+ isLoading: isUpdatingAgentApi,+ } = useAdminSetting("agent-api-enabled?");+ const isAgentApiEnabled = agentApiEnabledValue !== false;++ // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- Admin settings+ const { url: agentApiDocsUrl } = useDocsUrl("ai/agent-api");++ const selectedTab = getSelectedMetabotTab(params.metabotId, pathname, {+ hasEmbedding,+ });++ const handleAiFeaturesEnabledChange = async (checked: boolean) => {+ await updateAiSetting({+ key: "ai-features-enabled?",+ value: !checked,+ });+ };++ const handleAgentApiChange = async (checked: boolean) => {+ await updateAgentApiSetting({+ key: "agent-api-enabled?",+ value: checked,+ });+ };++ return (+ <SettingsPageWrapper+ title={t`AI features`}+ description={t`Manage AI integrations and Metabot.`}+ >+ {areAiFeaturesEnabled && (+ <>+ <MetabotSetup id={SETUP_SECTION_ID} />+ <DisabledSection disabled={!isConfigured}>+ <Stack gap="lg">+ <MetabotSettingsSection+ hasEmbedding={hasEmbedding}+ id={METABOT_SECTION_ID}+ selectedTab={selectedTab}+ />++ <McpAppsSettings id={MCP_SECTION_ID} />++ <ToggleSettingsSection+ checked={isAgentApiEnabled}+ description={jt`Enable external access to the Agent API. ${(+ <ExternalLink key="docs" href={agentApiDocsUrl}>+ {t`Learn more`}+ </ExternalLink>+ )}`}+ disabled={isUpdatingAgentApi}+ id={AGENT_API_SECTION_ID}+ onChange={handleAgentApiChange}+ title={t`Agent API`}+ />+ </Stack>+ </DisabledSection>+ </>+ )}++ <ToggleSettingsSection+ checked={!areAiFeaturesEnabled}+ description={t`Turn this on to hide AI features across your instance.`}+ disabled={isUpdatingAiFeatures}+ id={AI_FEATURES_ENABLED_SECTION_ID}+ onChange={handleAiFeaturesEnabledChange}+ title={t`Disable all AI features`}+ />+ </SettingsPageWrapper>+ );+}++function MetabotSettingsSection({+ hasEmbedding,+ id,+ selectedTab,+}: {+ hasEmbedding: boolean;+ id: string;+ selectedTab: MetabotTabValue;+}) {+ const activeMetabot =+ selectedTab === "embedded" ? EMBEDDED_METABOT : INTERNAL_METABOT;+ const showTabs = hasEmbedding;++ return (+ <SettingsSection id={id} title={t`Metabot settings`}>+ {showTabs && (+ <Tabs value={selectedTab}>+ <Tabs.List>+ <Tabs.Tab+ renderRoot={(props) => (+ <Link {...props} to={getMetabotTabPath("internal")} />+ )}+ value="internal"+ >+ {t`Internal`}+ </Tabs.Tab>+ <Tabs.Tab+ renderRoot={(props) => (+ <Link {...props} to={getMetabotTabPath("embedded")} />+ )}+ value="embedded"+ >+ {t`Embedded`}+ </Tabs.Tab>+ </Tabs.List>+ </Tabs>+ )}++ <MetabotSettingsPanel metabot={activeMetabot} />+ </SettingsSection>+ );+}++function ToggleSettingsSection({+ checked,+ description,+ disabled,+ id,+ onChange,+ title,+}: {+ checked: boolean;+ description: ReactNode;+ disabled: boolean;+ id: string;+ onChange: (checked: boolean) => Promise<void>;+ title: string;+}) {+ return (+ <SettingsSection+ id={id}+ title={+ <Flex align="center" gap="md" justify="space-between" w="100%">+ <div>{title}</div>+ <Switch+ aria-label={title}+ checked={checked}+ disabled={disabled}+ onChange={(event) => onChange(event.target.checked)}+ size="sm"+ w="auto"+ />+ </Flex>+ }+ description={description}+ >+ <></>+ </SettingsSection>+ );+}++function DisabledSection({+ children,+ disabled,+}: {+ children: ReactNode;+ disabled: boolean;+}) {+ return (+ <Stack+ gap="lg"+ opacity={disabled ? 0.4 : 1}+ aria-disabled={disabled || undefined}+ {...(disabled ? { inert: "" } : {})}+ >+ {children}+ </Stack>+ );+}++function getSelectedMetabotTab(+ metabotId: string | undefined,+ pathname: string,+ {+ hasEmbedding,+ }: {+ hasEmbedding: boolean;+ },+): MetabotTabValue {+ if (+ (metabotId === String(FIXED_METABOT_IDS.EMBEDDED) ||+ pathname === EMBEDDED_METABOT_PATH) &&+ hasEmbedding+ ) {+ return "embedded";+ }++ return "internal";+}++function getMetabotTabPath(tab: MetabotTabValue) {+ const pathname =+ tab === "embedded" ? EMBEDDED_METABOT_PATH : DEFAULT_METABOT_PATH;++ return `${pathname}#${METABOT_SECTION_ID}`;+}diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.unit.spec.tsxnew file mode 100644index 00000000000..6b40fbd56a4--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/AISettingsPage.unit.spec.tsx@@ -0,0 +1,203 @@+import userEvent from "@testing-library/user-event";+import { Route } from "react-router";++import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ findRequests,+ setupCollectionByIdEndpoint,+ setupCollectionsEndpoints,+ setupPropertiesEndpoints,+ setupRecentViewsAndSelectionsEndpoints,+ setupRootCollectionItemsEndpoint,+ setupSettingsEndpoints,+ setupUpdateSettingEndpoint,+} from "__support__/server-mocks";+import { setupMetabotPromptSuggestionsEndpoint } from "__support__/server-mocks/metabot";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { FIXED_METABOT_IDS } from "metabase/metabot/constants";+import { reinitialize } from "metabase/plugins";+import { createMockSettingsState } from "metabase/redux/store/mocks";+import {+ createMockCollection,+ createMockSettingDefinition,+ createMockSettings,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { AISettingsPage } from "./AISettingsPage";++const defaultSeedCollections = [+ createMockCollection({ id: "root", name: "Our Analytics" }),+];++const setup = async ({+ aiFeaturesEnabled = true,+ enableEmbedding = false,+ initialRoute = "/admin/metabot",+ isConfigured = true,+}: {+ aiFeaturesEnabled?: boolean;+ enableEmbedding?: boolean;+ initialRoute?: string;+ isConfigured?: boolean;+} = {}) => {+ const tokenFeatures = createMockTokenFeatures({+ embedding_sdk: enableEmbedding,+ });++ mockSettings({ "token-features": tokenFeatures });+ setupEnterprisePlugins();++ const settings = createMockSettings({+ "ai-features-enabled?": aiFeaturesEnabled,+ "agent-api-enabled?": true,+ "embedded-metabot-enabled?": true,+ "llm-metabot-configured?": isConfigured,+ "llm-metabot-provider": null,+ "mcp-enabled?": true,+ "metabot-enabled?": true,+ "token-features": tokenFeatures,+ });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([+ createMockSettingDefinition({+ key: "llm-metabot-provider",+ value: null,+ }),+ createMockSettingDefinition({+ key: "llm-anthropic-api-key",+ value: undefined,+ }),+ createMockSettingDefinition({+ key: "llm-openai-api-key",+ value: undefined,+ }),+ createMockSettingDefinition({+ key: "llm-openrouter-api-key",+ value: undefined,+ }),+ ]);+ setupUpdateSettingEndpoint();+ setupCollectionByIdEndpoint({+ collections: defaultSeedCollections.map((c: any) => ({+ id: c.model_id,+ ...c,+ })),+ });+ setupRootCollectionItemsEndpoint({ rootCollectionItems: [] });+ setupCollectionsEndpoints({ collections: [] });+ setupRecentViewsAndSelectionsEndpoints(defaultSeedCollections as any);++ [FIXED_METABOT_IDS.DEFAULT, FIXED_METABOT_IDS.EMBEDDED].forEach((metabotId) =>+ setupMetabotPromptSuggestionsEndpoint({+ metabotId,+ prompts: [],+ paginationContext: {+ offset: 0,+ limit: 10,+ total: 0,+ },+ }),+ );++ const view = renderWithProviders(+ <Route path="/admin/metabot*" component={AISettingsPage} />,+ {+ withRouter: true,+ initialRoute,+ storeInitialState: {+ settings: createMockSettingsState(settings),+ },+ },+ );++ await screen.findByText("Disable all AI features");++ return view;+};++describe("AISettingsPage", () => {+ afterEach(() => {+ reinitialize();+ jest.restoreAllMocks();+ });++ it("shows all sections on one page and disables non-connection sections until configured", async () => {+ await setup({ isConfigured: false, enableEmbedding: true });++ expect(screen.getByText("Connect to an AI provider")).toBeInTheDocument();+ expect(screen.getByText("Metabot settings")).toBeInTheDocument();+ expect(screen.getByText("Enable Metabot")).toBeInTheDocument();+ expect(screen.getByText("MCP server")).toBeInTheDocument();++ expect(+ screen.getByText("Enable Metabot", {+ selector: '[aria-disabled="true"] *',+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByText("MCP server", {+ selector: '[aria-disabled="true"] *',+ }),+ ).toBeInTheDocument();+ expect(screen.getByText("Agent API")).toBeInTheDocument();+ });++ it("shows docs links for MCP and Agent API", async () => {+ await setup();++ expect(+ screen+ .getAllByRole("link", { name: "Learn more" })+ .map((link) => link.getAttribute("href")),+ ).toEqual(+ expect.arrayContaining([+ "https://www.metabase.com/docs/latest/ai/mcp.html",+ "https://www.metabase.com/docs/latest/ai/agent-api.html",+ ]),+ );+ });++ it("hides every other section when AI features are disabled", async () => {+ await setup({ aiFeaturesEnabled: false });++ expect(+ screen.queryByText("Connect to an AI provider"),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("Metabot settings")).not.toBeInTheDocument();+ expect(screen.queryByText("MCP server")).not.toBeInTheDocument();+ expect(screen.queryByText("Agent API")).not.toBeInTheDocument();+ expect(screen.getByText("Disable all AI features")).toBeInTheDocument();+ });++ it("keeps the embedded deep link working by selecting the embedded tab", async () => {+ await setup({+ enableEmbedding: true,+ initialRoute: `/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}#metabot`,+ });++ expect(+ screen.getByRole("tab", { name: "Embedded", selected: true }),+ ).toBeInTheDocument();+ expect(screen.getByText("Enable Embedded Metabot")).toBeInTheDocument();+ });++ it("persists disable ai features", async () => {+ await setup();++ await userEvent.click(+ screen.getByRole("switch", { name: "Disable all AI features" }),+ );++ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ });++ const puts = await findRequests("PUT");+ expect(puts[0].url).toContain("/setting/ai-features-enabled%3F");+ expect(puts[0].body).toEqual({ value: false });+ });+});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsxindex 5cde1fc5d71..7758317af3c 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsx@@ -1,10 +1,12 @@import { useCallback, useState } from "react";-import { t } from "ttag";+import { jt, t } from "ttag";import { SettingsSection } from "metabase/admin/components/SettingsSection";import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";import { useAdminSetting } from "metabase/api/utils";-import { Box, Stack, Switch, Text, TextInput } from "metabase/ui";+import { ExternalLink } from "metabase/common/components/ExternalLink";+import { useDocsUrl } from "metabase/common/hooks";+import { Box, Flex, Stack, Switch, Text, TextInput } from "metabase/ui";const getMcpClients = () =>[@@ -22,17 +24,59 @@ const getMcpClients = () =>},] as const;-export const McpAppsSettings = () => (- <SettingsSection- title={t`MCP apps`}- // eslint-disable-next-line metabase/no-literal-metabase-strings -- admin UI- description={t`Allow MCP clients to connect to your Metabase instance by enabling CORS for their sandbox domains.`}- >- <CommonMcpClientsSection />-- <CustomMcpOriginsSection />- </SettingsSection>-);+export const McpAppsSettings = ({ id }: { id?: string }) => {+ const {+ value: mcpEnabled,+ updateSetting,+ isLoading,+ } = useAdminSetting("mcp-enabled?");+ // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- Admin settings+ const { url: mcpDocsUrl } = useDocsUrl("ai/mcp");++ const isEnabled = mcpEnabled !== false;++ return (+ <SettingsSection+ id={id}+ title={+ <Flex align="center" gap="md" justify="space-between" w="100%">+ <div>{t`MCP server`}</div>+ <Switch+ aria-label={t`MCP server`}+ checked={isEnabled}+ disabled={isLoading}+ onChange={(event) =>+ updateSetting({+ key: "mcp-enabled?",+ value: event.target.checked,+ })+ }+ size="sm"+ w="auto"+ />+ </Flex>+ }+ description={+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- admin UI+ jt`Allow MCP clients to connect to your Metabase instance. ${(+ <ExternalLink key="docs" href={mcpDocsUrl}>+ {t`Learn more`}+ </ExternalLink>+ )}`+ }+ >+ {isEnabled ? (+ <Stack gap="lg">+ <CommonMcpClientsSection />++ <CustomMcpOriginsSection />+ </Stack>+ ) : (+ <></>+ )}+ </SettingsSection>+ );+};function CommonMcpClientsSection() {const mcpClients = getMcpClients();diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsxindex 0093ef1339c..21c03249273 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsx@@ -16,11 +16,14 @@ import { McpAppsSettings } from "./McpAppsSettings";const setup = async ({commonOrigins = [],customOrigins = "",+ enabled = true,}: {commonOrigins?: string[];customOrigins?: string;+ enabled?: boolean;} = {}) => {const settings = createMockSettings({+ "mcp-enabled?": enabled,"mcp-apps-cors-enabled-clients": commonOrigins,"mcp-apps-cors-custom-origins": customOrigins,});@@ -35,10 +38,30 @@ const setup = async ({}),});- await screen.findByText("Supported MCP clients");+ await screen.findByText("MCP server");};describe("McpAppsSettings", () => {+ it("shows a docs link for the MCP server", async () => {+ await setup();++ expect(screen.getByRole("link", { name: "Learn more" })).toHaveAttribute(+ "href",+ "https://www.metabase.com/docs/latest/ai/mcp.html",+ );+ });++ it("can toggle the MCP server", async () => {+ await setup();++ await userEvent.click(screen.getByRole("switch", { name: "MCP server" }));++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ expect(puts[0].url).toContain("/setting/mcp-enabled%3F");+ expect(puts[0].body).toEqual({ value: false });+ });+it("should show all MCP client toggles", async () => {await setup();@@ -78,4 +101,13 @@ describe("McpAppsSettings", () => {expect(url).toContain("/setting/mcp-apps-cors-custom-origins");expect(body).toEqual({ value: "https://my-app.example.com" });});++ it("hides MCP client configuration when the MCP server is off", async () => {+ await setup({ enabled: false });++ expect(screen.queryByLabelText("Claude")).not.toBeInTheDocument();+ expect(+ screen.queryByPlaceholderText("https://*.example.com"),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsxindex 5562883f68d..3d14f008ec6 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx@@ -1,53 +1,31 @@+import { Fragment } from "react";import { t } from "ttag";import {AdminNavItem,AdminNavWrapper,} from "metabase/admin/components/AdminNav";-import { useSetting } from "metabase/common/hooks";-import { FIXED_METABOT_IDS } from "metabase/metabot/constants";-import {- PLUGIN_AI_CONTROLS,- PLUGIN_EMBEDDING_IFRAME_SDK,- PLUGIN_EMBEDDING_SDK,-} from "metabase/plugins";+import { PLUGIN_AI_CONTROLS } from "metabase/plugins";import { Flex } from "metabase/ui";export function MetabotNavPane() {- const isConfigured = useSetting("llm-metabot-configured?");- const hasEmbedding =- PLUGIN_EMBEDDING_SDK.isEnabled() || PLUGIN_EMBEDDING_IFRAME_SDK.isEnabled();+ const AiControlsNavItems = PLUGIN_AI_CONTROLS.AiControlsNavItems;++ if (!AiControlsNavItems) {+ return null;+ }return (<Flex direction="column" flex="0 0 auto"><AdminNavWrapper><AdminNavItemicon="gear"- label={t`Connection settings`}- path="/admin/metabot/setup"- />- {isConfigured && (- <>- <AdminNavItem- icon="metabot"- label={t`Metabot`}- path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}`}- />- {hasEmbedding && (- <AdminNavItem- icon="embed"- label={t`Embedded Metabot`}- path={`/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}`}- />- )}- {PLUGIN_AI_CONTROLS.getAiControlsNavItems()}- </>- )}- <AdminNavItem- icon="bolt"- label={t`MCP apps`}- path="/admin/metabot/mcp"+ label={t`AI Settings`}+ path="/admin/metabot/"/>+ <Fragment key="ai-controls">+ <AiControlsNavItems />+ </Fragment></AdminNavWrapper></Flex>);diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsxindex eb2658e1904..3937167d0ab 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx@@ -10,30 +10,36 @@ import { createMockTokenFeatures } from "metabase-types/api/mocks";import { MetabotNavPane } from "./MetabotNavPane";const setup = ({+ aiFeaturesEnabled = true,+ aiControlsEnabled = false,isConfigured = true,}: {+ aiFeaturesEnabled?: boolean;+ aiControlsEnabled?: boolean;isConfigured?: boolean;-} = {}) =>- renderWithProviders(+} = {}) => {+ mockSettings({+ "ai-features-enabled?": aiFeaturesEnabled,+ "token-features": createMockTokenFeatures({+ ai_controls: aiControlsEnabled,+ }),+ });++ setupEnterprisePlugins();++ return renderWithProviders(<Route path="/admin/metabot*" component={MetabotNavPane} />,{withRouter: true,- initialRoute: "/admin/metabot/setup",+ initialRoute: "/admin/metabot",storeInitialState: {settings: createMockSettingsState({+ "ai-features-enabled?": aiFeaturesEnabled,"llm-metabot-configured?": isConfigured,}),},},);--const setupEmbeddingPlugin = () => {- mockSettings({- "token-features": createMockTokenFeatures({- embedding_sdk: true,- }),- });- setupEnterprisePlugins();};describe("MetabotNavPane", () => {@@ -41,76 +47,32 @@ describe("MetabotNavPane", () => {reinitialize();});- it("should not show metabots if it isn't configured", async () => {- setup({ isConfigured: false });-- expect(screen.queryByText("Metabot")).not.toBeInTheDocument();- expect(screen.queryByText("Embedded Metabot")).not.toBeInTheDocument();- });-- it("should show metabots if it is configured", async () => {- setup({ isConfigured: true });-- expect(await screen.findByText("Metabot")).toBeInTheDocument();- expect(screen.queryByText("Embedded Metabot")).not.toBeInTheDocument();- });-- it("should show Embedded Metabot with embedding_sdk feature", async () => {- setupEmbeddingPlugin();- setup({ isConfigured: true });-- expect(await screen.findByText("Metabot")).toBeInTheDocument();- expect(await screen.findByText("Embedded Metabot")).toBeInTheDocument();- });-- it("should show Embedded Metabot with embedding_simple feature", async () => {- mockSettings({- "token-features": createMockTokenFeatures({- embedding_simple: true,- }),+ it("hides the ai controls items when all AI features are disabled", () => {+ setup({+ aiControlsEnabled: true,+ aiFeaturesEnabled: false,+ isConfigured: true,});- setupEnterprisePlugins();- setup({ isConfigured: true });-- expect(await screen.findByText("Metabot")).toBeInTheDocument();- expect(await screen.findByText("Embedded Metabot")).toBeInTheDocument();- });- it("should not show AI controls nav items by default", async () => {- setup({ isConfigured: true });-- expect(await screen.findByText("Metabot")).toBeInTheDocument();+ expect(screen.getByText("AI Settings")).toBeInTheDocument();expect(screen.queryByText("Usage controls")).not.toBeInTheDocument();expect(screen.queryByText("Customization")).not.toBeInTheDocument();expect(screen.queryByText("System prompts")).not.toBeInTheDocument();});- it("should show AI controls nav items when ai_controls plugin is enabled", async () => {- mockSettings({- "token-features": createMockTokenFeatures({- ai_controls: true,- }),- });- setupEnterprisePlugins();- setup({ isConfigured: true });-- expect(await screen.findByText("Metabot")).toBeInTheDocument();- expect(screen.getByText("Usage controls")).toBeInTheDocument();- expect(screen.getByText("Customization")).toBeInTheDocument();- expect(screen.getByText("System prompts")).toBeInTheDocument();- });+ it("displays the ai controls in a disabled state when not configured", async () => {+ setup({ aiControlsEnabled: true, isConfigured: false });- it("should not show AI controls nav items when metabot is not configured", async () => {- mockSettings({- "token-features": createMockTokenFeatures({- ai_controls: true,- }),- });- setupEnterprisePlugins();- setup({ isConfigured: false });+ expect(await screen.findByText("AI Settings")).toBeInTheDocument();- expect(screen.queryByText("Usage controls")).not.toBeInTheDocument();- expect(screen.queryByText("Customization")).not.toBeInTheDocument();- expect(screen.queryByText("System prompts")).not.toBeInTheDocument();+ expect(+ screen.getByText("Usage controls").closest('[data-disabled="true"]'),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Customization").closest('[data-disabled="true"]'),+ ).toBeInTheDocument();+ expect(+ screen.getByText("System prompts").closest('[data-disabled="true"]'),+ ).toBeInTheDocument();});});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.tsxdeleted file mode 100644index ee5d97fb25f..00000000000--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.tsx+++ /dev/null@@ -1,112 +0,0 @@-import { type ChangeEvent, useEffect, useMemo, useState } from "react";-import { c, jt, t } from "ttag";--import { SetByEnvVar } from "metabase/admin/settings/components/widgets/AdminSettingInput";-import { useUpdateMetabotSettingsMutation } from "metabase/api";-import { getErrorMessage, useAdminSetting } from "metabase/api/utils";-import { ExternalLink } from "metabase/common/components/ExternalLink";-import { Box, Button, Flex, TextInput } from "metabase/ui";--import {- API_KEY_SETTING_BY_PROVIDER,- type MetabotApiKeyProvider,- getProviderOptions,-} from "./utils";--export function MetabotProviderApiKey({- provider,- error,-}: {- provider: MetabotApiKeyProvider;- error?: string | null;-}) {- const selectedProvider = getProviderOptions(true)[provider];- const selectedApiKeySetting = API_KEY_SETTING_BY_PROVIDER[provider];- const { value, settingDetails } = useAdminSetting(selectedApiKeySetting);- const [updateMetabotSettings, updateMetabotSettingsResult] =- useUpdateMetabotSettingsMutation();- const [localValue, setLocalValue] = useState<string | null>(null);- const [localError, setLocalError] = useState<string | null>(null);-- const displayValue =- localValue ?? String(settingDetails?.value ?? value ?? "");- const savedValue = String(settingDetails?.value ?? value ?? "");- const isEnvSetting = Boolean(- settingDetails?.is_env_setting && settingDetails?.env_name,- );- const displayError = localError ?? (localValue == null ? error : null);- const canConnect = useMemo(- () => !isEnvSetting && localValue != null && localValue !== savedValue,- [isEnvSetting, localValue, savedValue],- );-- useEffect(() => {- setLocalValue(null);- setLocalError(null);- }, [provider, settingDetails?.value]);-- const handleChange = (event: ChangeEvent<HTMLInputElement>) => {- setLocalValue(event.target.value);- setLocalError(null);- };-- const handleConnect = async () => {- if (!canConnect) {- return;- }-- try {- await updateMetabotSettings({- provider,- "api-key": localValue || null,- }).unwrap();- setLocalError(null);- setLocalValue(null);- } catch (saveError) {- setLocalError(getErrorMessage(saveError, t`Unable to verify API key.`));- }- };-- return (- <Box>- <Flex gap="md" align="flex-end">- <TextInput- key={selectedApiKeySetting}- label={t`API key`}- type="password"- description={jt`Need a key? ${(- <ExternalLink- key={selectedProvider.value}- href={selectedProvider.apiKey.addKeyUrl}- >- {c("{0} is the name of an AI provider")- .t`Create one in ${selectedProvider.label}`}- </ExternalLink>- )}`}- placeholder={- selectedProvider.apiKey?.placeholder ?? t`Enter your API key`- }- value={displayValue}- onChange={handleChange}- error={displayError}- disabled={isEnvSetting}- w="100%"- />- {!isEnvSetting && (- <Button- onClick={handleConnect}- disabled={!canConnect}- loading={updateMetabotSettingsResult.isLoading}- flex="1 0 auto"- mb={displayError ? "1.35rem" : ""}- >- {t`Connect`}- </Button>- )}- </Flex>- {isEnvSetting && settingDetails?.env_name ? (- <SetByEnvVar varName={settingDetails.env_name} />- ) : null}- </Box>- );-}diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.unit.spec.tsxdeleted file mode 100644index 52f4cb1a8cd..00000000000--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotProviderApiKey.unit.spec.tsx+++ /dev/null@@ -1,184 +0,0 @@-import { fireEvent } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { setupPropertiesEndpoints } from "__support__/server-mocks";-import { renderWithProviders, screen, waitFor } from "__support__/ui";-import {- createMockSettingDefinition,- createMockSettings,-} from "metabase-types/api/mocks";--import { MetabotProviderApiKey } from "./MetabotProviderApiKey";--const SUCCESS_RESPONSE = {- value: "anthropic/claude-haiku-4-5",- models: [],-};--const setup = async ({- shouldFail = true,- isEnvSetting = false,- pauseResponse = false,-}: {- shouldFail?: boolean;- isEnvSetting?: boolean;- pauseResponse?: boolean;-} = {}) => {- let maskedApiKey: string | null = null;- let resolveRequest: (() => void) | null = null;-- setupPropertiesEndpoints(- createMockSettings({- "llm-anthropic-api-key": null,- }),- );- fetchMock.get("path:/api/setting", () => [- createMockSettingDefinition({- key: "llm-anthropic-api-key",- value: maskedApiKey,- is_env_setting: isEnvSetting,- env_name: isEnvSetting ? "LLM_ANTHROPIC_API_KEY" : "",- }),- ]);- fetchMock.put("path:/api/metabot/settings", async (call) => {- if (pauseResponse) {- await new Promise<void>((resolve) => {- resolveRequest = resolve;- });- }-- const body = JSON.parse(String(call.options?.body ?? "{}"));-- if (shouldFail) {- return {- status: 400,- body: "Anthropic API key expired or invalid",- };- }-- maskedApiKey = body["api-key"] ? "**********id" : null;-- return {- status: 200,- body: SUCCESS_RESPONSE,- };- });-- renderWithProviders(<MetabotProviderApiKey provider="anthropic" />);-- const input = await screen.findByLabelText("API key");-- return {- input,- resolveRequest: () => resolveRequest?.(),- setShouldFail: (value: boolean) => (shouldFail = value),- };-};--describe("MetabotProviderApiKey", () => {- it("shows API key verification errors on the API key field", async () => {- const { input } = await setup();-- fireEvent.change(input, { target: { value: "sk-ant-invalid" } });- await userEvent.click(screen.getByRole("button", { name: "Connect" }));-- expect(- await screen.findByText("Anthropic API key expired or invalid"),- ).toBeInTheDocument();- expect(- screen.queryByText("Unable to load models."),- ).not.toBeInTheDocument();-- await waitFor(() => {- expect(fetchMock.callHistory.called("path:/api/metabot/settings")).toBe(- true,- );- });-- const request = fetchMock.callHistory- .calls("path:/api/metabot/settings")- .find((call) => call.request?.method === "PUT");-- expect(request?.options?.body).toBe(- JSON.stringify({ provider: "anthropic", "api-key": "sk-ant-invalid" }),- );- });-- it("shows verifying API key while saving and hides it after success", async () => {- const { input, resolveRequest } = await setup({- shouldFail: false,- pauseResponse: true,- });-- fireEvent.change(input, { target: { value: "sk-ant-valid" } });- const connectButton = screen.getByRole("button", { name: "Connect" });-- await userEvent.click(connectButton);-- await waitFor(() => {- expect(connectButton).toHaveAttribute("data-loading", "true");- });-- resolveRequest();-- await waitFor(() => {- expect(connectButton).not.toHaveAttribute("data-loading", "true");- });- });-- it("resets local value and error after a successful save", async () => {- const { input, setShouldFail } = await setup();-- fireEvent.change(input, { target: { value: "sk-ant-invalid" } });- await userEvent.click(screen.getByRole("button", { name: "Connect" }));-- expect(- await screen.findByText("Anthropic API key expired or invalid"),- ).toBeInTheDocument();- expect(input).toHaveValue("sk-ant-invalid");-- setShouldFail(false);- fireEvent.change(input, { target: { value: "sk-ant-valid" } });- await userEvent.click(screen.getByRole("button", { name: "Connect" }));-- await waitFor(() => {- expect(- screen.queryByText("Anthropic API key expired or invalid"),- ).not.toBeInTheDocument();- });-- await waitFor(() => {- expect(input).toHaveValue("**********id");- });- });-- it("shows the env var message and disables the input when set by env var", async () => {- const { input } = await setup({ isEnvSetting: true, shouldFail: false });-- expect(- await screen.findByTestId("setting-env-var-message"),- ).toHaveTextContent(- "This has been set by the LLM_ANTHROPIC_API_KEY environment variable.",- );- expect(input).toBeDisabled();- });-- it("does not verify the API key until Connect is clicked", async () => {- const { input } = await setup({ shouldFail: false });-- fireEvent.change(input, { target: { value: "sk-ant-valid" } });-- expect(fetchMock.callHistory.called("path:/api/metabot/settings")).toBe(- false,- );-- await userEvent.click(screen.getByRole("button", { name: "Connect" }));-- await waitFor(() => {- expect(fetchMock.callHistory.called("path:/api/metabot/settings")).toBe(- true,- );- });- });-});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.tsxsimilarity index 65%rename from frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.tsxrename to frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.tsxindex e3df072ff13..75a50cd7bbc 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.tsx@@ -1,32 +1,21 @@import { useDisclosure } from "@mantine/hooks";-import { type ReactNode, useEffect, useMemo } from "react";-import { push } from "react-router-redux";-import { P, match } from "ts-pattern";+import type { ReactNode } from "react";+import { match } from "ts-pattern";import { c, t } from "ttag";-import _ from "underscore";-import { SettingsSection } from "metabase/admin/components/SettingsSection";import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";import {skipToken,useGetCollectionQuery,- useListMetabotsQuery,useUpdateMetabotMutation,} from "metabase/api";import { useAdminSetting } from "metabase/api/utils/settings";import { canonicalCollectionId } from "metabase/collections/utils";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";-import { useSetting, useToast } from "metabase/common/hooks";-import {- FIXED_METABOT_ENTITY_IDS,- FIXED_METABOT_IDS,-} from "metabase/metabot/constants";-import {- PLUGIN_EMBEDDING_IFRAME_SDK,- PLUGIN_EMBEDDING_SDK,- PLUGIN_MODERATION,-} from "metabase/plugins";+import { useToast } from "metabase/common/hooks";+import { FIXED_METABOT_ENTITY_IDS } from "metabase/metabot/constants";+import { PLUGIN_MODERATION } from "metabase/plugins";import {Box,Button,@@ -38,7 +27,6 @@ import {Text,} from "metabase/ui";import { getIcon } from "metabase/utils/icon";-import { useDispatch } from "metabase/utils/redux";import type {Collection,CollectionEssentials,@@ -47,59 +35,8 @@ import type {} from "metabase-types/api";import { MetabotPromptSuggestionPane } from "./MetabotAdminSuggestedPrompts";-import { useMetabotIdPath } from "./utils";--export function MetabotConfig() {- const isConfigured = useSetting("llm-metabot-configured?");-- const metabotId = useMetabotIdPath() ?? FIXED_METABOT_IDS.DEFAULT;- const { data, isLoading, error } = useListMetabotsQuery();-- const metabot = data?.items?.find((bot) => bot.id === metabotId);-- const dispatch = useDispatch();-- const hasEmbedding =- PLUGIN_EMBEDDING_SDK.isEnabled() || PLUGIN_EMBEDDING_IFRAME_SDK.isEnabled();-- const metabots = useMemo(() => _.sortBy(data?.items ?? [], "id"), [data]);-- useEffect(() => {- if (!isConfigured) {- dispatch(push("/admin/metabot/setup"));- }- }, [isConfigured, dispatch]);-- useEffect(() => {- if (metabotId === FIXED_METABOT_IDS.EMBEDDED && !hasEmbedding) {- dispatch(push(`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}`));- }- }, [metabotId, hasEmbedding, dispatch]);-- useEffect(() => {- if (!metabot && metabots.length) {- dispatch(push(`/admin/metabot/${metabots[0]?.id}`));- }- }, [metabots, metabotId, dispatch, metabot, isLoading]);-- if (isLoading || !metabot || !isConfigured) {- return (- <LoadingAndErrorWrapper- loading={isLoading || !data}- error={match({ isLoading, error, metabot, isConfigured })- .with(- { isLoading: false, error: P.not(null), isConfigured: true },- () => t`Error fetching Metabots`,- )- .with(- { isLoading: false, metabot: undefined, isConfigured: true },- () => t`Not found.`,- )- .otherwise(() => null)}- />- );- }+export function MetabotSettingsPanel({ metabot }: { metabot: MetabotInfo }) {const isEmbedMetabot =metabot.entity_id === FIXED_METABOT_ENTITY_IDS.EMBEDDED;@@ -108,25 +45,17 @@ export function MetabotConfig() {: "metabot-enabled?";return (- <SettingsSection key={metabotId}>- <Box>- <SettingHeader- id="configure-metabot"- title={c("{0} is the name of an AI assistant")- .t`Configure ${metabot.name}`}- description={c("{0} is the name of an AI assistant") // eslint-disable-next-line metabase/no-literal-metabase-strings -- admin ui- .t`${metabot.name} is Metabase's AI agent. To help ${metabot.name} more easily find and focus on the data you care about most, configure what content it should be able to access or use to create queries.`}- />- {isEmbedMetabot && (- <Text c="text-secondary" maw="40rem">- {t`If you're embedding the Metabot component in an app, you can specify a different collection that embedded Metabot is allowed to use for creating queries.`}- </Text>- )}- <MetabotEnabledToggle- settingKey={enabledSettingKey}- isEmbedMetabot={isEmbedMetabot}- />- </Box>+ <Stack gap="lg">+ {isEmbedMetabot && (+ <Text c="text-secondary" maw="40rem">+ {t`If you're embedding the Metabot component in an app, you can specify a different collection that embedded Metabot is allowed to use for creating queries.`}+ </Text>+ )}++ <MetabotEnabledToggle+ settingKey={enabledSettingKey}+ isEmbedMetabot={isEmbedMetabot}+ /><MetabotSettingsBody settingKey={enabledSettingKey}><PLUGIN_MODERATION.MetabotVerifiedContentConfigurationPane@@ -144,7 +73,7 @@ export function MetabotConfig() {<MetabotPromptSuggestionPane metabot={metabot} /></MetabotSettingsBody>- </SettingsSection>+ </Stack>);}@@ -162,7 +91,7 @@ function MetabotEnabledToggle({};return (- <Box mt="lg">+ <Box><SettingHeaderid="enable-metabot"title={isEmbedMetabot ? t`Enable Embedded Metabot` : t`Enable Metabot`}@@ -205,19 +134,11 @@ function MetabotSettingsBody({const { value } = useAdminSetting(settingKey);const isDisabled = value === false;- return (- <Stack- gap="lg"- opacity={isDisabled ? 0.4 : 1}- aria-disabled={isDisabled || undefined}- style={{- pointerEvents: isDisabled ? "none" : "auto",- transition: "opacity 150ms ease",- }}- >- {children}- </Stack>- );+ if (isDisabled) {+ return null;+ }++ return <Stack gap="lg">{children}</Stack>;}function MetabotCollectionConfigurationPane({diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.unit.spec.tsxsimilarity index 72%rename from frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.unit.spec.tsxrename to frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.unit.spec.tsxindex 5670511fa11..b5688fd4838 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotConfig.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSettingsPanel.unit.spec.tsx@@ -1,6 +1,5 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import { Route } from "react-router";import { setupEnterprisePlugins } from "__support__/enterprise";import {@@ -19,7 +18,6 @@ import {} from "__support__/server-mocks/metabot";import { mockSettings } from "__support__/settings";import {- act,mockGetBoundingClientRect,renderWithProviders,screen,@@ -33,7 +31,7 @@ import {} from "metabase/metabot/constants";import { reinitialize } from "metabase/plugins";import { createMockSettingsState } from "metabase/redux/store/mocks";-import type { MetabotId, RecentItem } from "metabase-types/api";+import type { MetabotId, MetabotInfo, RecentItem } from "metabase-types/api";import {createMockCollection,createMockMetabotInfo,@@ -41,12 +39,7 @@ import {createMockTokenFeatures,} from "metabase-types/api/mocks";-import { MetabotConfig } from "./MetabotConfig";-import * as hooks from "./utils";--const mockPathParam = (id: MetabotId) => {- jest.spyOn(hooks, "useMetabotIdPath").mockReturnValue(id);-};+import { MetabotSettingsPanel } from "./MetabotSettingsPanel";const defaultMetabots = [createMockMetabotInfo({@@ -97,17 +90,14 @@ const defaultSeedCollections = [];const setup = async (initialPathParam: MetabotId = 1,- metabots = defaultMetabots,+ metabots: MetabotInfo[] = defaultMetabots,seedCollections = defaultSeedCollections,- error = false,settings = createMockSettings({ "llm-metabot-configured?": true }),- waitForPageLoad = true,) => {mockGetBoundingClientRect();- mockPathParam(initialPathParam);setupPropertiesEndpoints(settings);setupSettingsEndpoints([]);- setupMetabotsEndpoints(metabots, error ? 500 : undefined);+ setupMetabotsEndpoints(metabots);setupCollectionByIdEndpoint({collections: seedCollections.map((c: any) => ({ id: c.model_id, ...c })),});@@ -129,20 +119,16 @@ const setup = async (}),);- const view = renderWithProviders(- <Route path="/admin/metabot*" component={MetabotConfig} />,- {- withRouter: true,- initialRoute: `/admin/metabot/${initialPathParam}`,- storeInitialState: {- settings: createMockSettingsState(settings),- },+ const metabot =+ metabots.find((mb) => mb.id === initialPathParam) ?? metabots[0];++ const view = renderWithProviders(<MetabotSettingsPanel metabot={metabot} />, {+ storeInitialState: {+ settings: createMockSettingsState(settings),},- );+ });- if (!error && waitForPageLoad) {- await screen.findByText(/Configure/);- }+ await screen.findByTestId("metabot-enabled-toggle");return view;};@@ -172,43 +158,14 @@ const setupContentVerificationPlugin = () => {setupEnterprisePlugins();};-describe("MetabotConfig", () => {+describe("MetabotSettingsPanel", () => {afterEach(() => {reinitialize();});- it("should render the page", async () => {+ it("should render the default metabot settings", async () => {await setup();- expect(screen.getByText(/Configure Metabot/)).toBeInTheDocument();- });-- it("should redirect to setup if not configured", async () => {- const { history } = await setup(- FIXED_METABOT_IDS.DEFAULT,- defaultMetabots,- defaultSeedCollections,- false,- createMockSettings({ "llm-metabot-configured?": false }),- false,- );-- await waitFor(() => {- expect(history?.getCurrentLocation()?.pathname).toBe(- "/admin/metabot/setup",- );- });- });-- it("should not redirect to setup if configured", async () => {- const { history } = await setup(- FIXED_METABOT_IDS.DEFAULT,- defaultMetabots,- defaultSeedCollections,- false,- createMockSettings({ "llm-metabot-configured?": true }),- );-- expect(history?.getCurrentLocation()?.pathname).toBe("/admin/metabot/1");+ expect(screen.getByText("Enable Metabot")).toBeInTheDocument();});it("should toggle default metabot enabled state", async () => {@@ -226,31 +183,13 @@ describe("MetabotConfig", () => {expect(call?.options?.body).toBe(JSON.stringify({ value: false }));});- it("should show collection picker for default metabot with NLQ title", async () => {+ it("should show the default collection section title", async () => {await setup();- expect(await screen.findByText("Configure Metabot")).toBeInTheDocument();expect(await screen.findByText(/Collection for natural language querying/),).toBeInTheDocument();});- it("should redirect from embedded metabot page to default without embedding features", async () => {- const { history } = await setup(- FIXED_METABOT_IDS.EMBEDDED,- defaultMetabots,- defaultSeedCollections,- false,- createMockSettings({ "llm-metabot-configured?": true }),- false,- );-- await waitFor(() => {- expect(history?.getCurrentLocation()?.pathname).toBe(- `/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}`,- );- });- });-it("should render a selected collection for embedded metabot", async () => {setupEmbeddingPlugin();await setup(FIXED_METABOT_IDS.EMBEDDED);@@ -270,18 +209,6 @@ describe("MetabotConfig", () => {expect(await screen.findByText("Our Analytics")).toBeInTheDocument();});- it("should be able to switch between metabots", async () => {- setupEmbeddingPlugin();- const { history } = await setup(FIXED_METABOT_IDS.DEFAULT);- expect(await screen.findByText("Configure Metabot")).toBeInTheDocument();-- mockPathParam(FIXED_METABOT_IDS.EMBEDDED);- act(() => {- history?.push(`/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}`);- });- expect(await screen.findByText("Collection Two")).toBeInTheDocument();- });-it("should change selected collection for embedded metabot", async () => {setupEmbeddingPlugin();await setup(FIXED_METABOT_IDS.EMBEDDED);@@ -311,12 +238,6 @@ describe("MetabotConfig", () => {new RegExp(`/api/metabot/metabot/${FIXED_METABOT_IDS.EMBEDDED}`),);expect(puts[0].body).toEqual({ collection_id: 31 });-- expect(- fetchMock.callHistory.calls(- `path:/api/metabot/metabot/${FIXED_METABOT_IDS.EMBEDDED}/prompt-suggestions?limit=10&offset=0`,- ).length,- ).toEqual(2); // +1 refetch for DELETE, +1 for PUT});it("should show special copy for embedded metabot", async () => {@@ -349,20 +270,9 @@ describe("MetabotConfig", () => {expect(call?.options?.body).toBe(JSON.stringify({ value: false }));});- it("should show an error message when a request fails", async () => {- await setup(404, defaultMetabots, defaultSeedCollections, true);-- expect(- await screen.findByText("Error fetching Metabots"),- ).toBeInTheDocument();- });-it("should not show verification switch without content_verification feature", async () => {await setup();- // First ensure the page has loaded- await screen.findByText(/Configure Metabot/);-expect(screen.queryByText("Verified content")).not.toBeInTheDocument();expect(screen.queryByText("Only use Verified content"),diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.tsxindex 3d8bcf7281a..aca58bd456b 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.tsx@@ -1,29 +1,43 @@-import { useCallback, useEffect, useMemo, useState } from "react";-import { t } from "ttag";+import {+ type ChangeEvent,+ type MutableRefObject,+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { P, match } from "ts-pattern";+import { c, t } from "ttag";import _ from "underscore";import { SettingsSection } from "metabase/admin/components/SettingsSection";import { SetByEnvVar } from "metabase/admin/settings/components/widgets/AdminSettingInput";import {- skipToken,useGetMetabotSettingsQuery,useUpdateMetabotSettingsMutation,+ useUpdateSettingsMutation,} from "metabase/api";import {getErrorMessage,useAdminSetting,useAdminSettings,} from "metabase/api/utils";-import { useSetting } from "metabase/common/hooks";+import { ExternalLink } from "metabase/common/components/ExternalLink";+import { useSetting, useToast } from "metabase/common/hooks";import { PLUGIN_METABOT } from "metabase/plugins";import {Badge,+ Button,type ComboboxItem,Flex,Group,Select,Stack,Text,+ TextInput,} from "metabase/ui";import type {MetabotProvider,@@ -31,13 +45,10 @@ import type {SettingDefinition,} from "metabase-types/api";-import { MetabotProviderApiKey } from "./MetabotProviderApiKey";import {API_KEY_SETTING_BY_PROVIDER,getProviderOptions,- isApiKeyMetabotProvider,isAvailableProvider,- isMetabotProvider,parseProviderAndModel,} from "./utils";@@ -54,210 +65,403 @@ function getModelDescription(provider: MetabotProvider | undefined) {return t`Available models are fetched from the selected provider using its configured API key.`;}-export function MetabotSetup() {+const MetabotSetupContext = createContext<{+ connectHandlerRef: MutableRefObject<(() => Promise<void>) | null> | null;+ isLoading: boolean;+ isConnectButtonEnabled: boolean;+ setIsConnectButtonEnabled: (enabled: boolean) => void;+}>({+ isLoading: false,+ connectHandlerRef: null,+ isConnectButtonEnabled: false,+ setIsConnectButtonEnabled: () => {},+});++export function useMetabotSetupContext(+ onConnect: (() => Promise<void>) | null,+) {+ const { connectHandlerRef, isLoading, setIsConnectButtonEnabled } =+ useContext(MetabotSetupContext);++ useEffect(() => {+ if (!connectHandlerRef) {+ return;+ }++ connectHandlerRef.current = onConnect;+ setIsConnectButtonEnabled(!!onConnect);++ return () => {+ setIsConnectButtonEnabled(false);+ connectHandlerRef.current = null;+ };+ }, [connectHandlerRef, onConnect, setIsConnectButtonEnabled]);++ return { isLoading };+}++export function MetabotSetup({ id }: { id?: string }) {const MetabaseAIProviderSetup = PLUGIN_METABOT.MetabaseAIProviderSetup;const offerMetabaseAiManaged = PLUGIN_METABOT.isEnabled;+ const [sendToast] = useToast();- const { value, settingDetails } = useAdminSetting("llm-metabot-provider");+ const { value: savedProviderValue, settingDetails } = useAdminSetting(+ "llm-metabot-provider",+ );const isEnvSetting =!!settingDetails &&!!settingDetails.is_env_setting &&!!settingDetails.env_name;const envSettingName = isEnvSetting ? settingDetails?.env_name : undefined;- const [updateMetabotSettings, updateMetabotSettingsResult] =- useUpdateMetabotSettingsMutation();- const savedProviderValue = updateMetabotSettingsResult.data?.value ?? value;const config = useMemo(() => parseProviderAndModel(savedProviderValue),[savedProviderValue],);+ const isConfigured = useSetting("llm-metabot-configured?");+ const connectedProvider = isConfigured ? config?.provider : undefined;+ const connectedModel = isConfigured ? config?.model : undefined;const [provider, setProvider] = useState<MetabotProvider | undefined>(- config?.provider,+ connectedProvider,);- const [model, setModel] = useState<string>(config?.model ?? "");- useEffect(() => {- setProvider(config?.provider);- setModel(config?.model ?? "");- }, [config]);- const handleMetabaseConnect = useCallback(async () => {- await updateMetabotSettings({ provider: "metabase", model: "" });- }, [updateMetabotSettings]);+ useEffect(() => {+ setProvider(connectedProvider);+ }, [connectedProvider]);- const metabotSettingsQuery = useGetMetabotSettingsQuery(- provider && provider !== "metabase" ? { provider } : skipToken,- );+ const [updateSettings, updateSettingsResult] = useUpdateSettingsMutation();- const isConfigured = useSetting("llm-metabot-configured?");const { details: providerApiKeyDetails } = useAdminSettings(["llm-anthropic-api-key","llm-openai-api-key","llm-openrouter-api-key",] as const);+ const handleDisconnect = useCallback(async () => {+ if (!connectedProvider) {+ return;+ }++ const settingsToClear: Record<string, null> = {+ "llm-metabot-provider": null,+ };++ if (connectedProvider !== "metabase") {+ const apiKeySettingKey = API_KEY_SETTING_BY_PROVIDER[connectedProvider];+ const apiKeySetting = providerApiKeyDetails[apiKeySettingKey];++ if (!apiKeySetting?.is_env_setting) {+ settingsToClear[apiKeySettingKey] = null;+ }+ }++ try {+ const response = await updateSettings(settingsToClear);++ if (response.error) {+ const message = getErrorMessage(+ response.error,+ t`Unable to save provider settings.`,+ );++ sendToast({+ message,+ icon: "warning",+ toastColor: "error",+ });+ }+ } catch (error) {+ const message = getErrorMessage(+ error,+ t`Unable to save provider settings.`,+ );++ sendToast({+ message,+ icon: "warning",+ toastColor: "error",+ });+ }+ }, [connectedProvider, providerApiKeyDetails, updateSettings, sendToast]);+const providerOptions = useMemo(() => {const options = Object.values(getProviderOptions(offerMetabaseAiManaged));- return options.map((o) => ({- ...o,- disabled: !isAvailableProvider(o.value),+ return options.map((option) => ({+ ...option,+ disabled: !isAvailableProvider(option.value),}));}, [offerMetabaseAiManaged]);+ const connectHandlerRef = useRef<(() => Promise<void>) | null>(null);++ const [isConnecting, setIsConnecting] = useState(false);+ const handleConnect = async () => {+ if (!connectHandlerRef.current) {+ return;+ }+ setIsConnecting(true);+ try {+ await connectHandlerRef.current();+ } finally {+ setIsConnecting(false);+ }+ };++ const isLoading = isConnecting || updateSettingsResult.isLoading;+ const [isConnectButtonEnabled, setIsConnectButtonEnabled] = useState(false);++ return (+ <MetabotSetupContext.Provider+ value={{+ connectHandlerRef,+ isLoading,+ setIsConnectButtonEnabled,+ isConnectButtonEnabled,+ }}+ >+ <SettingsSection+ id={id}+ title={+ <Flex justify="space-between" align="center">+ <Group gap="xs" wrap="nowrap">+ {isConfigured ? (+ <Badge circle size="12" bg="success" mr="sm" />+ ) : null}+ <div>+ {connectedProvider+ ? t`Connected to ${getProviderOptions(offerMetabaseAiManaged)[connectedProvider]?.label}`+ : t`Connect to an AI provider`}+ </div>+ </Group>+ </Flex>+ }+ description={+ !connectedProvider+ ? t`Select your AI provider to use AI explorations, SQL generation and Metabot.`+ : undefined+ }+ >+ <Stack gap="md">+ {!isConfigured && (+ <Select+ label={t`Provider`}+ placeholder={t`Select a provider`}+ data={providerOptions}+ value={provider}+ onChange={setProvider}+ disabled={isEnvSetting || isLoading}+ renderOption={({ option }) => (+ <Group+ gap="xs"+ p="sm"+ justify="space-between"+ wrap="nowrap"+ w="100%"+ >+ <Text+ lh="1rem"+ c={option.disabled ? "text-tertiary" : undefined}+ >+ {option.label}+ </Text>+ {!isAvailableProvider(option.value as MetabotProvider) && (+ <Text c="text-tertiary" lh="1rem" size="sm">+ {t`Coming soon`}+ </Text>+ )}+ </Group>+ )}+ />+ )}++ {match(provider)+ .with("metabase", () => <MetabaseAIProviderSetup />)+ .with(P.nonNullable, (selectedProvider) => (+ <AIProviderSetup+ selectedProvider={selectedProvider}+ connectedModel={connectedModel}+ isEnvSetting={isEnvSetting}+ />+ ))+ .with(P.nullish, () => null)+ .exhaustive()}++ {envSettingName && <SetByEnvVar varName={envSettingName} />}++ <Flex justify="end">+ {isConfigured ? (+ <Button+ c="danger"+ loading={isLoading}+ disabled={isLoading}+ onClick={handleDisconnect}+ >+ {t`Disconnect`}+ </Button>+ ) : (+ <Button+ variant="filled"+ loading={isLoading}+ disabled={isLoading || !isConnectButtonEnabled}+ onClick={handleConnect}+ >+ {t`Connect`}+ </Button>+ )}+ </Flex>+ </Stack>+ </SettingsSection>+ </MetabotSetupContext.Provider>+ );+}++const AIProviderSetup = ({+ selectedProvider,+ connectedModel,+ isEnvSetting,+}: {+ selectedProvider: Exclude<MetabotProvider, "metabase">;+ connectedModel: string | undefined;+ isEnvSetting: boolean;+}) => {+ const [model, setModel] = useState<string | undefined>(connectedModel);+ const [apiKeyLocalValue, setApiKeyLocalValue] = useState<string | null>(null);+ const [sendToast] = useToast();++ useEffect(() => {+ setModel(connectedModel);+ }, [connectedModel]);++ const [updateMetabotSettings, updateMetabotSettingsResult] =+ useUpdateMetabotSettingsMutation();++ const onConnect = async () => {+ await updateMetabotSettings({+ provider: selectedProvider,+ "api-key": apiKeyLocalValue || null,+ }).unwrap();++ setApiKeyLocalValue(null);+ };++ const { isLoading } = useMetabotSetupContext(onConnect);++ const { details: providerApiKeyDetails } = useAdminSettings([+ "llm-anthropic-api-key",+ "llm-openai-api-key",+ "llm-openrouter-api-key",+ ] as const);++ const selectedApiKeySetting =+ providerApiKeyDetails[API_KEY_SETTING_BY_PROVIDER[selectedProvider]];+ const selectedApiKeyValue = String(selectedApiKeySetting?.value ?? "");+ const needsApiKey = !hasConfiguredSettingValue(selectedApiKeySetting);++ const metabotSettingsQuery = useGetMetabotSettingsQuery(+ {+ provider: selectedProvider,+ },+ { skip: needsApiKey },+ );+const modelOptions = useMemo(() => getLlmModelOptions(metabotSettingsQuery.currentData?.models ?? []),[metabotSettingsQuery.currentData?.models],);- const apiKeyError = metabotSettingsQuery.data?.["api-key-error"] ?? undefined;- const modelError = getModelError(metabotSettingsQuery.error, provider);- const saveError = updateMetabotSettingsResult.error- ? getErrorMessage(- updateMetabotSettingsResult,- t`Unable to save provider settings.`,- )- : undefined;-- const handleProviderChange = (value: string) => {- if (isMetabotProvider(value)) {- setProvider(value);- const configModel =- value === config?.provider ? (config.model ?? "") : "";- setModel(configModel);- }+ const modelError = getModelError(+ metabotSettingsQuery.error,+ selectedProvider,+ );++ const displayApiKeyValue = apiKeyLocalValue ?? selectedApiKeyValue;++ useEffect(() => {+ setApiKeyLocalValue(null);+ }, [selectedProvider, selectedApiKeySetting?.value]);++ const handleApiKeyChange = (event: ChangeEvent<HTMLInputElement>) => {+ setApiKeyLocalValue(event.target.value);};const handleModelChange = async (value: string) => {setModel(value);- if (provider && value) {- await updateMetabotSettings({ provider, model: value });++ if (!value) {+ return;}- };- const isConnected = Boolean(- !updateMetabotSettingsResult.isLoading &&- config?.provider &&- config?.model &&- isConfigured,- );- const isMetabaseProviderConnected = Boolean(- isConnected && provider === "metabase" && config?.provider === "metabase",- );+ await updateMetabotSettings({+ provider: selectedProvider,+ model: value,+ }).unwrap();- const selectedApiKeySetting =- provider && isApiKeyMetabotProvider(provider)- ? providerApiKeyDetails[API_KEY_SETTING_BY_PROVIDER[provider]]- : undefined;+ sendToast({+ message: t`Settings saved successfully`,+ icon: "check",+ });+ };- const needsApiKey =- !!provider &&- !!selectedApiKeySetting &&- (!hasConfiguredSettingValue(selectedApiKeySetting) || !!apiKeyError);- const showModelSelector =- !needsApiKey && !isMetabaseProviderConnected && provider !== "metabase";+ const selectedProviderDetails = getProviderOptions(true)[selectedProvider];return (- <SettingsSection- title={- <Flex justify="space-between" align="center">- <div>{t`Connect to an AI provider`}</div>- {isConnected ? (- <Badge bg="success" variant="filled" size="sm">- {t`Connected`}- </Badge>- ) : (- <Badge- bg="background-tertiary"- c="text-tertiary"- variant="filled"- size="sm"- >- {t`Not connected`}- </Badge>- )}- </Flex>- }- description={t`Select your AI provider to get started with Metabot.`}- >- <Stack gap="md">+ <>+ <TextInput+ key={selectedProvider}+ label={t`API key`}+ type="password"+ description={+ <ExternalLink+ key={selectedProviderDetails.value}+ href={selectedProviderDetails.apiKey.addKeyUrl}+ >+ {c("{0} is the name of an AI provider")+ .t`Get or manage keys in ${selectedProviderDetails.label}`}+ </ExternalLink>+ }+ placeholder={+ selectedProviderDetails.apiKey?.placeholder ?? t`Enter your API key`+ }+ value={displayApiKeyValue}+ onChange={handleApiKeyChange}+ disabled={isLoading || isEnvSetting}+ w="100%"+ />++ {isEnvSetting && selectedApiKeySetting?.env_name ? (+ <SetByEnvVar varName={selectedApiKeySetting.env_name} />+ ) : null}++ {!needsApiKey && (<Select- label={t`Provider`}- placeholder={t`Select a provider`}- description={t`Choose your preferred AI provider.`}- data={providerOptions}- value={provider}- onChange={handleProviderChange}- disabled={isEnvSetting}- renderOption={({ option }) => (- <Group- gap="xs"- p="sm"- justify="space-between"- wrap="nowrap"- w="100%"- >- <Text lh="1rem" c={option.disabled ? "text-tertiary" : undefined}>- {option.label}- </Text>- {!isAvailableProvider(option.value as MetabotProvider) && (- <Text c="text-tertiary" lh="1rem" size="sm">- {t`Coming soon`}- </Text>- )}- </Group>- )}+ label={t`Model`}+ placeholder={+ metabotSettingsQuery.isFetching+ ? t`Loading models...`+ : t`Select a model`+ }+ description={getModelDescription(selectedProvider)}+ error={modelError}+ data={modelOptions}+ value={model}+ onChange={handleModelChange}+ disabled={isEnvSetting || needsApiKey || isLoading}+ searchable+ nothingFoundMessage={t`No models found`}/>+ )}- {provider === "metabase" && (- <MetabaseAIProviderSetup- isMetabaseProviderConnected={isMetabaseProviderConnected}- isSavingMetabaseConnection={updateMetabotSettingsResult.isLoading}- onConnect={handleMetabaseConnect}- />- )}-- {provider && isApiKeyMetabotProvider(provider) && (- <MetabotProviderApiKey provider={provider} error={apiKeyError} />- )}-- {showModelSelector && (- <Select- label={t`Model`}- placeholder={- provider- ? metabotSettingsQuery.isFetching- ? t`Loading models...`- : t`Select a model`- : t`Select a provider first`- }- description={getModelDescription(provider)}- error={modelError}- data={modelOptions}- value={model}- onChange={handleModelChange}- disabled={isEnvSetting || needsApiKey}- searchable- nothingFoundMessage={t`No models found`}- />- )}-- {envSettingName && <SetByEnvVar varName={envSettingName} />}-- {updateMetabotSettingsResult.isLoading && (- <Text size="sm" c="text-secondary">- {t`Saving provider settings...`}- </Text>- )}-- {saveError && (- <Text size="sm" c="error">- {saveError}- </Text>- )}- </Stack>- </SettingsSection>+ {updateMetabotSettingsResult.error && (+ <Text size="sm" c="error">+ {getErrorMessage(+ updateMetabotSettingsResult.error,+ t`Unable to save provider settings.`,+ )}+ </Text>+ )}+ </>);-}+};const getLlmModelOptions = (models: MetabotSettingsResponse["models"]) => {const modelOptions = models.map((m) => ({diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.unit.spec.tsxindex f88e1ea5a0d..3cf98079e5a 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSetup.unit.spec.tsx@@ -7,7 +7,6 @@ import {setupBillingEndpoints,setupMetabaseManagedAiEndpoints,setupPropertiesEndpoints,- setupSettingsEndpoints,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { act, renderWithProviders, screen, waitFor } from "__support__/ui";@@ -15,6 +14,7 @@ import { reinitialize } from "metabase/plugins";import type {MetabotProvider,MetabotSettingsResponse,+ SettingDefinition,TokenStatusFeature,} from "metabase-types/api";import {@@ -27,21 +27,6 @@ import {import { MetabotSetup } from "./MetabotSetup";import type { MetabotApiKeyProvider } from "./utils";-jest.mock("./MetabotProviderApiKey", () => ({- MetabotProviderApiKey: ({- provider,- error,- }: {- provider: MetabotProvider;- error?: string | null;- }) => (- <div>- <div>{`Provider API key: ${provider}`}</div>- {error ? <div>{`API key error: ${error}`}</div> : null}- </div>- ),-}));-const DEFAULT_RESPONSES: Record<MetabotProvider, MetabotSettingsResponse> = {metabase: {value: "metabase/anthropic/claude-sonnet-4-6",@@ -99,6 +84,23 @@ type MetabotUsageQuota = {updated_at: string | null;};+type MetabotSettingsApiResponse =+ | MetabotSettingsResponse+ | (() => Promise<MetabotSettingsResponse>);++type MetabotSettingKey =+ | "llm-metabot-provider"+ | "llm-anthropic-api-key"+ | "llm-openai-api-key"+ | "llm-openrouter-api-key";++type MetabotSettingDefinition = SettingDefinition<MetabotSettingKey>;+type MetabotSettingsUpdateBody = {+ provider: MetabotProvider;+ model?: string;+ "api-key"?: string | null;+};+type SetupOptions = {isHosted?: boolean;llmProxyConfigured?: boolean;@@ -115,12 +117,9 @@ type SetupOptions = {refreshedTokenStatusFeatures?: TokenStatusFeature[];purchaseCloudAddOnResponse?: number | { status: number; body: unknown };apiKeyValues?: Partial<Record<MetabotProvider, string | null>>;- responses?: Partial<- Record<- MetabotProvider,- MetabotSettingsResponse | (() => Promise<MetabotSettingsResponse>)- >- >;+ pauseUpdateResponse?: boolean;+ settingUpdateResponse?: number | { status: number; body?: unknown };+ responses?: Partial<Record<MetabotProvider, MetabotSettingsApiResponse>>;updateResponse?: MetabotSettingsResponse;};@@ -140,6 +139,8 @@ async function setup({refreshedTokenStatusFeatures = tokenStatusFeatures,purchaseCloudAddOnResponse = 200,apiKeyValues,+ pauseUpdateResponse = false,+ settingUpdateResponse = 204,responses,updateResponse = {value: "anthropic/claude-sonnet-4-5",@@ -180,28 +181,36 @@ async function setup({setupPropertiesEndpoints(sessionProperties);- setupSettingsEndpoints([- createMockSettingDefinition({+ const settingsDefinitions: Record<+ MetabotSettingKey,+ MetabotSettingDefinition+ > = {+ "llm-metabot-provider": createMockSettingDefinition({key: "llm-metabot-provider",value: savedProviderValue,is_env_setting: providerSettingIsEnv,env_name: providerSettingIsEnv ? providerSettingEnvName : undefined,}),- createMockSettingDefinition({+ "llm-anthropic-api-key": createMockSettingDefinition({key: "llm-anthropic-api-key",value: mergedApiKeyValues.anthropic ?? undefined,}),- createMockSettingDefinition({+ "llm-openai-api-key": createMockSettingDefinition({key: "llm-openai-api-key",value: mergedApiKeyValues.openai ?? undefined,}),- createMockSettingDefinition({+ "llm-openrouter-api-key": createMockSettingDefinition({key: "llm-openrouter-api-key",value: mergedApiKeyValues.openrouter ?? undefined,}),- ]);+ };- const responseMap = { ...DEFAULT_RESPONSES, ...responses };+ fetchMock.get("path:/api/setting", () => Object.values(settingsDefinitions));++ const responseMap: Record<MetabotProvider, MetabotSettingsApiResponse> = {+ ...DEFAULT_RESPONSES,+ ...responses,+ };if (isHosted) {setupBillingEndpoints({@@ -246,18 +255,98 @@ async function setup({});}- fetchMock.put("path:/api/metabot/settings", () => {- sessionProperties["llm-metabot-provider"] = updateResponse.value;- sessionProperties["llm-metabot-configured?"] = true;+ fetchMock.put("path:/api/metabot/settings", (call) => {+ if (pauseUpdateResponse) {+ return new Promise(() => undefined);+ }- return updateResponse;+ return handleMetabotSettingsUpdate(call);});- const { history } = renderWithProviders(+ const handleMetabotSettingsUpdate = (call: { options?: RequestInit }) => {+ const body = JSON.parse(+ String(call.options?.body ?? "{}"),+ ) as MetabotSettingsUpdateBody;++ if ("api-key" in body) {+ const apiKeySettingKey =+ body.provider === "anthropic"+ ? "llm-anthropic-api-key"+ : body.provider === "openai"+ ? "llm-openai-api-key"+ : "llm-openrouter-api-key";+ const maskedApiKey = body["api-key"]+ ? `**********${String(body["api-key"]).slice(-2)}`+ : undefined;++ settingsDefinitions[apiKeySettingKey] = createMockSettingDefinition({+ ...settingsDefinitions[apiKeySettingKey],+ key: apiKeySettingKey,+ value: maskedApiKey,+ });+ }++ if ("model" in body) {+ sessionProperties["llm-metabot-provider"] = updateResponse.value;+ sessionProperties["llm-metabot-configured?"] = true;+ settingsDefinitions["llm-metabot-provider"] = createMockSettingDefinition(+ {+ ...settingsDefinitions["llm-metabot-provider"],+ key: "llm-metabot-provider",+ value: updateResponse.value,+ },+ );++ return updateResponse;+ }++ const providerResponse = responseMap[body.provider];+ const providerSettings =+ typeof providerResponse === "function"+ ? DEFAULT_RESPONSES[body.provider]+ : providerResponse;++ return {+ value: sessionProperties["llm-metabot-provider"],+ models: providerSettings.models,+ };+ };++ fetchMock.put("path:/api/setting", (call) => {+ if (settingUpdateResponse !== 204) {+ return settingUpdateResponse;+ }++ const body = JSON.parse(String(call.options?.body ?? "{}")) as Partial<+ Record<MetabotSettingKey, string | null>+ >;++ Object.entries(body).forEach(([key, nextValue]) => {+ if (key in settingsDefinitions) {+ settingsDefinitions[key as keyof typeof settingsDefinitions] =+ createMockSettingDefinition({+ ...settingsDefinitions[key as keyof typeof settingsDefinitions],+ key: key as keyof typeof settingsDefinitions,+ value: (nextValue ??+ undefined) as MetabotSettingDefinition["value"],+ });+ }++ if (key === "llm-metabot-provider") {+ sessionProperties["llm-metabot-provider"] =+ (nextValue as string | null) ?? null;+ sessionProperties["llm-metabot-configured?"] = Boolean(nextValue);+ }+ });++ return 204;+ });++ const { history, store } = renderWithProviders(<Route path="/admin/metabot*" component={MetabotSetup} />,{withRouter: true,- initialRoute: "/admin/metabot/setup",+ initialRoute: "/admin/metabot",storeInitialState: {settings,},@@ -265,10 +354,17 @@ async function setup({);if (!isHosted) {- await screen.findByLabelText("Provider");+ await screen.findByText(+ isConfigured+ ? /Connected to|Connect to an AI provider/+ : "Connect to an AI provider",+ );}- return { history };+ return {+ history,+ store,+ };}async function openModelSelector() {@@ -288,6 +384,8 @@ describe("MetabotSetup", () => {it("shows the env var message and disables both provider and model inputs when provider is env-backed", async () => {await setup({+ savedProviderValue: null,+ isConfigured: false,providerSettingIsEnv: true,apiKeyValues: { anthropic: "**********45" },});@@ -298,11 +396,11 @@ describe("MetabotSetup", () => {"This has been set by the LLM_METABOT_PROVIDER environment variable.",);expect(screen.getByLabelText("Provider")).toBeDisabled();- expect(await screen.findByLabelText("Model")).toBeDisabled();+ expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();});it("shows Anthropic as selectable in the provider dropdown", async () => {- await setup();+ await setup({ savedProviderValue: null, isConfigured: false });await userEvent.click(screen.getByLabelText("Provider"));@@ -314,7 +412,7 @@ describe("MetabotSetup", () => {});it("shows Coming soon for non-Anthropic providers and disables them", async () => {- await setup();+ await setup({ savedProviderValue: null, isConfigured: false });await userEvent.click(screen.getByLabelText("Provider"));@@ -333,18 +431,35 @@ describe("MetabotSetup", () => {it("shows the connected badge with the saved provider and model", async () => {await setup();- await screen.findByText(/Provider API key: anthropic/);+ await screen.findByLabelText("API key");await screen.findByLabelText("Model");- expect(await screen.findByText("Connected")).toBeInTheDocument();+ expect(+ await screen.findByText("Connected to Anthropic"),+ ).toBeInTheDocument();+ expect(screen.queryByLabelText("Provider")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Disconnect" }),+ ).toBeInTheDocument();expect(screen.queryByText("Not connected")).not.toBeInTheDocument();});- it("shows the not connected badge when not configured", async () => {+ it("shows the disconnected title when not configured", async () => {await setup({ savedProviderValue: null, isConfigured: false });- expect(await screen.findByText("Not connected")).toBeInTheDocument();- expect(screen.queryByText("Connected")).not.toBeInTheDocument();+ expect(+ await screen.findByText("Connect to an AI provider"),+ ).toBeInTheDocument();+ expect(screen.queryByText(/^Connected to /)).not.toBeInTheDocument();+ });++ it("does not preselect a provider in the disconnected state", async () => {+ await setup({+ savedProviderValue: "anthropic/claude-haiku-4-5",+ isConfigured: false,+ });++ expect(await screen.findByLabelText("Provider")).toHaveValue("");});// TODO: Add these tests back once we allow configuring the model provider from the UI.@@ -425,7 +540,7 @@ describe("MetabotSetup", () => {it("does not show the API key input when no provider is selected", async () => {await setup({ savedProviderValue: null, isConfigured: false });- expect(screen.queryByText(/Provider API key:/)).not.toBeInTheDocument();+ expect(screen.queryByLabelText("API key")).not.toBeInTheDocument();});it("does not show the model selector when there is no API key", async () => {@@ -433,28 +548,23 @@ describe("MetabotSetup", () => {apiKeyValues: { anthropic: null },});- await screen.findByText(/Provider API key: anthropic/);+ await screen.findByLabelText("API key");expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();});- it("does not show the model selector when the configured API key is incorrect", async () => {+ it("keeps the provider selector visible after verifying an API key", async () => {await setup({- apiKeyValues: { anthropic: "**********45" },- responses: {- anthropic: {- value: "anthropic/claude-haiku-4-5",- "api-key-error": "Anthropic API key expired or invalid",- models: [],- },- },+ savedProviderValue: null,+ isConfigured: false,+ apiKeyValues: { anthropic: null },});- expect(- await screen.findByText(- "API key error: Anthropic API key expired or invalid",- ),- ).toBeInTheDocument();- expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();+ await selectProvider("Anthropic");+ await userEvent.type(screen.getByLabelText("API key"), "sk-ant-valid");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await screen.findByLabelText("Model");+ expect(screen.getByLabelText("Provider")).toHaveValue("Anthropic");});it("shows the connected Metabase-managed state without an API key or model picker", async () => {@@ -466,8 +576,11 @@ describe("MetabotSetup", () => {expect(await screen.findByText("Current billing cycle"),).toBeInTheDocument();- expect(screen.queryByText(/Provider API key:/)).not.toBeInTheDocument();+ expect(screen.queryByLabelText("API key")).not.toBeInTheDocument();expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Disconnect" }),+ ).toBeInTheDocument();});it("shows pricing details in a tooltip for the Metabase provider", async () => {@@ -477,6 +590,7 @@ describe("MetabotSetup", () => {isConfigured: false,});+ await selectProvider("Metabase");await screen.findByText("About Metabase AI service");await screen.findByTestId("metabase-ai-pricing-details");@@ -502,6 +616,7 @@ describe("MetabotSetup", () => {anyStoreUserEmailAddress: "[email protected]",});+ await selectProvider("Metabase");expect(await screen.findByText("Please ask a Metabase Store Admin ([email protected]) of your organization to enable this for you.",@@ -517,8 +632,8 @@ describe("MetabotSetup", () => {await setup({isHosted: true,- savedProviderValue: "anthropic/claude-haiku-4-5",- isConfigured: true,+ savedProviderValue: null,+ isConfigured: false,isStoreUser: false,tokenStatusFeatures: ["metabase-ai-managed"],updateResponse: {@@ -535,7 +650,7 @@ describe("MetabotSetup", () => {expect(screen.queryByRole("checkbox", {- name: /I agree with the Metabase AI add-on/i,+ name: /I agree with the Metabase AI Service/i,}),).not.toBeInTheDocument();@@ -582,8 +697,9 @@ describe("MetabotSetup", () => {},});+ await selectProvider("Metabase");const termsCheckbox = await screen.findByRole("checkbox", {- name: /I agree with the Metabase AI add-on/i,+ name: /I agree with the Metabase AI Service/i,});const connectButton = await screen.findByRole("button", {name: "Connect",@@ -652,6 +768,9 @@ describe("MetabotSetup", () => {expect(screen.queryByRole("button", { name: "Connect" }),).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Disconnect" }),+ ).toBeInTheDocument();const settingsRequest = fetchMock.callHistory.calls("path:/api/metabot/settings")@@ -703,8 +822,12 @@ describe("MetabotSetup", () => {expect(screen.getByText("$1.06")).toBeInTheDocument();});- it("saves when picking a model from the model picker", async () => {- await setup();+ it("saves when picking a model", async () => {+ const { store } = await setup({+ savedProviderValue: null,+ isConfigured: false,+ });+ await selectProvider("Anthropic");await screen.findByLabelText("Model");await openModelSelector();@@ -723,5 +846,95 @@ describe("MetabotSetup", () => {expect(request?.options?.body).toBe(JSON.stringify({ provider: "anthropic", model: "claude-sonnet-4-5" }),);++ await waitFor(() => {+ expect(+ store+ .getState()+ .undo.some(+ (toast) => toast.message === "Settings saved successfully",+ ),+ ).toBe(true);+ });++ expect(+ screen.queryByRole("button", { name: "Connect" }),+ ).not.toBeInTheDocument();+ });++ it("disconnects an API-key provider by clearing both the provider and API key settings", async () => {+ await setup();++ await screen.findByLabelText("API key");+ await userEvent.click(+ await screen.findByRole("button", { name: "Disconnect" }),+ );++ await waitFor(() => {+ expect(fetchMock.callHistory.called("path:/api/setting")).toBe(true);+ });++ const request = fetchMock.callHistory+ .calls("path:/api/setting")+ .find((call) => call.request?.method === "PUT");++ expect(request?.options?.body).toBe(+ JSON.stringify({+ "llm-metabot-provider": null,+ "llm-anthropic-api-key": null,+ }),+ );++ expect(+ await screen.findByText("Connect to an AI provider"),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Provider")).toHaveValue("");+ expect(+ screen.queryByRole("button", { name: "Disconnect" }),+ ).not.toBeInTheDocument();+ });++ it("disconnects the Metabase-managed provider without clearing an API key", async () => {+ await setup({+ isHosted: true,+ savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",+ });++ await screen.findByText("Current billing cycle");+ await userEvent.click(+ await screen.findByRole("button", { name: "Disconnect" }),+ );++ await waitFor(() => {+ expect(fetchMock.callHistory.called("path:/api/setting")).toBe(true);+ });++ const request = fetchMock.callHistory+ .calls("path:/api/setting")+ .find((call) => call.request?.method === "PUT");++ expect(request?.options?.body).toBe(+ JSON.stringify({+ "llm-metabot-provider": null,+ }),+ );+ });++ it("shows an error toast when disconnect fails", async () => {+ const { store } = await setup({ settingUpdateResponse: { status: 500 } });++ await userEvent.click(+ await screen.findByRole("button", { name: "Disconnect" }),+ );++ await waitFor(() => {+ expect(+ store+ .getState()+ .undo.some(+ (toast) => toast.message === "Unable to save provider settings.",+ ),+ ).toBe(true);+ });});});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsxindex bfda6d06e17..794da1eaa73 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx@@ -63,7 +63,7 @@ export function MetabotSetupRequiredAlert() {><Text mt="sm"><Link- to="/admin/metabot/setup"+ to="/admin/metabot#setup"variant="brand">{t`Connect to a provider`}</Link></Text>diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsxindex 8524bc83d33..cabd96b2d38 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx@@ -2,18 +2,14 @@ import { IndexRoute, Route } from "react-router";import { PLUGIN_AI_CONTROLS } from "metabase/plugins";-import { McpAppsSettings } from "./McpAppsSettings";+import { AISettingsPage } from "./AISettingsPage";import { MetabotAdminLayout } from "./MetabotAdminLayout";-import { MetabotConfig } from "./MetabotConfig";-import { MetabotSetup } from "./MetabotSetup";export function getMetabotAdminRoutes() {return [<Route key="layout" component={MetabotAdminLayout}>- <IndexRoute key="index" component={MetabotConfig} />- <Route key="setup" path="setup" component={MetabotSetup} />- <Route key="mcp" path="mcp" component={McpAppsSettings} />,- <Route key="metabot" path=":metabotId" component={MetabotConfig} />+ <IndexRoute key="index" component={AISettingsPage} />+ <Route key="metabot" path=":metabotId" component={AISettingsPage} />{PLUGIN_AI_CONTROLS.getAiControlsRoutes()}</Route>,];diff --git a/frontend/src/metabase/plugins/oss/ai-controls.ts b/frontend/src/metabase/plugins/oss/ai-controls.tsindex b6009db7c43..b47fd61dc74 100644--- a/frontend/src/metabase/plugins/oss/ai-controls.ts+++ b/frontend/src/metabase/plugins/oss/ai-controls.ts@@ -1,15 +1,15 @@-import type { ReactNode } from "react";+import type { ComponentType, ReactNode } from "react";export type AiControlsPlugin = {isEnabled: boolean;getAiControlsRoutes: () => ReactNode;- getAiControlsNavItems: () => ReactNode;+ AiControlsNavItems: ComponentType | null;};const getDefaultPluginAiControls = (): AiControlsPlugin => ({isEnabled: false,getAiControlsRoutes: () => null,- getAiControlsNavItems: () => null,+ AiControlsNavItems: null,});export const PLUGIN_AI_CONTROLS = getDefaultPluginAiControls();diff --git a/frontend/src/metabase/plugins/oss/metabot.ts b/frontend/src/metabase/plugins/oss/metabot.tsindex 672e7811ed3..3cb3407eb27 100644--- a/frontend/src/metabase/plugins/oss/metabot.ts+++ b/frontend/src/metabase/plugins/oss/metabot.ts@@ -2,21 +2,14 @@ import type { ComponentType } from "react";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";-type MetabaseAIProviderSetupProps = {- isMetabaseProviderConnected: boolean;- isSavingMetabaseConnection: boolean;- onConnect: () => Promise<void>;-};-const getDefaultPluginMetabot = () => ({isEnabled: false,- MetabaseAIProviderSetup:- PluginPlaceholder as ComponentType<MetabaseAIProviderSetupProps>,+ MetabaseAIProviderSetup: PluginPlaceholder as ComponentType,});export const PLUGIN_METABOT: {isEnabled: boolean;- MetabaseAIProviderSetup: ComponentType<MetabaseAIProviderSetupProps>;+ MetabaseAIProviderSetup: ComponentType;} = getDefaultPluginMetabot();/**diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex e80eb52e09e..5a2251ad331 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -4,6 +4,7 @@(:require[clojure.string :as str][malli.core :as mc]+ [metabase.agent-api.validation :as agent-api.validation][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.macros.scope :as scope]@@ -855,6 +856,10 @@"Agent API authentication middleware. Supports both session-based and stateless JWT authentication."(api.routes.common/wrap-middleware-for-open-api-spec-generation enforce-authentication))+(def +agent-api-enabled+ "Wrap routes so they may only be accessed when the Agent API is enabled."+ agent-api.validation/+agent-api-enabled)+;;; ---------------------------------------------------- Routes ------------------------------------------------------(def ^{:arglists '([request respond raise])} routesdiff --git a/src/metabase/agent_api/init.clj b/src/metabase/agent_api/init.cljnew file mode 100644index 00000000000..b71d06a86cb--- /dev/null+++ b/src/metabase/agent_api/init.clj@@ -0,0 +1,3 @@+(ns metabase.agent-api.init+ (:require+ [metabase.agent-api.settings]))diff --git a/src/metabase/agent_api/settings.clj b/src/metabase/agent_api/settings.cljnew file mode 100644index 00000000000..bfab4d53d07--- /dev/null+++ b/src/metabase/agent_api/settings.clj@@ -0,0 +1,15 @@+(ns metabase.agent-api.settings+ (:require+ [metabase.llm.settings :as llm.settings]+ [metabase.settings.core :as setting :refer [defsetting]]+ [metabase.util.i18n :refer [deferred-tru]]))++(defsetting agent-api-enabled?+ (deferred-tru "Whether the Agent API is enabled.")+ :type :boolean+ :visibility :public+ :default true+ :getter #(and (llm.settings/ai-features-enabled?)+ (setting/get-value-of-type :boolean :agent-api-enabled?))+ :export? true+ :doc false)diff --git a/src/metabase/agent_api/validation.clj b/src/metabase/agent_api/validation.cljnew file mode 100644index 00000000000..fff044640e7--- /dev/null+++ b/src/metabase/agent_api/validation.clj@@ -0,0 +1,33 @@+(ns metabase.agent-api.validation+ (:require+ [metabase.agent-api.settings :as agent-api.settings]+ [metabase.api.common :as api]+ [metabase.api.routes.common :as routes.common]+ [metabase.llm.settings :as llm.settings]+ [metabase.util.i18n :refer [tru]]))++(defn check-agent-api-enabled+ "Check that the Agent API is enabled, or throw a 403."+ []+ (api/check (llm.settings/ai-features-enabled?)+ [403 (tru "AI features are not enabled.")])+ (api/check (agent-api.settings/agent-api-enabled?)+ [403 (tru "Agent API is not enabled.")]))++(defn enforce-agent-api-enabled+ "Ring middleware that blocks external Agent API requests when the feature is disabled."+ [handler]+ (fn [request respond raise]+ (cond+ (not (llm.settings/ai-features-enabled?))+ (raise (ex-info (tru "AI features are not enabled.") {:status-code 403}))++ (agent-api.settings/agent-api-enabled?)+ (handler request respond raise)++ :else+ (raise (ex-info (tru "Agent API is not enabled.") {:status-code 403})))))++(def ^{:arglists '([handler])} +agent-api-enabled+ "Wrap routes so they may only be accessed when the Agent API is enabled."+ (routes.common/wrap-middleware-for-open-api-spec-generation enforce-agent-api-enabled))diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex a76e82323a4..f8b171fea98 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -155,7 +155,7 @@(def ^:private route-map{"/action" (+auth 'metabase.actions-rest.api)"/activity" (+auth 'metabase.activity-feed.api)- "/agent" metabase.agent-api.api/routes+ "/agent" (metabase.agent-api.api/+agent-api-enabled metabase.agent-api.api/routes)"/ai-entity-analysis" metabase.metabot.api.entity-analysis/routes"/alert" (+auth metabase.pulse.api/alert-routes)"/analytics" (+auth 'metabase.analytics.api)@@ -188,7 +188,7 @@"/llm" (+auth metabase.llm.api/routes)"/logger" (+auth 'metabase.logger.api)"/login-history" (+auth 'metabase.login-history.api)- "/mcp" metabase.mcp.api/handler+ "/mcp" (metabase.mcp.api/+mcp-enabled metabase.mcp.api/handler)"/measure" (+auth 'metabase.measures.api)"/metabot" metabase.metabot.api/routes"/metric" (+auth 'metabase.metrics.api)diff --git a/src/metabase/core/init.clj b/src/metabase/core/init.cljindex 090a4f4c40a..7a8bfc3a7de 100644--- a/src/metabase/core/init.clj+++ b/src/metabase/core/init.clj@@ -8,6 +8,7 @@(:require[metabase.actions.init][metabase.activity-feed.init]+ [metabase.agent-api.init][metabase.analytics.init][metabase.api-scope.init][metabase.api.init]diff --git a/src/metabase/llm/settings.clj b/src/metabase/llm/settings.cljindex ed340627562..fcbf2d3618d 100644--- a/src/metabase/llm/settings.clj+++ b/src/metabase/llm/settings.clj@@ -131,6 +131,15 @@:export? false:doc false)+(defsetting ai-service-base-url+ (deferred-tru "Base URL for the managed Metabase AI service.")+ :feature :metabase-ai-managed+ :encryption :no+ :visibility :internal+ :default nil+ :export? false+ :doc false)+(defsetting llm-proxy-configured?(deferred-tru "Whether the LLM proxy is configured for the managed Metabase AI service."):encryption :no@@ -142,6 +151,14 @@;;; -------------------------------------------------- General --------------------------------------------------+(defsetting ai-features-enabled?+ (deferred-tru "Whether AI features are enabled.")+ :type :boolean+ :visibility :public+ :default true+ :export? true+ :doc false)+(defsetting llm-max-tokens(deferred-tru "Maximum tokens for LLM responses."):type :integerdiff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljindex bbe03f7aa71..4b9b9694a0d 100644--- a/src/metabase/mcp/api.clj+++ b/src/metabase/mcp/api.clj@@ -10,6 +10,7 @@[metabase.api.macros.scope :as scope][metabase.api.open-api :as open-api][metabase.mcp.tools :as mcp.tools]+ [metabase.mcp.validation :as mcp.validation][metabase.oauth-server.core :as oauth-server][metabase.request.core :as request][metabase.server.streaming-response :as streaming-response]@@ -276,6 +277,10 @@(defn- www-authenticate-discovery [](str "Bearer realm=\"mcp\" resource_metadata=\"" (system/site-url) "/.well-known/oauth-protected-resource/api/mcp\""))+(def +mcp-enabled+ "Wrap routes so they may only be accessed when the MCP server is enabled."+ mcp.validation/+mcp-enabled)+(def ^{:arglists '([request respond raise])} handler"Ring async handler for the MCP endpoint.Uses JSON-RPC 2.0 over HTTP rather than REST, so the OpenAPI spec is empty."diff --git a/src/metabase/mcp/settings.clj b/src/metabase/mcp/settings.cljindex d134f7e2400..c147628115c 100644--- a/src/metabase/mcp/settings.clj+++ b/src/metabase/mcp/settings.clj@@ -2,7 +2,8 @@"Settings for MCP Apps CORS origins."(:require[clojure.string :as str]- [metabase.settings.core :refer [defsetting]]+ [metabase.llm.settings :as llm.settings]+ [metabase.settings.core :as setting :refer [defsetting]][metabase.util.i18n :refer [deferred-tru]]));;; ------------------------------------------------ Client → Domain Mapping --------------------------------@@ -18,6 +19,16 @@;;; ------------------------------------------------ Settings ------------------------------------------------+(defsetting mcp-enabled?+ (deferred-tru "Whether the MCP server is enabled.")+ :type :boolean+ :default true+ :visibility :public+ :getter #(and (llm.settings/ai-features-enabled?)+ (setting/get-value-of-type :boolean :mcp-enabled?))+ :export? true+ :doc false)+(defsetting mcp-apps-cors-enabled-clients(deferred-tru "Popular MCP clients enabled for CORS, stored as CSV client keys (e.g. claude, vscode)."):type :csvdiff --git a/src/metabase/mcp/validation.clj b/src/metabase/mcp/validation.cljnew file mode 100644index 00000000000..3b95284526c--- /dev/null+++ b/src/metabase/mcp/validation.clj@@ -0,0 +1,33 @@+(ns metabase.mcp.validation+ (:require+ [metabase.api.common :as api]+ [metabase.api.routes.common :as routes.common]+ [metabase.llm.settings :as llm.settings]+ [metabase.mcp.settings :as mcp.settings]+ [metabase.util.i18n :refer [tru]]))++(defn check-mcp-enabled+ "Check that the MCP server is enabled, or throw a 403."+ []+ (api/check (llm.settings/ai-features-enabled?)+ [403 (tru "AI features are not enabled.")])+ (api/check (mcp.settings/mcp-enabled?)+ [403 (tru "MCP server is not enabled.")]))++(defn enforce-mcp-enabled+ "Ring middleware that blocks external MCP requests when the feature is disabled."+ [handler]+ (fn [request respond raise]+ (cond+ (not (llm.settings/ai-features-enabled?))+ (raise (ex-info (tru "AI features are not enabled.") {:status-code 403}))++ (mcp.settings/mcp-enabled?)+ (handler request respond raise)++ :else+ (raise (ex-info (tru "MCP server is not enabled.") {:status-code 403})))))++(def ^{:arglists '([handler])} +mcp-enabled+ "Wrap routes so they may only be accessed when the MCP server is enabled."+ (routes.common/wrap-middleware-for-open-api-spec-generation enforce-mcp-enabled))diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex 037877ee117..66b6abb2faa 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -445,20 +445,13 @@[](provider-util/provider-and-model->provider (metabot.settings/llm-metabot-provider)))-(defn- api-error->status-code- [error]- (or (:status (ex-data error))- (:status-code (ex-data error))- 400))--(defn- verify-api-key!- [provider api-key]- (when-let [trimmed-api-key (non-blank-string api-key)]- (when-let [api-key-error (:api-key-error (provider-models-response provider trimmed-api-key))]- (throw (ex-info api-key-error- {:status-code 400- :api-error true}))))- nil)+(defn- throw-api-key-error!+ [response]+ (when-let [api-key-error (:api-key-error response)]+ (throw (ex-info api-key-error+ {:status-code 400+ :api-error true})))+ response)(api.macros/defendpoint :get "/settings":- metabot-settings-response-schema@@ -477,20 +470,14 @@body :- metabot-settings-request-schema](perms/check-has-application-permission :setting)(let [{:keys [provider model api-key]} body- model (effective-provider-model provider model)]- (verify-api-key! provider api-key)+ model (effective-provider-model provider model)+ response (-> (settings-response provider api-key)+ throw-api-key-error!)](when (contains? body :api-key)(setting/set! (provider-api-key-setting-key provider) (non-blank-string api-key)))(when model(setting/set! :llm-metabot-provider (str provider "/" model)))- (try- (settings-response provider)- (catch clojure.lang.ExceptionInfo e- (if (:api-error (ex-data e))- (throw (ex-info (.getMessage e)- (assoc (ex-data e) :status-code (api-error->status-code e))- e))- (throw e))))))+ (assoc response :value (metabot.settings/llm-metabot-provider))))(def ^{:arglists '([request respond raise])} routes"`/api/metabot` routes."diff --git a/src/metabase/metabot/config.clj b/src/metabase/metabot/config.cljindex abefbd89fbb..4fff414b73e 100644--- a/src/metabase/metabot/config.clj+++ b/src/metabase/metabot/config.clj@@ -2,6 +2,7 @@(:require[medley.core :as m][metabase.api.common :as api]+ [metabase.llm.settings :as llm.settings][metabase.metabot.settings :as metabot.settings][toucan2.core :as t2]))@@ -20,15 +21,21 @@(defn any-metabot-enabled?"Returns true if at least one of the metabot instances (internal or embedded) is enabled."[]- (or (metabot.settings/metabot-enabled?) (metabot.settings/embedded-metabot-enabled?)))+ (and (llm.settings/ai-features-enabled?)+ (or (metabot.settings/metabot-enabled?)+ (metabot.settings/embedded-metabot-enabled?))))(defn check-metabot-enabled!"Throws a 403 if metabot is not enabled. When called with no arguments, checks that at least one metabot instance is- enabled. When called with a `metabot-id`, checks the specific instance's setting."+ enabled. When called with a `metabot-id`, checks the specific instance's setting."([]+ (api/check (llm.settings/ai-features-enabled?)+ [403 "AI features are not enabled."])(api/check (any-metabot-enabled?)[403 "Metabot is not enabled."]))([metabot-id]+ (api/check (llm.settings/ai-features-enabled?)+ [403 "AI features are not enabled."])(if (= metabot-id embedded-metabot-id)(api/check (metabot.settings/embedded-metabot-enabled?)[403 "Embedded Metabot is not enabled."])diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.cljindex 7886eb86dab..cbd5787df3b 100644--- a/src/metabase/metabot/settings.clj+++ b/src/metabase/metabot/settings.clj@@ -19,6 +19,8 @@:type :boolean:visibility :public:default true+ :getter #(and (llm.settings/ai-features-enabled?)+ (setting/get-value-of-type :boolean :metabot-enabled?)):export? true:doc false)@@ -87,6 +89,8 @@:type :boolean:visibility :public:default true+ :getter #(and (llm.settings/ai-features-enabled?)+ (setting/get-value-of-type :boolean :embedded-metabot-enabled?)):export? true:doc false)diff --git a/src/metabase/premium_features/api.clj b/src/metabase/premium_features/api.cljindex bf40352a036..8bb774e7ff6 100644--- a/src/metabase/premium_features/api.clj+++ b/src/metabase/premium_features/api.clj@@ -1,10 +1,18 @@(ns metabase.premium-features.api(:require+ [clj-http.client :as http]+ [clojure.string :as str][metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.llm.settings :as llm.settings][metabase.premium-features.core :as premium-features][metabase.premium-features.token-check :as token-check]- [ring.util.response :as response]))+ [metabase.util.log :as log]+ [ring.util.response :as response])+ (:import+ (java.net URLEncoder)))++(set! *warn-on-reflection* true);; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -16,6 +24,20 @@[](api/check-404 (premium-features/token-status)))+(defn- invalidate-llm-proxy-token-cache!+ "Invalidation of the AI service's cached token status for the current instance token."+ []+ (when-let [service-base-url (llm.settings/ai-service-base-url)]+ (when-let [^String token (premium-features/premium-embedding-token)]+ (try+ (let [encoded-token (URLEncoder/encode ^String token "UTF-8")+ url (str (str/replace service-base-url #"/+$" "") "/v1/invalidate-token-cache/" encoded-token)+ response (http/post url {:throw-exceptions false})]+ (when-not (<= 200 (:status response) 299)+ (log/warnf "LLM proxy token cache invalidation failed with status %s" (:status response))))+ (catch Exception e+ (log/warn e "Failed to invalidate LLM proxy token cache"))))))+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/token/refresh""Clear all token caches and re-check the premium features token against the MetaStore.@@ -23,6 +45,7 @@are recognized without waiting for the cache TTL."[](token-check/clear-cache!)+ (invalidate-llm-proxy-token-cache!)(-> (api/check-404 (premium-features/token-status))response/response(assoc-in [:mb/cookies :cookie/premium-features-cache-timestamp] true)))diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex 4f223b40f0d..d44300594c1 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -6,6 +6,7 @@[environ.core :as env][java-time.api :as t][medley.core :as m]+ [metabase.agent-api.settings :as agent-api.settings][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.normalize :as lib.normalize]@@ -70,6 +71,19 @@(client/client :get 401 "agent/v1/ping"{:request-options {:headers {"x-metabase-session" session-key}}})))))))))+(deftest agent-api-enabled-setting-test+ (testing "External Agent API routes return 403 when disabled"+ (mt/with-temporary-setting-values [agent-api.settings/agent-api-enabled? false]+ (is (= "Agent API is not enabled."+ (mt/user-http-request :rasta :get 403 "agent/v1/ping"))))))++(deftest ai-features-enabled-setting-test+ (testing "External Agent API routes return 403 when AI features are globally disabled"+ (mt/with-temporary-raw-setting-values [:ai-features-enabled? "false"+ :agent-api-enabled? "true"]+ (is (= "AI features are not enabled."+ (mt/user-http-request :rasta :get 403 "agent/v1/ping"))))))+;;; ------------------------------------------------- Functional Tests --------------------------------------------------(deftest get-table-details-testdiff --git a/test/metabase/llm/settings_test.clj b/test/metabase/llm/settings_test.cljindex 9b08a05e2c1..7f26aa57330 100644--- a/test/metabase/llm/settings_test.clj+++ b/test/metabase/llm/settings_test.clj@@ -57,6 +57,22 @@#"Setting llm-proxy-base-url is not enabled because feature :metabase-ai-managed is not available"(llm.settings/llm-proxy-base-url! "https://proxy.example"))))))+(deftest ai-service-base-url-feature-guard-test+ (testing "can be set and read when :metabase-ai-managed feature is enabled"+ (mt/with-premium-features #{:metabase-ai-managed}+ (mt/with-temporary-setting-values [ai-service-base-url "https://ai-service.example"]+ (is (= "https://ai-service.example" (llm.settings/ai-service-base-url)))+ (testing "returns default (nil) when :metabase-ai-managed feature is not enabled, even if a value is set"+ (mt/with-premium-features #{}+ (is (nil? (llm.settings/ai-service-base-url))))))))++ (testing "cannot be set when :metabase-ai-managed feature is not enabled"+ (mt/with-premium-features #{}+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Setting ai-service-base-url is not enabled because feature :metabase-ai-managed is not available"+ (llm.settings/ai-service-base-url! "https://ai-service.example"))))))+;;; ------------------------------------------- Settings Defaults Tests -------------------------------------------(deftest llm-max-tokens-testdiff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex e57640d954d..fb5cbd9b775 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -2,8 +2,10 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [metabase.agent-api.settings :as agent-api.settings][metabase.api.macros.scope :as scope][metabase.mcp.api :as mcp.api]+ [metabase.mcp.settings :as mcp.settings][metabase.mcp.tools :as mcp.tools][metabase.oauth-server.core :as oauth-server][metabase.search.test-util :as search.tu]@@ -109,6 +111,21 @@(is (= 401 (:status response)))(is (= -32603 (get-in response [:body :error :code]))))))+(deftest mcp-enabled-setting-test+ (testing "external MCP requests return 403 when disabled"+ (mt/with-temporary-setting-values [mcp.settings/mcp-enabled? false]+ (let [response (mcp-request (jsonrpc-request "initialize"))]+ (is (= 403 (:status response)))+ (is (= "MCP server is not enabled." (:body response)))))))++(deftest ai-features-enabled-setting-test+ (testing "external MCP requests return 403 when AI features are globally disabled"+ (mt/with-temporary-raw-setting-values [:ai-features-enabled? "false"+ :mcp-enabled? "true"]+ (let [response (mcp-request (jsonrpc-request "initialize"))]+ (is (= 403 (:status response)))+ (is (= "AI features are not enabled." (:body response)))))))+(deftest initialize-test(testing "initialize returns protocol version, capabilities, and server info"(let [[session-id response] (initialize!)]@@ -516,6 +533,13 @@(is (not (:isError result))"Agent API should accept unrestricted scopes")))))+(deftest mcp-does-not-depend-on-external-agent-api-setting-test+ (testing "MCP tool calls still work when the external Agent API is disabled"+ (mt/with-temporary-setting-values [agent-api.settings/agent-api-enabled? false]+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{::scope/unrestricted} "get_table" {:id (mt/id :orders)}))]+ (is (not (:isError result)))))))+;;; ------------------------------------------------- Throttling ---------------------------------------------------(deftest mcp-throttle-returns-429-testdiff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex 84c7d08673e..8a71cac53fd 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -358,12 +358,8 @@(swap! calls inc)(is (= "anthropic" provider))(is (= "sk-ant-valid" api-key))- (case (long @calls)- 1 (is (nil? (llm.settings/llm-anthropic-api-key))- "verification should happen before saving the key")- 2 (is (= "sk-ant-valid" (llm.settings/llm-anthropic-api-key))- "response should use the saved key")- (is false (str "unexpected list-models call: " @calls)))+ (is (nil? (llm.settings/llm-anthropic-api-key))+ "verification should happen before saving the key"){:models [{:id "claude-haiku-4-5":display_name "Claude Haiku 4.5"}]})](is (= {:value (metabot.settings/llm-metabot-provider)@@ -373,8 +369,8 @@(mt/user-http-request :crowberto :put 200 "metabot/settings"{:provider "anthropic":api-key "sk-ant-valid"})))- (is (= 2 @calls)- "should verify first, then fetch models again after saving")+ (is (= 1 @calls)+ "should verify before saving and reuse the verified response")(is (= "sk-ant-valid"(llm.settings/llm-anthropic-api-key))))))))@@ -412,6 +408,22 @@(is (= "OpenAI API is not working but not saying why" (:message response)))(is (nil? (llm.settings/llm-openai-api-key)))))))+(deftest settings-put-does-not-save-model-when-preflight-fails-test+ (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"+ llm.settings/llm-anthropic-api-key "sk-ant-valid"]+ (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ (throw (ex-info "Anthropic API key has insufficient permissions"+ {:api-error true+ :status-code 403})))]+ (let [response (mt/user-http-request :crowberto :put 400 "metabot/settings"+ {:provider "anthropic"+ :model "claude-sonnet-4-5"})]+ (is (= "Anthropic API key has insufficient permissions" (:message response)))+ (is (= "anthropic/claude-haiku-4-5"+ (metabot.settings/llm-metabot-provider)))))))+(deftest settings-get-surfaces-invalid-api-key-error-test(mt/with-temporary-setting-values [llm.settings/llm-openai-api-key "sk-invalid"](with-redefs [metabot.self/list-models (fn [_provider _opts]diff --git a/test/metabase/metabot/config_test.clj b/test/metabase/metabot/config_test.cljindex 5eb4b719a0a..37ae355322e 100644--- a/test/metabase/metabot/config_test.clj+++ b/test/metabase/metabot/config_test.clj@@ -53,7 +53,17 @@(mt/with-temporary-setting-values [metabot-enabled? false embedded-metabot-enabled? true](is (thrown-with-msg? clojure.lang.ExceptionInfo #"Metabot is not enabled"(metabot.config/check-metabot-enabled! metabot.config/internal-metabot-id)))- (is (metabot.config/check-metabot-enabled! metabot.config/embedded-metabot-id)))))+ (is (metabot.config/check-metabot-enabled! metabot.config/embedded-metabot-id))))+ (testing "global AI disable blocks all Metabot instances"+ (mt/with-temporary-raw-setting-values [:ai-features-enabled? "false"+ :metabot-enabled? "true"+ :embedded-metabot-enabled? "true"]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"AI features are not enabled"+ (metabot.config/check-metabot-enabled!)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"AI features are not enabled"+ (metabot.config/check-metabot-enabled! metabot.config/internal-metabot-id)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"AI features are not enabled"+ (metabot.config/check-metabot-enabled! metabot.config/embedded-metabot-id))))))(deftest integrated-resolution-test(testing "combination of metabot-id and profile-id precedence resolution"diff --git a/test/metabase/premium_features/api_test.clj b/test/metabase/premium_features/api_test.cljindex c1d5c6ba9ca..b0021f41ed3 100644--- a/test/metabase/premium_features/api_test.clj+++ b/test/metabase/premium_features/api_test.clj@@ -1,57 +1,92 @@(ns metabase.premium-features.api-test(:require+ [clj-http.client :as http][clj-http.cookies :as cookies][clojure.test :refer :all]+ [metabase.premium-features.core :as premium-features][metabase.premium-features.token-check :as token-check][metabase.test :as mt]))(set! *warn-on-reflection* true)+(def fake-token-status+ {:valid true+ :status "fake"+ :features ["test" "fixture"]+ :trial false})+(deftest get-token-status-test(testing "GET /api/premium-features/token/status"- (mt/with-random-premium-token! [_token]- (testing "returns correctly"- (is (= {:valid true- :status "fake"- :features ["test" "fixture"]- :trial false}- (mt/user-http-request :crowberto :get 200 "premium-features/token/status"))))-- (testing "requires superusers"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :get 403 "premium-features/token/status")))))-- (mt/with-temporary-setting-values [:premium-embedding-token nil]- (testing "returns 404 if no token is set"+ (testing "returns correctly"+ (with-redefs [premium-features/token-status (constantly fake-token-status)]+ (is (= fake-token-status+ (mt/user-http-request :crowberto :get 200 "premium-features/token/status")))))++ (testing "requires superusers"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "premium-features/token/status"))))++ (testing "returns 404 if no token is set"+ (with-redefs [premium-features/token-status (constantly nil)](is (= "Not found."(mt/user-http-request :crowberto :get 404 "premium-features/token/status")))))))(deftest post-token-refresh-test(testing "POST /api/premium-features/token/refresh"- (mt/with-random-premium-token! [_token]- (testing "clears cache and returns fresh token status"- (let [cleared? (atom false)]- (with-redefs [token-check/clear-cache! (fn [] (reset! cleared? true))]- (is (=? {:valid true- :status "fake"- :features ["test" "fixture"]}+ (testing "clears cache and returns fresh token status"+ (let [cleared? (atom false)]+ (mt/with-temporary-setting-values [llm-proxy-base-url nil]+ (with-redefs [premium-features/token-status (constantly fake-token-status)+ premium-features/premium-embedding-token (constantly nil)+ token-check/clear-cache! (fn [] (reset! cleared? true))]+ (is (=? (dissoc fake-token-status :trial)(mt/user-http-request :crowberto :post 200 "premium-features/token/refresh")))- (is (true? @cleared?)))))+ (is (true? @cleared?))))))- (testing "requires superusers"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "premium-features/token/refresh")))))+ (testing "requires superusers"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "premium-features/token/refresh"))))- (mt/with-temporary-setting-values [:premium-embedding-token nil]- (testing "returns 404 if no token is set"+ (testing "returns 404 if no token is set"+ (with-redefs [premium-features/token-status (constantly nil)+ premium-features/premium-embedding-token (constantly nil)](is (= "Not found."(mt/user-http-request :crowberto :post 404 "premium-features/token/refresh")))))))+(deftest post-token-refresh-invalidates-llm-proxy-cache-test+ (testing "POST /api/premium-features/token/refresh invalidates the AI service token cache when explicitly configured"+ (let [token "SOME_RANDOM_TOKEN"]+ (mt/with-premium-features #{:metabase-ai-managed}+ (mt/with-temp-env-var-value! [mb-premium-embedding-token nil]+ (mt/with-temporary-raw-setting-values [premium-embedding-token token]+ (mt/with-temporary-setting-values [llm-proxy-base-url "https://proxy.example.com/llm/"+ ai-service-base-url "https://ai-service.example.com/"]+ (let [request* (atom nil)]+ (with-redefs [premium-features/token-status (constantly fake-token-status)+ http/post (fn [url request-options]+ (reset! request* [url request-options])+ {:status 200})]+ (mt/user-http-request :crowberto :post 200 "premium-features/token/refresh")+ (is (= [(str "https://ai-service.example.com/v1/invalidate-token-cache/" token)+ {:throw-exceptions false}]+ @request*))))))))))++ (testing "POST /api/premium-features/token/refresh does not invalidate the AI service cache when it is not configured"+ (mt/with-temporary-setting-values [llm-proxy-base-url nil]+ (with-redefs [premium-features/token-status (constantly fake-token-status)+ premium-features/premium-embedding-token (constantly "proxy-token")+ http/post (fn [& _]+ (throw (ex-info "should not be called" {})))]+ (is (=? (dissoc fake-token-status :trial)+ (mt/user-http-request :crowberto :post 200 "premium-features/token/refresh")))))))+(deftest token-refresh-sets-premium-features-cookie-test(testing "POST /api/premium-features/token/refresh sets the premium-features-last-updated cookie"- (mt/with-random-premium-token! [_token]- (let [cs (cookies/cookie-store)]- (mt/user-real-request :crowberto :post 200 "premium-features/token/refresh"- {:request-options {:cookie-store cs}})- (let [pf-cookie (get (cookies/get-cookies cs) "metabase.PREMIUM_FEATURES_LAST_UPDATED")]- (is (some? pf-cookie) "No premium-features-last-updated cookie set"))))))+ (mt/with-temporary-setting-values [llm-proxy-base-url nil]+ (with-redefs [premium-features/token-status (constantly fake-token-status)+ premium-features/premium-embedding-token (constantly nil)]+ (let [cs (cookies/cookie-store)]+ (mt/user-real-request :crowberto :post 200 "premium-features/token/refresh"+ {:request-options {:cookie-store cs}})+ (let [pf-cookie (get (cookies/get-cookies cs) "metabase.PREMIUM_FEATURES_LAST_UPDATED")]+ (is (some? pf-cookie) "No premium-features-last-updated cookie set")))))))diff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yamlindex 5ab04a34ea1..dda68c5ccc1 100644--- a/test_resources/serialization_baseline/settings.yaml+++ b/test_resources/serialization_baseline/settings.yaml@@ -1,4 +1,6 @@+agent-api-enabled?: nullaggregated-query-row-limit: null+ai-features-enabled?: nullallowed-iframe-hosts: nullapplication-colors: nullapplication-favicon-url: null@@ -49,6 +51,7 @@ metabot-nlq-system-prompt: nullmetabot-quota-reached-message: nullmetabot-show-illustrations: nullmetabot-sql-system-prompt: null+mcp-enabled?: nullnative-query-autocomplete-match-style: nullno-data-illustration: nullno-data-illustration-custom: null