Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Allow Admins to purchase Metabot AI (#74602)

Ryan Laurie16156549a7b0
diff --git a/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj b/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
index 60993881468..f20c786d164 100644
--- a/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
@@ -27,8 +27,6 @@
(deferred-tru "Can only access Store API for Metabase Cloud instances."))
(def ^:private error-not-eligible
(deferred-tru "Can only purchase add-ons for eligible subscriptions."))
-(def ^:private error-not-store-user
- (deferred-tru "Only Metabase Store users can purchase add-ons."))
(def ^:private error-terms-not-accepted
(deferred-tru "Need to accept terms of service."))
(def ^:private error-no-quantity
@@ -38,8 +36,6 @@
{:status 400 :body error-not-hosted})
(def ^:private response-not-eligible
{:status 400 :body error-not-eligible})
-(def ^:private response-not-store-user
- {:status 403 :body error-not-store-user})
(def ^:private response-terms-not-accepted
{:status 400 :body {:errors {:terms_of_service error-terms-not-accepted}}})
(def ^:private response-no-quantity
@@ -149,10 +145,6 @@
(premium-features/enable-python-transforms?))
response-not-eligible
- (not (contains? (set (map :email (:store-users (premium-features/token-status))))
- (:email @api/*current-user*)))
- response-not-store-user
-
:else
(try
(let [add-on (cond-> {:product-type product-type}
diff --git a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
index e9ba9c4459a..76fba5ef9b9 100644
--- a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
@@ -24,47 +24,38 @@
(is (=? "Can only access Store API for Metabase Cloud instances."
(mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/metabase-ai"
{:terms_of_service true})))))
- (testing "requires current user being a store user"
- (mt/with-premium-features #{:hosting}
- (is (=? "Only Metabase Store users can purchase add-ons."
- (mt/user-http-request :crowberto :post 403 "ee/cloud-add-ons/metabase-ai"
- {:terms_of_service true})))))
(testing "when all conditions are met"
- (mt/with-temp [:model/User user {:is_superuser true}]
- (mt/with-premium-features #{:hosting :audit-app}
- ;; FIXME: With `(mt/with-temporary-setting-values [token-status {:store-users [{:email (:email user)}]}])`,
- ;; `(premium-features/token-status)` still returns `nil`; thus resort to `with-redefs`:
- (with-redefs [premium-features/token-status (constantly {:store-users [{:email (:email user)}]})]
- (doseq [[status-code error-message] {404 "Could not establish a connection to Metabase Cloud."
- 403 "Could not establish a connection to Metabase Cloud."
- 401 "Could not establish a connection to Metabase Cloud."
- 400 "Could not purchase this add-on."}]
- (testing (format "passes through HTTP status %d from Store API" status-code)
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
- (is (=? error-message
- (mt/user-http-request user :post status-code "ee/cloud-add-ons/metabase-ai"
- {:terms_of_service true}))))))
- (testing "responds with HTTP status 500 for other errors from Store API"
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
- (is (=? "Unexpected error"
- (mt/user-http-request user :post 500 "ee/cloud-add-ons/metabase-ai"
- {:terms_of_service true})))))
- (testing "succeeds"
- (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))
- {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]
- (with-redefs [hm.client/call store-api-proxy
- premium-features/clear-cache! clear-token-cache-proxy]
- (is (=? {}
- (mt/user-http-request user :post 200 "ee/cloud-add-ons/metabase-ai"
- {:terms_of_service true})))
- (is (not-empty @store-api-calls)
- "Store API was called")
- (is (not-empty @clear-token-cache-calls)
- "Token cache was cleared")
- (testing "audit log entry generated"
- (let [{:keys [details user_id]} (mt/latest-audit-log-entry "cloud-add-on-purchase")]
- (is (= (:id user) user_id))
- (is (= {:add-on {:product-type "metabase-ai"}} details)))))))))))))
+ (mt/with-premium-features #{:hosting :audit-app}
+ (doseq [[status-code error-message] {404 "Could not establish a connection to Metabase Cloud."
+ 403 "Could not establish a connection to Metabase Cloud."
+ 401 "Could not establish a connection to Metabase Cloud."
+ 400 "Could not purchase this add-on."}]
+ (testing (format "passes through HTTP status %d from Store API" status-code)
+ (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
+ (is (=? error-message
+ (mt/user-http-request :crowberto :post status-code "ee/cloud-add-ons/metabase-ai"
+ {:terms_of_service true}))))))
+ (testing "responds with HTTP status 500 for other errors from Store API"
+ (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
+ (is (=? "Unexpected error"
+ (mt/user-http-request :crowberto :post 500 "ee/cloud-add-ons/metabase-ai"
+ {:terms_of_service true})))))
+ (testing "succeeds"
+ (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))
+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]
+ (with-redefs [hm.client/call store-api-proxy
+ premium-features/clear-cache! clear-token-cache-proxy]
+ (is (=? {}
+ (mt/user-http-request :crowberto :post 200 "ee/cloud-add-ons/metabase-ai"
+ {:terms_of_service true})))
+ (is (not-empty @store-api-calls)
+ "Store API was called")
+ (is (not-empty @clear-token-cache-calls)
+ "Token cache was cleared")
+ (testing "audit log entry generated"
+ (let [{:keys [details user_id]} (mt/latest-audit-log-entry "cloud-add-on-purchase")]
+ (is (= (mt/user->id :crowberto) user_id))
+ (is (= {:add-on {:product-type "metabase-ai"}} details)))))))))))
(deftest ^:sequential post-transforms-test
(doseq [[product-type feature] [["python-execution" :transforms-python]
@@ -86,18 +77,11 @@
(mt/with-premium-features #{:hosting feature}
(is (=? "Can only purchase add-ons for eligible subscriptions."
(mt/user-http-request :crowberto :post 400 (str "ee/cloud-add-ons/" product-type) {})))))
- (testing "requires current user being a store user"
- (mt/with-temp [:model/User user {:is_superuser true}]
- (mt/with-premium-features #{:hosting}
- (is (=? "Only Metabase Store users can purchase add-ons."
- (mt/user-http-request user :post 403 (str "ee/cloud-add-ons/" product-type) {}))))))
(testing "succeeds when all conditions are met"
- (mt/with-temp [:model/User user {:is_superuser true}]
- (mt/with-premium-features #{:hosting}
- (with-redefs [premium-features/token-status (constantly {:store-users [{:email (:email user)}]})
- hm.client/call (constantly nil)]
- (is (=? {}
- (mt/user-http-request user :post 200 (str "ee/cloud-add-ons/" product-type) {}))))))))))
+ (mt/with-premium-features #{:hosting}
+ (with-redefs [hm.client/call (constantly nil)]
+ (is (=? {}
+ (mt/user-http-request :crowberto :post 200 (str "ee/cloud-add-ons/" product-type) {})))))))))
(deftest ^:sequential delete-product-type-test
(testing "DELETE /api/ee/cloud-add-ons/metabase-ai-managed"
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx
index aadfb32dc74..b5fc315e31f 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.tsx
@@ -12,7 +12,7 @@ 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 { getUserIsAdmin } from "metabase/selectors/user";
import {
Anchor,
Box,
@@ -65,7 +65,7 @@ export function MetabaseAIProviderSetup({
!!hasPremiumFeature(METABOT_V3_FEATURE);
const isConfigured = !!useSetting("llm-metabot-configured?");
- const { isStoreUser, anyStoreUserEmailAddress } = useSelector(getStoreUsers);
+ const isAdmin = useSelector(getUserIsAdmin);
const [updateMetabotSettings, updateMetabotSettingsResult] =
useUpdateMetabotSettingsMutation();
@@ -107,7 +107,7 @@ export function MetabaseAIProviderSetup({
hasMetabaseManagedAiProviderFeature,
hasDeprecatedMetabaseAiProvider,
isConfigured,
- isStoreUser,
+ isAdmin,
})
.with({ isConfigured: true }, () => null)
.with({ hasMetabaseManagedAiProviderFeature: true }, () => handleConnect)
@@ -116,7 +116,7 @@ export function MetabaseAIProviderSetup({
{ hasMetabaseManagedAiProviderFeature: false, hasAcceptedTerms: false },
() => null,
)
- .with({ isStoreUser: false }, () => null)
+ .with({ isAdmin: false }, () => null)
.otherwise(() => handleMetabasePurchase);
const onDisconnect = useCallback(async () => {
@@ -228,7 +228,7 @@ export function MetabaseAIProviderSetup({
hasDeprecatedMetabaseAiProvider,
hasMetabaseManagedAiProviderFeature,
offerMetabaseManagedAi,
- isStoreUser,
+ isAdmin,
})
.with(
{
@@ -244,10 +244,9 @@ export function MetabaseAIProviderSetup({
)
.with({ hasDeprecatedMetabaseAiProvider: true }, () => null)
.with({ hasMetabaseManagedAiProviderFeature: true }, () => null)
- .with({ isStoreUser: false }, () => (
+ .with({ isAdmin: false }, () => (
<Text fw="bold">
- {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- This string only shows for admins. */}
- {t`Please ask a Metabase Store Admin${anyStoreUserEmailAddress && ` (${anyStoreUserEmailAddress})`} of your organization to enable this for you.`}
+ {t`Please ask an Admin user to enable this for you.`}
</Text>
))
.otherwise(() => (
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.ts
deleted file mode 100644
index 5b8d1fbb8a4..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { createElement } from "react";
-
-import { render, screen } from "__support__/ui";
-import type { MetabotUsageResponse } from "metabase-enterprise/api";
-
-import type { MetabaseManagedAiPricing } from "../../useMetabaseManagedAiPricing";
-
-import {
- MetabasePricingText,
- getMetabaseUsageCost,
-} from "./MetabaseAIProviderSetup";
-
-const PRICING: MetabaseManagedAiPricing = {
- price: "$3.00",
- unit: "1M",
- pricePerUnit: 3,
- unitCount: 1_000_000,
- freeUnits: null,
-};
-
-function createUsage(tokens: number, freeTokens: number): MetabotUsageResponse {
- return {
- tokens,
- free_tokens: freeTokens,
- updated_at: null,
- is_locked: false,
- };
-}
-
-describe("getMetabaseUsageCost", () => {
- it.each([
- { tokens: 100, freeTokens: 100 },
- { tokens: 50, freeTokens: 100 },
- ])(
- "returns 0 when tokens ($tokens) are less than or equal to free tokens ($freeTokens)",
- ({ tokens, freeTokens }) => {
- expect(
- getMetabaseUsageCost(createUsage(tokens, freeTokens), PRICING),
- ).toBe(0);
- },
- );
-
- it("calculates cost only for tokens above the free allocation", () => {
- expect(
- getMetabaseUsageCost(createUsage(3_000_000, 1_000_000), PRICING),
- ).toBe(6);
- });
-});
-
-describe("MetabasePricingText", () => {
- it("shows the free-token pricing message when free units are available", () => {
- render(
- createElement(MetabasePricingText, {
- pricing: { ...PRICING, freeUnits: "1M" },
- }),
- );
-
- expect(
- screen.getByText(
- "You get 1M tokens for free. Price per token afterward - $3.00 per 1M tokens",
- ),
- ).toBeInTheDocument();
- });
-
- it("shows the standard pricing message when no free units are available", () => {
- render(
- createElement(MetabasePricingText, {
- pricing: { ...PRICING, freeUnits: null },
- }),
- );
-
- expect(
- screen.getByText("Price per token - $3.00 per 1M tokens"),
- ).toBeInTheDocument();
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.tsx
new file mode 100644
index 00000000000..88ecd14490f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabaseAIProviderSetup.unit.spec.tsx
@@ -0,0 +1,399 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import {
+ setupMetabaseManagedAiEndpoints,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { reinitialize } from "metabase/plugins";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { MetabotUsageResponse } from "metabase-enterprise/api";
+import type { TokenStatusFeature } from "metabase-types/api";
+import {
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockTokenStatus,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import type { MetabaseManagedAiPricing } from "../../useMetabaseManagedAiPricing";
+
+import {
+ MetabaseAIProviderSetup,
+ MetabasePricingText,
+ getMetabaseUsageCost,
+} from "./MetabaseAIProviderSetup";
+
+type MetabotUsageQuota = {
+ tokens?: number | null;
+ free_tokens?: number | null;
+ is_locked?: boolean;
+};
+
+type SetupOptions = {
+ isAdmin?: boolean;
+ isConfigured?: boolean;
+ hasManagedAi?: boolean;
+ hasDeprecatedAi?: boolean;
+ offerMetabaseManagedAi?: boolean;
+ metabasePricePerUnit?: number;
+ pauseAddOnsResponse?: boolean;
+ metabotUsageQuota?: MetabotUsageQuota | null;
+};
+
+function setup({
+ isAdmin = true,
+ isConfigured = false,
+ hasManagedAi = false,
+ hasDeprecatedAi = false,
+ offerMetabaseManagedAi = false,
+ metabasePricePerUnit = 3.0,
+ pauseAddOnsResponse = false,
+ metabotUsageQuota = null,
+}: SetupOptions = {}) {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+
+ const tokenFeatures: TokenStatusFeature[] = [];
+ if (hasManagedAi) {
+ tokenFeatures.push("metabase-ai-managed");
+ }
+ if (hasDeprecatedAi) {
+ tokenFeatures.push("metabot-v3");
+ }
+ if (offerMetabaseManagedAi) {
+ tokenFeatures.push("offer-metabase-ai-managed");
+ }
+
+ const sessionProperties = createMockSettings({
+ "is-hosted?": true,
+ "llm-metabot-configured?": isConfigured,
+ "token-features": createMockTokenFeatures({
+ hosting: true,
+ "offer-metabase-ai-managed": offerMetabaseManagedAi,
+ "metabase-ai-managed": hasManagedAi,
+ "metabot-v3": hasDeprecatedAi,
+ }),
+ "token-status": createMockTokenStatus({
+ features: tokenFeatures,
+ }),
+ });
+
+ setupPropertiesEndpoints(sessionProperties);
+
+ setupMetabaseManagedAiEndpoints({
+ metabasePricePerUnit,
+ metabotUsageQuota: metabotUsageQuota
+ ? {
+ tokens: metabotUsageQuota.tokens ?? null,
+ free_tokens: metabotUsageQuota.free_tokens ?? null,
+ is_locked: metabotUsageQuota.is_locked ?? false,
+ updated_at: null,
+ }
+ : null,
+ });
+
+ if (pauseAddOnsResponse) {
+ fetchMock.removeRoute("path:/api/ee/cloud-add-ons/addons");
+ fetchMock.get(
+ "path:/api/ee/cloud-add-ons/addons",
+ () => new Promise(() => undefined),
+ );
+ }
+
+ fetchMock.post(
+ "path:/api/premium-features/token/refresh",
+ () => sessionProperties["token-status"],
+ );
+
+ const storeInitialState = createMockState({
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ settings: mockSettings(sessionProperties),
+ });
+
+ setupEnterpriseOnlyPlugin("metabot");
+
+ return renderWithProviders(<MetabaseAIProviderSetup />, {
+ storeInitialState,
+ });
+}
+
+const PRICING: MetabaseManagedAiPricing = {
+ price: "$3.00",
+ unit: "1M",
+ pricePerUnit: 3,
+ unitCount: 1_000_000,
+ freeUnits: null,
+};
+
+function createUsage(
+ tokens: number | null,
+ freeTokens: number | null,
+): MetabotUsageResponse {
+ return {
+ tokens,
+ free_tokens: freeTokens,
+ updated_at: null,
+ is_locked: false,
+ };
+}
+
+describe("MetabaseAIProviderSetup", () => {
+ afterEach(() => {
+ reinitialize();
+ });
+
+ describe("disconnected state", () => {
+ it("shows the Metabase AI service introduction with loaded pricing", async () => {
+ setup();
+
+ expect(
+ await screen.findByText("About Metabase AI service"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/The simplest way to get started with AI in Metabase/),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText("Price per token - $3.00 per 1M tokens"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not render pricing text while the add-ons request is in flight", () => {
+ setup({ pauseAddOnsResponse: true });
+
+ expect(screen.queryByText(/Price per token/i)).not.toBeInTheDocument();
+ expect(screen.getByText("About Metabase AI service")).toBeInTheDocument();
+ });
+
+ it("shows the Terms of Service checkbox when no managed AI feature is enabled", async () => {
+ setup();
+
+ const checkbox = await screen.findByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ });
+ expect(checkbox).not.toBeChecked();
+ expect(
+ screen.getByRole("link", { name: "Terms of Service" }),
+ ).toHaveAttribute("href", "https://www.metabase.com/license/hosting");
+ });
+
+ it("toggles the Terms of Service checkbox when clicked", async () => {
+ setup();
+
+ const checkbox = await screen.findByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ });
+ expect(checkbox).not.toBeChecked();
+
+ await userEvent.click(checkbox);
+ expect(checkbox).toBeChecked();
+ });
+
+ it("hides the Terms checkbox and shows the legacy pricing notice when migrating from tiered AI to managed AI", async () => {
+ setup({
+ hasDeprecatedAi: true,
+ offerMetabaseManagedAi: true,
+ });
+
+ expect(
+ await screen.findByText(
+ "You're on legacy tiered AI pricing today. On your next billing cycle, you'll switch to metered AI pricing.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("hides the Terms checkbox when the user already has the managed AI provider feature", async () => {
+ setup({ hasManagedAi: true });
+
+ expect(
+ await screen.findByText("About Metabase AI service"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("hides the Terms checkbox when the user has the deprecated AI provider without a migration offer", async () => {
+ setup({
+ hasDeprecatedAi: true,
+ offerMetabaseManagedAi: false,
+ });
+
+ expect(
+ await screen.findByText("About Metabase AI service"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/legacy tiered AI/i)).not.toBeInTheDocument();
+ });
+
+ it("asks non-admin users to contact an admin instead of showing the Terms checkbox", async () => {
+ setup({ isAdmin: false });
+
+ expect(
+ await screen.findByText(
+ "Please ask an Admin user to enable this for you.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("checkbox", {
+ name: /I agree with the Metabase AI Service/i,
+ }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("connected state with managed AI feature", () => {
+ it("shows the locked state UI when the user has run out of tokens", async () => {
+ setup({
+ isConfigured: true,
+ hasManagedAi: true,
+ metabotUsageQuota: {
+ tokens: 2_000_000,
+ free_tokens: 0,
+ is_locked: true,
+ },
+ });
+
+ expect(
+ await screen.findByText("You've run out of AI service tokens"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Current billing cycle"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the free trial usage row when within the free-token allowance", async () => {
+ setup({
+ isConfigured: true,
+ hasManagedAi: true,
+ metabotUsageQuota: { tokens: 250_000, free_tokens: 1_000_000 },
+ });
+
+ expect(await screen.findByText("Included use")).toBeInTheDocument();
+ expect(screen.getByText("Free trial tokens")).toBeInTheDocument();
+ expect(screen.getByText("250,000 / 1,000,000")).toBeInTheDocument();
+ expect(
+ await screen.findByText("Price per token afterward"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Current billing cycle"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the current billing cycle UI once free tokens are exhausted", async () => {
+ setup({
+ isConfigured: true,
+ hasManagedAi: true,
+ metabasePricePerUnit: 3.0,
+ metabotUsageQuota: { tokens: 3_000_000, free_tokens: 1_000_000 },
+ });
+
+ expect(
+ await screen.findByText("Current billing cycle"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Total tokens")).toBeInTheDocument();
+ expect(screen.getByText("3,000,000")).toBeInTheDocument();
+ expect(screen.getByText("Total cost")).toBeInTheDocument();
+ // (3M - 1M) tokens at $3 per 1M tokens = $6.00
+ expect(await screen.findByText("$6.00")).toBeInTheDocument();
+ expect(screen.queryByText("Included use")).not.toBeInTheDocument();
+ });
+
+ it("refreshes the token status when the connected card mounts", async () => {
+ setup({
+ isConfigured: true,
+ hasManagedAi: true,
+ metabotUsageQuota: { tokens: 0, free_tokens: 0 },
+ });
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called(
+ "path:/api/premium-features/token/refresh",
+ ),
+ ).toBe(true);
+ });
+ });
+ });
+
+ describe("connected state with deprecated AI provider", () => {
+ it("shows the legacy tiered pricing notice when the user can still migrate", async () => {
+ setup({
+ isConfigured: true,
+ hasDeprecatedAi: true,
+ offerMetabaseManagedAi: true,
+ metabotUsageQuota: { tokens: 1_000_000, free_tokens: 0 },
+ });
+
+ expect(
+ await screen.findByText(
+ /You're on legacy tiered AI pricing today\. On your next billing cycle/i,
+ ),
+ ).toBeInTheDocument();
+ // The managed-feature usage rows should not appear without the
+ // metabase-ai-managed feature.
+ expect(screen.queryByText("Total tokens")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("You've run out of AI service tokens"),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
+
+describe("getMetabaseUsageCost", () => {
+ it.each([
+ { tokens: 100, freeTokens: 100 },
+ { tokens: 50, freeTokens: 100 },
+ ])(
+ "returns 0 when tokens ($tokens) are less than or equal to free tokens ($freeTokens)",
+ ({ tokens, freeTokens }) => {
+ expect(
+ getMetabaseUsageCost(createUsage(tokens, freeTokens), PRICING),
+ ).toBe(0);
+ },
+ );
+
+ it("calculates cost only for tokens above the free allocation", () => {
+ expect(
+ getMetabaseUsageCost(createUsage(3_000_000, 1_000_000), PRICING),
+ ).toBe(6);
+ });
+});
+
+describe("MetabasePricingText", () => {
+ it("shows the free-token pricing message when free units are available", () => {
+ renderWithProviders(
+ <MetabasePricingText pricing={{ ...PRICING, freeUnits: "1M" }} />,
+ );
+
+ expect(
+ screen.getByText(
+ "You get 1M tokens for free. Price per token afterward - $3.00 per 1M tokens",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("shows the standard pricing message when no free units are available", () => {
+ renderWithProviders(
+ <MetabasePricingText pricing={{ ...PRICING, freeUnits: null }} />,
+ );
+
+ expect(
+ screen.getByText("Price per token - $3.00 per 1M tokens"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
index b6151c724e4..ae6c4873ecb 100644
--- a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
@@ -24,6 +24,7 @@ import {
createMockSettings,
createMockTokenFeatures,
createMockTokenStatus,
+ createMockUser,
} from "metabase-types/api/mocks";
import { MetabotSetup, MetabotSetupInner } from "./MetabotSetup";
@@ -116,7 +117,7 @@ type SetupOptions = {
providerSettingEnvName?: string;
apiKeySettingIsEnv?: boolean;
apiKeySettingEnvName?: string;
- isStoreUser?: boolean;
+ isAdmin?: boolean;
anyStoreUserEmailAddress?: string;
metabasePricePerUnit?: number;
metabaseBillingPeriodMonths?: number;
@@ -147,8 +148,7 @@ async function setup({
providerSettingEnvName = "LLM_METABOT_PROVIDER",
apiKeySettingIsEnv = false,
apiKeySettingEnvName = "LLM_ANTHROPIC_API_KEY",
- isStoreUser = isHosted,
- anyStoreUserEmailAddress = "[email protected]",
+ isAdmin = false,
metabasePricePerUnit = 3.75,
metabaseBillingPeriodMonths = 1,
metabotUsageQuotas = null,
@@ -201,11 +201,6 @@ async function setup({
"token-features": createTokenFeatureFlags(tokenStatusFeatures),
"token-status": createMockTokenStatus({
features: tokenStatusFeatures,
- "store-users": isStoreUser
- ? [{ email: "[email protected]" }]
- : anyStoreUserEmailAddress
- ? [{ email: anyStoreUserEmailAddress }]
- : [],
}),
});
@@ -382,7 +377,9 @@ async function setup({
return 204;
});
- const storeInitialState = { settings };
+ const user = createMockUser({ is_superuser: isAdmin });
+
+ const storeInitialState = { settings, currentUser: user };
const view = renderAsModal
? renderWithProviders(<MetabotSetupInner isModal onClose={onClose} />, {
storeInitialState,
@@ -825,6 +822,7 @@ describe("MetabotSetup", () => {
it("shows pricing details in a tooltip for the Metabase provider", async () => {
await setup({
isHosted: true,
+ isAdmin: true,
savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",
isConfigured: false,
});
@@ -846,19 +844,19 @@ describe("MetabotSetup", () => {
).toHaveAttribute("href", "https://www.metabase.com/license/hosting");
});
- it("shows a contact-admin notice for non-store users on the Metabase provider", async () => {
+ it("shows a contact-admin notice for non-admin users on the Metabase provider", async () => {
await setup({
isHosted: true,
savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",
isConfigured: false,
- isStoreUser: false,
+ isAdmin: false,
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.",
+ "Please ask an Admin user to enable this for you.",
),
).toBeInTheDocument();
expect(
@@ -873,7 +871,7 @@ describe("MetabotSetup", () => {
isHosted: true,
savedProviderValue: null,
isConfigured: false,
- isStoreUser: false,
+ isAdmin: false,
tokenStatusFeatures: ["metabase-ai-managed"],
updateResponse: {
value: "metabase/anthropic/claude-sonnet-4-6",
@@ -926,7 +924,7 @@ describe("MetabotSetup", () => {
isHosted: true,
savedProviderValue: null,
isConfigured: false,
- isStoreUser: false,
+ isAdmin: false,
tokenStatusFeatures: ["metabase-ai-managed"],
updateResponse: {
value: "metabase/anthropic/claude-sonnet-4-6",
@@ -968,7 +966,7 @@ describe("MetabotSetup", () => {
isHosted: true,
savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",
isConfigured: false,
- isStoreUser: true,
+ isAdmin: true,
tokenStatusFeatures: [],
refreshedTokenStatusFeatures: ["metabase-ai-managed"],
deferPurchaseCloudAddOnResponse: true,
@@ -1143,7 +1141,7 @@ describe("MetabotSetup", () => {
isHosted: true,
savedProviderValue: "metabase/anthropic/claude-sonnet-4-6",
isConfigured: false,
- isStoreUser: true,
+ isAdmin: true,
tokenStatusFeatures: [],
refreshedTokenStatusFeatures: ["metabase-ai-managed"],
deferPurchaseCloudAddOnResponse: true,