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
Metabot configure popup when trying to use w/o configuration (#72298)
Maksym Yakubych2eb9d4973897
diff --git a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.tsindex 00d31ec6367..de7cf60beea 100644--- a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts+++ b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts@@ -26,11 +26,16 @@ describe("Metabot Query Builder", () => {cy.intercept("POST", "/api/metabot/agent-streaming").as("agentReq");});- it("should redirect to notebook when llm-metabot-configured? is false", () => {+ it("should show setup guidance when llm-metabot-configured? is false", () => {H.updateSetting("llm-anthropic-api-key", "");cy.visit("/question/ask");- cy.url().should("include", "/question#");- cy.findByTestId("metabot-send-message").should("not.exist");+ cy.url().should("include", "/question/ask");+ cy.get("main")+ .findByText("To use AI exploration, please", { exact: false })+ .should("be.visible");+ cy.findByRole("button", { name: "connect to a model" }).click();+ cy.findByTestId("ai-provider-configuration-modal").should("be.visible");+ cy.findByTestId("metabot-send-message").should("be.disabled");});it("should redirect to notebook when metabot-enabled? is false", () => {diff --git a/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.tsindex 3797b929c0a..786c0d18e91 100644--- a/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts+++ b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts@@ -17,7 +17,7 @@ const rejectButton = () => cy.findByTestId("reject-proposed-changes-button");const generatingLoader = () => cy.findByTestId("metabot-inline-sql-generating");describe("Native SQL generation", () => {- it("should not be available when metabot is not configured", () => {+ it("should show setup guidance when metabot is not configured", () => {H.restore();cy.signInAsAdmin();H.activateToken("pro-self-hosted");@@ -25,7 +25,14 @@ describe("Native SQL generation", () => {H.startNewNativeQuestion();H.NativeEditor.get().should("be.visible");toggleInlineSQLPrompt();- inlinePrompt().should("not.exist");+ inlinePrompt().should("be.visible");+ inlinePrompt()+ .findByText(/To use SQL generation, please/)+ .should("be.visible");+ generateButton().should("not.exist");++ cy.findByRole("button", { name: "connect to a model" }).click();+ cy.findByTestId("ai-provider-configuration-modal").should("be.visible");});describe("single db", () => {diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsxindex 04091f6726e..338d6f944cd 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx@@ -10,6 +10,7 @@ import {import { getErrorMessage } from "metabase/api/utils";import { useSetting } from "metabase/common/hooks";import { MetabotManagedProviderLimitActions } from "metabase/metabot/components/MetabotManagedProviderLimit";+import type { MetabaseAIProviderSetupProps } from "metabase/plugins";import { useSelector } from "metabase/redux";import { getStoreUsers } from "metabase/selectors/store-users";import {@@ -51,7 +52,9 @@ import { usePurchaseMetabaseManagedAi } from "../../usePurchaseMetabaseManagedAiimport { MetabotSettingUpModal } from "./MetabotSettingUpModal";-export function MetabaseAIProviderSetup() {+export function MetabaseAIProviderSetup({+ onConnect,+}: MetabaseAIProviderSetupProps) {const offerMetabaseManagedAi = !!hasPremiumFeature(OFFER_METABASE_MANAGED_AI_FEATURE,);@@ -69,7 +72,8 @@ export function MetabaseAIProviderSetup() {const handleConnect = useCallback(async () => {await updateMetabotSettings({ provider: "metabase", model: "" }).unwrap();- }, [updateMetabotSettings]);+ onConnect?.();+ }, [onConnect, updateMetabotSettings]);const {pricing: metabaseManagedAiPricing,@@ -98,7 +102,7 @@ export function MetabaseAIProviderSetup() {}}, [handleConnect, hasAcceptedTerms, metabaseManagedAiPurchase]);- const onConnect = match({+ const connectAction = match({hasAcceptedTerms,hasMetabaseManagedAiProviderFeature,hasDeprecatedMetabaseAiProvider,@@ -161,7 +165,7 @@ export function MetabaseAIProviderSetup() {]);const { isLoading, handleDisconnect, resetProvider, isModal } =- useMetabotSetupContext(onConnect, onDisconnect);+ useMetabotSetupContext(connectAction, onDisconnect);const metabaseManagedAiPurchaseError = metabaseManagedAiPurchase.error? getErrorMessage(diff --git a/frontend/src/metabase/admin/ai/MetabotSetup.tsx b/frontend/src/metabase/admin/ai/MetabotSetup.tsxindex 1b27fa966f7..174e6920829 100644--- a/frontend/src/metabase/admin/ai/MetabotSetup.tsx+++ b/frontend/src/metabase/admin/ai/MetabotSetup.tsx@@ -401,7 +401,9 @@ export function MetabotSetupInner({)}{match(provider)- .with("metabase", () => <MetabaseAIProviderSetup />)+ .with("metabase", () => (+ <MetabaseAIProviderSetup onConnect={onClose} />+ )).with(P.nonNullable, (selectedProvider) => (<AIProviderSetupselectedProvider={selectedProvider}diff --git a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsxindex b39c998a3ad..9a40653c5d3 100644--- a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx@@ -132,6 +132,7 @@ type SetupOptions = {responses?: Partial<Record<MetabotProvider, MetabotSettingsApiResponse>>;updateResponse?: MetabotSettingsResponse;renderAsModal?: boolean;+ onClose?: jest.Mock;};async function setup({@@ -165,6 +166,7 @@ async function setup({models: DEFAULT_RESPONSES.anthropic.models,},renderAsModal = false,+ onClose = jest.fn(),}: SetupOptions = {}) {fetchMock.removeRoutes();fetchMock.clearHistory();@@ -381,7 +383,7 @@ async function setup({const storeInitialState = { settings };const view = renderAsModal- ? renderWithProviders(<MetabotSetupInner isModal onClose={jest.fn()} />, {+ ? renderWithProviders(<MetabotSetupInner isModal onClose={onClose} />, {storeInitialState,}): renderWithProviders(@@ -403,6 +405,7 @@ async function setup({return {...view,+ onClose,resolvePurchaseCloudAddOnResponse: () =>purchaseCloudAddOnDeferred.resolve(),resolveMetabotSettingsUpdateResponse: () =>@@ -877,6 +880,38 @@ describe("MetabotSetup", () => {);});+ it("calls onClose after directly connecting to the Metabase provider in modal mode", async () => {+ const onClose = jest.fn();++ await setup({+ isHosted: true,+ savedProviderValue: null,+ isConfigured: false,+ isStoreUser: false,+ tokenStatusFeatures: ["metabase-ai-managed"],+ updateResponse: {+ value: "metabase/anthropic/claude-sonnet-4-6",+ models: DEFAULT_RESPONSES.metabase.models,+ },+ renderAsModal: true,+ onClose,+ });++ await selectProvider("Metabase");+ await userEvent.click(+ await screen.findByRole("button", { name: "Connect" }),+ );++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called("path:/api/metabot/settings", {+ method: "PUT",+ }),+ ).toBe(true);+ expect(onClose).toHaveBeenCalledTimes(1);+ });+ });+it("waits for the purchase and settings save before showing Metabase AI as ready", async () => {let resolvePurchaseCloudAddOnResponse = () => {};let resolveMetabotSettingsUpdateResponse = () => {};@@ -1060,6 +1095,77 @@ describe("MetabotSetup", () => {}});+ it("calls onClose after purchasing the Metabase add-on and connecting in modal mode", async () => {+ const onClose = jest.fn();+ const {+ resolvePurchaseCloudAddOnResponse,+ resolveMetabotSettingsUpdateResponse,+ } = await setup({+ isHosted: true,+ savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",+ isConfigured: false,+ isStoreUser: true,+ tokenStatusFeatures: [],+ refreshedTokenStatusFeatures: ["metabase-ai-managed"],+ deferPurchaseCloudAddOnResponse: true,+ deferMetabotSettingsUpdateResponse: true,+ updateResponse: {+ value: "metabase/anthropic/claude-sonnet-4-6",+ models: DEFAULT_RESPONSES.metabase.models,+ },+ renderAsModal: true,+ onClose,+ });++ await selectProvider("Metabase");++ await userEvent.click(+ await screen.findByRole("checkbox", {+ name: /I agree with the Metabase AI Service/i,+ }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Connect" }),+ );++ expect(onClose).not.toHaveBeenCalled();++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called(+ "path:/api/ee/cloud-add-ons/metabase-ai-managed",+ ),+ ).toBe(true);+ });++ await act(async () => {+ resolvePurchaseCloudAddOnResponse();+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(+ fetchMock.callHistory+ .calls("path:/api/metabot/settings")+ .some(+ (call) =>+ call.request?.method === "PUT" || call.options?.method === "PUT",+ ),+ ).toBe(true);+ });++ expect(onClose).not.toHaveBeenCalled();++ await act(async () => {+ resolveMetabotSettingsUpdateResponse();+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(onClose).toHaveBeenCalledTimes(1);+ });+ });+it("shows live pricing for the Metabase provider", async () => {await setup({isHosted: true,diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsxindex 0463fa73ba0..4baf55a54b2 100644--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx@@ -1,10 +1,12 @@import userEvent from "@testing-library/user-event";+import { setupEnterprisePlugins } from "__support__/enterprise";import {setupCollectionByIdEndpoint,setupDatabasesEndpoints,setupUserMetabotPermissionsEndpoint,} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";import { renderWithProviders, screen } from "__support__/ui";import { NewModals } from "metabase/new/components/NewModals/NewModals";import { createMockState } from "metabase/redux/store/mocks";@@ -25,6 +27,7 @@ type SetupOpts = {databases?: Database[];hasModels?: boolean;canWrite?: boolean;+ isConfigured?: boolean;};const SAMPLE_DATABASE = createSampleDatabase();@@ -33,12 +36,19 @@ const COLLECTION = createMockCollection();async function setup({databases = [SAMPLE_DATABASE],canWrite = true,+ isConfigured = true,}: SetupOpts = {}) {+ const settings = mockSettings({+ "llm-metabot-configured?": isConfigured,+ "metabot-enabled?": true,+ });+setupUserMetabotPermissionsEndpoint();setupDatabasesEndpoints(databases);setupCollectionByIdEndpoint({collections: [COLLECTION],});+ setupEnterprisePlugins();renderWithProviders(<>@@ -47,6 +57,7 @@ async function setup({</>,{storeInitialState: createMockState({+ settings,currentUser: createMockUser({permissions: createMockUserPermissions({can_create_queries: true,@@ -76,11 +87,23 @@ describe("NewItemMenu", () => {expect(screen.queryByText("Action")).not.toBeInTheDocument();});+ it("shows AI exploration when NLQ access exists but AI is not configured", async () => {+ await setup({ isConfigured: false });++ expect(await screen.findByText("AI exploration")).toBeInTheDocument();+ });+it("should support keyboard navigation", async () => {await setup();await userEvent.keyboard("{ArrowDown}");+ expect(+ await screen.findByRole("menuitem", { name: /AI exploration/ }),+ ).toHaveFocus();++ await userEvent.keyboard("{ArrowDown}");+expect(await screen.findByRole("menuitem", { name: /Question/ }),).toHaveFocus();diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsxindex 4d11d15c644..b5ed97da8df 100644--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx@@ -42,7 +42,7 @@ export const NewItemMenuView = ({const canWriteToCollections = useSelector(getUserCanWriteToCollections);- const { canUseNlq } = useUserMetabotPermissions();+ const { hasNlqAccess } = useUserMetabotPermissions();const menuItems = useMemo(() => {const items = [];@@ -50,7 +50,7 @@ export const NewItemMenuView = ({const aiExplorationItem = getNewMenuItemAIExploration(hasDataAccess,collectionId,- canUseNlq,+ hasNlqAccess,);if (aiExplorationItem) {items.push(aiExplorationItem);@@ -128,7 +128,7 @@ export const NewItemMenuView = ({hasDatabaseWithJsonEngine,dispatch,canWriteToCollections,- canUseNlq,+ hasNlqAccess,]);if (menuItems.length === 0) {diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationModal.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationModal.tsxnew file mode 100644index 00000000000..d0b43354669--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationModal.tsx@@ -0,0 +1,21 @@+import { t } from "ttag";++import { MetabotSetupInner } from "metabase/admin/ai/MetabotSetup";+import { Modal, type ModalProps } from "metabase/ui";++export function AIProviderConfigurationModal({+ opened,+ onClose,+}: Pick<ModalProps, "opened" | "onClose">) {+ return (+ <Modal+ opened={opened}+ onClose={onClose}+ title={t`Connect to an AI provider`}+ size="lg"+ data-testid="ai-provider-configuration-modal"+ >+ <MetabotSetupInner isModal onClose={onClose} />+ </Modal>+ );+}diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationNotice.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationNotice.tsxnew file mode 100644index 00000000000..bdc02516d26--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationNotice.tsx@@ -0,0 +1,99 @@+import { useDisclosure } from "@mantine/hooks";+import { useCallback } from "react";+import { jt, t } from "ttag";++import { useDispatch, useSelector } from "metabase/redux";+import { dismissUndo } from "metabase/redux/undo";+import { canAccessSettings } from "metabase/selectors/user";+import { Anchor, Flex, Text, type TextProps } from "metabase/ui";++import { AIProviderConfigurationModal } from "./AIProviderConfigurationModal";++export function AIProviderConfigurationNotice({+ featureName,+ onConfigureAi,+ inline,+ ...rest+}: {+ featureName: string;+ onConfigureAi: () => void;+ inline?: boolean;+} & TextProps) {+ const canConfigureAi = useSelector(canAccessSettings);++ return (+ <Text+ c="text-tertiary"+ maw={!inline ? "16rem" : undefined}+ ta={!inline ? "center" : undefined}+ lh="lg"+ {...rest}+ >+ {canConfigureAi+ ? jt`To use ${featureName}, please ${(+ <Anchor+ key="configure-ai-link"+ component="button"+ type="button"+ fz="inherit"+ inline+ onClick={onConfigureAi}+ >+ {t`connect to a model`}+ </Anchor>+ )}.`+ : t`Ask your admin to connect to a model to use ${featureName}.`}+ </Text>+ );+}++const METABOT_NOT_CONFIGURED_TOAST_ID = "metabot-not-configured";++const MetabotNotConfiguredToastContent = ({+ featureName,+}: {+ featureName: string;+}) => {+ const dispatch = useDispatch();++ const dismissToast = useCallback(() => {+ dispatch(dismissUndo({ undoId: METABOT_NOT_CONFIGURED_TOAST_ID }));+ }, [dispatch]);++ const [isModalOpen, { close: closeModal, open: openModal }] = useDisclosure(+ false,+ { onClose: dismissToast },+ );++ return (+ <Flex direction="column" gap="xs">+ <AIProviderConfigurationNotice+ inline={true}+ onConfigureAi={openModal}+ featureName={featureName}+ />+ <AIProviderConfigurationModal opened={isModalOpen} onClose={closeModal} />+ </Flex>+ );+};++export const getMetabotNotConfiguredToastProps = ({+ featureName,+}: {+ featureName: string;+}) => ({+ id: METABOT_NOT_CONFIGURED_TOAST_ID,+ dark: false,+ icon: "metabot" as const,+ iconColor: "brand" as const,+ toastColor: "error",+ dismissIconColor: "text-secondary" as const,+ timeout: 0,+ style: {+ padding: "1rem",+ width: "min(24rem, calc(100vw - 2 * var(--mantine-spacing-md)))",+ },+ renderChildren: () => (+ <MetabotNotConfiguredToastContent featureName={featureName} />+ ),+});diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsxindex 343e6d8aff6..fa560bf635e 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx@@ -1,22 +1,37 @@import { t } from "ttag";import { ToolbarButton } from "metabase/common/components/ToolbarButton";+import { useToast } from "metabase/common/hooks/use-toast";import {useMetabotAgent,+ useMetabotName,useUserMetabotPermissions,} from "metabase/metabot/hooks";import { trackExplainChartClicked } from "../analytics";+import { getMetabotNotConfiguredToastProps } from "./AIProviderConfigurationNotice";+export const AIQuestionAnalysisButton = () => {- const { canUseMetabot } = useUserMetabotPermissions();+ const { hasMetabotAccess, canUseMetabot } = useUserMetabotPermissions();const { submitInput } = useMetabotAgent("omnibot");+ const metabotName = useMetabotName();+ const [sendToast] = useToast();- if (!canUseMetabot) {+ if (!hasMetabotAccess) {return null;}const handleClick = () => {+ if (!canUseMetabot) {+ sendToast(+ getMetabotNotConfiguredToastProps({+ featureName: metabotName,+ }),+ );+ return;+ }+trackExplainChartClicked();submitInput("Analyze this chart");};diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsxindex f5d6d7e2293..f2fc88c3a82 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx@@ -21,9 +21,10 @@ const mockAgentEndpoint = () =>function setup({isMetabotEnabled = true,-}: { isMetabotEnabled?: boolean } = {}) {+ isConfigured = true,+}: { isMetabotEnabled?: boolean; isConfigured?: boolean } = {}) {const settings = mockSettings({- "llm-metabot-configured?": true,+ "llm-metabot-configured?": isConfigured,"metabot-enabled?": isMetabotEnabled,});@@ -41,11 +42,16 @@ function setup({settings,metabot: metabotState,} as any),+ withUndos: true,},);}describe("AIQuestionAnalysisButton", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });+it("should render the button when metabot is enabled", async () => {setup({ isMetabotEnabled: true });expect(@@ -53,6 +59,13 @@ describe("AIQuestionAnalysisButton", () => {).toBeInTheDocument();});+ it("should render the button when metabot is enabled but not configured", async () => {+ setup({ isConfigured: false, isMetabotEnabled: true });+ expect(+ await screen.findByRole("button", { name: "Explain this chart" }),+ ).toBeInTheDocument();+ });+it("should not render the button when metabot is disabled", () => {setup({ isMetabotEnabled: false });expect(@@ -73,4 +86,18 @@ describe("AIQuestionAnalysisButton", () => {const body = JSON.parse(lastCall?.[1]?.body as string);expect(body.message).toBe("Analyze this chart");});++ it("should show the not-configured toast instead of submitting when AI is not configured", async () => {+ const agentSpy = mockAgentEndpoint();++ setup({ isConfigured: false, isMetabotEnabled: true });++ await userEvent.click(+ await screen.findByRole("button", { name: "Explain this chart" }),+ );++ expect(await screen.findByTestId("toast-undo")).toBeInTheDocument();+ expect(await screen.findByText(/connect to a model/)).toBeInTheDocument();+ expect(agentSpy).not.toHaveBeenCalled();+ });});diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.tsxindex ca758e3beed..1313fc5ef7f 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.tsx@@ -1,3 +1,4 @@+import { useDisclosure } from "@mantine/hooks";import { useEffect, useRef } from "react";import { usePrevious } from "react-use";import { t } from "ttag";@@ -5,6 +6,7 @@ import { t } from "ttag";import { useAnalyzeChartMutation } from "metabase/api";import { CopyButton } from "metabase/common/components/CopyButton";import { SidebarContent } from "metabase/common/components/SidebarContent";+import { useSetting } from "metabase/common/hooks";import { getIsLoadingComplete } from "metabase/query_builder/selectors";import { useSelector } from "metabase/redux";import { Box } from "metabase/ui";@@ -16,6 +18,8 @@ import type Question from "metabase-lib/v1/Question";import type { Timeline, TimelineEvent } from "metabase-types/api";import { AIAnalysisContent } from "../AIAnalysisContent/AIAnalysisContent";+import { AIProviderConfigurationModal } from "../AIProviderConfigurationModal";+import { AIProviderConfigurationNotice } from "../AIProviderConfigurationNotice";import { getTimelineEventsForAnalysis } from "./utils";@@ -38,6 +42,14 @@ export function AIQuestionAnalysisSidebar({onClose,}: AIQuestionAnalysisSidebarProps) {const previousQuestion = usePrevious(question);+ const [+ isAiProviderConfigurationModalOpen,+ {+ close: closeAiProviderConfigurationModal,+ open: openAiProviderConfigurationModal,+ },+ ] = useDisclosure(false);+ const isConfigured = !!useSetting("llm-metabot-configured?");const [analyzeChart, { data: analysisData }] = useAnalyzeChartMutation();const isLoadingComplete = useSelector(getIsLoadingComplete);const pendingAnalysisRef = useRef(false);@@ -54,7 +66,7 @@ export function AIQuestionAnalysisSidebar({}, [previousQuestion, question]);useEffect(() => {- if (!pendingAnalysisRef.current || !isLoadingComplete) {+ if (!isConfigured || !pendingAnalysisRef.current || !isLoadingComplete) {return;}@@ -94,6 +106,7 @@ export function AIQuestionAnalysisSidebar({};}, [analyzeChart,+ isConfigured,isLoadingComplete,question,timelines,@@ -101,7 +114,7 @@ export function AIQuestionAnalysisSidebar({]);const renderCopyButton = () => {- if (!analysisData?.summary) {+ if (!isConfigured || !analysisData?.summary) {return null;}@@ -123,7 +136,18 @@ export function AIQuestionAnalysisSidebar({headerActions={renderCopyButton()}><Box px="1.5rem" py="0.5rem">- <AIAnalysisContent explanation={analysisData?.summary} />+ {isConfigured ? (+ <AIAnalysisContent explanation={analysisData?.summary} />+ ) : (+ <AIProviderConfigurationNotice+ featureName={t`chart analysis`}+ onConfigureAi={openAiProviderConfigurationModal}+ />+ )}+ <AIProviderConfigurationModal+ opened={isAiProviderConfigurationModalOpen}+ onClose={closeAiProviderConfigurationModal}+ /></Box></SidebarContent>);diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.unit.spec.tsxindex c21daecd5f4..4c1c1439b5f 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisSidebar/AIQuestionAnalysisSidebar.unit.spec.tsx@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";import _ from "underscore";import { setupAnalyzeChartEndpoint } from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";import { renderWithProviders } from "__support__/ui";import { createMockQueryBuilderState } from "metabase/redux/store/mocks";import Question from "metabase-lib/v1/Question";@@ -11,6 +12,7 @@ import {createMockCard,createMockTimeline,createMockTimelineEvent,+ createMockUser,} from "metabase-types/api/mocks";import { AIQuestionAnalysisSidebar } from "./AIQuestionAnalysisSidebar";@@ -37,6 +39,7 @@ describe("AIQuestionAnalysisSidebar", () => {<AIQuestionAnalysisSidebar question={question} onClose={jest.fn()} />,{storeInitialState: {+ settings: mockSettings({ "llm-metabot-configured?": true }),qb: createMockQueryBuilderState({queryStatus: "complete",}),@@ -123,6 +126,7 @@ describe("AIQuestionAnalysisSidebar", () => {/>,{storeInitialState: {+ settings: mockSettings({ "llm-metabot-configured?": true }),qb: createMockQueryBuilderState({queryStatus: "complete",}),@@ -151,4 +155,35 @@ describe("AIQuestionAnalysisSidebar", () => {_.pick(visibleTimelineEventFromAnotherCollection, analysisEventsFields),);});++ it("should show a configuration notice instead of running analysis when AI is not configured", async () => {+ const question = new Question(createMockCard());++ renderWithProviders(+ <AIQuestionAnalysisSidebar question={question} onClose={jest.fn()} />,+ {+ storeInitialState: {+ currentUser: createMockUser({ is_superuser: true }),+ settings: mockSettings({ "llm-metabot-configured?": false }),+ qb: createMockQueryBuilderState({+ queryStatus: "complete",+ }),+ },+ },+ );++ expect(+ await screen.findByText("To use chart analysis, please", {+ exact: false,+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "connect to a model" }),+ ).toBeInTheDocument();+ expect(+ fetchMock.callHistory.called(+ "path:/api/ai-entity-analysis/analyze-chart",+ ),+ ).toBe(false);+ });});diff --git a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsxindex 52f8a40aef2..3d2f511ab9d 100644--- a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx+++ b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx@@ -14,19 +14,29 @@ import { useDispatch } from "metabase/redux";import { Button } from "metabase/ui";import { trackQueryFixClicked } from "../../analytics";+import { getMetabotNotConfiguredToastProps } from "../AIProviderConfigurationNotice";export function FixSqlQueryButton() {const dispatch = useDispatch();- const { canUseSqlGeneration } = useUserMetabotPermissions();+ const { hasSqlGenerationAccess, canUseSqlGeneration } =+ useUserMetabotPermissions();const metabotName = useMetabotName();const [sendToast] = useToast();const { submitInput, isDoingScience } = useMetabotAgent("sql");- if (!canUseSqlGeneration) {+ if (!hasSqlGenerationAccess) {return null;}const handleClick = async () => {+ if (!canUseSqlGeneration) {+ sendToast(+ getMetabotNotConfiguredToastProps({+ featureName: metabotName,+ }),+ );+ return;+ }trackQueryFixClicked();await dispatch(setIsNativeEditorOpen(true));// SQL and error message are included in the context.diff --git a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsxindex 6e6aa5e5109..fee777f4768 100644--- a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx@@ -1,38 +1,24 @@import userEvent from "@testing-library/user-event";import { renderWithProviders, screen } from "__support__/ui";-import { useToast } from "metabase/common/hooks/use-toast";import { METABOT_ERR_MSG } from "metabase/metabot/constants";import {useMetabotAgent,useUserMetabotPermissions,} from "metabase/metabot/hooks";import { setIsNativeEditorOpen } from "metabase/query_builder/actions";-import { useDispatch } from "metabase/redux";import { trackQueryFixClicked } from "../../analytics";import { FixSqlQueryButton } from "./FixSqlQueryButton";const mockSubmitInput = jest.fn();-const mockDispatch = jest.fn();-const mockSendToast = jest.fn();const mockSetIsNativeEditorOpen = jest.fn();jest.mock("../../analytics", () => ({trackQueryFixClicked: jest.fn(),}));-jest.mock("metabase/redux", () => ({- ...jest.requireActual("metabase/redux"),- useDispatch: jest.fn(),-}));--jest.mock("metabase/common/hooks/use-toast", () => ({- ...jest.requireActual("metabase/common/hooks/use-toast"),- useToast: jest.fn(),-}));-jest.mock("metabase/metabot/hooks", () => ({...jest.requireActual("metabase/metabot/hooks"),useMetabotAgent: jest.fn(),@@ -45,37 +31,45 @@ jest.mock("metabase/query_builder/actions", () => ({}));function setup(options?: {- isMetabotEnabled?: boolean;+ canUseSqlGeneration?: boolean;+ hasSqlGenerationAccess?: boolean;isDoingScience?: boolean;}) {- const { isMetabotEnabled = true, isDoingScience = false } = options ?? {};+ const {+ canUseSqlGeneration = true,+ hasSqlGenerationAccess = true,+ isDoingScience = false,+ } = options ?? {};jest.mocked(useUserMetabotPermissions).mockReturnValue({isLoading: false,isError: false,- canUseMetabot: isMetabotEnabled,- canUseSqlGeneration: isMetabotEnabled,- canUseNlq: isMetabotEnabled,- canUseOtherTools: isMetabotEnabled,+ isConfigured: canUseSqlGeneration,+ canConfigure: true,+ hasMetabotAccess: hasSqlGenerationAccess,+ canUseMetabot: canUseSqlGeneration,+ hasSqlGenerationAccess,+ canUseSqlGeneration,+ hasNlqAccess: hasSqlGenerationAccess,+ canUseNlq: canUseSqlGeneration,+ hasOtherToolsAccess: hasSqlGenerationAccess,+ canUseOtherTools: canUseSqlGeneration,});jest.mocked(useMetabotAgent).mockReturnValue({submitInput: mockSubmitInput,isDoingScience,} as any);- jest.mocked(useToast).mockReturnValue([mockSendToast, jest.fn()]);- jest.mocked(useDispatch).mockReturnValue(mockDispatch as any);jest.mocked(setIsNativeEditorOpen).mockImplementation(mockSetIsNativeEditorOpen as any);- return renderWithProviders(<FixSqlQueryButton />);+ return renderWithProviders(<FixSqlQueryButton />, { withUndos: true });}describe("FixSqlQueryButton", () => {beforeEach(() => {jest.clearAllMocks();mockSubmitInput.mockResolvedValue(undefined);- mockDispatch.mockImplementation((action) => action);mockSetIsNativeEditorOpen.mockReturnValue({type: "metabase/qb/SET_IS_NATIVE_EDITOR_OPEN",isNativeEditorOpen: true,@@ -83,7 +77,7 @@ describe("FixSqlQueryButton", () => {});it("should render the button with correct text when metabot is enabled", () => {- setup({ isMetabotEnabled: true });+ setup({ canUseSqlGeneration: true });expect(screen.getByRole("button", { name: /Have Metabot fix it/ }),).toBeInTheDocument();@@ -91,12 +85,34 @@ describe("FixSqlQueryButton", () => {});it("should not render the button when metabot is disabled", () => {- setup({ isMetabotEnabled: false });+ setup({ canUseSqlGeneration: false, hasSqlGenerationAccess: false });expect(screen.queryByRole("button", { name: /Have Metabot fix it/ }),).not.toBeInTheDocument();});+ it("is visible when SQL generation access exists but Metabot is not configured", () => {+ setup({ canUseSqlGeneration: false, hasSqlGenerationAccess: true });++ expect(+ screen.getByRole("button", { name: /Have Metabot fix it/ }),+ ).toBeInTheDocument();+ });++ it("shows the not-configured toast instead of starting SQL fixing when Metabot is not configured", async () => {+ setup({ canUseSqlGeneration: false, hasSqlGenerationAccess: true });++ await userEvent.click(+ screen.getByRole("button", { name: /Have Metabot fix it/ }),+ );++ expect(await screen.findByTestId("toast-undo")).toBeInTheDocument();+ expect(await screen.findByText(/connect to a model/)).toBeInTheDocument();+ expect(trackQueryFixClicked).not.toHaveBeenCalled();+ expect(mockSetIsNativeEditorOpen).not.toHaveBeenCalled();+ expect(mockSubmitInput).not.toHaveBeenCalled();+ });+it("should submit an SQL fix prompt when clicked", async () => {setup();@@ -106,10 +122,6 @@ describe("FixSqlQueryButton", () => {expect(trackQueryFixClicked).toHaveBeenCalled();expect(mockSetIsNativeEditorOpen).toHaveBeenCalledWith(true);- expect(mockDispatch).toHaveBeenCalledWith({- type: "metabase/qb/SET_IS_NATIVE_EDITOR_OPEN",- isNativeEditorOpen: true,- });expect(mockSubmitInput).toHaveBeenCalledWith("Fix this SQL query", {preventOpenSidebar: true,});@@ -143,14 +155,9 @@ describe("FixSqlQueryButton", () => {screen.getByRole("button", { name: /Have Metabot fix it/ }),);- expect(mockSendToast).toHaveBeenCalledWith(- expect.objectContaining({- id: "metabot-managed-provider-limit",- icon: null,- timeout: 0,- toastColor: "error",- }),- );+ expect(+ await screen.findByText("You've run out of AI service tokens"),+ ).toBeInTheDocument();});it("shows the error when fixing SQL fails", async () => {@@ -171,11 +178,7 @@ describe("FixSqlQueryButton", () => {screen.getByRole("button", { name: /Have Metabot fix it/ }),);- expect(mockSendToast).toHaveBeenCalledWith({- icon: "warning",- toastColor: "error",- message: "Something went wrong",- });+ expect(await screen.findByText("Something went wrong")).toBeInTheDocument();});it("falls back to the default Metabot error message when none is returned", async () => {@@ -192,10 +195,8 @@ describe("FixSqlQueryButton", () => {screen.getByRole("button", { name: /Have Metabot fix it/ }),);- expect(mockSendToast).toHaveBeenCalledWith({- icon: "warning",- toastColor: "error",- message: METABOT_ERR_MSG.default,- });+ expect(+ await screen.findByText(METABOT_ERR_MSG.default),+ ).toBeInTheDocument();});});diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsxindex 0ff52b3eea5..9e9f608c85f 100644--- a/frontend/src/metabase/metabot/components/Metabot.tsx+++ b/frontend/src/metabase/metabot/components/Metabot.tsx@@ -111,12 +111,12 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {export const Metabot = (props: MetabotProps) => {const currentUser = useSelector(getUser);- const { canUseMetabot } = useUserMetabotPermissions();+ const { hasMetabotAccess } = useUserMetabotPermissions();// NOTE: do not render Metabot if the user is not authenticated.// doing so will cause a redirect for unauthenticated requests// which will break interactive embedding. See (metabase#58687).- if (!currentUser || !canUseMetabot) {+ if (!currentUser || !hasMetabotAccess) {return null;}diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsxindex b600b134671..e1787d58c4d 100644--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx@@ -20,11 +20,11 @@ export function MetabotAppBarButton({className,...rest}: MetabotAppBarButtonProps) {- const { canUseMetabot } = useUserMetabotPermissions();+ const { hasMetabotAccess } = useUserMetabotPermissions();const metabot = useMetabotAgent("omnibot");const metabotName = useMetabotName();- if (!canUseMetabot) {+ if (!hasMetabotAccess) {return null;}diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsxindex f91a76b514c..3d21b3ff184 100644--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx@@ -14,9 +14,11 @@ import { MetabotAppBarButton } from "./MetabotAppBarButton";function setup({isMetabotEnabled = true,+ isConfigured = true,permissionOverrides,}: {isMetabotEnabled?: boolean;+ isConfigured?: boolean;permissionOverrides?: Partial<UserMetabotPermissions>;} = {}) {fetchMock.get(@@ -25,7 +27,7 @@ function setup({);const settings = mockSettings({- "llm-metabot-configured?": true,+ "llm-metabot-configured?": isConfigured,"metabot-enabled?": isMetabotEnabled,});setupEnterprisePlugins();@@ -52,6 +54,13 @@ describe("MetabotAppBarButton", () => {).toBeInTheDocument();});+ it("should render the button when metabot is enabled but not configured", async () => {+ setup({ isConfigured: false, isMetabotEnabled: true });+ expect(+ await screen.findByRole("button", { name: /Chat with Metabot/ }),+ ).toBeInTheDocument();+ });+it("should not render the button when metabot is globally disabled", () => {setup({ isMetabotEnabled: false });expect(diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsxindex efe262dd7d6..7f4a4b2555f 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx@@ -1,3 +1,4 @@+import { useDisclosure } from "@mantine/hooks";import cx from "classnames";import { useMemo } from "react";import { t } from "ttag";@@ -5,6 +6,8 @@ import { t } from "ttag";import EmptyDashboardBot from "assets/img/dashboard-empty.svg?component";import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";import { useSetting } from "metabase/common/hooks";+import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";+import { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";import { MetabotResetLongChatButton } from "metabase/metabot/components/MetabotChat/MetabotResetLongChatButton";import { useSelector } from "metabase/redux";import { getIsHosted } from "metabase/setup/selectors";@@ -20,7 +23,11 @@ import {Tooltip,} from "metabase/ui";-import { useMetabotAgent, useMetabotName } from "../../hooks";+import {+ useMetabotAgent,+ useMetabotName,+ useUserMetabotPermissions,+} from "../../hooks";import type { MetabotConfig } from "../Metabot";import Styles from "./MetabotChat.module.css";@@ -47,8 +54,16 @@ export const MetabotChat = ({config?: MetabotConfig;}) => {const isHosted = useSelector(getIsHosted);+ const [+ isAiProviderConfigurationModalOpen,+ {+ close: closeAiProviderConfigurationModal,+ open: openAiProviderConfigurationModal,+ },+ ] = useDisclosure(false);const metabot = useMetabotAgent(config.agentId);const metabotName = useMetabotName();+ const { isConfigured } = useUserMetabotPermissions();const showIllustrations = useSetting("metabot-show-illustrations");const hasMessages = metabot.messages.length > 0;@@ -56,11 +71,14 @@ export const MetabotChat = ({const { scrollContainerRef, headerRef, fillerRef } =useScrollManager(hasMessages);- const suggestedPromptsReq = useGetSuggestedMetabotPromptsQuery({- metabot_id: metabot.metabotId,- limit: 3,- sample: true,- });+ const suggestedPromptsReq = useGetSuggestedMetabotPromptsQuery(+ {+ metabot_id: metabot.metabotId,+ limit: 3,+ sample: true,+ },+ { skip: !isConfigured },+ );const suggestedPrompts = useMemo(() => {return suggestedPromptsReq.currentData?.prompts ?? [];}, [suggestedPromptsReq.currentData?.prompts]);@@ -88,14 +106,16 @@ export const MetabotChat = ({</Flex><Flex gap="sm">- <Tooltip label={t`Clear conversation`} position="bottom">- <ActionIcon- onClick={handleResetChat}- data-testid="metabot-reset-chat"- >- <Icon c="text-primary" name="revert" />- </ActionIcon>- </Tooltip>+ {isConfigured && (+ <Tooltip label={t`Clear conversation`} position="bottom">+ <ActionIcon+ onClick={handleResetChat}+ data-testid="metabot-reset-chat"+ >+ <Icon c="text-primary" name="revert" />+ </ActionIcon>+ </Tooltip>+ )}{!config.preventClose && (<ActionIcon onClick={handleClose} data-testid="metabot-close-chat"><Icon c="text-primary" name="close" />@@ -124,14 +144,21 @@ export const MetabotChat = ({{showIllustrations && (<Box component={EmptyDashboardBot} w="6rem" />)}- <Text c="text-tertiary" maw="12rem" ta="center" lh="lg">- {config.emptyText ??- (showIllustrations- ? t`I can help you explore your metrics and models.`- : t`Explore your metrics and models with AI.`)}- </Text>+ {!isConfigured ? (+ <AIProviderConfigurationNotice+ featureName={metabotName}+ onConfigureAi={openAiProviderConfigurationModal}+ />+ ) : (+ <Text c="text-tertiary" maw="12rem" ta="center" lh="lg">+ {config.emptyText ??+ (showIllustrations+ ? t`I can help you explore your metrics and models.`+ : t`Explore your metrics and models with AI.`)}+ </Text>+ )}</Flex>- {!config.hideSuggestedPrompts && (+ {isConfigured && !config.hideSuggestedPrompts && (<Stackgap="sm"className={Styles.promptSuggestionsContainer}@@ -187,26 +214,32 @@ export const MetabotChat = ({)}</Box>- <Box className={Styles.textInputContainer}>- <Paper- className={cx(- Styles.inputContainer,- metabot.isDoingScience && Styles.inputContainerLoading,- )}- >- <MetabotChatEditor- ref={metabot.promptInputRef}- value={metabot.prompt}- autoFocus- isResponding={metabot.isDoingScience}- placeholder={t`How can I help? Type @ to mention items.`}- onChange={metabot.setPrompt}- onSubmit={handleEditorSubmit}- onStop={metabot.cancelRequest}- suggestionConfig={{ suggestionModels: config.suggestionModels }}- />- </Paper>- </Box>+ {isConfigured && (+ <Box className={Styles.textInputContainer}>+ <Paper+ className={cx(+ Styles.inputContainer,+ metabot.isDoingScience && Styles.inputContainerLoading,+ )}+ >+ <MetabotChatEditor+ ref={metabot.promptInputRef}+ value={metabot.prompt}+ autoFocus+ isResponding={metabot.isDoingScience}+ placeholder={t`How can I help? Type @ to mention items.`}+ onChange={metabot.setPrompt}+ onSubmit={handleEditorSubmit}+ onStop={metabot.cancelRequest}+ suggestionConfig={{ suggestionModels: config.suggestionModels }}+ />+ </Paper>+ </Box>+ )}+ <AIProviderConfigurationModal+ opened={isAiProviderConfigurationModalOpen}+ onClose={closeAiProviderConfigurationModal}+ /></Box>);};diff --git a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsxindex 0b537c69d48..ec97f25ddf4 100644--- a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx+++ b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx@@ -16,12 +16,12 @@ import { trackMetabotChatOpened } from "../analytics";import { MetabotIcon } from "./MetabotIcon";export const MetabotDataStudioButton = () => {- const { canUseMetabot } = useUserMetabotPermissions();+ const { hasMetabotAccess } = useUserMetabotPermissions();const metabot = useMetabotAgent("omnibot");const metabotName = useMetabotName();const location = useSelector(getLocation);- if (!canUseMetabot) {+ if (!hasMetabotAccess) {return null;}diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsxindex 5b8d42892ff..ccbb7b2f5ff 100644--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx@@ -1,16 +1,23 @@+import { useDisclosure } from "@mantine/hooks";import { useCallback, useEffect, useRef } from "react";import { tinykeys } from "tinykeys";import { t } from "ttag";import type { MetabotPromptInputRef } from "metabase/metabot";+import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";import { MetabotManagedProviderLimitHoverCard } from "metabase/metabot/components/MetabotManagedProviderLimit";import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";-import { useMetabotName } from "metabase/metabot/hooks";+import {+ useMetabotName,+ useUserMetabotPermissions,+} from "metabase/metabot/hooks";import type { MetabotAgentTurnDisplayError } from "metabase/metabot/state";import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";import { Box, Button, Flex, Icon, Loader, Tooltip } from "metabase/ui";import type { DatabaseId } from "metabase-types/api";+import { AIProviderConfigurationNotice } from "../AIProviderConfigurationNotice";+import S from "./MetabotInlineSQLPrompt.module.css";interface MetabotInlineSQLPromptProps {@@ -39,9 +46,17 @@ export const MetabotInlineSQLPrompt = ({onValueChange,}: MetabotInlineSQLPromptProps) => {const promptInputRef = useRef<MetabotPromptInputRef>(null);+ const [+ isAiProviderConfigurationModalOpen,+ {+ close: closeAiProviderConfigurationModal,+ open: openAiProviderConfigurationModal,+ },+ ] = useDisclosure(false);+ const { canUseSqlGeneration } = useUserMetabotPermissions();const metabotName = useMetabotName();- const isSubmitDisabled = !value.trim() || isLoading;+ const isSubmitDisabled = !canUseSqlGeneration || !value.trim() || isLoading;const handleSubmit = useCallback(async () => {const prompt = promptInputRef.current?.getValue?.().trim() ?? "";@@ -74,21 +89,33 @@ export const MetabotInlineSQLPrompt = ({return (<Box className={S.container} data-testid="metabot-inline-sql-prompt">- <Box className={S.inputContainer}>- <MetabotPromptInput- ref={promptInputRef}- value={value}- placeholder={t`Describe what SQL you want, type @ to mention an item.`}- autoFocus- disabled={isLoading}- onChange={onValueChange}- onStop={handleClose}- suggestionConfig={{- suggestionModels,- onlyDatabaseId: databaseId ?? undefined,- }}+ {!canUseSqlGeneration ? (+ <AIProviderConfigurationNotice+ inline+ featureName={t`SQL generation`}+ fz="sm"+ p="0.25rem 0.125rem"+ ff="var(--mb-default-font-family)"+ onConfigureAi={openAiProviderConfigurationModal}/>- </Box>+ ) : (+ <Box className={S.inputContainer}>+ <MetabotPromptInput+ ref={promptInputRef}+ value={value}+ placeholder={t`Describe what SQL you want, type @ to mention an item.`}+ autoFocus+ disabled={isLoading}+ onChange={onValueChange}+ onStop={handleClose}+ suggestionConfig={{+ suggestionModels,+ onlyDatabaseId: databaseId ?? undefined,+ }}+ />+ </Box>+ )}+<Flex justify="space-between" align="center" gap="sm" mt="xs"><Box data-testid="metabot-inline-sql-error" w="100%" fz="sm" c="error">{error?.type === "locked" ? (@@ -98,29 +125,31 @@ export const MetabotInlineSQLPrompt = ({)}</Box><Flex gap="xs" flex="1 0 auto">- <Tooltip disabled={isLoading} label={t`Send to ${metabotName}`}>- <Button- className={S.submitButton}- data-testid="metabot-inline-sql-generate"- size="xs"- variant="filled"- px="0"- w="1.875rem"- styles={{ label: { display: "flex" } }}- onClick={handleSubmit}- disabled={isSubmitDisabled}- >- {isLoading ? (- <Loader- size="xs"- color="text-tertiary"- data-testid="metabot-inline-sql-generating"- />- ) : (- <Icon name="send" />- )}- </Button>- </Tooltip>+ {canUseSqlGeneration && (+ <Tooltip disabled={isLoading} label={t`Send to ${metabotName}`}>+ <Button+ className={S.submitButton}+ data-testid="metabot-inline-sql-generate"+ size="xs"+ variant="filled"+ px="0"+ w="1.875rem"+ styles={{ label: { display: "flex" } }}+ onClick={handleSubmit}+ disabled={isSubmitDisabled}+ >+ {isLoading ? (+ <Loader+ size="xs"+ color="text-tertiary"+ data-testid="metabot-inline-sql-generating"+ />+ ) : (+ <Icon name="send" />+ )}+ </Button>+ </Tooltip>+ )}<ButtonclassName={S.cancelButton}data-testid="metabot-inline-sql-cancel"@@ -132,6 +161,10 @@ export const MetabotInlineSQLPrompt = ({</Button></Flex></Flex>+ <AIProviderConfigurationModal+ opened={isAiProviderConfigurationModalOpen}+ onClose={closeAiProviderConfigurationModal}+ /></Box>);};diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.unit.spec.tsxnew file mode 100644index 00000000000..f0bdac351e1--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.unit.spec.tsx@@ -0,0 +1,74 @@+import type { ComponentProps } from "react";++import { setupEnterprisePlugins } from "__support__/enterprise";+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockState } from "metabase/redux/store/mocks";+import { createMockUser } from "metabase-types/api/mocks";++import { MetabotInlineSQLPrompt } from "./MetabotInlineSQLPrompt";++const defaultProps: ComponentProps<typeof MetabotInlineSQLPrompt> = {+ databaseId: 1,+ onClose: jest.fn(),+ isLoading: false,+ error: undefined,+ generate: jest.fn(),+ cancelRequest: jest.fn(),+ suggestionModels: [],+ getSourceSql: jest.fn(() => "select 1"),+ value: "",+ onValueChange: jest.fn(),+};++function setup(+ props?: Partial<ComponentProps<typeof MetabotInlineSQLPrompt>>,+ options?: { isAdmin?: boolean },+) {+ const { isAdmin = true } = options ?? {};+ const settings = mockSettings({+ "llm-metabot-configured?": false,+ "metabot-enabled?": true,+ });++ setupUserMetabotPermissionsEndpoint();+ setupEnterprisePlugins();++ renderWithProviders(<MetabotInlineSQLPrompt {...defaultProps} {...props} />, {+ storeInitialState: createMockState({+ settings,+ currentUser: createMockUser({ is_superuser: isAdmin }),+ }),+ });+}++describe("MetabotInlineSQLPrompt", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("shows a configure link instead of submit controls when disabled", async () => {+ setup();++ expect(+ screen.getByText(/To use SQL generation, please/),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("metabot-inline-sql-generate"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "connect to a model" }),+ ).toBeInTheDocument();+ });++ it("shows the admin message when the user cannot configure AI", () => {+ setup(undefined, { isAdmin: false });++ expect(+ screen.getByText(+ "Ask your admin to connect to a model to use SQL generation.",+ ),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsxindex 7b7bef19c58..98b90f0f45b 100644--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx@@ -57,7 +57,8 @@ export function useInlineSQLPrompt(question: Question,bufferId: string,): UseInlineSqlEditResult {- const { canUseSqlGeneration: isEnabled } = useUserMetabotPermissions();+ const { canUseSqlGeneration, hasSqlGenerationAccess } =+ useUserMetabotPermissions();const databaseId = question.databaseId();@@ -169,7 +170,7 @@ export function useInlineSQLPrompt(const extensions = useMemo(() =>- isEnabled+ hasSqlGenerationAccess? [createPromptInputExtension(setPortalTarget),keymap.of([@@ -201,13 +202,13 @@ export function useInlineSQLPrompt(}),]: [],- [isEnabled],+ [hasSqlGenerationAccess],);return {extensions,portalElement:- isEnabled && portalTarget+ hasSqlGenerationAccess && portalTarget? createPortal(<MetabotInlineSQLPromptdatabaseId={databaseId}@@ -224,8 +225,12 @@ export function useInlineSQLPrompt(portalTarget.container,): null,- proposedQuestion: isEnabled ? proposedQuestion : undefined,- handleRejectProposed: isEnabled ? handleRejectProposed : undefined,- handleAcceptProposed: isEnabled ? handleAcceptProposed : undefined,+ proposedQuestion: canUseSqlGeneration ? proposedQuestion : undefined,+ handleRejectProposed: canUseSqlGeneration+ ? handleRejectProposed+ : undefined,+ handleAcceptProposed: canUseSqlGeneration+ ? handleAcceptProposed+ : undefined,};}diff --git a/frontend/src/metabase/metabot/components/MetabotManagedProviderLimit.tsx b/frontend/src/metabase/metabot/components/MetabotManagedProviderLimit.tsxindex 3c0aed029a1..380d5daea7f 100644--- a/frontend/src/metabase/metabot/components/MetabotManagedProviderLimit.tsx+++ b/frontend/src/metabase/metabot/components/MetabotManagedProviderLimit.tsx@@ -40,7 +40,7 @@ export const MetabotManagedProviderLimitActions = ({const configureModal = (<Modal- title="Connect to an AI provider"+ title={t`Connect to an AI provider`}onClose={close}opened={isOpen}size="lg"diff --git a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsxindex bbbe217f43c..c860b20d9b8 100644--- a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx+++ b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx@@ -1,3 +1,4 @@+import { useDisclosure } from "@mantine/hooks";import { isFulfilled, isRejected } from "@reduxjs/toolkit";import cx from "classnames";import { useEffect, useState } from "react";@@ -9,6 +10,7 @@ import _ from "underscore";import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";import { MetabotLogo } from "metabase/common/components/MetabotLogo";import { useSetting } from "metabase/common/hooks";+import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";import { QueryBuilder } from "metabase/query_builder/containers/QueryBuilder";import { useDispatch, useSelector } from "metabase/redux";@@ -26,6 +28,7 @@ import {import * as Urls from "metabase/urls";import { useMetabotAgent, useUserMetabotPermissions } from "../../hooks";+import { AIProviderConfigurationNotice } from "../AIProviderConfigurationNotice";import S from "./MetabotQueryBuilder.module.css";@@ -57,6 +60,15 @@ const responseHasNavigateTo = (action: SubmitInputResult) =>);const MetabotQueryBuilderInner = () => {+ const { canUseNlq } = useUserMetabotPermissions();+ const [+ isAiProviderConfigurationModalOpen,+ {+ close: closeAiProviderConfigurationModal,+ open: openAiProviderConfigurationModal,+ },+ ] = useDisclosure(false);+const dispatch = useDispatch();const {setVisible,@@ -186,19 +198,28 @@ const MetabotQueryBuilderInner = () => {)}><Box className={S.editorWrapper}>- <MetabotPromptInput- ref={promptInputRef}- value={prompt}- autoFocus- disabled={isDoingScience}- placeholder={t`Ask about your data, and type @ to mention an item`}- onChange={setPrompt}- onSubmit={handleEditorSubmit}- onStop={cancelRequest}- suggestionConfig={{- suggestionModels: [...defaultSuggestionModels],- }}- />+ {!canUseNlq ? (+ <AIProviderConfigurationNotice+ py="0.5rem"+ featureName={t`AI exploration`}+ inline+ onConfigureAi={openAiProviderConfigurationModal}+ />+ ) : (+ <MetabotPromptInput+ ref={promptInputRef}+ value={prompt}+ autoFocus+ disabled={isDoingScience}+ placeholder={t`Ask about your data, and type @ to mention an item`}+ onChange={setPrompt}+ onSubmit={handleEditorSubmit}+ onStop={cancelRequest}+ suggestionConfig={{+ suggestionModels: [...defaultSuggestionModels],+ }}+ />+ )}</Box><Box className={S.inputActions}>{hasError ? (@@ -212,7 +233,7 @@ const MetabotQueryBuilderInner = () => {className={S.sendButton}variant="filled"size="2rem"- disabled={inputDisabled}+ disabled={!canUseNlq || inputDisabled}loading={isDoingScience}onClick={handleEditorSubmit}data-testid="metabot-send-message"@@ -224,27 +245,33 @@ const MetabotQueryBuilderInner = () => {</Paper><Box className={S.promptSuggestionsContainer}>- {suggestedPrompts?.map(({ prompt: suggestedPrompt }, index) => (- <UnstyledButton- key={index}- className={cx(S.promptSuggestion, {- [S.promptSuggestionShow]: !isDoingScience,- [S.promptSuggestionHide]: isDoingScience,- })}- style={{- animationDelay: isDoingScience- ? `${(suggestedPromptCount - index - 1) * 50}ms`- : `${index * 75}ms`,- }}- onClick={() => handleSubmitPrompt(suggestedPrompt)}- disabled={isDoingScience}- >- <Text>{suggestedPrompt}</Text>- </UnstyledButton>- ))}+ {canUseNlq+ ? suggestedPrompts?.map(({ prompt: suggestedPrompt }, index) => (+ <UnstyledButton+ key={index}+ className={cx(S.promptSuggestion, {+ [S.promptSuggestionShow]: !isDoingScience,+ [S.promptSuggestionHide]: isDoingScience,+ })}+ style={{+ animationDelay: isDoingScience+ ? `${(suggestedPromptCount - index - 1) * 50}ms`+ : `${index * 75}ms`,+ }}+ onClick={() => handleSubmitPrompt(suggestedPrompt)}+ disabled={isDoingScience}+ >+ <Text>{suggestedPrompt}</Text>+ </UnstyledButton>+ ))+ : null}</Box></Stack></Box>+ <AIProviderConfigurationModal+ opened={isAiProviderConfigurationModalOpen}+ onClose={closeAiProviderConfigurationModal}+ /></Box>);};@@ -252,7 +279,7 @@ const MetabotQueryBuilderInner = () => {export const MetabotQueryBuilder = (props: React.ComponentProps<typeof QueryBuilder>,) => {- const { canUseNlq, isLoading } = useUserMetabotPermissions();+ const { hasNlqAccess, isLoading } = useUserMetabotPermissions();const areSettingsLoading = useSelector(getSettingsLoading);// Wait until settings and metabot permissions are both resolved before// deciding which view to render. Otherwise QueryBuilder may mount briefly@@ -260,7 +287,7 @@ export const MetabotQueryBuilder = (if (areSettingsLoading || isLoading) {return null;}- if (!canUseNlq) {+ if (!hasNlqAccess) {return <QueryBuilder {...props} />;}return <MetabotQueryBuilderInner />;diff --git a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.unit.spec.tsxindex b8283767ea9..ccc2d6aa3a2 100644--- a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.unit.spec.tsx@@ -1,6 +1,7 @@import type { ComponentType } from "react";import { Route } from "react-router";+import { setupBookmarksEndpoints } from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { renderWithProviders, screen } from "__support__/ui";import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";@@ -39,8 +40,12 @@ function setup({suggestedPrompts = [],}: SetupOptions = {}) {jest.mocked(useUserMetabotPermissions).mockReturnValue({+ hasNlqAccess: true,canUseNlq: true,} as any);++ setupBookmarksEndpoints([]);+jest.mocked(useMetabotAgent).mockReturnValue({setVisible: jest.fn(),resetConversation: jest.fn(),diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-embedding-aware-enabled.ts b/frontend/src/metabase/metabot/hooks/use-metabot-embedding-aware-enabled.tsindex 6cb1a81e6ba..718319ec862 100644--- a/frontend/src/metabase/metabot/hooks/use-metabot-embedding-aware-enabled.ts+++ b/frontend/src/metabase/metabot/hooks/use-metabot-embedding-aware-enabled.ts@@ -4,11 +4,14 @@ import { isWithinIframe } from "metabase/utils/iframe";/** Returns the value for `metabot-enabled?` or `embedded-metabot-enabled?` depending on the context* only if the metabot token feature is enabled.+ * By default, this also requires the provider configuration to be complete.* Use `forceEmbedding` to always check the embedding setting (e.g. in the embed wizard). */export const useMetabotEnabledEmbeddingAware = ({forceEmbedding = false,+ requireConfiguration = true,}: {forceEmbedding?: boolean;+ requireConfiguration?: boolean;} = {}): boolean => {const isEmbedding = forceEmbedding || isWithinIframe() || isEmbeddingSdk();const isEnabled = useSetting(@@ -16,5 +19,5 @@ export const useMetabotEnabledEmbeddingAware = ({);const isConfigured = !!useSetting("llm-metabot-configured?");- return isEnabled && isConfigured;+ return isEnabled && (!requireConfiguration || isConfigured);};diff --git a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.tsindex 0c210ea7d0a..479bce88cd6 100644--- a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts+++ b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts@@ -1,35 +1,63 @@import { useMemo } from "react";import { useGetUserMetabotPermissionsQuery } from "metabase/api";+import { useSetting } from "metabase/common/hooks";import { useSelector } from "metabase/redux";-import { getUser } from "metabase/selectors/user";+import { canAccessSettings, getUser } from "metabase/selectors/user";import { useMetabotEnabledEmbeddingAware } from "./use-metabot-embedding-aware-enabled";/** Returns granular metabot permission booleans for the current user.* Combines the global metabot-enabled setting with per-user group permissions.- * Returns all false while loading or on error. */+ * Returns all false while loading or on error.+ * Access booleans (`has*Access`) only depend on feature toggles and permissions.+ * Usage booleans (`canUse*`) additionally require the AI provider to be configured. */export const useUserMetabotPermissions = () => {- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();+ const isMetabotEnabled = useMetabotEnabledEmbeddingAware({+ requireConfiguration: false,+ });const isAuthenticated = !!useSelector(getUser);+ const isConfigured = !!useSetting("llm-metabot-configured?");+ const canConfigure = useSelector(canAccessSettings);const { data, isLoading, isError } = useGetUserMetabotPermissionsQuery(undefined,{ skip: !isMetabotEnabled || !isAuthenticated },);const perms = data?.permissions;- const hasAccess = isMetabotEnabled && !isLoading && perms?.metabot === "yes";+ const hasMetabotAccess =+ isMetabotEnabled && !isLoading && perms?.metabot === "yes";++ const hasSqlGenerationAccess =+ hasMetabotAccess && perms?.["metabot-sql-generation"] === "yes";+ const hasNlqAccess = hasMetabotAccess && perms?.["metabot-nlq"] === "yes";+ const hasOtherToolsAccess =+ hasMetabotAccess && perms?.["metabot-other-tools"] === "yes";return useMemo(() => ({isLoading,isError,- canUseMetabot: hasAccess,- canUseSqlGeneration:- hasAccess && perms?.["metabot-sql-generation"] === "yes",- canUseNlq: hasAccess && perms?.["metabot-nlq"] === "yes",- canUseOtherTools: hasAccess && perms?.["metabot-other-tools"] === "yes",+ isConfigured,+ canConfigure,+ hasMetabotAccess,+ canUseMetabot: hasMetabotAccess && isConfigured,+ hasSqlGenerationAccess,+ canUseSqlGeneration: hasSqlGenerationAccess && isConfigured,+ hasNlqAccess,+ canUseNlq: hasNlqAccess && isConfigured,+ hasOtherToolsAccess,+ canUseOtherTools: hasOtherToolsAccess && isConfigured,}),- [isLoading, isError, hasAccess, perms],+ [+ canConfigure,+ hasMetabotAccess,+ hasNlqAccess,+ hasOtherToolsAccess,+ hasSqlGenerationAccess,+ isConfigured,+ isError,+ isLoading,+ ],);};diff --git a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsxindex fa9d598a17c..3d35d1f90eb 100644--- a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx+++ b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx@@ -20,11 +20,13 @@ function TestComponent() {function setup({isMetabotEnabled = true,isAuthenticated = true,+ isConfigured = true,apiResponse,apiStatus = 200,}: {isMetabotEnabled?: boolean;isAuthenticated?: boolean;+ isConfigured?: boolean;apiResponse?: UserMetabotPermissionsResponse;apiStatus?: number;} = {}) {@@ -38,7 +40,7 @@ function setup({}const settings = mockSettings({- "llm-metabot-configured?": true,+ "llm-metabot-configured?": isConfigured,"metabot-enabled?": isMetabotEnabled,"token-features": createMockTokenFeatures({ ai_controls: true }),});@@ -76,6 +78,32 @@ describe("useUserMetabotPermissions", () => {it("returns all false when metabot is globally disabled", async () => {setup({ isMetabotEnabled: false });const perms = await getPerms();+ expect(perms.hasMetabotAccess).toBe(false);+ expect(perms.canUseMetabot).toBe(false);+ expect(perms.canUseSqlGeneration).toBe(false);+ expect(perms.canUseNlq).toBe(false);+ expect(perms.canUseOtherTools).toBe(false);+ });++ it("does not fetch user permissions without an authenticated user", async () => {+ setup({ isAuthenticated: false });+ const perms = await getPerms();+ expect(perms.hasMetabotAccess).toBe(false);+ expect(+ fetchMock.callHistory.called(+ "path:/api/metabot/permissions/user-permissions",+ ),+ ).toBe(false);+ });++ it("returns access booleans but no usage booleans when AI is not configured", async () => {+ setup({ isConfigured: false });+ const perms = await getPerms();+ expect(perms.hasMetabotAccess).toBe(true);+ expect(perms.hasSqlGenerationAccess).toBe(true);+ expect(perms.hasNlqAccess).toBe(true);+ expect(perms.hasOtherToolsAccess).toBe(true);+ expect(perms.isConfigured).toBe(false);expect(perms.canUseMetabot).toBe(false);expect(perms.canUseSqlGeneration).toBe(false);expect(perms.canUseNlq).toBe(false);@@ -113,6 +141,7 @@ describe("useUserMetabotPermissions", () => {apiResponse: createMockUserMetabotPermissions({ metabot: "no" }),});const perms = await getPerms();+ expect(perms.hasMetabotAccess).toBe(false);expect(perms.canUseMetabot).toBe(false);expect(perms.canUseSqlGeneration).toBe(false);expect(perms.canUseNlq).toBe(false);@@ -126,6 +155,7 @@ describe("useUserMetabotPermissions", () => {}),});const perms = await getPerms();+ expect(perms.hasSqlGenerationAccess).toBe(false);expect(perms.canUseMetabot).toBe(true);expect(perms.canUseSqlGeneration).toBe(false);expect(perms.canUseNlq).toBe(true);@@ -137,6 +167,7 @@ describe("useUserMetabotPermissions", () => {apiResponse: createMockUserMetabotPermissions({ "metabot-nlq": "no" }),});const perms = await getPerms();+ expect(perms.hasNlqAccess).toBe(false);expect(perms.canUseMetabot).toBe(true);expect(perms.canUseSqlGeneration).toBe(true);expect(perms.canUseNlq).toBe(false);@@ -150,6 +181,7 @@ describe("useUserMetabotPermissions", () => {}),});const perms = await getPerms();+ expect(perms.hasOtherToolsAccess).toBe(false);expect(perms.canUseMetabot).toBe(true);expect(perms.canUseSqlGeneration).toBe(true);expect(perms.canUseNlq).toBe(true);diff --git a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsxindex 3b429b4678c..ea3e0cae755 100644--- a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx@@ -8,6 +8,7 @@ import { useMetabotAgent } from "metabase/metabot/hooks";import { metabotActions } from "metabase/metabot/state";import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import * as domModule from "metabase/utils/dom";+import { createMockUser } from "metabase-types/api/mocks";import { Metabot } from "../components/Metabot";@@ -40,6 +41,31 @@ describe("metabot > ui", () => {).toBeInTheDocument();});+ it("should show a setup prompt and disable chat input when metabot is not configured", async () => {+ setup({+ currentUser: createMockUser({ is_superuser: true }),+ isConfigured: false,+ });++ expect(+ await screen.findByText("To use Metabot, please", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "connect to a model" }),+ ).toBeInTheDocument();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ });++ it("should ask non-admins to contact an admin when metabot is not configured", async () => {+ setup({ isConfigured: false });++ expect(+ await screen.findByText(+ "Ask your admin to connect to a model to use Metabot.",+ ),+ ).toBeInTheDocument();+ });+it("should show empty state ui if conversation is empty", async () => {setup();mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsxindex c4ad4d20f35..884f36c325c 100644--- a/frontend/src/metabase/metabot/tests/utils.tsx+++ b/frontend/src/metabase/metabot/tests/utils.tsx@@ -185,10 +185,11 @@ export function setup(isHosted?: boolean;storeInitialState?: RenderWithProvidersOptions["storeInitialState"];customReducers?: RenderWithProvidersOptions["customReducers"];+ isConfigured?: boolean;} | void,) {const settings = mockSettings({- "llm-metabot-configured?": true,+ "llm-metabot-configured?": options?.isConfigured ?? true,"is-hosted?": options?.isHosted ?? false,});diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsxindex 98ecd673627..ddcdaa7aafd 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx@@ -61,7 +61,8 @@ const AppBarLarge = ({const { isVisible: isGitSyncVisible } =PLUGIN_REMOTE_SYNC.useGitSyncVisible();- const { canUseMetabot: isMetabotEnabled } = useUserMetabotPermissions();+ const { hasMetabotAccess: isMetabotVisibleToUser } =+ useUserMetabotPermissions();return (<AppBarRoot@@ -104,7 +105,7 @@ const AppBarLarge = ({{(isSearchVisible ||isNewButtonVisible ||isAppSwitcherVisible ||- isMetabotEnabled) && (+ isMetabotVisibleToUser) && (<Flexalign="center"gap="sm"diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 21bb354f661..b930f813374 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -74,7 +74,10 @@ export {type PublishTablesModalProps,type UnpublishTablesModalProps,} from "./oss/library";-export { PLUGIN_METABOT } from "./oss/metabot";+export {+ PLUGIN_METABOT,+ type MetabaseAIProviderSetupProps,+} from "./oss/metabot";export { PLUGIN_MODEL_PERSISTENCE } from "./oss/model-persistence";export {PLUGIN_MODERATION,diff --git a/frontend/src/metabase/plugins/oss/metabot.ts b/frontend/src/metabase/plugins/oss/metabot.tsindex 3cb3407eb27..b11269acd7b 100644--- a/frontend/src/metabase/plugins/oss/metabot.ts+++ b/frontend/src/metabase/plugins/oss/metabot.ts@@ -2,14 +2,19 @@ import type { ComponentType } from "react";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";+export type MetabaseAIProviderSetupProps = {+ onConnect?: VoidFunction;+};+const getDefaultPluginMetabot = () => ({isEnabled: false,- MetabaseAIProviderSetup: PluginPlaceholder as ComponentType,+ MetabaseAIProviderSetup:+ PluginPlaceholder as ComponentType<MetabaseAIProviderSetupProps>,});export const PLUGIN_METABOT: {isEnabled: boolean;- MetabaseAIProviderSetup: ComponentType;+ MetabaseAIProviderSetup: ComponentType<MetabaseAIProviderSetupProps>;} = getDefaultPluginMetabot();/**diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsxindex 7db61d6504e..f3a0570e11e 100644--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx@@ -72,9 +72,10 @@ export const CodeMirrorEditor = forwardRef<ref,) {const editorRef = useRef<CodeMirrorRef>(null);- const { canUseSqlGeneration: isEnabled } = useUserMetabotPermissions();+ const { hasSqlGenerationAccess } = useUserMetabotPermissions();const placeholder =- placeholderProp ?? getPlaceholderText(Lib.engine(query), isEnabled);+ placeholderProp ??+ getPlaceholderText(Lib.engine(query), hasSqlGenerationAccess);const baseExtensions = useExtensions({query,diff: !!proposedQuery,diff --git a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsxindex 53c57f7181f..ba38c13a2ee 100644--- a/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx+++ b/frontend/src/metabase/transforms/pages/JobListPage/JobListPage.unit.spec.tsx@@ -7,9 +7,11 @@ import {setupDeleteTransformJobEndpoint,setupListTransformJobsEndpoint,setupUpdateTransformJobEndpoint,+ setupUserMetabotPermissionsEndpoint,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor, within } from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks/state";+import * as Urls from "metabase/urls";import type { TransformJob } from "metabase-types/api";import {createMockTransformJob,@@ -77,11 +79,12 @@ async function setup({jobs: TransformJob[];isAdmin?: boolean;}) {+ setupUserMetabotPermissionsEndpoint();setupListTransformJobsEndpoint(jobs);jobs.forEach(setupUpdateTransformJobEndpoint);jobs.forEach((job) => setupDeleteTransformJobEndpoint(job.id));- const path = "/transforms/jobs";+ const path = Urls.transformJobList();const { history } = renderWithProviders(<Route path={path} component={JobListPage} />,{@@ -134,7 +137,9 @@ describe("JobListPage", () => {expect(await screen.findByRole("menuitem", { name: /Disable/ }),).toBeInTheDocument();- expect(history?.getCurrentLocation().pathname).toBe("/transforms/jobs");+ expect(history?.getCurrentLocation().pathname).toBe(+ Urls.transformJobList(),+ );});it("disables a job from the row action menu without navigating", async () => {@@ -160,7 +165,9 @@ describe("JobListPage", () => {method: "PUT",});expect(await call?.request?.json()).toEqual({ active: false });- expect(history?.getCurrentLocation().pathname).toBe("/transforms/jobs");+ expect(history?.getCurrentLocation().pathname).toBe(+ Urls.transformJobList(),+ );});it("deletes a job from the row action menu without visiting the detail page", async () => {diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.unit.spec.tsxindex 36fbb4d6367..c6eb918e425 100644--- a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.unit.spec.tsx+++ b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupCollectionTreeEndpoint,setupDatabaseListEndpoint,setupListTransformsEndpoint,+ setupUserMetabotPermissionsEndpoint,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import {@@ -56,6 +57,7 @@ async function setup({ tokenFeatures = {} }: SetupOpts = {}) {setupCollectionTreeEndpoint([]);setupListTransformsEndpoint([]);setupDatabaseListEndpoint([]);+ setupUserMetabotPermissionsEndpoint();const state = createMockState({settings: mockSettings({