Skip to content

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

Metabot AI Usage Limits page (#71699)

Andersonc989e0195253
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 7fb63e8c868..246d7059219 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1004,8 +1004,7 @@
internal-stats
{:team "UX West"
- :api #{metabase.internal-stats.core
- metabase.internal-stats.metabot}
+ :api #{metabase.internal-stats.core}
:uses #{app-db
models
util}
@@ -1180,26 +1179,25 @@
{:team "Metabot"
:api #{metabase.metabot.api
metabase.metabot.api.entity-analysis
- metabase.metabot.core
- metabase.metabot.init
- metabase.metabot.self
- metabase.metabot.settings}
+ metabase.metabot.core
+ metabase.metabot.init
+ metabase.metabot.self
+ metabase.metabot.settings}
:friends #{agent-api
enterprise/metabot
slackbot}
- :uses #{activity-feed
- analytics
- api
- api-scope
- app-db
- audit-app
- channel
- collections
- config
- documents
- driver
- internal-stats
- legacy-mbql
+ :uses #{activity-feed
+ analytics
+ api
+ api-scope
+ app-db
+ audit-app
+ channel
+ collections
+ config
+ documents
+ driver
+ legacy-mbql
lib
lib-be
llm
@@ -1225,7 +1223,7 @@
transforms-base
util
warehouses}
- :model-exports #{:model/MetabotMessage}
+ :model-exports #{:model/AiUsageLog :model/MetabotMessage}
:model-imports #{:model/Card
:model/Collection
:model/Dashboard
@@ -2159,7 +2157,7 @@
premium-features
search
util}
- :model-imports #{:model/Card :model/Dashboard}}
+ :model-imports #{:model/AiUsageLog :model/Card :model/Dashboard}}
tiles
{:team "UX West"
@@ -2965,7 +2963,8 @@
enterprise/metabot
{:team "Metabot"
- :api #{metabase-enterprise.metabot.api.routes}
+ :api #{metabase-enterprise.metabot.api.routes
+ metabase-enterprise.metabot.init}
:friends #{enterprise/agent-api
slackbot
mcp
@@ -2975,10 +2974,13 @@
metabot
models
premium-features
+ settings
+ task
util
enterprise/dependencies
enterprise/transforms-python}
- :model-imports #{:model/Card
+ :model-imports #{:model/AiUsageLog
+ :model/Card
:model/PermissionsGroup
:model/PermissionsGroupMembership
:model/Transform}}
diff --git a/e2e/support/config.js b/e2e/support/config.js
index 98d99f9f383..550a6a08207 100644
--- a/e2e/support/config.js
+++ b/e2e/support/config.js
@@ -16,6 +16,10 @@ import {
} from "./commands/downloads/downloadUtils";
import * as dbTasks from "./db_tasks";
import { signJwt } from "./helpers/e2e-jwt-tasks";
+import {
+ startMockLlmServer,
+ stopMockLlmServer,
+} from "./helpers/e2e-mock-llm-tasks";
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor"); // This function is called when a project is opened or re-opened (e.g. due to the project's config changing)
const {
@@ -136,6 +140,8 @@ const defaultConfig = {
copyDirectory,
removeDirectory,
signJwt,
+ startMockLlmServer,
+ stopMockLlmServer,
});
/********************************************************************
diff --git a/e2e/support/helpers/e2e-mock-llm-tasks.ts b/e2e/support/helpers/e2e-mock-llm-tasks.ts
new file mode 100644
index 00000000000..fb49307b0ce
--- /dev/null
+++ b/e2e/support/helpers/e2e-mock-llm-tasks.ts
@@ -0,0 +1,83 @@
+import http from "node:http";
+
+let server: http.Server | null = null;
+
+/**
+ * Build a raw Anthropic SSE response that streams the given text as a single
+ * content_block_delta and then closes the message cleanly.
+ *
+ * The format follows the Anthropic /v1/messages streaming specification:
+ * https://docs.anthropic.com/en/api/messages-streaming
+ */
+function buildAnthropicSSE(text: string): string {
+ const lines = [
+ "event: message_start",
+ `data: ${JSON.stringify({ type: "message_start", message: { id: "msg_mock", type: "message", role: "assistant", content: [], model: "claude-haiku-4-5", stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } })}`,
+ "",
+ "event: content_block_start",
+ `data: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}`,
+ "",
+ "event: content_block_delta",
+ `data: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text } })}`,
+ "",
+ "event: content_block_stop",
+ `data: ${JSON.stringify({ type: "content_block_stop", index: 0 })}`,
+ "",
+ "event: message_delta",
+ `data: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 8 } })}`,
+ "",
+ "event: message_stop",
+ `data: ${JSON.stringify({ type: "message_stop" })}`,
+ "",
+ ];
+ return lines.join("\n");
+}
+
+/**
+ * Start a mock server that impersonates the Anthropic Messages API.
+ *
+ * Every POST to /v1/messages responds with a valid SSE stream containing
+ * the given `responseText`. The server listens on `port`.
+ *
+ * Call `stopMockLlmServer` to tear it down.
+ */
+export function startMockLlmServer({
+ port,
+ responseText,
+}: {
+ port: number;
+ responseText: string;
+}): Promise<null> {
+ return new Promise((resolve, reject) => {
+ if (server) {
+ server.close();
+ server = null;
+ }
+
+ server = http.createServer((_req, res) => {
+ res.writeHead(200, {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ });
+ res.end(buildAnthropicSSE(responseText));
+ });
+
+ server.on("error", reject);
+ server.listen(port, () => resolve(null));
+ });
+}
+
+/**
+ * Stop the mock LLM server started by `startMockLlmServer`.
+ */
+export function stopMockLlmServer(): Promise<null> {
+ return new Promise((resolve) => {
+ if (server) {
+ server.close(() => resolve(null));
+ server = null;
+ } else {
+ resolve(null);
+ }
+ });
+}
diff --git a/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
index 57112e2b5a1..22f6234d453 100644
--- a/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
+++ b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
@@ -1,17 +1,21 @@
-import { ALL_USERS_GROUP_ID } from "e2e/support/cypress_sample_instance_data";
+import {
+ ALL_USERS_GROUP_ID,
+ NORMAL_USER_ID,
+} from "e2e/support/cypress_sample_instance_data";
const { H } = cy;
-// A tiny valid PNG (1×1 transparent pixel) as a data URI, used for icon upload tests
-const TINY_PNG_DATA_URI =
- "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
-
describe("AI Controls > Metabot access and customization", () => {
beforeEach(() => {
H.restore();
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
- H.updateSetting("llm-anthropic-api-key", "sk-ant-test-key");
+ H.updateSetting("metabot-enabled?", true);
+ llmMockServerSetup();
+ });
+
+ afterEach(() => {
+ llmMockServerTeardown();
});
describe("Feature Access page", () => {
@@ -296,3 +300,442 @@ describe("AI Controls > Metabot access and customization", () => {
});
});
});
+
+describe("AI controls > AI usage limits", () => {
+ const AI_USAGE_LIMITS_URL = "/admin/metabot/1/usage-controls/ai-usage-limits";
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ llmMockServerSetup();
+ });
+
+ afterEach(() => {
+ llmMockServerTeardown();
+ });
+
+ describe("AI Limits settings can be saved properly", () => {
+ beforeEach(() => {
+ cy.intercept("GET", "/api/ee/ai-controls/usage/instance").as(
+ "getInstanceLimit",
+ );
+ cy.intercept("PUT", "/api/ee/ai-controls/usage/instance").as(
+ "updateInstanceLimit",
+ );
+ cy.intercept("GET", "/api/ee/ai-controls/usage/group").as(
+ "getGroupLimits",
+ );
+ cy.intercept("PUT", "/api/setting/metabot-limit-unit").as(
+ "saveLimitUnit",
+ );
+ cy.intercept("PUT", "/api/setting/metabot-limit-reset-rate").as(
+ "saveLimitPeriod",
+ );
+ cy.intercept("PUT", "/api/setting/metabot-quota-reached-message").as(
+ "saveQuotaMessage",
+ );
+ });
+
+ it("should save limit type, reset period, instance limit, and quota-reached message when changed", () => {
+ cy.visit(AI_USAGE_LIMITS_URL);
+ cy.wait("@getInstanceLimit");
+
+ // Change limit type to messages
+ cy.findByRole("radio", { name: "By message count" }).click({
+ force: true,
+ });
+ cy.wait("@saveLimitUnit").then(({ request }) => {
+ expect(request.body).to.deep.equal({ value: "messages" });
+ });
+
+ // Change reset period to weekly
+ cy.findByRole("radio", { name: "Weekly" }).click({ force: true });
+ cy.wait("@saveLimitPeriod").then(({ request }) => {
+ expect(request.body).to.deep.equal({ value: "weekly" });
+ });
+
+ // Type an instance limit value
+ cy.findByLabelText(/Total weekly instance limit/).type("500");
+ cy.wait("@updateInstanceLimit").then(({ request }) => {
+ expect(request.body).to.deep.equal({ max_usage: 500 });
+ });
+
+ // Type a quota-reached message
+ cy.findByLabelText("Quota-reached message")
+ .clear()
+ .type("You have hit the AI usage limit.");
+ cy.wait("@saveQuotaMessage").then(({ request }) => {
+ expect(request.body).to.deep.equal({
+ value: "You have hit the AI usage limit.",
+ });
+ });
+ });
+
+ it("should save instance limit as null when the field is cleared", () => {
+ // Pre-set a limit so there's something to clear
+ cy.request("PUT", "/api/ee/ai-controls/usage/instance", {
+ max_usage: 100,
+ });
+
+ cy.visit(AI_USAGE_LIMITS_URL);
+ cy.wait("@getInstanceLimit");
+
+ cy.findByDisplayValue("100").clear();
+ cy.wait("@updateInstanceLimit").then(({ request }) => {
+ expect(request.body).to.deep.equal({ max_usage: null });
+ });
+ });
+ });
+
+ describe("When instance limit is set to 0", () => {
+ beforeEach(() => {
+ // Enable Metabot with a configured LLM key
+ H.updateSetting("metabot-enabled?", true);
+
+ // Set messages as the limit type (easier to trigger with 0)
+ // (These settings are added in PR #71699, so we call the API directly)
+ cy.request("PUT", "/api/setting/metabot-limit-unit", {
+ value: "messages",
+ });
+
+ // Set a custom quota-reached message
+ cy.request("PUT", "/api/setting/metabot-quota-reached-message", {
+ value: DEFAULT_QUOTA_MESSAGE,
+ });
+
+ // Set instance limit to 0 — any usage will immediately exceed it
+ cy.request("PUT", "/api/ee/ai-controls/usage/instance", {
+ max_usage: 0,
+ });
+
+ cy.intercept("POST", "/api/metabot/agent-streaming").as("agentReq");
+ cy.intercept("GET", "/api/automagic-dashboards/database/*/candidates").as(
+ "xrayCandidates",
+ );
+
+ llmMockServerSetup();
+ });
+
+ afterEach(() => {
+ llmMockServerTeardown();
+ });
+
+ it("should show the quota-reached message when the user sends a message to Metabot", () => {
+ cy.visit("/");
+ cy.wait("@xrayCandidates");
+
+ H.openMetabotViaSearchButton();
+ H.sendMetabotMessage("hello");
+
+ // The backend returns the quota-reached message when limit is exceeded
+ H.lastChatMessage().should("have.text", DEFAULT_QUOTA_MESSAGE);
+ });
+ });
+
+ describe("Group limits handling", () => {
+ let groupAId: number;
+ let groupBId: number;
+
+ beforeEach(() => {
+ cy.request("PUT", "/api/setting/metabot-limit-unit", {
+ value: "messages",
+ });
+ cy.request("PUT", "/api/setting/metabot-quota-reached-message", {
+ value: DEFAULT_QUOTA_MESSAGE,
+ });
+
+ // Set instance limit high so it doesn't interfere
+ cy.request("PUT", "/api/ee/ai-controls/usage/instance", {
+ max_usage: 1000,
+ });
+
+ // limit-for-user returns NULL (unlimited) when any of the user's groups
+ // has no metabot_group_limit row, and returns the MAX across all groups.
+ // Set a low limit (1) on every pre-existing group the normal user
+ // belongs to so the effective limit equals Group B's 100.
+ // Note: the membership API is keyed by user_id, with each entry
+ // containing a group_id property.
+ cy.request("GET", "/api/permissions/membership").then(({ body }) => {
+ const memberships = body[String(NORMAL_USER_ID)] as
+ | Array<{ group_id: number }>
+ | undefined;
+ if (memberships) {
+ for (const m of memberships) {
+ cy.request("PUT", `/api/ee/ai-controls/usage/group/${m.group_id}`, {
+ max_usage: 1,
+ });
+ }
+ }
+ });
+
+ // Create group A (low limit: 5) and group B (high limit: 100);
+ // add the normal user to both
+ cy.request("POST", "/api/permissions/group", {
+ name: "AI Limit Group A (low)",
+ }).then(({ body }) => {
+ groupAId = body.id;
+
+ cy.request("PUT", `/api/ee/ai-controls/usage/group/${groupAId}`, {
+ max_usage: 5,
+ });
+
+ cy.request("POST", "/api/permissions/membership", {
+ group_id: groupAId,
+ user_id: NORMAL_USER_ID,
+ });
+ });
+
+ cy.request("POST", "/api/permissions/group", {
+ name: "AI Limit Group B (high)",
+ }).then(({ body }) => {
+ groupBId = body.id;
+
+ cy.request("PUT", `/api/ee/ai-controls/usage/group/${groupBId}`, {
+ max_usage: 100,
+ });
+
+ cy.request("POST", "/api/permissions/membership", {
+ group_id: groupBId,
+ user_id: NORMAL_USER_ID,
+ });
+ });
+
+ cy.intercept("GET", "/api/automagic-dashboards/database/*/candidates").as(
+ "xrayCandidates",
+ );
+ });
+
+ afterEach(() => {
+ // Sign back in as admin for cleanup (tests may end signed in as normal user)
+ cy.signInAsAdmin();
+
+ // Clean up seeded usage rows and groups
+ cy.request("DELETE", "/api/testing/metabot/seed-ai-usage", {
+ user_id: NORMAL_USER_ID,
+ });
+ cy.request("PUT", "/api/ee/ai-controls/usage/instance", {
+ max_usage: null,
+ });
+ cy.then(() => {
+ if (groupAId) {
+ cy.request("DELETE", `/api/permissions/group/${groupAId}`);
+ }
+ if (groupBId) {
+ cy.request("DELETE", `/api/permissions/group/${groupBId}`);
+ }
+ });
+ });
+
+ it("should display both groups with their configured limits and note that users get the highest limit", () => {
+ cy.visit(AI_USAGE_LIMITS_URL);
+
+ // Both groups should appear in the group limits table with correct values
+ cy.findByLabelText(
+ "Max messages per user for AI Limit Group A (low)",
+ ).should("have.value", "5");
+
+ cy.findByLabelText(
+ "Max messages per user for AI Limit Group B (high)",
+ ).should("have.value", "100");
+
+ // The section description should explain that users get the highest limit
+ cy.findByTestId("group-limits-tab").within(() => {
+ cy.findByText(
+ /If a user belongs to more than one group, they'll be given the highest limit among all the groups/i,
+ )
+ .scrollIntoView()
+ .should("be.visible");
+ });
+ });
+
+ it("should respect the effective user limit (max across their groups)", () => {
+ // Normal user is in group A (limit 5) and group B (limit 100).
+ // Effective limit = max(1, 1, 1, 5, 100) = 100.
+ // (pre-existing groups are set to 1 in beforeEach)
+
+ // Seed 10 usage rows — below the effective limit of 100
+ cy.request("POST", "/api/testing/metabot/seed-ai-usage", {
+ user_id: NORMAL_USER_ID,
+ count: 10,
+ });
+
+ cy.signInAsNormalUser();
+ cy.visit("/");
+ cy.wait("@xrayCandidates");
+
+ H.openMetabotViaSearchButton();
+ H.sendMetabotMessage("hello");
+
+ // With usage (10) < effective limit (100) the backend passes the quota
+ // check, calls the mock LLM, and streams its response to the frontend.
+ H.lastChatMessage().should("contain.text", MOCK_LLM_RESPONSE);
+
+ // Seed additional rows so total usage (101) exceeds effective group limit (100)
+ cy.signInAsAdmin();
+ cy.request("POST", "/api/testing/metabot/seed-ai-usage", {
+ user_id: NORMAL_USER_ID,
+ count: 91,
+ });
+
+ cy.signInAsNormalUser();
+ cy.visit("/");
+ cy.wait("@xrayCandidates");
+
+ H.openMetabotViaSearchButton();
+ H.sendMetabotMessage("hello");
+
+ // With usage (101) > effective group limit (100) the backend short-circuits
+ // before calling the LLM and returns the quota-reached message.
+ H.lastChatMessage().should("have.text", DEFAULT_QUOTA_MESSAGE);
+ });
+ });
+});
+
+describe("AI Controls > Tenant usage limits", () => {
+ let tenantId: number;
+ let tenantUserId: number;
+ const TENANT_USER_EMAIL = "[email protected]";
+ const TENANT_USER_PASSWORD = "12341234";
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.updateSetting("metabot-enabled?", true);
+
+ cy.request("PUT", "/api/setting/metabot-quota-reached-message", {
+ value: DEFAULT_QUOTA_MESSAGE,
+ });
+
+ // Enable multi-tenancy
+ H.updateSetting("use-tenants", true);
+
+ // Create a tenant
+ cy.request("POST", "/api/ee/tenant", {
+ name: "Test Corp",
+ slug: "test-corp",
+ }).then(({ body }) => {
+ tenantId = body.id;
+
+ // Create a user belonging to that tenant
+ cy.request("POST", "/api/user", {
+ first_name: "Tenant",
+ last_name: "User",
+ email: TENANT_USER_EMAIL,
+ password: TENANT_USER_PASSWORD,
+ tenant_id: tenantId,
+ }).then(({ body: user }) => {
+ tenantUserId = user.id;
+ });
+ });
+
+ cy.intercept("POST", "/api/metabot/agent-streaming").as("agentReq");
+ cy.intercept("GET", "/api/automagic-dashboards/database/*/candidates").as(
+ "xrayCandidates",
+ );
+ cy.intercept("PUT", "/api/ee/ai-controls/usage/tenant/*").as(
+ "updateTenantLimit",
+ );
+ llmMockServerSetup();
+ });
+
+ afterEach(() => {
+ llmMockServerTeardown();
+ });
+
+ it("should allow updating tenant limits when tenants are enabled", () => {
+ cy.visit("/admin/metabot/1/usage-controls/ai-usage-limits");
+
+ cy.findByRole("tab", { name: "Specific tenants" }).click();
+
+ cy.findByTestId("tenant-limits-tab").should("be.visible");
+ cy.findByTestId("tenant-limits-tab")
+ .findByText("Test Corp")
+ .should("be.visible");
+ cy.findByLabelText(
+ "Max total monthly tokens for Test Corp (millions)",
+ ).type("10");
+ cy.wait("@updateTenantLimit").its("response.statusCode").should("eq", 200);
+ });
+
+ it("should show the quota-reached message when the tenant limit is set to 0 and the user sends a message", () => {
+ // Set tenant limit to 0 — any usage will immediately exceed it
+ cy.request("PUT", `/api/ee/ai-controls/usage/tenant/${tenantId}`, {
+ max_usage: 0,
+ });
+ // Clear the backend limit-check cache so the new limit is seen immediately,
+ cy.request("DELETE", "/api/testing/metabot/seed-ai-usage", {
+ user_id: tenantUserId,
+ });
+
+ // Sign in as the tenant user
+ cy.request("POST", "/api/session", {
+ username: TENANT_USER_EMAIL,
+ password: TENANT_USER_PASSWORD,
+ });
+
+ cy.visit("/");
+ cy.wait("@xrayCandidates");
+
+ H.openMetabotViaSearchButton();
+ H.sendMetabotMessage("hello");
+
+ // The backend returns the quota-reached message when the tenant limit is exceeded
+ H.lastChatMessage().should("contain.text", DEFAULT_QUOTA_MESSAGE);
+ });
+
+ it("should not show the quota-reached message when no tenant limit is set", () => {
+ // No tenant limit is set — the chat input should be available without a quota message
+ cy.request("PUT", `/api/ee/ai-controls/usage/tenant/${tenantId}`, {
+ max_usage: null,
+ });
+ // Clear the backend limit-check cache so the new null limit is seen immediately,
+ cy.request("DELETE", "/api/testing/metabot/seed-ai-usage", {
+ user_id: tenantUserId,
+ });
+
+ // Sign in as the tenant user
+ cy.request("POST", "/api/session", {
+ username: TENANT_USER_EMAIL,
+ password: TENANT_USER_PASSWORD,
+ });
+
+ cy.visit("/");
+ cy.wait("@xrayCandidates");
+
+ H.openMetabotViaSearchButton();
+ H.sendMetabotMessage("hello");
+
+ H.lastChatMessage().should("contain.text", MOCK_LLM_RESPONSE);
+ H.lastChatMessage().should("not.contain.text", DEFAULT_QUOTA_MESSAGE);
+ });
+});
+
+// A tiny valid PNG (1×1 transparent pixel) as a data URI, used for icon upload tests
+const TINY_PNG_DATA_URI =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
+const MOCK_LLM_PORT = 6123;
+const MOCK_LLM_RESPONSE = "Hello from mock LLM!";
+const DEFAULT_QUOTA_MESSAGE =
+ "You have reached your AI usage limit for this period. Please try again later, Batman.";
+
+function llmMockServerSetup() {
+ // Start a mock server that impersonates the Anthropic Messages API
+ // so requests flow through the full backend (including quota checks)
+ // without needing a real LLM key.
+ cy.task("startMockLlmServer", {
+ port: MOCK_LLM_PORT,
+ responseText: MOCK_LLM_RESPONSE,
+ });
+
+ H.updateSetting("llm-anthropic-api-key", "sk-ant-test-key");
+ H.updateSetting(
+ "llm-anthropic-api-base-url",
+ `http://localhost:${MOCK_LLM_PORT}`,
+ );
+}
+
+function llmMockServerTeardown() {
+ cy.task("stopMockLlmServer");
+}
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index 2ce755356df..a265b9855d1 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -13,6 +13,7 @@
[metabase-enterprise.database-replication.init]
[metabase-enterprise.dependencies.init]
[metabase-enterprise.gsheets.init]
+ [metabase-enterprise.metabot.init]
[metabase-enterprise.remote-sync.init]
[metabase-enterprise.scim.init]
[metabase-enterprise.semantic-search.init]
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj b/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj
index 50c232f6f82..9609f001bc9 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj
@@ -2,9 +2,11 @@
"Routes for enterprise metabot API endpoints."
(:require
[metabase-enterprise.metabot.api.permissions]
+ [metabase-enterprise.metabot.api.usage]
[metabase.api.util.handlers :as handlers]))
(def ^{:arglists '([request respond raise])} routes
"Ring routes for enterprise metabot API endpoints."
(handlers/route-map-handler
- {"/permissions" metabase-enterprise.metabot.api.permissions/routes}))
+ {"/permissions" metabase-enterprise.metabot.api.permissions/routes
+ "/usage" metabase-enterprise.metabot.api.usage/routes}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/api/usage.clj b/enterprise/backend/src/metabase_enterprise/metabot/api/usage.clj
new file mode 100644
index 00000000000..2eb8abc3c39
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/api/usage.clj
@@ -0,0 +1,83 @@
+(ns metabase-enterprise.metabot.api.usage
+ "`/api/ee/ai-controls/usage` routes"
+ (:require
+ [metabase-enterprise.metabot.models.metabot-group-limit :as group-limit]
+ [metabase-enterprise.metabot.models.metabot-instance-limit :as instance-limit]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]))
+
+(defn- without-id [row]
+ (some-> row (dissoc :id)))
+
+(api.macros/defendpoint :get "/instance"
+ :- [:map [:max_usage [:maybe nat-int?]]]
+ "Get the instance-wide metabot usage limit. Returns `max_usage: null` if no limit is set (unlimited)."
+ []
+ (api/check-superuser)
+ (or (some-> (instance-limit/instance-limit nil) (dissoc :id :tenant_id))
+ {:max_usage nil}))
+
+(api.macros/defendpoint :put "/instance"
+ :- [:map [:max_usage [:maybe nat-int?]]]
+ "Set or update the instance-wide metabot usage limit. Pass `max_usage: null` to remove the limit (unlimited)."
+ [_route-params
+ _query-params
+ body :- [:map [:max_usage [:maybe nat-int?]]]]
+ (api/check-superuser)
+ (or (some-> (instance-limit/set-instance-limit! nil (:max_usage body)) (dissoc :id :tenant_id))
+ {:max_usage nil}))
+
+(api.macros/defendpoint :get "/tenant"
+ :- [:sequential [:map [:tenant_id pos-int?] [:max_usage nat-int?]]]
+ "Get all tenant-level metabot usage limits."
+ []
+ (api/check-superuser)
+ (mapv without-id (instance-limit/all-tenant-limits)))
+
+(api.macros/defendpoint :get "/tenant/:tenant-id"
+ :- [:map [:tenant_id pos-int?] [:max_usage [:maybe nat-int?]]]
+ "Get the metabot usage limit for a specific tenant. Returns `max_usage: null` if no limit is set."
+ [{:keys [tenant-id]} :- [:map [:tenant-id pos-int?]]]
+ (api/check-superuser)
+ (or (without-id (instance-limit/instance-limit tenant-id))
+ {:tenant_id tenant-id :max_usage nil}))
+
+(api.macros/defendpoint :put "/tenant/:tenant-id"
+ :- [:map [:tenant_id pos-int?] [:max_usage [:maybe nat-int?]]]
+ "Set or update the metabot usage limit for a specific tenant. Pass `max_usage: null` to remove the limit."
+ [{:keys [tenant-id]} :- [:map [:tenant-id pos-int?]]
+ _query-params
+ body :- [:map [:max_usage [:maybe nat-int?]]]]
+ (api/check-superuser)
+ (or (without-id (instance-limit/set-instance-limit! tenant-id (:max_usage body)))
+ {:tenant_id tenant-id :max_usage nil}))
+
+(api.macros/defendpoint :get "/group"
+ :- [:sequential [:map [:group_id pos-int?] [:max_usage nat-int?]]]
+ "Get all group-level metabot usage limits."
+ []
+ (api/check-superuser)
+ (mapv without-id (group-limit/all-group-limits)))
+
+(api.macros/defendpoint :get "/group/:group-id"
+ :- [:map [:group_id pos-int?] [:max_usage [:maybe nat-int?]]]
+ "Get the metabot usage limit for a specific group. Returns `max_usage: null` if no limit is set."
+ [{:keys [group-id]} :- [:map [:group-id pos-int?]]]
+ (api/check-superuser)
+ (or (without-id (group-limit/group-limit group-id))
+ {:group_id group-id :max_usage nil}))
+
+(api.macros/defendpoint :put "/group/:group-id"
+ :- [:map [:group_id pos-int?] [:max_usage [:maybe nat-int?]]]
+ "Set or update the metabot usage limit for a specific group. Pass `max_usage: null` to remove the limit."
+ [{:keys [group-id]} :- [:map [:group-id pos-int?]]
+ _query-params
+ body :- [:map [:max_usage [:maybe nat-int?]]]]
+ (api/check-superuser)
+ (or (without-id (group-limit/set-group-limit! group-id (:max_usage body)))
+ {:group_id group-id :max_usage nil}))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/ai-controls/usage` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/init.clj b/enterprise/backend/src/metabase_enterprise/metabot/init.clj
new file mode 100644
index 00000000000..ad029ad880b
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/init.clj
@@ -0,0 +1,5 @@
+(ns metabase-enterprise.metabot.init
+ (:require
+ [metabase-enterprise.metabot.permissions]
+ [metabase-enterprise.metabot.settings]
+ [metabase-enterprise.metabot.task.ai-usage-trimmer]))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj
new file mode 100644
index 00000000000..d4cabf96ee1
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj
@@ -0,0 +1,45 @@
+(ns metabase-enterprise.metabot.models.metabot-group-limit
+ (:require
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/MetabotGroupLimit [_model] :metabot_group_limit)
+
+(doto :model/MetabotGroupLimit
+ (derive :metabase/model)
+ (derive ::mi/write-policy.superuser))
+
+(defn all-group-limits
+ "Returns all group-level limits, ordered by group_id."
+ []
+ (t2/select :model/MetabotGroupLimit {:order-by [[:group_id :asc]]}))
+
+(defn group-limit
+ "Returns the limit for a specific group, or nil if none is set."
+ [group-id]
+ (t2/select-one :model/MetabotGroupLimit :group_id group-id))
+
+(defn limit-for-user
+ "Returns the maximum `max_usage` across all group limits for groups the user belongs to.
+ Returns nil if the user has any groups with a null (unlimited) limit"
+ [user-id]
+ (:max_usage
+ (t2/query-one {:select [[[:case
+ [:= [[:count :*]] [[:count :gl.max_usage]]]
+ [[:max :gl.max_usage]]]
+ :max_usage]]
+ :from [[:permissions_group_membership :pgm]]
+ :left-join [[:metabot_group_limit :gl] [:= :pgm.group_id :gl.group_id]]
+ :where [:= :pgm.user_id user-id]})))
+
+(defn set-group-limit!
+ "Sets or removes the limit for a specific group. Pass nil to remove (unlimited).
+ Returns the updated row, or nil if removed."
+ [group-id max-usage]
+ (if (nil? max-usage)
+ (t2/delete! :model/MetabotGroupLimit :group_id group-id)
+ (if-let [existing (group-limit group-id)]
+ (t2/update! :model/MetabotGroupLimit (:id existing) {:max_usage max-usage})
+ (t2/insert! :model/MetabotGroupLimit {:group_id group-id :max_usage max-usage})))
+ (group-limit group-id))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj
new file mode 100644
index 00000000000..e6cd572715d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj
@@ -0,0 +1,33 @@
+(ns metabase-enterprise.metabot.models.metabot-instance-limit
+ (:require
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/MetabotInstanceLimit [_model] :metabot_instance_limit)
+
+(doto :model/MetabotInstanceLimit
+ (derive :metabase/model)
+ (derive ::mi/write-policy.superuser))
+
+(defn instance-limit
+ "Returns the limit for a given tenant, or the instance-wide limit when `tenant-id` is nil.
+ Returns nil if no limit is set."
+ [tenant-id]
+ (t2/select-one :model/MetabotInstanceLimit :tenant_id tenant-id))
+
+(defn set-instance-limit!
+ "Sets or removes the limit for a given tenant (or instance-wide when `tenant-id` is nil).
+ Pass nil for `max-usage` to remove the limit. Returns the updated row, or nil if removed."
+ [tenant-id max-usage]
+ (if (nil? max-usage)
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id tenant-id)
+ (if-let [existing (instance-limit tenant-id)]
+ (t2/update! :model/MetabotInstanceLimit (:id existing) {:max_usage max-usage})
+ (t2/insert! :model/MetabotInstanceLimit {:tenant_id tenant-id :max_usage max-usage})))
+ (instance-limit tenant-id))
+
+(defn all-tenant-limits
+ "Returns all tenant-level limits (where tenant_id is not null), ordered by tenant_id."
+ []
+ (t2/select :model/MetabotInstanceLimit :tenant_id [:not= nil] {:order-by [[:tenant_id :asc]]}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/settings.clj b/enterprise/backend/src/metabase_enterprise/metabot/settings.clj
new file mode 100644
index 00000000000..19d06edce36
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/settings.clj
@@ -0,0 +1,50 @@
+(ns metabase-enterprise.metabot.settings
+ "Enterprise-only metabot settings for usage limits."
+ (:require
+ [metabase.settings.core :as setting :refer [defsetting]]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(def ^:private valid-limit-units #{:tokens :messages})
+
+(defsetting metabot-limit-unit
+ (deferred-tru "The unit used for metabot usage limits.")
+ :type :keyword
+ :default :tokens
+ :visibility :settings-manager
+ :encryption :no
+ :export? true
+ :doc false
+ :setter (fn [new-value]
+ (let [v (some-> new-value keyword)]
+ (when (and v (not (contains? valid-limit-units v)))
+ (throw (ex-info (str "Invalid limit unit: " (pr-str new-value)
+ ". Must be one of: tokens, messages.")
+ {:status-code 400})))
+ (setting/set-value-of-type! :keyword :metabot-limit-unit v))))
+
+(def ^:private valid-reset-rates #{:daily :weekly :monthly})
+
+(defsetting metabot-limit-reset-rate
+ (deferred-tru "How often metabot usage limits reset.")
+ :type :keyword
+ :default :monthly
+ :visibility :settings-manager
+ :encryption :no
+ :export? true
+ :doc false
+ :setter (fn [new-value]
+ (let [v (some-> new-value keyword)]
+ (when (and v (not (contains? valid-reset-rates v)))
+ (throw (ex-info (str "Invalid reset rate: " (pr-str new-value)
+ ". Must be one of: daily, weekly, monthly.")
+ {:status-code 400})))
+ (setting/set-value-of-type! :keyword :metabot-limit-reset-rate v))))
+
+(defsetting metabot-quota-reached-message
+ (deferred-tru "The message shown to users when they reach their usage quota.")
+ :type :string
+ :default "You have reached your AI usage limit for the current period. Please contact your administrator."
+ :visibility :settings-manager
+ :encryption :no
+ :export? true
+ :doc false)
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj
new file mode 100644
index 00000000000..2c2a86bbdcb
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj
@@ -0,0 +1,44 @@
+(ns metabase-enterprise.metabot.task.ai-usage-trimmer
+ "Scheduled task to delete old ai_usage_log rows (older than 3 months)."
+ (:require
+ [clojurewerkz.quartzite.jobs :as jobs]
+ [clojurewerkz.quartzite.schedule.cron :as cron]
+ [clojurewerkz.quartzite.triggers :as triggers]
+ [metabase.task.core :as task]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2])
+ (:import
+ (java.sql Timestamp)
+ (org.quartz DisallowConcurrentExecution)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private trimmer-job-key (jobs/key "metabase.task.metabot.ai-usage-trimmer.job"))
+(def ^:private trimmer-trigger-key (triggers/key "metabase.task.metabot.ai-usage-trimmer.trigger"))
+
+(def ^:private retention-months 3)
+
+(defn- trim-old-usage-data!
+ []
+ (log/info "Trimming old AI usage log data.")
+ (let [cutoff (Timestamp/valueOf (.minusMonths (java.time.LocalDateTime/now) retention-months))
+ deleted (t2/delete! :model/AiUsageLog {:where [:< :created_at cutoff]})]
+ (log/infof "AI usage log cleanup complete. Deleted %d rows." (or deleted 0))))
+
+(task/defjob ^{DisallowConcurrentExecution true
+ :doc "Delete old ai_usage_log rows"}
+ AiUsageTrimmer [_ctx]
+ (trim-old-usage-data!))
+
+(defmethod task/init! ::AiUsageTrimmer
+ [_]
+ (let [job (jobs/build
+ (jobs/of-type AiUsageTrimmer)
+ (jobs/with-identity trimmer-job-key))
+ trigger (triggers/build
+ (triggers/with-identity trimmer-trigger-key)
+ (triggers/start-now)
+ (triggers/with-schedule
+ ;; daily at 23:14:37
+ (cron/cron-schedule "37 14 23 * * ?")))]
+ (task/schedule-task! job trigger)))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/usage.clj b/enterprise/backend/src/metabase_enterprise/metabot/usage.clj
new file mode 100644
index 00000000000..ccdffbe9a64
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/usage.clj
@@ -0,0 +1,146 @@
+(ns metabase-enterprise.metabot.usage
+ "Enterprise implementation of metabot usage logging and limit checking."
+ (:require
+ [clojure.core.memoize :as memoize]
+ [metabase-enterprise.metabot.models.metabot-group-limit :as group-limit]
+ [metabase-enterprise.metabot.models.metabot-instance-limit :as instance-limit]
+ [metabase-enterprise.metabot.settings :as metabot.settings]
+ [metabase.api.common :as api]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2])
+ (:import
+ (java.time DayOfWeek LocalDate YearMonth ZoneOffset)
+ (java.time.temporal TemporalAdjusters)))
+
+(set! *warn-on-reflection* true)
+
+(defenterprise log-ai-usage!
+ "Record an LLM API call in the ai_usage_log table."
+ :feature :none
+ [{:keys [source model prompt-tokens completion-tokens
+ user-id tenant-id conversation-id profile-id request-id]}]
+ (when-not (= "user-intent-classification" source)
+ (try
+ (let [total-tokens (+ prompt-tokens completion-tokens)]
+ (t2/insert! :model/AiUsageLog
+ {:source source
+ :model model
+ :prompt_tokens prompt-tokens
+ :completion_tokens completion-tokens
+ :total_tokens total-tokens
+ :user_id (or user-id api/*current-user-id*)
+ :tenant_id (or tenant-id (some-> api/*current-user* deref :tenant_id))
+ :conversation_id conversation-id
+ :profile_id (some-> profile-id name)
+ :request_id request-id}))
+ (catch Exception e
+ (log/warn e "Failed to log LLM usage to ai_usage_log")))))
+
+(defn- period-start
+ "Return the start of the current billing period as an Instant, based on the reset rate setting."
+ []
+ (let [rate (metabot.settings/metabot-limit-reset-rate)
+ today (LocalDate/now ZoneOffset/UTC)]
+ (.toInstant
+ (.atStartOfDay
+ (case rate
+ :daily today
+ :weekly (.with today (TemporalAdjusters/previousOrSame DayOfWeek/MONDAY))
+ :monthly (.atDay (YearMonth/from today) 1)))
+ ZoneOffset/UTC)))
+
+(defn- usage-query
+ "Query ai_usage_log for current-period usage. `where-clauses` are additional HoneySQL where conditions.
+ Returns a token sum or row count depending on `metabot-limit-unit`."
+ [where-clauses]
+ (let [limit-type (metabot.settings/metabot-limit-unit)
+ start (period-start)
+ base-where [:and
+ [:>= :created_at start]]
+ full-where (if (seq where-clauses)
+ (into base-where where-clauses)
+ base-where)]
+ (case limit-type
+ :tokens
+ (quot (or (:sum (t2/query-one {:select [[[:sum :total_tokens] :sum]]
+ :from [:ai_usage_log]
+ :where full-where}))
+ 0)
+ 1000000)
+
+ :messages
+ (:cnt (t2/query-one {:select [[[:count :*] :cnt]]
+ :from [:ai_usage_log]
+ :where full-where})))))
+
+(defn- check-instance-limit
+ "Check the instance-wide limit. Returns an error message string if exceeded, nil otherwise."
+ []
+ (when-let [max-usage (:max_usage (instance-limit/instance-limit nil))]
+ (let [usage (usage-query [])]
+ (when (>= usage max-usage)
+ (metabot.settings/metabot-quota-reached-message)))))
+
+(defn- check-tenant-limit
+ "Check the tenant-level limit. Returns an error message string if exceeded, nil otherwise."
+ [tenant-id]
+ (when tenant-id
+ (when-let [max-usage (:max_usage (instance-limit/instance-limit tenant-id))]
+ (let [usage (usage-query [[:= :tenant_id tenant-id]])]
+ (when (>= usage max-usage)
+ (metabot.settings/metabot-quota-reached-message))))))
+
+(defn- check-user-limit
+ "Check the user-level limit (max across all their groups). Returns an error message if exceeded, nil otherwise."
+ [user-id]
+ (when user-id
+ (when-let [max-usage (group-limit/limit-for-user user-id)]
+ (let [usage (usage-query [[:= :user_id user-id]])]
+ (when (>= usage max-usage)
+ (metabot.settings/metabot-quota-reached-message))))))
+
+(def ^:private ^:const cache-ttl-ms
+ "Cache TTL in milliseconds."
+ (* 10 1000))
+
+(def ^:private check-instance-limit*
+ (memoize/ttl
+ (fn [_cache-key] (check-instance-limit))
+ :ttl/threshold cache-ttl-ms))
+
+(def ^:private check-tenant-limit*
+ (memoize/ttl
+ check-tenant-limit
+ :ttl/threshold cache-ttl-ms))
+
+(def ^:private check-user-limit*
+ (memoize/ttl
+ check-user-limit
+ :ttl/threshold cache-ttl-ms))
+
+(defn clear-limit-cache!
+ "Clear all cached limit check results. Useful for tests."
+ []
+ (memoize/memo-clear! check-instance-limit*)
+ (memoize/memo-clear! check-tenant-limit*)
+ (memoize/memo-clear! check-user-limit*))
+
+(defenterprise clear-metabot-limit-cache!
+ "EE implementation: clears the memoized limit-check results so they re-evaluate immediately."
+ :feature :none
+ []
+ (clear-limit-cache!))
+
+(defenterprise check-usage-limits!
+ "Check all usage limits for the current user. Returns nil if all limits are within bounds,
+ or a user-friendly error message string if any limit is exceeded.
+
+ Results are cached for `cache-ttl-ms`."
+ :feature :none
+ []
+ (let [user-id api/*current-user-id*
+ tenant-id (some-> api/*current-user* deref :tenant_id)]
+ (or (check-instance-limit* :instance)
+ (check-tenant-limit* tenant-id)
+ (check-user-limit* user-id))))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 0871f061492..b6f89905ebe 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -57,7 +57,8 @@
(def excluded-models
"List of models which are not going to be serialized ever."
- ["AnalysisFinding"
+ ["AiUsageLog"
+ "AnalysisFinding"
"AnalysisFindingError"
"ApiKey"
"ApplicationPermissionsRevision"
@@ -83,6 +84,8 @@
"ImplicitAction"
"LoginHistory"
"MetabotConversation"
+ "MetabotGroupLimit"
+ "MetabotInstanceLimit"
"MetabotMessage"
"MetabotPermissions"
"ModelIndex"
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj
index 2fa5c86167d..2795c0b06fd 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj
@@ -1,6 +1,7 @@
(ns metabase-enterprise.metabot.api.permissions-test
(:require
[clojure.test :refer [deftest is testing]]
+ [metabase-enterprise.metabot.permissions]
[metabase.test :as mt]
[toucan2.core :as t2]))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/api/usage_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/api/usage_test.clj
new file mode 100644
index 00000000000..bd07a585cab
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot/api/usage_test.clj
@@ -0,0 +1,175 @@
+(ns metabase-enterprise.metabot.api.usage-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+;;; ------------------------------------------------ Instance limits -------------------------------------------------
+
+(deftest get-instance-limit-test
+ (testing "GET /api/ee/ai-controls/usage/instance"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/usage/instance"))))
+ (testing "returns max_usage: null when no limit is set"
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id nil)
+ (is (= {:max_usage nil}
+ (mt/user-http-request :crowberto :get 200 "ee/ai-controls/usage/instance"))))
+ (testing "returns max_usage when set"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 1000}]
+ (is (= {:max_usage 1000}
+ (mt/user-http-request :crowberto :get 200 "ee/ai-controls/usage/instance"))))))))
+
+(deftest put-instance-limit-test
+ (testing "PUT /api/ee/ai-controls/usage/instance"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "ee/ai-controls/usage/instance" {:max_usage 500}))))
+ (testing "creates a new limit when none exists"
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id nil)
+ (is (= {:max_usage 500}
+ (mt/user-http-request :crowberto :put 200 "ee/ai-controls/usage/instance" {:max_usage 500})))
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id nil))
+ (testing "updates an existing limit"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 1000}]
+ (is (= {:max_usage 2000}
+ (mt/user-http-request :crowberto :put 200 "ee/ai-controls/usage/instance" {:max_usage 2000})))))
+ (testing "removes the limit when max_usage is null"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 1000}]
+ (is (= {:max_usage nil}
+ (mt/user-http-request :crowberto :put 200 "ee/ai-controls/usage/instance" {:max_usage nil})))
+ (is (nil? (t2/select-one :model/MetabotInstanceLimit :tenant_id nil))))))))
+
+;;; ------------------------------------------------- Tenant limits --------------------------------------------------
+
+(deftest get-tenant-limits-test
+ (testing "GET /api/ee/ai-controls/usage/tenant"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/usage/tenant"))))
+ (testing "returns all tenant limits as a flat list"
+ (mt/with-temp [:model/Tenant {tenant-a :id} {}
+ :model/Tenant {tenant-b :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-a :max_usage 100}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-b :max_usage 200}]
+ (let [limits (mt/user-http-request :crowberto :get 200 "ee/ai-controls/usage/tenant")
+ by-tenant (into {} (map (juxt :tenant_id :max_usage)) limits)]
+ (is (= 100 (get by-tenant tenant-a)))
+ (is (= 200 (get by-tenant tenant-b)))
+ (is (every? #(not (contains? % :id)) limits))))))))
+
+(deftest get-tenant-limit-test
+ (testing "GET /api/ee/ai-controls/usage/tenant/:tenant-id"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/usage/tenant/1"))))
+ (testing "returns tenant_id and max_usage: null when no limit is set"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}]
+ (is (= {:tenant_id tenant-id :max_usage nil}
+ (mt/user-http-request :crowberto :get 200
+ (format "ee/ai-controls/usage/tenant/%d" tenant-id))))))
+ (testing "returns tenant_id and max_usage when set"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-id :max_usage 500}]
+ (is (= {:tenant_id tenant-id :max_usage 500}
+ (mt/user-http-request :crowberto :get 200
+ (format "ee/ai-controls/usage/tenant/%d" tenant-id)))))))))
+
+(deftest put-tenant-limit-test
+ (testing "PUT /api/ee/ai-controls/usage/tenant/:tenant-id"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "ee/ai-controls/usage/tenant/1" {:max_usage 500}))))
+ (testing "creates a new limit"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}]
+ (is (= {:tenant_id tenant-id :max_usage 300}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/tenant/%d" tenant-id)
+ {:max_usage 300})))
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id tenant-id)))
+ (testing "updates an existing limit"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-id :max_usage 300}]
+ (is (= {:tenant_id tenant-id :max_usage 600}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/tenant/%d" tenant-id)
+ {:max_usage 600})))))
+ (testing "removes the limit when max_usage is null"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-id :max_usage 300}]
+ (is (= {:tenant_id tenant-id :max_usage nil}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/tenant/%d" tenant-id)
+ {:max_usage nil})))
+ (is (nil? (t2/select-one :model/MetabotInstanceLimit :tenant_id tenant-id))))))))
+
+;;; -------------------------------------------------- Group limits ---------------------------------------------------
+
+(deftest get-group-limits-test
+ (testing "GET /api/ee/ai-controls/usage/group"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/usage/group"))))
+ (testing "returns all group limits as a flat list"
+ (mt/with-temp [:model/PermissionsGroup {group-a :id} {:name "Limit Group A"}
+ :model/PermissionsGroup {group-b :id} {:name "Limit Group B"}
+ :model/MetabotGroupLimit _ {:group_id group-a :max_usage 100}
+ :model/MetabotGroupLimit _ {:group_id group-b :max_usage 200}]
+ (let [limits (mt/user-http-request :crowberto :get 200 "ee/ai-controls/usage/group")
+ by-group (into {} (map (juxt :group_id :max_usage)) limits)]
+ (is (= 100 (get by-group group-a)))
+ (is (= 200 (get by-group group-b)))
+ (is (every? #(not (contains? % :id)) limits))))))))
+
+(deftest get-group-limit-test
+ (testing "GET /api/ee/ai-controls/usage/group/:group-id"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/usage/group/1"))))
+ (testing "returns group_id and max_usage: null when no limit is set"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "No Limit Group"}]
+ (is (= {:group_id group-id :max_usage nil}
+ (mt/user-http-request :crowberto :get 200
+ (format "ee/ai-controls/usage/group/%d" group-id))))))
+ (testing "returns group_id and max_usage when set"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Limited Group"}
+ :model/MetabotGroupLimit _ {:group_id group-id :max_usage 500}]
+ (is (= {:group_id group-id :max_usage 500}
+ (mt/user-http-request :crowberto :get 200
+ (format "ee/ai-controls/usage/group/%d" group-id)))))))))
+
+(deftest put-group-limit-test
+ (testing "PUT /api/ee/ai-controls/usage/group/:group-id"
+ (mt/with-premium-features #{:ai-controls}
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "ee/ai-controls/usage/group/1" {:max_usage 500}))))
+ (testing "creates a new limit"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "New Limit Group"}]
+ (is (= {:group_id group-id :max_usage 300}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/group/%d" group-id)
+ {:max_usage 300})))
+ (t2/delete! :model/MetabotGroupLimit :group_id group-id)))
+ (testing "updates an existing limit"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Update Limit Group"}
+ :model/MetabotGroupLimit _ {:group_id group-id :max_usage 300}]
+ (is (= {:group_id group-id :max_usage 600}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/group/%d" group-id)
+ {:max_usage 600})))))
+ (testing "removes the limit when max_usage is null"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Remove Limit Group"}
+ :model/MetabotGroupLimit _ {:group_id group-id :max_usage 300}]
+ (is (= {:group_id group-id :max_usage nil}
+ (mt/user-http-request :crowberto :put 200
+ (format "ee/ai-controls/usage/group/%d" group-id)
+ {:max_usage nil})))
+ (is (nil? (t2/select-one :model/MetabotGroupLimit :group_id group-id))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/usage_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/usage_test.clj
new file mode 100644
index 00000000000..d861fd7022e
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot/usage_test.clj
@@ -0,0 +1,355 @@
+(ns metabase-enterprise.metabot.usage-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase-enterprise.metabot.usage :as ee.usage]
+ [metabase.api.common :as api]
+ [metabase.metabot.usage :as usage]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- insert-usage!
+ "Insert a test ai_usage_log row for the given user with the specified total_tokens."
+ ([user-id total-tokens]
+ (insert-usage! user-id total-tokens nil))
+ ([user-id total-tokens tenant-id]
+ (t2/insert! :model/AiUsageLog
+ (cond-> {:source "test"
+ :model "test/model"
+ :prompt_tokens 0
+ :completion_tokens 0
+ :total_tokens total-tokens
+ :user_id user-id}
+ tenant-id (assoc :tenant_id tenant-id)))))
+
+(defn- cleanup-test-usage! [user-id]
+ (t2/delete! :model/AiUsageLog :user_id user-id :source "test"))
+
+;;; ------------------------------------------------ log-ai-usage! ------------------------------------------------
+
+(deftest log-ai-usage!-records-usage-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "log-ai-usage! inserts a row into ai_usage_log"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-test-user :rasta
+ (let [before-count (t2/count :model/AiUsageLog :user_id user-id :source "log-test")]
+ (usage/log-ai-usage!
+ {:source "log-test"
+ :model "anthropic/claude-test"
+ :prompt-tokens 100
+ :completion-tokens 50})
+ (try
+ (is (= (inc before-count)
+ (t2/count :model/AiUsageLog :user_id user-id :source "log-test")))
+ (let [row (t2/select-one :model/AiUsageLog :user_id user-id :source "log-test"
+ {:order-by [[:id :desc]]})]
+ (is (= "anthropic/claude-test" (:model row)))
+ (is (= 100 (:prompt_tokens row)))
+ (is (= 50 (:completion_tokens row)))
+ (is (= 150 (:total_tokens row)))
+ (is (= user-id (:user_id row))))
+ (finally
+ (t2/delete! :model/AiUsageLog :user_id user-id :source "log-test")))))))))
+
+(deftest log-ai-usage!-skips-intent-classification-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "log-ai-usage! skips user-intent-classification source"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-test-user :rasta
+ (let [before-count (t2/count :model/AiUsageLog :user_id user-id
+ :source "user-intent-classification")]
+ (usage/log-ai-usage!
+ {:source "user-intent-classification"
+ :model "anthropic/claude-test"
+ :prompt-tokens 10
+ :completion-tokens 5})
+ (is (= before-count
+ (t2/count :model/AiUsageLog :user_id user-id
+ :source "user-intent-classification")))))))))
+
+(deftest log-ai-usage!-defaults-user-id-from-binding-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "log-ai-usage! uses api/*current-user-id* when user-id not provided"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-test-user :rasta
+ (usage/log-ai-usage!
+ {:source "binding-test"
+ :model "test/model"
+ :prompt-tokens 1
+ :completion-tokens 1})
+ (try
+ (let [row (t2/select-one :model/AiUsageLog :source "binding-test"
+ {:order-by [[:id :desc]]})]
+ (is (= user-id (:user_id row))))
+ (finally
+ (t2/delete! :model/AiUsageLog :source "binding-test"))))))))
+
+(deftest log-ai-usage!-converts-profile-id-keyword-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "log-ai-usage! converts keyword profile-id to string"
+ (mt/with-test-user :rasta
+ (usage/log-ai-usage!
+ {:source "profile-test"
+ :model "test/model"
+ :prompt-tokens 1
+ :completion-tokens 1
+ :profile-id :internal})
+ (try
+ (let [row (t2/select-one :model/AiUsageLog :source "profile-test"
+ {:order-by [[:id :desc]]})]
+ (is (= "internal" (:profile_id row))))
+ (finally
+ (t2/delete! :model/AiUsageLog :source "profile-test")))))))
+
+(deftest log-ai-usage!-explicit-user-id-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "log-ai-usage! uses explicitly passed user-id over bound value"
+ (let [crowberto-id (mt/user->id :crowberto)]
+ (mt/with-test-user :rasta
+ (usage/log-ai-usage!
+ {:source "explicit-user-test"
+ :model "test/model"
+ :prompt-tokens 1
+ :completion-tokens 1
+ :user-id crowberto-id})
+ (try
+ (let [row (t2/select-one :model/AiUsageLog :source "explicit-user-test"
+ {:order-by [[:id :desc]]})]
+ (is (= crowberto-id (:user_id row))))
+ (finally
+ (t2/delete! :model/AiUsageLog :source "explicit-user-test"))))))))
+
+;;; ------------------------------------------ check-usage-limits! ------------------------------------------
+
+(deftest no-limits-configured-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "check-usage-limits! returns nil when no limits are configured"
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!)))))))
+
+(deftest instance-limit-nil-max-usage-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "Instance limit with nil max_usage means unlimited"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage nil}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 999999)
+ (try
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id))))))))
+
+(deftest instance-limit-under-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "Instance limit: under limit returns nil"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 999999999}]
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))))))
+
+(deftest instance-limit-exceeded-returns-message-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "test limit reached"]
+ (testing "Instance limit: at/over limit returns quota message"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 100}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 150000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+(deftest instance-limit-exactly-at-limit-returns-message-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "test limit reached"]
+ (testing "Instance limit: exactly at limit returns quota message (>= check)"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 100}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 100000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+;;; ------------------------------------------ Tenant limit tests ------------------------------------------
+
+(deftest tenant-limit-exceeded-returns-message-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "test limit reached"]
+ (testing "Tenant limit: over limit returns quota message"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-id :max_usage 50}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 100000000 tenant-id)
+ (try
+ (binding [api/*current-user-id* user-id
+ api/*current-user* (delay {:tenant_id tenant-id})]
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+(deftest tenant-limit-nil-max-usage-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "Tenant limit with nil max_usage means unlimited"
+ (mt/with-temp [:model/Tenant {tenant-id :id} {}
+ :model/MetabotInstanceLimit _ {:tenant_id tenant-id :max_usage nil}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 999999 tenant-id)
+ (try
+ (binding [api/*current-user-id* user-id
+ api/*current-user* (delay {:tenant_id tenant-id})]
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id))))))))
+
+(deftest no-tenant-skips-tenant-check-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "User without a tenant skips tenant limit check"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 999999999}]
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))))))
+
+;;; ------------------------------------------ User group limit tests ------------------------------------------
+
+(deftest user-group-limit-exceeded-returns-message-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "test limit reached"]
+ (testing "User group limit: user over their group limit returns message"
+ (let [user-id (mt/user->id :rasta)
+ group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id)
+ group-id (first group-ids)]
+ (mt/with-temp [:model/MetabotGroupLimit _ {:group_id group-id :max_usage 50}]
+ (insert-usage! user-id 100000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+(deftest user-group-limit-takes-max-across-groups-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id nil)
+ (testing "User group limit: takes the max limit across all groups the user is in"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-temp [:model/PermissionsGroup {g1 :id} {:name "Low limit group"}
+ :model/PermissionsGroup {g2 :id} {:name "High limit group"}
+ :model/PermissionsGroupMembership _ {:group_id g1 :user_id user-id}
+ :model/PermissionsGroupMembership _ {:group_id g2 :user_id user-id}
+ :model/MetabotGroupLimit _ {:group_id g1 :max_usage 10}
+ :model/MetabotGroupLimit _ {:group_id g2 :max_usage 1000}]
+ (insert-usage! user-id 50000000)
+ (try
+ (mt/with-test-user :rasta
+ ;; 50 < 1000 (the max across groups), so should pass
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id))))))))
+
+(deftest user-group-null-limit-means-unlimited-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (t2/delete! :model/MetabotInstanceLimit :tenant_id nil)
+ (testing "User group limit: if any of the user's groups has no limit configured, user is unlimited"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-temp [:model/PermissionsGroup {g1 :id} {:name "Limited group"}
+ :model/PermissionsGroup {g2 :id} {:name "Unlimited group"}
+ :model/PermissionsGroupMembership _ {:group_id g1 :user_id user-id}
+ :model/PermissionsGroupMembership _ {:group_id g2 :user_id user-id}
+ :model/MetabotGroupLimit _ {:group_id g1 :max_usage 10}]
+ ;; g2 has no limit row — being in any unlimited group makes the user unlimited
+ (insert-usage! user-id 50000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id))))))))
+
+(deftest user-group-no-limit-configured-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (testing "User with no group limits configured returns nil"
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 999999)
+ (try
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))
+
+;;; ------------------------------------------ Messages limit type ------------------------------------------
+
+(deftest messages-limit-type-counts-rows-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-limit-unit "messages"
+ metabot-quota-reached-message "test limit reached"]
+ (testing "Instance limit with :messages type counts rows, not tokens"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 2}]
+ (let [user-id (mt/user->id :rasta)]
+ ;; Insert 3 rows each with 1 token — row count (3) exceeds limit (2)
+ (dotimes [_ 3]
+ (insert-usage! user-id 1))
+ (try
+ (mt/with-test-user :rasta
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+(deftest messages-under-limit-returns-nil-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-limit-unit "messages"]
+ (testing "Instance limit with :messages type: under limit returns nil"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 100}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 1)
+ (try
+ (mt/with-test-user :rasta
+ (is (nil? (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+;;; ------------------------------------------ Custom quota message ------------------------------------------
+
+(deftest custom-quota-message-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "Custom limit message"]
+ (testing "check-usage-limits! returns the configured quota message"
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 1}]
+ (let [user-id (mt/user->id :rasta)]
+ (insert-usage! user-id 2000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (= "Custom limit message" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
+
+;;; ------------------------------------------ Priority ordering ------------------------------------------
+
+(deftest instance-limit-checked-first-test
+ (mt/with-premium-features #{:ai-controls}
+ (ee.usage/clear-limit-cache!)
+ (mt/with-temporary-setting-values [metabot-quota-reached-message "test limit reached"]
+ (testing "Instance limit blocks even when user group limit would allow"
+ (let [user-id (mt/user->id :rasta)
+ group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id)
+ group-id (first group-ids)]
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 1}
+ :model/MetabotGroupLimit _ {:group_id group-id :max_usage 999999}]
+ (insert-usage! user-id 2000000)
+ (try
+ (mt/with-test-user :rasta
+ (is (= "test limit reached" (usage/check-usage-limits!))))
+ (finally
+ (cleanup-test-usage! user-id)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index a396ba04112..15ad3c35590 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -32,7 +32,8 @@
- not exported in serialization; or
- exported as a child of something else (eg. timeline_event under timeline)
so they don't need a generated entity_id."
- #{:model/AnalysisFinding
+ #{:model/AiUsageLog
+ :model/AnalysisFinding
:model/AnalysisFindingError
:model/ApiKey
:model/AuthIdentity
@@ -57,6 +58,8 @@
:model/LoginHistory
:model/FieldValues
:model/MetabotConversation
+ :model/MetabotGroupLimit
+ :model/MetabotInstanceLimit
:model/MetabotMessage
:model/MetabotPermissions
:model/ModelIndex
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts
new file mode 100644
index 00000000000..f4b3644e93e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts
@@ -0,0 +1 @@
+export { useAdminSettingWithDebouncedInput } from "./useAdminSettingWithDebouncedInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithDebouncedInput.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithDebouncedInput.ts
new file mode 100644
index 00000000000..7665f5ed694
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithDebouncedInput.ts
@@ -0,0 +1,58 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useCallback, useEffect, useState } from "react";
+import { c } from "ttag";
+
+import { useAdminSetting } from "metabase/api/utils";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import type {
+ EnterpriseSettingKey,
+ EnterpriseSettingValue,
+} from "metabase-types/api";
+
+export const SAVE_DEBOUNCE_MS = 500;
+
+export function useAdminSettingWithDebouncedInput<T>(
+ settingName: EnterpriseSettingKey,
+ defaultValue: T | null = null,
+) {
+ const { value: settingValue, updateSetting } = useAdminSetting(settingName);
+ const [inputValue, setInputValue] = useState<T>(settingValue as T);
+ const { sendErrorToast } = useMetadataToasts();
+
+ // Local input state initialization
+ useEffect(() => {
+ if (
+ inputValue === undefined && // Input has not been initialized
+ settingValue !== undefined // and setting has been fetched
+ ) {
+ setInputValue((settingValue || defaultValue) as T);
+ }
+ }, [defaultValue, inputValue, settingValue]);
+
+ const debouncedSaveSetting = useDebouncedCallback(async (value: T) => {
+ const response = await updateSetting({
+ key: settingName,
+ value: value as EnterpriseSettingValue<typeof settingName>,
+ toast: false,
+ });
+ if (response.error) {
+ sendErrorToast(
+ c("{0} is the setting name")
+ .t`Failed to update setting: ${settingName}`,
+ );
+ }
+ }, SAVE_DEBOUNCE_MS);
+
+ const handleInputChange = useCallback(
+ (newValue: T) => {
+ setInputValue(newValue);
+ debouncedSaveSetting(newValue);
+ },
+ [debouncedSaveSetting],
+ );
+
+ return {
+ inputValue,
+ handleInputChange,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx
index 280947f4137..6d3c92b1536 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx
@@ -15,6 +15,10 @@ export function getAiControlsNavItems() {
label={t`AI feature access`}
path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/usage-controls/ai-feature-access`}
/>
+ <AdminNavItem
+ label={t`AI usage limits`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/usage-controls/ai-usage-limits`}
+ />
</AdminNavItem>
<AdminNavItem
icon="palette"
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx
index 2994ee3e70c..a8a7e972130 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx
@@ -1,34 +1,17 @@
-import { useDebouncedCallback } from "@mantine/hooks";
-import { useEffect, useState } from "react";
import { t } from "ttag";
import {
SettingsPageWrapper,
SettingsSection,
} from "metabase/admin/components/SettingsSection";
-import { useAdminSetting } from "metabase/api/utils";
import { TextInput } from "metabase/ui";
+import { useAdminSettingWithDebouncedInput } from "metabase-enterprise/ai-controls/hooks";
import { MetabotIconField } from "./MetabotIconField";
-const SAVE_DEBOUNCE_MS = 500;
-
export function MetabotCustomizationPage() {
- const { value: initialInputValue, updateSetting: updateName } =
- useAdminSetting("metabot-name");
- const [nameInput, setNameInput] = useState<string>();
-
- useEffect(() => {
- if (nameInput === undefined && initialInputValue !== undefined) {
- setNameInput(initialInputValue ?? "");
- }
- }, [initialInputValue, nameInput]);
-
- const debouncedSaveName = useDebouncedCallback((value: string) => {
- if (value) {
- updateName({ key: "metabot-name", value, toast: false });
- }
- }, SAVE_DEBOUNCE_MS);
+ const { handleInputChange, inputValue: nameInput } =
+ useAdminSettingWithDebouncedInput<string | null>("metabot-name");
return (
<SettingsPageWrapper title={t`Customization`} mt="sm">
@@ -40,11 +23,8 @@ export function MetabotCustomizationPage() {
label={t`Metabot's name`}
placeholder={t`Metabot`}
mb="sm"
- value={nameInput}
- onChange={(e) => {
- setNameInput(e.currentTarget.value);
- debouncedSaveName(e.currentTarget.value);
- }}
+ value={nameInput || ""}
+ onChange={(e) => handleInputChange(e.target.value)}
error={nameInput ? undefined : t`Metabot's name is required`}
/>
<MetabotIconField />
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts
index ff211882704..5d8443efc6c 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts
@@ -2,11 +2,11 @@ import { useDebouncedCallback } from "@mantine/hooks";
import { useEffect, useState } from "react";
import { t } from "ttag";
-import {
- useGetMetabotPermissionsQuery,
- useUpdateMetabotPermissionsMutation,
-} from "metabase/api";
import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ useGetAIControlsGroupPermissionsQuery,
+ useUpdateAIControlsGroupPermissionsMutation,
+} from "metabase-enterprise/api";
import { AIToolKey, type MetabotGroupPermission } from "metabase-types/api";
export type GroupTab = "user-groups" | "tenant-groups";
@@ -24,8 +24,9 @@ const PERMISSIONS_SAVE_DEBOUNCE = 500;
export const useMetabotGroupPermissions = () => {
const { data: permissionsQueryData, error: permissionsQueryError } =
- useGetMetabotPermissionsQuery();
- const [updateMetabotPermissions] = useUpdateMetabotPermissionsMutation();
+ useGetAIControlsGroupPermissionsQuery();
+ const [updateMetabotPermissions] =
+ useUpdateAIControlsGroupPermissionsMutation();
const [groupPermissions, setGroupPermissions] = useState<
MetabotGroupPermission[]
>([]);
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
index ad03e2efa6a..946f6533b3c 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
@@ -7,23 +7,26 @@ import {
import { useSelector } from "metabase/lib/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Text, Textarea } from "metabase/ui";
+import { useAdminSettingWithDebouncedInput } from "metabase-enterprise/ai-controls/hooks";
import S from "./MetabotSystemPromptsPage.module.css";
-import type { SystemPromptSettingKey } from "./hooks/useSystemPromptInput";
-import { useSystemPromptInput } from "./hooks/useSystemPromptInput";
-interface SystemPromptPageProps {
+type SystemPromptSettingKey =
+ | "metabot-chat-system-prompt"
+ | "metabot-nlq-system-prompt"
+ | "metabot-sql-system-prompt";
+
+type SystemPromptPageProps = {
title: string;
description: string;
settingKey: SystemPromptSettingKey;
-}
+};
-function SystemPromptPage({
- title,
- description,
- settingKey,
-}: SystemPromptPageProps) {
- const { inputText, onInputChange } = useSystemPromptInput(settingKey);
+function SystemPromptPage(props: SystemPromptPageProps) {
+ const { title, description, settingKey } = props;
+ const { handleInputChange, inputValue } = useAdminSettingWithDebouncedInput<
+ string | null
+ >(settingKey);
return (
<SettingsPageWrapper title={title} mt="sm">
@@ -34,9 +37,9 @@ function SystemPromptPage({
<Textarea
aria-label={title}
className={S.textareaWrapper}
- onChange={onInputChange}
+ onChange={(e) => handleInputChange(e.target.value)}
placeholder={getPlaceholder()}
- value={inputText}
+ value={inputValue || ""}
/>
</SettingsSection>
</SettingsPageWrapper>
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx
deleted file mode 100644
index 0c18b73bd04..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useDebouncedCallback } from "@mantine/hooks";
-import { type ChangeEvent, useEffect, useState } from "react";
-
-import { useAdminSetting } from "metabase/api/utils";
-
-export type SystemPromptSettingKey =
- | "metabot-chat-system-prompt"
- | "metabot-nlq-system-prompt"
- | "metabot-sql-system-prompt";
-
-const DEBOUNCE_DELAY = 500;
-
-export function useSystemPromptInput(settingKey: SystemPromptSettingKey) {
- const { value: initialPromptText, updateSetting } =
- useAdminSetting(settingKey);
- const [inputText, setInputText] = useState<string>();
-
- useEffect(() => {
- if (inputText === undefined && initialPromptText !== undefined) {
- setInputText(initialPromptText ?? "");
- }
- }, [initialPromptText, inputText]);
-
- const debouncedUpdateSystemPrompt = useDebouncedCallback((value: string) => {
- updateSetting({
- key: settingKey,
- value: value || null,
- toast: false,
- });
- }, DEBOUNCE_DELAY);
-
- const onInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
- const newValue = event.currentTarget.value;
- setInputText(newValue);
- debouncedUpdateSystemPrompt(newValue);
- };
-
- return {
- inputText,
- onInputChange,
- };
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.module.css
new file mode 100644
index 00000000000..542d9ab24b8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.module.css
@@ -0,0 +1,20 @@
+.SegmentedControlRoot {
+ align-self: flex-start;
+}
+
+.Label {
+ padding-inline: 0.75rem;
+}
+
+.InstanceTokenLimitInput {
+ max-width: 15rem;
+}
+
+.QuotaMessageInput {
+ max-width: 26rem;
+}
+
+.InputDescription {
+ color: var(--mb-color-text-secondary);
+ line-height: 1rem;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.tsx
new file mode 100644
index 00000000000..9a172a7bf47
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.tsx
@@ -0,0 +1,103 @@
+import { t } from "ttag";
+
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+import { SegmentedControl, Stack, Text, TextInput } from "metabase/ui";
+import type { MetabotLimitPeriod, MetabotLimitType } from "metabase-types/api";
+
+import S from "./GeneralLimitsSettingsSection.module.css";
+import {
+ useAdminSettingWithDebouncedInput,
+ useInstanceLimitDebouncedInput,
+} from "./hooks";
+import {
+ getInstanceLimitInputLabel,
+ getQuotaMessageInputDescription,
+ limitTypeOptions,
+ resetPeriodOptions,
+ sanitizeUsageLimitValue,
+} from "./utils";
+
+export function GeneralLimitsSettingsSection() {
+ const { instanceLimit, handleInstanceLimitInputChange } =
+ useInstanceLimitDebouncedInput();
+ const { handleInputChange: handleLimitTypeChange, inputValue: limitType } =
+ useAdminSettingWithDebouncedInput<MetabotLimitType>(
+ "metabot-limit-unit",
+ "tokens",
+ );
+ const {
+ inputValue: limitPeriod,
+ handleInputChange: handleLimitPeriodChange,
+ } = useAdminSettingWithDebouncedInput<MetabotLimitPeriod>(
+ "metabot-limit-reset-rate",
+ "monthly",
+ );
+ const {
+ inputValue: quotaMessage,
+ handleInputChange: handleQuotaMessageChange,
+ } = useAdminSettingWithDebouncedInput<string | null>(
+ "metabot-quota-reached-message",
+ );
+
+ return (
+ <SettingsSection title={t`Settings and general limits`}>
+ <Stack gap="xl" align="flex-start">
+ <Stack gap="sm">
+ <Text fw="bold">{t`How do you want to limit AI usage?`}</Text>
+ <SegmentedControl
+ data={limitTypeOptions}
+ classNames={{
+ root: S.SegmentedControlRoot,
+ label: S.Label,
+ }}
+ value={limitType}
+ onChange={handleLimitTypeChange}
+ />
+ </Stack>
+ <Stack gap="sm">
+ <Text fw="bold">{t`When should usage limits reset?`}</Text>
+ <SegmentedControl
+ data={resetPeriodOptions}
+ classNames={{
+ root: S.SegmentedControlRoot,
+ label: S.Label,
+ }}
+ value={limitPeriod}
+ onChange={handleLimitPeriodChange}
+ />
+ </Stack>
+ <TextInput
+ label={getInstanceLimitInputLabel(
+ limitType || "tokens",
+ limitPeriod || "monthly",
+ )}
+ description={t`This is the maximum amount all users should be able to use in total.`}
+ placeholder={t`Unlimited`}
+ classNames={{
+ input: S.InstanceTokenLimitInput,
+ description: S.InputDescription,
+ }}
+ type="number"
+ min={1}
+ value={instanceLimit != null ? instanceLimit : ""}
+ onChange={(e) =>
+ handleInstanceLimitInputChange(
+ sanitizeUsageLimitValue(e.target.value),
+ )
+ }
+ />
+ <TextInput
+ label={t`Quota-reached message`}
+ description={getQuotaMessageInputDescription(limitPeriod)}
+ placeholder={t`You have reached your AI usage limit for the current period. Please contact your administrator.`}
+ classNames={{
+ input: S.QuotaMessageInput,
+ description: S.InputDescription,
+ }}
+ value={quotaMessage || ""}
+ onChange={(e) => handleQuotaMessageChange(e.target.value)}
+ />
+ </Stack>
+ </SettingsSection>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.unit.spec.tsx
new file mode 100644
index 00000000000..26d8e9cbeee
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GeneralLimitsSettingsSection.unit.spec.tsx
@@ -0,0 +1,150 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+ setupUpdateSettingEndpoint,
+} from "__support__/server-mocks";
+import {
+ setupAIControlsInstanceLimitEndpoint,
+ setupUpdateAIControlsInstanceLimitEndpoint,
+} from "__support__/server-mocks/metabot";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { MetabotLimitPeriod, MetabotLimitType } from "metabase-types/api";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import { GeneralLimitsSettingsSection } from "./GeneralLimitsSettingsSection";
+
+function setup({
+ limitType = "tokens" as MetabotLimitType,
+ limitPeriod = "monthly" as MetabotLimitPeriod,
+ quotaMessage = "",
+ instanceMaxUsage = null as number | null,
+} = {}) {
+ setupPropertiesEndpoints(
+ createMockSettings({
+ "metabot-limit-unit": limitType,
+ "metabot-limit-reset-rate": limitPeriod,
+ "metabot-quota-reached-message": quotaMessage || null,
+ }),
+ );
+ setupSettingsEndpoints([]);
+ setupUpdateSettingEndpoint();
+ setupAIControlsInstanceLimitEndpoint({ max_usage: instanceMaxUsage });
+ setupUpdateAIControlsInstanceLimitEndpoint();
+
+ renderWithProviders(<GeneralLimitsSettingsSection />);
+}
+
+describe("GeneralLimitsSettingsSection", () => {
+ it("renders the limit type segmented control with saved value", async () => {
+ setup({ limitType: "messages" });
+
+ expect(
+ await screen.findByText("How do you want to limit AI usage?"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("By token usage")).toBeInTheDocument();
+ expect(screen.getByText("By message count")).toBeInTheDocument();
+
+ // The radio input for the saved value should be checked
+ await waitFor(() => {
+ expect(
+ screen.getByRole("radio", { name: "By message count" }),
+ ).toBeChecked();
+ });
+
+ expect(
+ screen.getByRole("radio", { name: "By token usage" }),
+ ).not.toBeChecked();
+ });
+
+ it("renders the reset period segmented control with saved value", async () => {
+ setup({ limitPeriod: "weekly" });
+
+ expect(
+ await screen.findByText("When should usage limits reset?"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Daily")).toBeInTheDocument();
+ expect(screen.getByText("Weekly")).toBeInTheDocument();
+ expect(screen.getByText("Monthly")).toBeInTheDocument();
+
+ // The radio input for the saved value should be checked
+ await waitFor(() => {
+ expect(screen.getByRole("radio", { name: "Weekly" })).toBeChecked();
+ });
+
+ expect(screen.getByRole("radio", { name: "Daily" })).not.toBeChecked();
+ expect(screen.getByRole("radio", { name: "Monthly" })).not.toBeChecked();
+ });
+
+ it("shows token-based label for instance limit when limit type is tokens", async () => {
+ setup({ limitType: "tokens" });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/Total monthly instance limit \(millions of tokens\)/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("shows message-based label for instance limit when limit type is messages", async () => {
+ setup({ limitType: "messages" });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/instance limit \(message count\)/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("populates the instance limit input from API data", async () => {
+ setup({ instanceMaxUsage: 500 });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ await waitFor(() => {
+ expect(screen.getByDisplayValue("500")).toBeInTheDocument();
+ });
+ });
+
+ it("shows 'Unlimited' placeholder when instance limit is null", async () => {
+ setup({ instanceMaxUsage: null });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ expect(screen.getByPlaceholderText("Unlimited")).toBeInTheDocument();
+ });
+
+ it("renders the quota-reached message input with saved value", async () => {
+ setup({ quotaMessage: "You hit the limit!" });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ await waitFor(() => {
+ expect(
+ screen.getByDisplayValue("You hit the limit!"),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("updates limit type setting when user clicks a different option", async () => {
+ setup({ limitType: "tokens" });
+ await screen.findByText("How do you want to limit AI usage?");
+
+ await userEvent.click(screen.getByText("By message count"));
+
+ expect(
+ screen.getByText(/instance limit \(message count\)/),
+ ).toBeInTheDocument();
+ });
+
+ it("updates reset period setting when user clicks a different option", async () => {
+ setup({ limitPeriod: "monthly" });
+ await screen.findByText("When should usage limits reset?");
+
+ await userEvent.click(screen.getByText("Daily"));
+
+ await waitFor(() => {
+ expect(screen.getByText(/daily.*instance limit/i)).toBeInTheDocument();
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.tsx
new file mode 100644
index 00000000000..49244b5b668
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.tsx
@@ -0,0 +1,139 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+import { useListPermissionsGroupsQuery } from "metabase/api";
+import { useSetting } from "metabase/common/hooks";
+import { PLUGIN_TENANTS } from "metabase/plugins";
+import { Tabs } from "metabase/ui";
+import {
+ useGetAIControlsGroupLimitsQuery,
+ useGetAIControlsInstanceLimitQuery,
+ useGetAIControlsTenantLimitsQuery,
+} from "metabase-enterprise/api";
+import type { MetabotLimitPeriod, MetabotLimitType } from "metabase-types/api";
+
+import { GroupLimitsTab } from "./GroupLimitsTab";
+import { TenantLimitsTab } from "./TenantLimitsTab";
+
+type GroupLimitsTabValue = "user-groups" | "tenant-groups" | "specific-tenants";
+
+export function GroupLimitsSettingsSection() {
+ const isUsingTenants = useSetting("use-tenants");
+ const limitPeriod =
+ (useSetting("metabot-limit-reset-rate") as MetabotLimitPeriod) ?? "monthly";
+ const limitType =
+ (useSetting("metabot-limit-unit") as MetabotLimitType) ?? "tokens";
+ const [activeTab, setActiveTab] =
+ useState<GroupLimitsTabValue>("user-groups");
+
+ // Groups data
+ const {
+ data: userGroups = [],
+ isLoading: isLoadingUserGroups,
+ error: userGroupsError,
+ } = useListPermissionsGroupsQuery(
+ isUsingTenants ? { tenancy: "internal" } : undefined,
+ );
+
+ const {
+ data: tenantGroups = [],
+ isLoading: isLoadingTenantGroups,
+ error: tenantGroupsError,
+ } = useListPermissionsGroupsQuery(
+ isUsingTenants ? { tenancy: "external" } : undefined,
+ { skip: !isUsingTenants },
+ );
+
+ const {
+ data: tenants = [],
+ isLoading: isLoadingTenants,
+ error: tenantsError,
+ } = PLUGIN_TENANTS.useListActiveTenants();
+
+ // Usage limits data
+ const {
+ data: groupLimits = [],
+ isLoading: isLoadingGroupLimits,
+ error: groupLimitsError,
+ } = useGetAIControlsGroupLimitsQuery();
+ const { data: instanceLimitData } = useGetAIControlsInstanceLimitQuery();
+ const {
+ data: tenantLimits = [],
+ isLoading: isLoadingTenantLimits,
+ error: tenantLimitsError,
+ } = useGetAIControlsTenantLimitsQuery(undefined, {
+ skip: !isUsingTenants,
+ });
+
+ const instanceLimit = instanceLimitData?.max_usage ?? null;
+
+ const commonLimitPeriodProps = {
+ instanceLimit,
+ limitPeriod,
+ limitType,
+ };
+
+ if (!isUsingTenants) {
+ return (
+ <SettingsSection title={t`Group limits`}>
+ <GroupLimitsTab
+ data-testid="user-group-limits-tab"
+ {...commonLimitPeriodProps}
+ hasGroupsError={!!(userGroupsError || groupLimitsError)}
+ groupLimits={groupLimits}
+ groups={userGroups}
+ isLoading={isLoadingUserGroups || isLoadingGroupLimits}
+ variant="regular-groups"
+ />
+ </SettingsSection>
+ );
+ }
+
+ return (
+ <SettingsSection title={t`Group and tenant limits`}>
+ <Tabs
+ value={activeTab}
+ onChange={(value) => setActiveTab(value as GroupLimitsTabValue)}
+ >
+ <Tabs.List mb="md">
+ <Tabs.Tab value="user-groups">{t`User groups`}</Tabs.Tab>
+ <Tabs.Tab value="tenant-groups">{t`Tenant groups`}</Tabs.Tab>
+ <Tabs.Tab value="specific-tenants">{t`Specific tenants`}</Tabs.Tab>
+ </Tabs.List>
+
+ <Tabs.Panel value="user-groups">
+ <GroupLimitsTab
+ {...commonLimitPeriodProps}
+ hasGroupsError={!!(userGroupsError || groupLimitsError)}
+ groupLimits={groupLimits}
+ groups={userGroups}
+ isLoading={isLoadingUserGroups || isLoadingGroupLimits}
+ variant="regular-groups"
+ />
+ </Tabs.Panel>
+
+ <Tabs.Panel value="tenant-groups">
+ <GroupLimitsTab
+ {...commonLimitPeriodProps}
+ hasGroupsError={!!(tenantGroupsError || groupLimitsError)}
+ groupLimits={groupLimits}
+ groups={tenantGroups}
+ isLoading={isLoadingTenantGroups || isLoadingGroupLimits}
+ variant="tenant-groups"
+ />
+ </Tabs.Panel>
+
+ <Tabs.Panel value="specific-tenants">
+ <TenantLimitsTab
+ {...commonLimitPeriodProps}
+ hasTenantsError={!!(tenantsError || tenantLimitsError)}
+ isLoading={isLoadingTenants || isLoadingTenantLimits}
+ tenantLimits={tenantLimits}
+ tenants={tenants}
+ />
+ </Tabs.Panel>
+ </Tabs>
+ </SettingsSection>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.unit.spec.tsx
new file mode 100644
index 00000000000..3b4dca9de40
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsSettingsSection.unit.spec.tsx
@@ -0,0 +1,108 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupGroupsEndpoint } from "__support__/server-mocks/group";
+import {
+ setupAIControlsGroupLimitsEndpoint,
+ setupAIControlsInstanceLimitEndpoint,
+ setupAIControlsTenantLimitsEndpoint,
+ setupUpdateAIControlsGroupLimitEndpoint,
+} from "__support__/server-mocks/metabot";
+import { renderWithProviders, screen } from "__support__/ui";
+import type { MetabotGroupLimit } from "metabase-types/api";
+import { createMockGroup } from "metabase-types/api/mocks";
+import { createMockSettingsState } from "metabase-types/store/mocks";
+
+import { GroupLimitsSettingsSection } from "./GroupLimitsSettingsSection";
+
+const adminGroup = createMockGroup({
+ id: 1,
+ name: "Administrators",
+ magic_group_type: "admin",
+});
+
+const allUsersGroup = createMockGroup({
+ id: 2,
+ name: "All Users",
+ magic_group_type: "all-internal-users",
+});
+
+const defaultGroups = [adminGroup, allUsersGroup];
+
+function setup({
+ useTenants = false,
+ groups = defaultGroups,
+ groupLimits = [] as MetabotGroupLimit[],
+ instanceMaxUsage = null as number | null,
+} = {}) {
+ setupGroupsEndpoint(groups);
+ setupAIControlsGroupLimitsEndpoint(groupLimits);
+ setupAIControlsInstanceLimitEndpoint({ max_usage: instanceMaxUsage });
+ setupAIControlsTenantLimitsEndpoint([]);
+ setupUpdateAIControlsGroupLimitEndpoint();
+
+ renderWithProviders(<GroupLimitsSettingsSection />, {
+ storeInitialState: {
+ settings: createMockSettingsState({
+ "use-tenants": useTenants,
+ "metabot-limit-unit": "tokens",
+ "metabot-limit-reset-rate": "monthly",
+ }),
+ },
+ });
+}
+
+describe("GroupLimitsSettingsSection", () => {
+ it("renders group names with limit inputs when not using tenants", async () => {
+ setup();
+
+ expect(await screen.findByText("Group limits")).toBeInTheDocument();
+ expect(await screen.findByText("Administrators")).toBeInTheDocument();
+ expect(screen.getByText("All Users")).toBeInTheDocument();
+ });
+
+ it("does not show tabs when not using tenants", async () => {
+ setup({ useTenants: false });
+ await screen.findByText("Group limits");
+
+ expect(screen.queryByText("User groups")).not.toBeInTheDocument();
+ expect(screen.queryByText("Tenant groups")).not.toBeInTheDocument();
+ });
+
+ it("shows tabs when using tenants", async () => {
+ setup({ useTenants: true });
+
+ expect(
+ await screen.findByText("Group and tenant limits"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("User groups")).toBeInTheDocument();
+ expect(screen.getByText("Tenant groups")).toBeInTheDocument();
+ expect(screen.getByText("Specific tenants")).toBeInTheDocument();
+ });
+
+ it("switches between tabs when using tenants", async () => {
+ setup({ useTenants: true });
+ await screen.findByText("Group and tenant limits");
+
+ await userEvent.click(screen.getByText("Specific tenants"));
+
+ expect(
+ screen.getByText(/set total token usage limits for specific tenants/),
+ ).toBeInTheDocument();
+ });
+
+ it("shows 'Unlimited' placeholder when no instance limit is set", async () => {
+ setup({ instanceMaxUsage: null });
+ await screen.findByText("Administrators");
+
+ const inputs = screen.getAllByPlaceholderText("Unlimited");
+ expect(inputs.length).toBeGreaterThan(0);
+ });
+
+ it("shows instance limit as placeholder when set", async () => {
+ setup({ instanceMaxUsage: 1000 });
+ await screen.findByText("Administrators");
+
+ const inputs = screen.getAllByPlaceholderText("1000");
+ expect(inputs.length).toBeGreaterThan(0);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.module.css
new file mode 100644
index 00000000000..68b480a8bd3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.module.css
@@ -0,0 +1,44 @@
+.TableContainer {
+ border: 1px solid var(--mb-color-border);
+ border-radius: 0.5rem;
+ background: var(--mb-color-background-primary);
+ overflow: hidden;
+}
+
+.Table {
+ border-collapse: collapse;
+ table-layout: fixed;
+ width: 100%;
+}
+
+.HeaderCell {
+ background: var(--mb-color-background-primary);
+ border-bottom: 1px solid var(--mb-color-border);
+ box-sizing: border-box;
+ color: var(--mb-color-text-primary);
+ font-size: var(--mantine-font-size-md);
+ font-weight: 600;
+ padding: 0.5rem 1rem;
+ text-align: left;
+ vertical-align: middle;
+ white-space: nowrap;
+}
+
+.BodyRow {
+ border-bottom: 1px solid var(--mb-color-border);
+
+ &:last-child {
+ border-bottom: none;
+ }
+}
+
+.BodyCell {
+ padding: 0.5rem 1rem;
+ vertical-align: middle;
+ font-size: var(--mantine-font-size-md);
+ color: var(--mb-color-text-primary);
+}
+
+.LimitInput {
+ max-width: 10rem;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.tsx
new file mode 100644
index 00000000000..a012e1b6f48
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.tsx
@@ -0,0 +1,132 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+import { isEmpty } from "underscore";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { Box, Stack, Text, TextInput } from "metabase/ui";
+import { useUpdateAIControlsGroupLimitMutation } from "metabase-enterprise/api";
+import type { GroupInfo } from "metabase-types/api";
+
+import S from "./GroupLimitsTab.module.css";
+import {
+ type GroupLimitsMap,
+ type GroupLimitsTabProps,
+ SAVE_DEBOUNCE_MS,
+ getColumnName,
+ getDescription,
+ getErrorMessage,
+ getGroupLimitAriaLabel,
+ sanitizeUsageLimitValue,
+} from "./utils";
+
+export function GroupLimitsTab(props: GroupLimitsTabProps) {
+ const {
+ variant,
+ groups,
+ isLoading,
+ hasGroupsError,
+ limitPeriod,
+ limitType,
+ groupLimits,
+ instanceLimit,
+ } = props;
+
+ const [updateGroupLimit] = useUpdateAIControlsGroupLimitMutation();
+ const [localLimitsMap, setLocalLimitsMap] = useState<GroupLimitsMap>({});
+ const limitsMap = useMemo(
+ () =>
+ groupLimits.reduce(
+ (map, limitObj) => ({
+ ...map,
+ [limitObj.group_id]: limitObj.max_usage,
+ }),
+ {} as GroupLimitsMap,
+ ),
+ [groupLimits],
+ );
+ const { sendErrorToast } = useMetadataToasts();
+
+ // Local state initialization
+ useEffect(() => {
+ if (!isEmpty(localLimitsMap) || isEmpty(limitsMap)) {
+ return;
+ }
+
+ setLocalLimitsMap(limitsMap);
+ }, [limitsMap, localLimitsMap]);
+
+ const debouncedSaveGroupLimit = useDebouncedCallback(
+ async (group: GroupInfo, maxUsage: number | null) => {
+ try {
+ await updateGroupLimit({
+ groupId: group.id,
+ max_usage: maxUsage,
+ }).unwrap();
+ } catch {
+ sendErrorToast(
+ t`Usage limit could not be updated for ${group.name} group`,
+ );
+ }
+ },
+ SAVE_DEBOUNCE_MS,
+ );
+
+ const placeholder =
+ instanceLimit != null ? String(instanceLimit) : t`Unlimited`;
+
+ const handleChange = (group: GroupInfo, inputValue: string) => {
+ const maxUsage = sanitizeUsageLimitValue(inputValue);
+ setLocalLimitsMap((prev) => ({ ...prev, [group.id]: maxUsage }));
+ debouncedSaveGroupLimit(group, maxUsage);
+ };
+
+ return (
+ <Stack gap="xl" data-testid="group-limits-tab">
+ <Text c="text-secondary">{getDescription(variant, limitPeriod)}</Text>
+ <LoadingAndErrorWrapper
+ loading={isLoading}
+ error={getErrorMessage(hasGroupsError, variant)}
+ >
+ {groups.length > 0 && (
+ <Box className={S.TableContainer}>
+ <table className={S.Table}>
+ <thead>
+ <tr>
+ <th className={S.HeaderCell}>
+ {variant === "tenant-groups" ? t`Tenant group` : t`Group`}
+ </th>
+ <th className={S.HeaderCell}>
+ {getColumnName(limitType, limitPeriod)}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {groups.map((group) => (
+ <tr key={group.id} className={S.BodyRow}>
+ <td className={S.BodyCell}>{group.name}</td>
+ <td className={S.BodyCell}>
+ <TextInput
+ placeholder={placeholder}
+ value={localLimitsMap?.[group.id] ?? ""}
+ onChange={(e) => handleChange(group, e.target.value)}
+ classNames={{ input: S.LimitInput }}
+ type="number"
+ min={1}
+ aria-label={getGroupLimitAriaLabel(
+ limitType,
+ group.name,
+ )}
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </Box>
+ )}
+ </LoadingAndErrorWrapper>
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.unit.spec.tsx
new file mode 100644
index 00000000000..61fa8f5ebe4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/GroupLimitsTab.unit.spec.tsx
@@ -0,0 +1,156 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupUpdateAIControlsGroupLimitEndpoint } from "__support__/server-mocks/metabot";
+import { renderWithProviders, screen } from "__support__/ui";
+import type {
+ GroupInfo,
+ MetabotGroupLimit,
+ MetabotLimitPeriod,
+ MetabotLimitType,
+} from "metabase-types/api";
+import { createMockGroup } from "metabase-types/api/mocks";
+
+import { GroupLimitsTab } from "./GroupLimitsTab";
+
+const adminGroup = createMockGroup({
+ id: 1,
+ name: "Administrators",
+ magic_group_type: "admin",
+});
+const marketingGroup = createMockGroup({
+ id: 2,
+ name: "Marketing",
+ magic_group_type: null,
+});
+const defaultGroups = [adminGroup, marketingGroup];
+
+type SetupOpts = Partial<{
+ groups: GroupInfo[];
+ groupLimits: MetabotGroupLimit[];
+ instanceLimit: number | null;
+ limitType: MetabotLimitType;
+ limitPeriod: MetabotLimitPeriod;
+ variant: "regular-groups" | "tenant-groups";
+ hasError: boolean;
+ isLoading: boolean;
+}>;
+
+function setup({
+ groups = defaultGroups,
+ groupLimits = [],
+ instanceLimit = null,
+ limitType = "tokens",
+ limitPeriod = "monthly",
+ variant = "regular-groups",
+ hasError = false,
+ isLoading = false,
+}: SetupOpts = {}) {
+ setupUpdateAIControlsGroupLimitEndpoint();
+
+ renderWithProviders(
+ <GroupLimitsTab
+ hasGroupsError={hasError}
+ groupLimits={groupLimits}
+ groups={groups}
+ instanceLimit={instanceLimit}
+ isLoading={isLoading}
+ limitPeriod={limitPeriod}
+ limitType={limitType}
+ variant={variant}
+ />,
+ );
+}
+
+describe("GroupLimitsTab", () => {
+ it("renders a row for each group with a limit input", () => {
+ setup();
+
+ expect(screen.getByText("Administrators")).toBeInTheDocument();
+ expect(screen.getByText("Marketing")).toBeInTheDocument();
+
+ const adminInput = screen.getByRole("spinbutton", {
+ name: /Administrators/,
+ });
+ expect(adminInput).toBeInTheDocument();
+ });
+
+ it("shows token-based column header when limitType is tokens", () => {
+ setup({ limitType: "tokens" });
+
+ expect(screen.getByText(/Max tokens per user/)).toBeInTheDocument();
+ });
+
+ it("shows message-based column header when limitType is messages", () => {
+ setup({ limitType: "messages" });
+
+ expect(screen.getByText(/Max messages per user/)).toBeInTheDocument();
+ });
+
+ it("shows 'Group' column header for regular-groups variant", () => {
+ setup({ variant: "regular-groups" });
+ expect(screen.getByText("Group")).toBeInTheDocument();
+ });
+
+ it("shows 'Tenant group' column header for tenant-groups variant", () => {
+ setup({ variant: "tenant-groups" });
+ expect(screen.getByText("Tenant group")).toBeInTheDocument();
+ });
+
+ it("populates inputs from existing group limits", () => {
+ setup({
+ groupLimits: [
+ { group_id: 1, max_usage: 100 },
+ { group_id: 2, max_usage: 50 },
+ ],
+ });
+
+ expect(screen.getByDisplayValue("100")).toBeInTheDocument();
+ expect(screen.getByDisplayValue("50")).toBeInTheDocument();
+ });
+
+ it("shows 'Unlimited' placeholder when instance limit is null", () => {
+ setup({ instanceLimit: null });
+
+ const inputs = screen.getAllByPlaceholderText("Unlimited");
+ expect(inputs).toHaveLength(2);
+ });
+
+ it("shows instance limit value as placeholder when set", () => {
+ setup({ instanceLimit: 500 });
+
+ const inputs = screen.getAllByPlaceholderText("500");
+ expect(inputs).toHaveLength(2);
+ });
+
+ it("updates the input value when user types", async () => {
+ setup();
+
+ const adminInput = screen.getByRole("spinbutton", {
+ name: /Administrators/,
+ });
+ await userEvent.type(adminInput, "250");
+
+ expect(adminInput).toHaveValue(250);
+ });
+
+ it("shows error message when error is present", () => {
+ setup({ hasError: true, groups: undefined });
+ expect(screen.getByText("Error loading groups")).toBeInTheDocument();
+ });
+
+ it("shows tenant-specific error when variant is tenant-groups", () => {
+ setup({
+ hasError: true,
+ groups: undefined,
+ variant: "tenant-groups",
+ });
+
+ expect(screen.getByText("Error loading tenant groups")).toBeInTheDocument();
+ });
+
+ it("uses the correct period noun in column headers", () => {
+ setup({ limitPeriod: "weekly", limitType: "tokens" });
+
+ expect(screen.getByText(/each week/)).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/index.ts
new file mode 100644
index 00000000000..9b61e304c29
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/index.ts
@@ -0,0 +1 @@
+export { GroupLimitsTab } from "./GroupLimitsTab";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/utils.ts
new file mode 100644
index 00000000000..78b884377d5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/GroupLimitsTab/utils.ts
@@ -0,0 +1,103 @@
+import { c, t } from "ttag";
+
+import type {
+ GroupInfo,
+ MetabotGroupLimit,
+ MetabotLimitPeriod,
+ MetabotLimitType,
+} from "metabase-types/api";
+export { SAVE_DEBOUNCE_MS, sanitizeUsageLimitValue } from "../../utils";
+
+export type GroupLimitsTabProps = {
+ groupLimits: MetabotGroupLimit[];
+ groups: GroupInfo[];
+ hasGroupsError: boolean;
+ instanceLimit: number | null;
+ isLoading: boolean;
+ limitPeriod: MetabotLimitPeriod;
+ limitType: MetabotLimitType;
+ variant: "regular-groups" | "tenant-groups";
+};
+
+export type GroupLimitsMap = Record<number, number | null>;
+
+export function getGroupLimitAriaLabel(
+ limitType: MetabotLimitType,
+ groupName: string,
+) {
+ if (limitType === "tokens") {
+ return c("{0} is the group name")
+ .t`Max tokens per user for ${groupName} (millions)`;
+ }
+
+ return c("{0} is the group name").t`Max messages per user for ${groupName}`;
+}
+
+const columnNameMap: Record<
+ MetabotLimitType,
+ Record<MetabotLimitPeriod, string>
+> = {
+ get tokens() {
+ return {
+ daily: t`Max tokens per user each day (millions)`,
+ weekly: t`Max tokens per user each week (millions)`,
+ monthly: t`Max tokens per user each month (millions)`,
+ };
+ },
+ get messages() {
+ return {
+ daily: t`Max messages per user each day`,
+ weekly: t`Max messages per user each week`,
+ monthly: t`Max messages per user each month`,
+ };
+ },
+};
+
+export function getColumnName(
+ limitType: MetabotLimitType,
+ limitPeriod: MetabotLimitPeriod,
+): string {
+ return columnNameMap[limitType][limitPeriod];
+}
+
+const descriptionMap: Record<
+ GroupLimitsTabProps["variant"],
+ Record<MetabotLimitPeriod, string>
+> = {
+ get ["tenant-groups"]() {
+ return {
+ daily: t`Daily limits for each individual user in each tenant group.`,
+ weekly: t`Weekly limits for each individual user in each tenant group.`,
+ monthly: t`Monthly limits for each individual user in each tenant group.`,
+ };
+ },
+ get ["regular-groups"]() {
+ return {
+ daily: t`Daily limits for each individual user in each group.`,
+ weekly: t`Weekly limits for each individual user in each group.`,
+ monthly: t`Monthly limits for each individual user in each group.`,
+ };
+ },
+};
+
+export function getDescription(
+ variant: GroupLimitsTabProps["variant"],
+ limitPeriod: MetabotLimitPeriod,
+): string {
+ const additionalDesc = t`If a user belongs to more than one group, they'll be given the highest limit among all the groups they belong to.`;
+
+ return `${descriptionMap[variant][limitPeriod]} ${additionalDesc}`;
+}
+
+export function getErrorMessage(
+ hasError: boolean,
+ variant: GroupLimitsTabProps["variant"],
+) {
+ if (hasError) {
+ return variant === "tenant-groups"
+ ? t`Error loading tenant groups`
+ : t`Error loading groups`;
+ }
+
+ return null;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.tsx
new file mode 100644
index 00000000000..e772aafc16d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.tsx
@@ -0,0 +1,168 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useEffect, useMemo, useState } from "react";
+import { c, t } from "ttag";
+import { isEmpty } from "underscore";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { Alert, Box, Icon, Stack, Text, TextInput } from "metabase/ui";
+import { useUpdateAIControlsTenantLimitMutation } from "metabase-enterprise/api";
+import type { Tenant } from "metabase-types/api";
+
+import S from "../GroupLimitsTab/GroupLimitsTab.module.css";
+
+import {
+ SAVE_DEBOUNCE_MS,
+ type SpecificTenantsTabProps,
+ type TenantLimitsMap,
+ getColumnName,
+ getDescription,
+ getInputLabel,
+ sanitizeUsageLimitValue,
+} from "./utils";
+
+export function TenantLimitsTab(props: SpecificTenantsTabProps) {
+ const {
+ hasTenantsError,
+ instanceLimit,
+ isLoading,
+ limitPeriod,
+ limitType,
+ tenantLimits,
+ tenants,
+ } = props;
+ const [search, setSearch] = useState("");
+ const [updateTenantLimit] = useUpdateAIControlsTenantLimitMutation();
+ const [localLimitsMap, setLocalLimitsMap] = useState<TenantLimitsMap>({});
+ const limitsMap = useMemo(
+ () =>
+ tenantLimits.reduce(
+ (map, limitObj) => ({
+ ...map,
+ [limitObj.tenant_id]: limitObj.max_usage,
+ }),
+ {} as TenantLimitsMap,
+ ),
+ [tenantLimits],
+ );
+ const { sendErrorToast } = useMetadataToasts();
+
+ // Local state initialization
+ useEffect(() => {
+ if (!isEmpty(localLimitsMap) || isEmpty(limitsMap)) {
+ return;
+ }
+
+ setLocalLimitsMap(limitsMap);
+ }, [limitsMap, localLimitsMap]);
+
+ const debouncedSaveTenantLimit = useDebouncedCallback(
+ async (tenant: Tenant, maxUsage: number | null) => {
+ try {
+ await updateTenantLimit({
+ tenantId: tenant.id,
+ max_usage: maxUsage,
+ }).unwrap();
+ } catch {
+ sendErrorToast(
+ c("{0} is the tenant name")
+ .t`Usage limit could not be updated for ${tenant.name} tenant`,
+ );
+ }
+ },
+ SAVE_DEBOUNCE_MS,
+ );
+
+ const handleChange = (tenant: Tenant, inputValue: string) => {
+ const maxUsage = sanitizeUsageLimitValue(inputValue);
+ setLocalLimitsMap((prev: Record<number, number | null>) => ({
+ ...prev,
+ [tenant.id]: maxUsage,
+ }));
+ debouncedSaveTenantLimit(tenant, maxUsage);
+ };
+
+ const filteredTenants = useMemo(() => {
+ if (!tenants.length) {
+ return [];
+ }
+
+ const query = search.trim().toLowerCase();
+
+ if (!query) {
+ return tenants;
+ }
+
+ return tenants.filter((tenant) =>
+ tenant.name.toLowerCase().includes(query),
+ );
+ }, [tenants, search]);
+
+ const noTenantsToShow =
+ tenants?.length === 0 && !hasTenantsError && !isLoading;
+ const placeholder =
+ instanceLimit != null ? String(instanceLimit) : t`Unlimited`;
+
+ return (
+ <Stack gap="xl" data-testid="tenant-limits-tab">
+ <Text c="text-secondary">{getDescription(limitType)}</Text>
+ <LoadingAndErrorWrapper
+ loading={isLoading}
+ error={hasTenantsError ? t`Error loading tenants` : null}
+ >
+ {noTenantsToShow ? (
+ <Alert mb="md" variant="error" icon={<Icon name="warning" />}>
+ {t`No tenants to show`}
+ </Alert>
+ ) : (
+ <Stack gap="xl">
+ <TextInput
+ placeholder={t`Search...`}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ leftSection={<Icon name="search" />}
+ />
+ {tenants.length > 0 && (
+ <Box className={S.TableContainer}>
+ <table className={S.Table}>
+ <thead>
+ <tr>
+ <th className={S.HeaderCell}>{t`Tenant`}</th>
+ <th className={S.HeaderCell}>
+ {getColumnName(limitType, limitPeriod)}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredTenants.map((tenant) => (
+ <tr key={tenant.id} className={S.BodyRow}>
+ <td className={S.BodyCell}>{tenant.name}</td>
+ <td className={S.BodyCell}>
+ <TextInput
+ placeholder={placeholder}
+ value={localLimitsMap?.[tenant.id] ?? ""}
+ onChange={(e) =>
+ handleChange(tenant, e.target.value)
+ }
+ classNames={{ input: S.LimitInput }}
+ type="number"
+ min={1}
+ aria-label={getInputLabel(
+ tenant.name,
+ limitType,
+ limitPeriod,
+ )}
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </Box>
+ )}
+ </Stack>
+ )}
+ </LoadingAndErrorWrapper>
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.unit.spec.tsx
new file mode 100644
index 00000000000..e5827c06fed
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/TenantLimitsTab.unit.spec.tsx
@@ -0,0 +1,148 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupUpdateAIControlsTenantLimitEndpoint } from "__support__/server-mocks/metabot";
+import { renderWithProviders, screen } from "__support__/ui";
+import type {
+ MetabotLimitPeriod,
+ MetabotLimitType,
+ MetabotTenantLimit,
+ Tenant,
+} from "metabase-types/api";
+
+import { TenantLimitsTab } from "./TenantLimitsTab";
+
+const createMockTenant = (opts?: Partial<Tenant>): Tenant => ({
+ id: 1,
+ name: "Acme Corp",
+ slug: "acme-corp",
+ member_count: 10,
+ is_active: true,
+ attributes: null,
+ tenant_collection_id: null,
+ ...opts,
+});
+
+const tenant1 = createMockTenant({ id: 1, name: "Acme Corp", slug: "acme" });
+const tenant2 = createMockTenant({
+ id: 2,
+ name: "Beta Inc",
+ slug: "beta-inc",
+});
+const defaultTenants = [tenant1, tenant2];
+
+type SetupOpts = Partial<{
+ tenants: Tenant[];
+ tenantLimits: MetabotTenantLimit[];
+ instanceLimit: number | null;
+ limitType: MetabotLimitType;
+ limitPeriod: MetabotLimitPeriod;
+ hasError: boolean;
+ isLoading: boolean;
+}>;
+
+function setup({
+ tenants = defaultTenants,
+ tenantLimits = [],
+ instanceLimit = null,
+ limitType = "tokens",
+ limitPeriod = "monthly",
+ hasError = false,
+ isLoading = false,
+}: SetupOpts = {}) {
+ setupUpdateAIControlsTenantLimitEndpoint();
+
+ renderWithProviders(
+ <TenantLimitsTab
+ hasTenantsError={hasError}
+ instanceLimit={instanceLimit}
+ isLoading={isLoading}
+ limitPeriod={limitPeriod}
+ limitType={limitType}
+ tenantLimits={tenantLimits}
+ tenants={tenants}
+ />,
+ );
+}
+
+describe("TenantLimitsTab", () => {
+ it("renders a row for each tenant with a limit input", () => {
+ setup();
+
+ expect(screen.getByText("Acme Corp")).toBeInTheDocument();
+ expect(screen.getByText("Beta Inc")).toBeInTheDocument();
+ });
+
+ it("shows token-based column header when limitType is tokens", () => {
+ setup({ limitType: "tokens" });
+
+ expect(screen.getByText(/Max total.*token usage/)).toBeInTheDocument();
+ });
+
+ it("shows message-based column header when limitType is messages", () => {
+ setup({ limitType: "messages" });
+
+ expect(screen.getByText(/Max total.*messages/)).toBeInTheDocument();
+ });
+
+ it("populates inputs from existing tenant limits", () => {
+ setup({
+ tenantLimits: [
+ { tenant_id: 1, max_usage: 200 },
+ { tenant_id: 2, max_usage: 75 },
+ ],
+ });
+
+ expect(screen.getByDisplayValue("200")).toBeInTheDocument();
+ expect(screen.getByDisplayValue("75")).toBeInTheDocument();
+ });
+
+ it("shows 'Unlimited' placeholder when instance limit is null", () => {
+ setup({ instanceLimit: null });
+
+ const inputs = screen.getAllByPlaceholderText("Unlimited");
+ expect(inputs.length).toBeGreaterThan(0);
+ });
+
+ it("filters tenants by search query", async () => {
+ setup();
+
+ const searchInput = screen.getByPlaceholderText("Search...");
+ await userEvent.type(searchInput, "Acme");
+
+ expect(screen.getByText("Acme Corp")).toBeInTheDocument();
+ expect(screen.queryByText("Beta Inc")).not.toBeInTheDocument();
+ });
+
+ it("shows all tenants when search is cleared", async () => {
+ setup();
+
+ const searchInput = screen.getByPlaceholderText("Search...");
+ await userEvent.type(searchInput, "Acme");
+ await userEvent.clear(searchInput);
+
+ expect(screen.getByText("Acme Corp")).toBeInTheDocument();
+ expect(screen.getByText("Beta Inc")).toBeInTheDocument();
+ });
+
+ it("shows 'No tenants to show' when tenants list is empty", () => {
+ setup({ tenants: [] });
+
+ expect(screen.getByText("No tenants to show")).toBeInTheDocument();
+ });
+
+ it("shows error message when error is present", () => {
+ setup({ hasError: true, tenants: undefined });
+ expect(screen.getByText("Error loading tenants")).toBeInTheDocument();
+ });
+
+ it("updates input value when user types", async () => {
+ setup();
+
+ const acmeInput = screen.getByRole("spinbutton", {
+ name: /Acme Corp/,
+ });
+ await userEvent.type(acmeInput, "300");
+
+ expect(acmeInput).toHaveValue(300);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/index.ts
new file mode 100644
index 00000000000..26aee46d99b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/index.ts
@@ -0,0 +1 @@
+export { TenantLimitsTab } from "./TenantLimitsTab";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/utils.ts
new file mode 100644
index 00000000000..f712a480b04
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/TenantLimitsTab/utils.ts
@@ -0,0 +1,88 @@
+import { c, t } from "ttag";
+
+import type {
+ MetabotLimitPeriod,
+ MetabotLimitType,
+ MetabotTenantLimit,
+ Tenant,
+} from "metabase-types/api";
+
+export { SAVE_DEBOUNCE_MS, sanitizeUsageLimitValue } from "../../utils";
+
+export type SpecificTenantsTabProps = {
+ hasTenantsError: boolean;
+ instanceLimit: number | null;
+ isLoading: boolean;
+ limitPeriod: MetabotLimitPeriod;
+ limitType: MetabotLimitType;
+ tenantLimits: MetabotTenantLimit[];
+ tenants: Tenant[];
+};
+
+export type TenantLimitsMap = Record<number, number | null>;
+
+export function getInputLabel(
+ tenantName: string,
+ limitType: MetabotLimitType,
+ limitPeriod: MetabotLimitPeriod,
+): string {
+ const inputLabelMap: Record<
+ MetabotLimitType,
+ Record<MetabotLimitPeriod, string>
+ > = {
+ tokens: {
+ daily: c("{0} is the tenant name")
+ .t`Max total daily tokens for ${tenantName} (millions)`,
+ weekly: c("{0} is the tenant name")
+ .t`Max total weekly tokens for ${tenantName} (millions)`,
+ monthly: c("{0} is the tenant name")
+ .t`Max total monthly tokens for ${tenantName} (millions)`,
+ },
+ messages: {
+ daily: c("{0} is the tenant name")
+ .t`Max total daily messages for ${tenantName}`,
+ weekly: c("{0} is the tenant name")
+ .t`Max total weekly messages for ${tenantName}`,
+ monthly: c("{0} is the tenant name")
+ .t`Max total monthly messages for ${tenantName}`,
+ },
+ };
+
+ return inputLabelMap[limitType][limitPeriod];
+}
+
+const columnNameMap: Record<
+ MetabotLimitType,
+ Record<MetabotLimitPeriod, string>
+> = {
+ get tokens() {
+ return {
+ daily: t`Max total daily token usage (millions)`,
+ weekly: t`Max total weekly token usage (millions)`,
+ monthly: t`Max total monthly token usage (millions)`,
+ };
+ },
+ get messages() {
+ return {
+ daily: t`Max total daily messages`,
+ weekly: t`Max total weekly messages`,
+ monthly: t`Max total monthly messages`,
+ };
+ },
+};
+
+export function getColumnName(
+ limitType: MetabotLimitType,
+ limitPeriod: MetabotLimitPeriod,
+) {
+ return columnNameMap[limitType][limitPeriod];
+}
+
+export function getDescription(limitType: MetabotLimitType) {
+ const descriptionMap: Record<MetabotLimitType, string> = {
+ tokens: t`Here you can set total token usage limits for specific tenants.`,
+ messages: t`Here you can set total message count limits for specific tenants.`,
+ };
+
+ return descriptionMap[limitType];
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/index.ts
new file mode 100644
index 00000000000..ba18eff36fb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/GroupLimitsSettingsSection/index.ts
@@ -0,0 +1 @@
+export { GroupLimitsSettingsSection } from "./GroupLimitsSettingsSection";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx
index 69a3a2e8a24..f728d406c6b 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx
@@ -1,22 +1,15 @@
import { t } from "ttag";
-import {
- SettingsPageWrapper,
- SettingsSection,
-} from "metabase/admin/components/SettingsSection";
-import { Group, Icon, Text } from "metabase/ui";
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+
+import { GeneralLimitsSettingsSection } from "./GeneralLimitsSettingsSection";
+import { GroupLimitsSettingsSection } from "./GroupLimitsSettingsSection";
export function MetabotUsageLimitsPage() {
return (
<SettingsPageWrapper title={t`AI usage limits`} mt="sm">
- <SettingsSection>
- <Group>
- <Icon name="ai" />
- <Text fz="md" c="text-secondary">
- {t`Not implemented yet. Come back later.`}
- </Text>
- </Group>
- </SettingsSection>
+ <GeneralLimitsSettingsSection />
+ <GroupLimitsSettingsSection />
</SettingsPageWrapper>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/index.ts
new file mode 100644
index 00000000000..18898bc0896
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useAdminSettingWithDebouncedInput } from "metabase-enterprise/ai-controls/hooks";
+export { useInstanceLimitDebouncedInput } from "./useInstanceLimitDebouncedInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/useInstanceLimitDebouncedInput.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/useInstanceLimitDebouncedInput.ts
new file mode 100644
index 00000000000..e946292853c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/hooks/useInstanceLimitDebouncedInput.ts
@@ -0,0 +1,50 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useCallback, useEffect, useState } from "react";
+import { t } from "ttag";
+
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ useGetAIControlsInstanceLimitQuery,
+ useUpdateAIControlsInstanceLimitMutation,
+} from "metabase-enterprise/api";
+
+import { SAVE_DEBOUNCE_MS } from "../utils";
+
+export function useInstanceLimitDebouncedInput() {
+ const { data: settingValue } = useGetAIControlsInstanceLimitQuery();
+ const [updateInstanceLimit] = useUpdateAIControlsInstanceLimitMutation();
+ const initialInstanceLimit = settingValue?.max_usage;
+ const [instanceLimit, setInstanceLimit] = useState<number | null>();
+ const { sendErrorToast } = useMetadataToasts();
+
+ useEffect(() => {
+ // Initialize instance limit local state
+ if (instanceLimit === undefined && initialInstanceLimit !== undefined) {
+ setInstanceLimit(initialInstanceLimit);
+ }
+ }, [initialInstanceLimit, instanceLimit]);
+
+ const debouncedSaveInstanceLimit = useDebouncedCallback(
+ async (maxUsage: number | null) => {
+ try {
+ await updateInstanceLimit({ max_usage: maxUsage }).unwrap();
+ } catch {
+ sendErrorToast(t`Failed to update instance limit`);
+ }
+ },
+ SAVE_DEBOUNCE_MS,
+ );
+
+ const handleInstanceLimitInputChange = useCallback(
+ (maxUsage: number | null) => {
+ setInstanceLimit(maxUsage);
+ debouncedSaveInstanceLimit(maxUsage);
+ },
+ [debouncedSaveInstanceLimit],
+ );
+
+ return {
+ instanceLimit,
+ handleInstanceLimitInputChange,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/utils.ts
new file mode 100644
index 00000000000..efa115f8a25
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/utils.ts
@@ -0,0 +1,108 @@
+import { t } from "ttag";
+
+import type { SegmentedControlItem } from "metabase/ui";
+import type { MetabotLimitPeriod, MetabotLimitType } from "metabase-types/api";
+
+export const SAVE_DEBOUNCE_MS = 500;
+export const MAX_LIMIT_INPUT = 999999999;
+
+/**
+ * Sanitizes the input value for a usage limit.
+ * Return an integer value or null if the input is empty.
+ */
+export const sanitizeUsageLimitValue = (inputValue: string) => {
+ let sanitizedStrValue = inputValue.trim();
+
+ if (sanitizedStrValue !== "") {
+ sanitizedStrValue = Math.min(
+ Number(inputValue),
+ MAX_LIMIT_INPUT,
+ ).toString();
+ }
+
+ return sanitizedStrValue ? parseInt(sanitizedStrValue) : null;
+};
+
+type LimitTypeOption = SegmentedControlItem<MetabotLimitType>;
+type PeriodOption = SegmentedControlItem<MetabotLimitPeriod>;
+
+export const limitTypeOptions: LimitTypeOption[] = [
+ {
+ value: "tokens",
+ get label() {
+ return t`By token usage`;
+ },
+ },
+ {
+ value: "messages",
+ get label() {
+ return t`By message count`;
+ },
+ },
+];
+
+export const resetPeriodOptions: PeriodOption[] = [
+ {
+ value: "daily",
+ get label() {
+ return t`Daily`;
+ },
+ },
+ {
+ value: "weekly",
+ get label() {
+ return t`Weekly`;
+ },
+ },
+ {
+ value: "monthly",
+ get label() {
+ return t`Monthly`;
+ },
+ },
+];
+
+const instanceLimitLabelMap: Record<
+ MetabotLimitType,
+ Record<MetabotLimitPeriod, string>
+> = {
+ get tokens() {
+ return {
+ daily: t`Total daily instance limit (millions of tokens)`,
+ weekly: t`Total weekly instance limit (millions of tokens)`,
+ monthly: t`Total monthly instance limit (millions of tokens)`,
+ };
+ },
+ get messages() {
+ return {
+ daily: t`Total daily instance limit (message count)`,
+ weekly: t`Total weekly instance limit (message count)`,
+ monthly: t`Total monthly instance limit (message count)`,
+ };
+ },
+};
+
+export function getInstanceLimitInputLabel(
+ limitType: MetabotLimitType = "tokens",
+ limitPeriod: MetabotLimitPeriod = "monthly",
+) {
+ return instanceLimitLabelMap[limitType][limitPeriod];
+}
+
+const messageDescriptionMap: Record<MetabotLimitPeriod, string> = {
+ get daily() {
+ return t`The message shown to users when they reach their daily quota.`;
+ },
+ get weekly() {
+ return t`The message shown to users when they reach their weekly quota.`;
+ },
+ get monthly() {
+ return t`The message shown to users when they reach their monthly quota.`;
+ },
+};
+
+export function getQuotaMessageInputDescription(
+ limitPeriod: MetabotLimitPeriod = "monthly",
+) {
+ return messageDescriptionMap[limitPeriod];
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts
new file mode 100644
index 00000000000..2d8440911db
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts
@@ -0,0 +1,104 @@
+import type {
+ MetabotGroupLimit,
+ MetabotInstanceLimit,
+ MetabotPermissionsResponse,
+ MetabotTenantLimit,
+ UpdateMetabotPermissionsRequest,
+} from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import { invalidateTags, listTag } from "./tags";
+
+export const aiControlsApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ getAIControlsGroupPermissions: builder.query<
+ MetabotPermissionsResponse,
+ void
+ >({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/ai-controls/permissions",
+ }),
+ providesTags: () => [listTag("ai-controls-permissions")],
+ }),
+ updateAIControlsGroupPermissions: builder.mutation<
+ void,
+ UpdateMetabotPermissionsRequest
+ >({
+ query: (body) => ({
+ method: "PUT",
+ url: "/api/ee/ai-controls/permissions",
+ body,
+ }),
+ invalidatesTags: [listTag("ai-controls-permissions")],
+ }),
+ getAIControlsInstanceLimit: builder.query<MetabotInstanceLimit, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/ai-controls/usage/instance",
+ }),
+ providesTags: () => [listTag("ai-controls-usage-instance-limit")],
+ }),
+ updateAIControlsInstanceLimit: builder.mutation<
+ MetabotInstanceLimit,
+ MetabotInstanceLimit
+ >({
+ query: (body) => ({
+ method: "PUT",
+ url: "/api/ee/ai-controls/usage/instance",
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("ai-controls-usage-instance-limit")]),
+ }),
+ getAIControlsGroupLimits: builder.query<MetabotGroupLimit[], void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/ai-controls/usage/group",
+ }),
+ providesTags: () => [listTag("ai-controls-usage-group-limits")],
+ }),
+ updateAIControlsGroupLimit: builder.mutation<
+ MetabotGroupLimit,
+ { groupId: number; max_usage: number | null }
+ >({
+ query: ({ groupId, max_usage }) => ({
+ method: "PUT",
+ url: `/api/ee/ai-controls/usage/group/${groupId}`,
+ body: { max_usage },
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("ai-controls-usage-group-limits")]),
+ }),
+ getAIControlsTenantLimits: builder.query<MetabotTenantLimit[], void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/ai-controls/usage/tenant",
+ }),
+ providesTags: () => [listTag("ai-controls-usage-tenant-limits")],
+ }),
+ updateAIControlsTenantLimit: builder.mutation<
+ MetabotTenantLimit,
+ { tenantId: number; max_usage: number | null }
+ >({
+ query: ({ tenantId, max_usage }) => ({
+ method: "PUT",
+ url: `/api/ee/ai-controls/usage/tenant/${tenantId}`,
+ body: { max_usage },
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("ai-controls-usage-tenant-limits")]),
+ }),
+ }),
+});
+
+export const {
+ useGetAIControlsGroupPermissionsQuery,
+ useUpdateAIControlsGroupPermissionsMutation,
+ useGetAIControlsInstanceLimitQuery,
+ useUpdateAIControlsInstanceLimitMutation,
+ useGetAIControlsGroupLimitsQuery,
+ useUpdateAIControlsGroupLimitMutation,
+ useGetAIControlsTenantLimitsQuery,
+ useUpdateAIControlsTenantLimitMutation,
+} = aiControlsApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index 4fdf6333723..f86311916fc 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -1,3 +1,4 @@
+export * from "./ai-controls";
export * from "./api";
export * from "./audit-info";
export * from "./billing-info";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 5113dfaf208..3edb67456d1 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -52,6 +52,10 @@ export const ENTERPRISE_TAG_TYPES = [
"support-access-grant",
"support-access-grant-current",
"library-collection",
+ "ai-controls-permissions",
+ "ai-controls-usage-instance-limit",
+ "ai-controls-usage-group-limits",
+ "ai-controls-usage-tenant-limits",
] as const;
export type EnterpriseTagType = TagType | (typeof ENTERPRISE_TAG_TYPES)[number];
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 450cacf2cf0..297c1a6300c 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -28,6 +28,7 @@ import {
import { getIsTenantUser, getUserIsAdmin } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Text } from "metabase/ui";
+import { useListTenantsQuery } from "metabase-enterprise/api";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { EditUserStrategyModal } from "./EditUserStrategyModal";
@@ -72,6 +73,13 @@ export function initializePlugin() {
if (hasPremiumFeature("tenants")) {
PLUGIN_TENANTS.isEnabled = true;
+ PLUGIN_TENANTS.useListActiveTenants = () => {
+ const { data, isLoading, error } = useListTenantsQuery({
+ status: "active",
+ });
+ return { data: data?.data, isLoading, error };
+ };
+
// Register tenant collection permissions tabs and routes
PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.push({
name: t`Shared collections`,
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 5f09906bcd9..d75a903320b 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -347,3 +347,15 @@ export type UserMetabotPermissions = {
export type UserMetabotPermissionsResponse = {
permissions: UserMetabotPermissions;
};
+
+export type MetabotLimitPeriod = "daily" | "weekly" | "monthly";
+export type MetabotLimitType = "tokens" | "messages";
+
+/* Metabot v3 - Usage Limits */
+
+export type MetabotInstanceLimit = { max_usage: number | null };
+export type MetabotGroupLimit = { group_id: number; max_usage: number };
+export type MetabotTenantLimit = {
+ tenant_id: number;
+ max_usage: number | null;
+};
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index a096042624c..7f549ec45fd 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -371,6 +371,9 @@ export const createMockSettings = (
"metabot-name": "Metabot",
"metabot-icon": "metabot",
"metabot-show-illustrations": true,
+ "metabot-limit-unit": "tokens",
+ "metabot-limit-reset-rate": "monthly",
+ "metabot-quota-reached-message": null,
"metabot-chat-system-prompt": null,
"metabot-nlq-system-prompt": null,
"metabot-sql-system-prompt": null,
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index d009c2bc0a0..e7e869693b1 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -7,6 +7,7 @@ import type { InputSettingType } from "./actions";
import type { DashboardId } from "./dashboard";
import type { DatabaseId } from "./database";
import type { GroupId } from "./group";
+import type { MetabotLimitPeriod, MetabotLimitType } from "./metabot";
import type { UserId } from "./user";
export interface OidcAuthProvider {
@@ -510,6 +511,7 @@ interface SettingsManagerSettings {
"bcc-enabled?": boolean;
"llm-openai-api-key"?: string;
"llm-anthropic-api-key"?: string | null;
+ "llm-anthropic-api-base-url"?: string | null;
"llm-openrouter-api-key"?: string | null;
"openai-api-key": string | null;
"openai-available-models"?: OpenAiModel[];
@@ -594,6 +596,9 @@ interface PublicSettings {
"metabot-name": string;
"metabot-icon": string | null;
"metabot-show-illustrations": boolean;
+ "metabot-limit-unit": MetabotLimitType;
+ "metabot-limit-reset-rate": MetabotLimitPeriod;
+ "metabot-quota-reached-message": string | null;
"metabot-chat-system-prompt": string | null;
"metabot-nlq-system-prompt": string | null;
"metabot-sql-system-prompt": string | null;
diff --git a/frontend/src/metabase/api/metabot.ts b/frontend/src/metabase/api/metabot.ts
index 4881075c805..afa23c40d64 100644
--- a/frontend/src/metabase/api/metabot.ts
+++ b/frontend/src/metabase/api/metabot.ts
@@ -5,13 +5,11 @@ import type {
MetabotGenerateContentResponse,
MetabotId,
MetabotInfo,
- MetabotPermissionsResponse,
MetabotProvider,
MetabotSettingsResponse,
MetabotSlackSettings,
SuggestedMetabotPromptsRequest,
SuggestedMetabotPromptsResponse,
- UpdateMetabotPermissionsRequest,
UpdateMetabotSettingsRequest,
UserMetabotPermissionsResponse,
} from "metabase-types/api";
@@ -136,13 +134,6 @@ export const metabotApi = Api.injectEndpoints({
}),
invalidatesTags: ["session-properties"],
}),
- getMetabotPermissions: builder.query<MetabotPermissionsResponse, void>({
- query: () => ({
- method: "GET",
- url: "/api/ee/ai-controls/permissions",
- }),
- providesTags: () => [listTag("metabot-permissions")],
- }),
getUserMetabotPermissions: builder.query<
UserMetabotPermissionsResponse,
void
@@ -153,17 +144,6 @@ export const metabotApi = Api.injectEndpoints({
}),
providesTags: () => [listTag("metabot-permissions")],
}),
- updateMetabotPermissions: builder.mutation<
- void,
- UpdateMetabotPermissionsRequest
- >({
- query: (body) => ({
- method: "PUT",
- url: "/api/ee/ai-controls/permissions",
- body,
- }),
- invalidatesTags: [listTag("metabot-permissions")],
- }),
}),
});
@@ -178,7 +158,5 @@ export const {
useLazyMetabotGenerateContentQuery,
useSubmitMetabotFeedbackMutation,
useUpdateMetabotSlackSettingsMutation,
- useGetMetabotPermissionsQuery,
useGetUserMetabotPermissionsQuery,
- useUpdateMetabotPermissionsMutation,
} = metabotApi;
diff --git a/frontend/src/metabase/api/utils/settings.ts b/frontend/src/metabase/api/utils/settings.ts
index 67d0531b7c2..53e1a78c052 100644
--- a/frontend/src/metabase/api/utils/settings.ts
+++ b/frontend/src/metabase/api/utils/settings.ts
@@ -94,7 +94,9 @@ export const useAdminSetting = <SettingName extends EnterpriseSettingKey>(
[updateSettings, sendToast],
);
- const settingValue = settings?.[settingName];
+ const settingValue = settings?.[
+ settingName
+ ] as EnterpriseSettingValue<SettingName>;
return {
value: settingValue,
diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.ts
index 6c430a22e30..6953dfbbfbe 100644
--- a/frontend/src/metabase/plugins/oss/tenants.ts
+++ b/frontend/src/metabase/plugins/oss/tenants.ts
@@ -13,6 +13,7 @@ import type {
CollectionNamespace,
DataSegregationStrategy,
Group,
+ Tenant,
User,
} from "metabase-types/api";
@@ -34,8 +35,19 @@ export type TenantCollectionPathItem = {
is_tenant_dashboard?: boolean;
};
+export type UseListActiveTenantsResult = {
+ data: Tenant[] | undefined;
+ isLoading: boolean;
+ error: unknown;
+};
+
const getDefaultPluginTenants = () => ({
isEnabled: false,
+ useListActiveTenants: (): UseListActiveTenantsResult => ({
+ data: undefined,
+ isLoading: false,
+ error: undefined,
+ }),
userStrategyRoute: null as React.ReactElement | null,
tenantsRoutes: null as React.ReactElement | null,
CreateTenantsOnboardingStep: PluginPlaceholder as React.ComponentType<{
@@ -106,6 +118,7 @@ const getDefaultPluginTenants = () => ({
export const PLUGIN_TENANTS: {
isEnabled: boolean;
+ useListActiveTenants: () => UseListActiveTenantsResult;
userStrategyRoute: React.ReactElement | null;
useTenantMainNavbarData: () => {
canAccessTenantSpecificCollections: boolean;
diff --git a/frontend/test/__support__/server-mocks/metabot.ts b/frontend/test/__support__/server-mocks/metabot.ts
index 441f8a987b0..0862bf326bf 100644
--- a/frontend/test/__support__/server-mocks/metabot.ts
+++ b/frontend/test/__support__/server-mocks/metabot.ts
@@ -1,10 +1,13 @@
import fetchMock, { type UserRouteConfig } from "fetch-mock";
import type {
+ MetabotGroupLimit,
MetabotGroupPermission,
MetabotId,
MetabotInfo,
+ MetabotInstanceLimit,
MetabotSettingsResponse,
+ MetabotTenantLimit,
SuggestedMetabotPrompt,
SuggestedMetabotPromptsResponse,
UpdateMetabotSettingsRequest,
@@ -179,6 +182,51 @@ export function setupUpdateMetabotGroupPermissionsEndpoint() {
});
}
+const AI_CONTROLS_INSTANCE_LIMIT_ROUTE_NAME = "ai-controls-instance-limit";
+
+export function setupAIControlsInstanceLimitEndpoint(
+ response: MetabotInstanceLimit = { max_usage: null },
+) {
+ fetchMock.removeRoute(AI_CONTROLS_INSTANCE_LIMIT_ROUTE_NAME);
+ fetchMock.get("path:/api/ee/ai-controls/usage/instance", response, {
+ name: AI_CONTROLS_INSTANCE_LIMIT_ROUTE_NAME,
+ });
+}
+
+export function setupUpdateAIControlsInstanceLimitEndpoint() {
+ fetchMock.put("path:/api/ee/ai-controls/usage/instance", 200);
+}
+
+const AI_CONTROLS_GROUP_LIMITS_ROUTE_NAME = "ai-controls-group-limits";
+
+export function setupAIControlsGroupLimitsEndpoint(
+ response: MetabotGroupLimit[] = [],
+) {
+ fetchMock.removeRoute(AI_CONTROLS_GROUP_LIMITS_ROUTE_NAME);
+ fetchMock.get("path:/api/ee/ai-controls/usage/group", response, {
+ name: AI_CONTROLS_GROUP_LIMITS_ROUTE_NAME,
+ });
+}
+
+export function setupUpdateAIControlsGroupLimitEndpoint() {
+ fetchMock.put("express:/api/ee/ai-controls/usage/group/:id", 200);
+}
+
+const AI_CONTROLS_TENANT_LIMITS_ROUTE_NAME = "ai-controls-tenant-limits";
+
+export function setupAIControlsTenantLimitsEndpoint(
+ response: MetabotTenantLimit[] = [],
+) {
+ fetchMock.removeRoute(AI_CONTROLS_TENANT_LIMITS_ROUTE_NAME);
+ fetchMock.get("path:/api/ee/ai-controls/usage/tenant", response, {
+ name: AI_CONTROLS_TENANT_LIMITS_ROUTE_NAME,
+ });
+}
+
+export function setupUpdateAIControlsTenantLimitEndpoint() {
+ fetchMock.put("express:/api/ee/ai-controls/usage/tenant/:id", 200);
+}
+
const USER_METABOT_PERMISSIONS_ROUTE_NAME = "metabot-user-permissions";
export function setupUserMetabotPermissionsEndpoint(
diff --git a/resources/migrations/061/20260330_ai_usage_log.yaml b/resources/migrations/061/20260330_ai_usage_log.yaml
new file mode 100644
index 00000000000..cbbb04d5c66
--- /dev/null
+++ b/resources/migrations/061/20260330_ai_usage_log.yaml
@@ -0,0 +1,172 @@
+## AI usage log table
+
+databaseChangeLog:
+ - changeSet:
+ id: v61.t42424d
+ author: nvoxland
+ comment: Create metabot_instance_limit table
+ changes:
+ - createTable:
+ tableName: metabot_instance_limit
+ remarks: Metabot usage limits at the instance or tenant level
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: tenant_id
+ type: int
+ remarks: The tenant ID, or null for instance-wide limit
+ constraints:
+ nullable: true
+ unique: true
+ - column:
+ name: max_usage
+ type: int
+ remarks: The maximum usage value, interpreted according to the metabot-limit-unit setting. Null is unlimited
+
+ - changeSet:
+ id: v61.44ga4
+ author: nvoxland
+ comment: Add foreign key on metabot_instance_limit.tenant_id referencing tenant
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: metabot_instance_limit
+ baseColumnNames: tenant_id
+ referencedTableName: tenant
+ referencedColumnNames: id
+ constraintName: fk_metabot_instance_limit_ref_tenant
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v61.gr34fp
+ author: nvoxland
+ comment: Create metabot_group_limit table
+ changes:
+ - createTable:
+ tableName: metabot_group_limit
+ remarks: Metabot usage limits per group
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: group_id
+ type: int
+ remarks: The ID of the associated permissions group
+ constraints:
+ nullable: false
+ unique: true
+ - column:
+ name: max_usage
+ type: int
+ remarks: The maximum usage value, interpreted according to the metabot-limit-unit setting
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v61.gr34fp-fk
+ author: nvoxland
+ comment: Add foreign key on metabot_group_limit.group_id referencing permissions_group
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: metabot_group_limit
+ baseColumnNames: group_id
+ referencedTableName: permissions_group
+ referencedColumnNames: id
+ constraintName: fk_metabot_group_limit_ref_permissions_group
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v61.gresdvx
+ author: nvoxland
+ comment: Create the ai_usage_log
+ changes:
+ - createTable:
+ tableName: ai_usage_log
+ remarks: Universal ledger for all LLM API call usage tracking
+ columns:
+ - column:
+ name: id
+ type: bigint
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ remarks: 'When the LLM call was made'
+ - column:
+ name: source
+ type: varchar(100)
+ constraints:
+ nullable: false
+ remarks: 'Origin of the LLM call, e.g. agent, slackbot, document-gen, intent-classification, example-question-gen, oss-sql-gen, semantic-search-embedding'
+ - column:
+ name: model
+ type: varchar(255)
+ constraints:
+ nullable: false
+ remarks: 'Full model identifier, e.g. anthropic/claude-sonnet-4-20250514'
+ - column:
+ name: prompt_tokens
+ type: int
+ constraints:
+ nullable: false
+ remarks: 'Number of input/prompt tokens'
+ - column:
+ name: completion_tokens
+ type: int
+ constraints:
+ nullable: false
+ remarks: 'Number of output/completion tokens'
+ - column:
+ name: total_tokens
+ type: int
+ constraints:
+ nullable: false
+ remarks: 'Sum of prompt_tokens + completion_tokens'
+ - column:
+ name: user_id
+ type: int
+ remarks: 'Metabase user who triggered the call. NULL for system/background calls.'
+ - column:
+ name: tenant_id
+ type: int
+ remarks: 'Snapshot of user tenant at request time. NULL for non-tenant users.'
+ - column:
+ name: conversation_id
+ type: varchar(36)
+ remarks: 'Reference to metabot_conversation. NULL for non-conversational calls.'
+ - column:
+ name: profile_id
+ type: varchar(100)
+ remarks: 'AI profile used, e.g. nlq, sql, slackbot'
+ - column:
+ name: request_id
+ type: varchar(36)
+ remarks: 'UUID for correlating with Snowplow events'
+
+ - changeSet:
+ id: v61.8g8esw
+ author: nvoxland
+ comment: Index on ai_usage_log.user_id
+ changes:
+ - createIndex:
+ indexName: idx_ai_usage_log_user_id
+ tableName: ai_usage_log
+ columns:
+ - column:
+ name: user_id
diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.clj
index 1f985c1cefb..947d0122d2b 100644
--- a/src/metabase/cmd/copy.clj
+++ b/src/metabase/cmd/copy.clj
@@ -136,6 +136,8 @@
:model/MetabotPrompt]
(when config/ee-available?
[:model/MetabotPermissions
+ :model/MetabotGroupLimit
+ :model/MetabotInstanceLimit
:model/Sandbox
:model/Tenant
:model/ConnectionImpersonation])))
diff --git a/src/metabase/llm/api.clj b/src/metabase/llm/api.clj
index b9d18c5f9b3..2a04b948b44 100644
--- a/src/metabase/llm/api.clj
+++ b/src/metabase/llm/api.clj
@@ -187,6 +187,8 @@
(when-not (llm.settings/llm-anthropic-api-key)
(throw (ex-info (tru "LLM SQL generation is not configured. Please set an Anthropic API key in admin settings.")
{:status-code 403})))
+ (when-let [limit-msg (metabot/check-usage-limits!)]
+ (throw (ex-info limit-msg {:status-code 429})))
(throttle/with-throttling [(sql-gen-throttlers :ip-address) (request/ip-address request)
(sql-gen-throttlers :user-id) api/*current-user-id*]
(let [{:keys [prompt database_id source_sql referenced_entities]} body
@@ -237,6 +239,11 @@
;; for some reason, :source convention is snake_case and :tag is (mostly) kebab
:source "oss_metabot"
:tag "oss-sqlgen"})
+ (metabot/log-ai-usage!
+ {:source "oss-sql-gen"
+ :model (:model usage)
+ :prompt-tokens (:prompt usage)
+ :completion-tokens (:completion usage)})
(track-sqlgen-event!
{:duration-ms (u/since-ms start-timer)
:result "success"
diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.clj
index 28fead05a7e..e62f87a80c1 100644
--- a/src/metabase/metabot/core.clj
+++ b/src/metabase/metabot/core.clj
@@ -3,6 +3,7 @@
(:require
[metabase.metabot.provider-util]
[metabase.metabot.scope]
+ [metabase.metabot.usage]
[potemkin :as p]))
(p/import-vars
@@ -16,6 +17,11 @@
agent-search
agent-table-read])
+(p/import-vars
+ [metabase.metabot.usage
+ check-usage-limits!
+ log-ai-usage!])
+
;; TODO: Port analyze-chart to use the native LLM infrastructure
;; instead of the deleted `metabase.metabot.client`.
;; The frontend (`AIQuestionAnalysisSidebar`, `useDashCardAnalysis`) actively calls
diff --git a/src/metabase/metabot/models/ai_usage_log.clj b/src/metabase/metabot/models/ai_usage_log.clj
new file mode 100644
index 00000000000..ff4d9c3441c
--- /dev/null
+++ b/src/metabase/metabot/models/ai_usage_log.clj
@@ -0,0 +1,9 @@
+(ns metabase.metabot.models.ai-usage-log
+ (:require
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/AiUsageLog [_model] :ai_usage_log)
+
+(doto :model/AiUsageLog
+ (derive :metabase/model))
diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.clj
index 8cf7b64c551..6080dbc301c 100644
--- a/src/metabase/metabot/self.clj
+++ b/src/metabase/metabot/self.clj
@@ -18,6 +18,7 @@
[metabase.metabot.self.core :as core]
[metabase.metabot.self.openai :as openai]
[metabase.metabot.self.openrouter :as openrouter]
+ [metabase.metabot.usage :as usage]
[metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.o11y :refer [with-span]]))
@@ -178,7 +179,15 @@
:request-id (some-> request-id analytics/uuid->ai-service-hex-uuid)
:session-id session-id
:source source
- :tag tag})))
+ :tag tag})
+ (usage/log-ai-usage!
+ {:source (or tag source "unknown")
+ :model model
+ :prompt-tokens prompt
+ :completion-tokens completion
+ :conversation-id session-id
+ :profile-id profile-id
+ :request-id request-id})))
part))))
(defn- report-tool-usage-xf
@@ -260,31 +269,35 @@
([provider-and-model system-msg parts tools tracking-opts]
(call-llm provider-and-model system-msg parts tools tracking-opts nil))
([provider-and-model system-msg parts tools tracking-opts {:keys [tool-choice]}]
- (let [{:keys [provider stream-fn model ai-proxy?]} (parse-provider-model provider-and-model)]
- (log/info "Calling LLM" {:provider provider :model model :parts (count parts) :tools (count tools)
- :tool-choice tool-choice :ai-proxy? ai-proxy?})
- (let [tracking-opts (assoc tracking-opts :model provider-and-model)
- streaming-opts (cond-> {:model model :input parts :tools (vals tools) :ai-proxy? ai-proxy?}
- system-msg (assoc :system system-msg)
- (and (seq tools)
- tool-choice) (assoc :tool_choice tool-choice))
- make-source (fn []
- (eduction (comp (core/tool-executor-xf tools)
- (core/lite-aisdk-xf)
- (report-aisdk-errors-xf tracking-opts)
- (report-token-usage-xf tracking-opts)
- (report-tool-usage-xf tracking-opts))
- (stream-fn streaming-opts)))]
- (reify clojure.lang.IReduceInit
- (reduce [_ rf init]
- (with-span :info {:name :metabot.agent/call-llm
- :provider provider
- :model model
- :part-count (count parts)
- :tool-count (count tools)}
- (with-retries
- tracking-opts
- #(reduce rf init (make-source))))))))))
+ (if-let [limit-msg (usage/check-usage-limits!)]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (rf init {:type :text :text limit-msg})))
+ (let [{:keys [provider stream-fn model ai-proxy?]} (parse-provider-model provider-and-model)]
+ (log/info "Calling LLM" {:provider provider :model model :parts (count parts) :tools (count tools)
+ :tool-choice tool-choice :ai-proxy? ai-proxy?})
+ (let [tracking-opts (assoc tracking-opts :model provider-and-model)
+ streaming-opts (cond-> {:model model :input parts :tools (vals tools) :ai-proxy? ai-proxy?}
+ system-msg (assoc :system system-msg)
+ (and (seq tools)
+ tool-choice) (assoc :tool_choice tool-choice))
+ make-source (fn []
+ (eduction (comp (core/tool-executor-xf tools)
+ (core/lite-aisdk-xf)
+ (report-aisdk-errors-xf tracking-opts)
+ (report-token-usage-xf tracking-opts)
+ (report-tool-usage-xf tracking-opts))
+ (stream-fn streaming-opts)))]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (with-span :info {:name :metabot.agent/call-llm
+ :provider provider
+ :model model
+ :part-count (count parts)
+ :tool-count (count tools)}
+ (with-retries
+ tracking-opts
+ #(reduce rf init (make-source)))))))))))
(defn call-llm-structured
"Make an LLM call that returns structured JSON output.
diff --git a/src/metabase/metabot/usage.clj b/src/metabase/metabot/usage.clj
index 979ee701015..e2887b810db 100644
--- a/src/metabase/metabot/usage.clj
+++ b/src/metabase/metabot/usage.clj
@@ -1,11 +1,38 @@
(ns metabase.metabot.usage
- "Deprecated: use [[metabase.internal-stats.metabot]] instead."
+ "LLM usage logging and limit enforcement.
+
+ Logging: [[log-ai-usage!]] records each LLM call to the `ai_usage_log` table (EE only).
+
+ Limit checking: [[check-usage-limits!]] checks instance, tenant, and user limits.
+ In OSS, no limits are enforced and no usage is logged."
(:require
- [metabase.internal-stats.metabot :as internal-stats.metabot]))
+ [metabase.premium-features.core :refer [defenterprise defenterprise-schema]]
+ [metabase.util.malli.schema :as ms]))
+
+(def ^:private usage-map-schema
+ [:map
+ [:source :string]
+ [:model :string]
+ [:prompt-tokens [:int {:min 0}]]
+ [:completion-tokens [:int {:min 0}]]
+ [:user-id {:optional true} [:maybe ms/PositiveInt]]
+ [:tenant-id {:optional true} [:maybe ms/PositiveInt]]
+ [:conversation-id {:optional true} [:maybe :string]]
+ [:profile-id {:optional true} [:maybe :keyword]]
+ [:request-id {:optional true} [:maybe :string]]])
+
+(defenterprise-schema log-ai-usage! :- :any
+ "Record an LLM API call in the ai_usage_log table.
+ In OSS, this is a no-op."
+ metabase-enterprise.metabot.usage
+ [_usage-map :- usage-map-schema]
+ nil)
+
+(defenterprise check-usage-limits!
+ "Check all usage limits for the current user. Returns nil if all limits are within bounds,
+ or a user-friendly error message string if any limit is exceeded.
-(defn metabot-stats
- "Calculate total Metabot token usage over a window of the previous UTC day 00:00-23:59.
- Deprecated: use [[metabase.internal-stats.metabot/metabot-stats]] instead."
- {:deprecated "0.56.0"}
+ In OSS, always returns nil (no limits enforced)."
+ metabase-enterprise.metabot.usage
[]
- (internal-stats.metabot/metabot-stats))
+ nil)
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 154d141474b..5f2657cbcec 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -57,6 +57,9 @@
:model/Metabot metabase.metabot.models.metabot
:model/MetabotConversation metabase.metabot.models.metabot-conversation
:model/MetabotMessage metabase.metabot.models.metabot-message
+ :model/AiUsageLog metabase.metabot.models.ai-usage-log
+ :model/MetabotGroupLimit metabase-enterprise.metabot.models.metabot-group-limit
+ :model/MetabotInstanceLimit metabase-enterprise.metabot.models.metabot-instance-limit
:model/MetabotPermissions metabase-enterprise.metabot.models.metabot-permissions
:model/MetabotPrompt metabase.metabot.models.metabot-prompt
:model/ModelIndex metabase.indexed-entities.models.model-index
diff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.clj
index 71c72fb4e41..282a70d3a4d 100644
--- a/src/metabase/testing_api/api.clj
+++ b/src/metabase/testing_api/api.clj
@@ -237,6 +237,12 @@
metabase-enterprise.cache.task.refresh-cache-configs
[])
+(defenterprise clear-metabot-limit-cache!
+ "Clears the metabot usage limit memoization cache on EE so that limit checks re-evaluate immediately.
+ No-op on OSS."
+ metabase-enterprise.metabot.usage
+ [])
+
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
;;
@@ -267,3 +273,39 @@
[:ref ::lib.schema.test-spec/test-native-query-spec]]]
(-> (lib-be/application-database-metadata-provider database)
(lib/test-native-query native-query-spec)))
+
+;;;; Metabot AI usage seeding
+
+(def ^:private e2e-usage-source "e2e-test")
+
+(api.macros/defendpoint :post "/metabot/seed-ai-usage"
+ :- [:map [:inserted :int]]
+ "Insert `count` rows into `ai_usage_log` for the given `user_id`, then clear the metabot limit
+ cache so limit checks re-evaluate immediately. Intended only for E2E tests."
+ [_route-params
+ _query-params
+ {:keys [user_id count]} :- [:map
+ [:user_id ms/PositiveInt]
+ [:count ms/PositiveInt]]]
+ (dotimes [_ count]
+ (t2/insert! :model/AiUsageLog
+ {:source e2e-usage-source
+ :model "test/model"
+ :prompt_tokens 0
+ :completion_tokens 0
+ :total_tokens 0
+ :user_id user_id}))
+ (clear-metabot-limit-cache!)
+ {:inserted count})
+
+(api.macros/defendpoint :delete "/metabot/seed-ai-usage"
+ :- [:map [:deleted :int]]
+ "Delete all `ai_usage_log` rows inserted by the seeding endpoint for the given `user_id`, then
+ clear the metabot limit cache. Intended only for E2E tests."
+ [_route-params
+ _query-params
+ {:keys [user_id]} :- [:map
+ [:user_id ms/PositiveInt]]]
+ (let [deleted (t2/delete! :model/AiUsageLog :user_id user_id :source e2e-usage-source)]
+ (clear-metabot-limit-cache!)
+ {:deleted deleted}))
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index e79bb430886..a29cc946ec4 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -25,7 +25,8 @@
(def ^:private models-to-exclude
"Models that should *not* be migrated in `load-from-h2`."
- #{:model/AnalysisFinding
+ #{:model/AiUsageLog
+ :model/AnalysisFinding
:model/AnalysisFindingError
:model/ApiKey
:model/CacheConfig
@@ -37,6 +38,7 @@
:model/Dependency
:model/MetabotGroupLimit
:model/MetabotInstanceLimit
+ :model/MetabotPermissions
:model/PythonLibrary
:model/PremiumFeaturesCache
:model/Query
diff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yaml
index 8fbf4793b82..5ab04a34ea1 100644
--- a/test_resources/serialization_baseline/settings.yaml
+++ b/test_resources/serialization_baseline/settings.yaml
@@ -42,8 +42,11 @@ login-page-illustration-custom: null
metabot-chat-system-prompt: null
metabot-enabled?: null
metabot-icon: null
+metabot-limit-reset-rate: null
+metabot-limit-unit: null
metabot-name: null
metabot-nlq-system-prompt: null
+metabot-quota-reached-message: null
metabot-show-illustrations: null
metabot-sql-system-prompt: null
native-query-autocomplete-match-style: null