Skip to content

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

GDGT-2932: Refactor AI Analytics views to use internal routes and shared layout (#79010)

Stas Gavrylov62c29ab1eba2
diff --git a/e2e/test/scenarios/monitor/ai-auditing/mcp-analytics.cy.spec.ts b/e2e/test/scenarios/monitor/ai-auditing/mcp-analytics.cy.spec.ts
index 77eb31dcae0..c88a159be72 100644
--- a/e2e/test/scenarios/monitor/ai-auditing/mcp-analytics.cy.spec.ts
+++ b/e2e/test/scenarios/monitor/ai-auditing/mcp-analytics.cy.spec.ts
@@ -59,7 +59,7 @@ describe("scenarios > monitor > ai auditing > mcp analytics", () => {
});
cy.log("The seeded tool call shows up in the Events table");
- H.main().findByRole("tab", { name: "Tool calls" }).click();
+ H.main().findByRole("link", { name: "Tool calls" }).click();
cy.wait("@dataset");
H.main().findByText(SEED_TOOL_NAME).should("be.visible");
});
@@ -88,7 +88,7 @@ describe("scenarios > monitor > ai auditing > mcp analytics", () => {
cy.log(
"The Tool calls table shows the derived error type and gated message",
);
- H.main().findByRole("tab", { name: "Tool calls" }).click();
+ H.main().findByRole("link", { name: "Tool calls" }).click();
cy.wait("@dataset");
H.main().within(() => {
cy.findByText(SEED_ERROR_TOOL).scrollIntoView().should("be.visible");
diff --git a/e2e/test/scenarios/monitor/tools/tools.cy.spec.ts b/e2e/test/scenarios/monitor/tools/tools.cy.spec.ts
index 5199050f16b..5637720c603 100644
--- a/e2e/test/scenarios/monitor/tools/tools.cy.spec.ts
+++ b/e2e/test/scenarios/monitor/tools/tools.cy.spec.ts
@@ -647,11 +647,11 @@ describe("scenarios > monitor > tools > task runs", () => {
cy.findByTestId("tasks-table").should("be.visible");
- cy.findByRole("tab", { name: /Runs/i }).click();
+ cy.findByRole("link", { name: "Runs" }).click();
cy.location("pathname").should("eq", "/monitor/tasks/runs");
cy.findByTestId("task-runs-table").should("be.visible");
- cy.findByRole("tab", { name: /Tasks/i }).click();
+ cy.findByRole("link", { name: "Tasks" }).click();
cy.location("pathname").should("eq", "/monitor/tasks/list");
cy.findByTestId("tasks-table").should("be.visible");
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/components/SnippetHeader/SnippetHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/components/SnippetHeader/SnippetHeader.tsx
index 0e2e78d029a..f7e20c74db3 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/components/SnippetHeader/SnippetHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/components/SnippetHeader/SnippetHeader.tsx
@@ -5,13 +5,15 @@ import { useUpdateSnippetMutation } from "metabase/api";
import { getErrorMessage } from "metabase/api/utils";
import { isRootCollection } from "metabase/common/collections/utils";
import { Link } from "metabase/common/components/Link";
+import {
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";
import {
PaneHeader,
PaneHeaderInput,
type PaneHeaderProps,
- type PaneHeaderTab,
- PaneHeaderTabs,
} from "metabase/common/data-studio/components/PaneHeader";
import { useCollectionPath } from "metabase/common/data-studio/hooks/use-collection-path/useCollectionPath";
import { useToast } from "metabase/common/hooks";
@@ -135,11 +137,11 @@ type SnippetTabsProps = {
function SnippetTabs({ snippet }: SnippetTabsProps) {
const tabs = getTabs(snippet.id);
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
}
-function getTabs(snippetId: number): PaneHeaderTab[] {
- const tabs: PaneHeaderTab[] = [
+function getTabs(snippetId: number): PillTab[] {
+ const tabs: PillTab[] = [
{
label: t`Definition`,
to: Urls.dataStudioSnippet(snippetId),
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
index 51692dbfc10..dee3edfe497 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
@@ -1,9 +1,9 @@
import { t } from "ttag";
import {
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
import { type Location, useLocation } from "metabase/router";
import * as Urls from "metabase/urls";
@@ -16,14 +16,14 @@ type TableTabsProps = {
export function TableTabs({ table }: TableTabsProps) {
const location = useLocation();
const tabs = getTabs(table, location);
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
}
function getTabs(
table: Table,
location: Omit<Location, "query" | "action">,
-): PaneHeaderTab[] {
- const tabs: PaneHeaderTab[] = [];
+): PillTab[] {
+ const tabs: PillTab[] = [];
tabs.push({
label: t`Overview`,
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.tsx
deleted file mode 100644
index aa4f0a018e0..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.tsx
+++ /dev/null
@@ -1,252 +0,0 @@
-import { useMemo } from "react";
-import { match } from "ts-pattern";
-import { t } from "ttag";
-
-import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
-import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
-import { useLocation } from "metabase/router";
-import { useSetting } from "metabase/settings";
-import { Flex, Loader, SimpleGrid, Stack, Tabs, Title } from "metabase/ui";
-import {
- VIEW_AGENT_API_CALLS,
- VIEW_GROUP_MEMBERS,
-} from "metabase-enterprise/monitor/ai-auditing/cli-analytics/constants";
-import { useCliHasData } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData";
-import { buildCallsByDayByStatusQuery } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/query-utils";
-import type { CliTab } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state";
-import { cliUrlStateConfig } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state";
-import {
- // The shared audit filter bar; aliased since it has nothing to do with Metabot "conversations".
- ConversationFilters as CliCallsFilter,
- useFilterOptions,
-} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationFilters";
-import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
-
-import { CliAnalyticsEmptyState } from "./CliAnalyticsEmptyState";
-import { CliBreakoutChart } from "./CliBreakoutChart";
-import { CliCallerLivenessTable } from "./CliCallerLivenessTable";
-import { CliCallsTimelineChart } from "./CliCallsTimelineChart";
-import { CliEventsTable } from "./CliEventsTable";
-
-/**
- * AI Auditing CLI analytics page. Renders live ad-hoc queries over the `v_agent_api_calls` audit view
- * across two tabs (Charts and a row-level Calls table), sharing URL-state date/user/group
- * filters. Shows a single empty state (no tabs) when the filtered view has no activity.
- */
-export function CliAnalyticsPage() {
- const location = useLocation();
- const [
- { date, user, group, tenant, tab, page, sort_column, sort_direction },
- { patchUrlState },
- ] = useUrlState(location, cliUrlStateConfig);
-
- const {
- dateFilter,
- userId,
- groupId,
- tenantId,
- groupNoFilterValue,
- userOptions,
- groupOptions,
- tenantOptions,
- hasTenants,
- } = useFilterOptions({ date, user, group, tenant });
-
- const hasPii = useSetting("analytics-pii-retention-enabled") === true;
-
- const callsAudit = useAuditTable(VIEW_AGENT_API_CALLS);
- const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);
-
- const dataSources = {
- provider: callsAudit.provider,
- table: callsAudit.table,
- groupMembersTable: groupMembersAudit.table,
- };
-
- const chartFilters = { dateFilter, userId, groupId, tenantId };
-
- const sortingOptions = useMemo(
- () => ({ sort_column, sort_direction }),
- [sort_column, sort_direction],
- );
-
- const { isInitialLoading, isRefetching, hasData, count } = useCliHasData({
- ...dataSources,
- ...chartFilters,
- });
- const showEmpty = !isInitialLoading && !isRefetching && !hasData;
-
- // Only surface the errors section when the current filters actually match failed calls, so a
- // healthy instance doesn't show a row of empty error charts.
- const { hasData: hasErrors } = useCliHasData({
- ...dataSources,
- ...chartFilters,
- errorsOnly: true,
- });
-
- // The Calls tab is a data grid that should scroll internally.
- const isEventsTab = tab === "events";
-
- const content = (
- <MonitorMain>
- <Stack gap="lg" {...(isEventsTab ? { flex: 1, mih: 0 } : {})}>
- <MonitorHeaderTitle>{t`CLI analytics`}</MonitorHeaderTitle>
-
- <Tabs
- variant="pills"
- value={tab}
- // tab/val _is_ a CliTab, but Mantine's Tab only deals with strings ¯\_(ツ)_/¯
- onChange={(val) => patchUrlState({ tab: val as CliTab })}
- keepMounted={false}
- {...(isEventsTab
- ? {
- flex: 1,
- mih: 0,
- display: "flex",
- style: { flexDirection: "column" as const },
- }
- : {})}
- >
- <Tabs.List mb="md">
- <Tabs.Tab value="charts">{t`Usage`}</Tabs.Tab>
- <Tabs.Tab value="events">{t`Calls`}</Tabs.Tab>
- </Tabs.List>
-
- <CliCallsFilter
- date={date}
- onDateChange={(val) => patchUrlState({ date: val, page: 0 })}
- user={user}
- onUserChange={(val) => patchUrlState({ user: val, page: 0 })}
- userOptions={userOptions}
- group={group}
- onGroupChange={(val) => patchUrlState({ group: val, page: 0 })}
- groupOptions={groupOptions}
- groupNoFilterValue={groupNoFilterValue}
- tenant={tenant}
- onTenantChange={(val) => patchUrlState({ tenant: val, page: 0 })}
- tenantOptions={tenantOptions}
- hasTenants={hasTenants}
- />
-
- {match({ isInitialLoading, showEmpty })
- .with({ isInitialLoading: true }, () => (
- <Tabs.Panel value={tab} mt="md">
- <Flex mih="60vh" align="center" justify="center">
- <Loader size="lg" />
- </Flex>
- </Tabs.Panel>
- ))
- .with({ showEmpty: true }, () => (
- <Tabs.Panel value={tab} mt="md">
- <CliAnalyticsEmptyState />
- </Tabs.Panel>
- ))
- .otherwise(() => (
- <>
- <Tabs.Panel value="charts" mt="md">
- <Stack gap="lg">
- <CliCallsTimelineChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by client over time`}
- />
- <SimpleGrid cols={2} spacing="lg">
- <CliBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by client`}
- display="pie"
- breakoutColumn="client_display_name"
- h={500}
- />
- <CliBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by operation`}
- display="row"
- breakoutColumn="operation"
- h={500}
- />
- </SimpleGrid>
- <SimpleGrid cols={2} spacing="lg">
- <CliBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by user`}
- display="row"
- breakoutColumn="user_display_name"
- h={500}
- />
- <CliCallerLivenessTable
- {...dataSources}
- {...chartFilters}
- title={t`User activity`}
- h={500}
- />
- </SimpleGrid>
-
- {hasErrors && (
- <>
- <Title order={3} mt="md">{t`Errors`}</Title>
- <CliCallsTimelineChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by status over time`}
- buildQuery={buildCallsByDayByStatusQuery}
- />
- <CliBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Errors by operation`}
- display="row"
- breakoutColumn="operation"
- errorsOnly
- h={500}
- />
- </>
- )}
- </Stack>
- </Tabs.Panel>
-
- <Tabs.Panel
- value="events"
- mt="md"
- flex={1}
- mih={0}
- display="flex"
- style={{ flexDirection: "column" }}
- >
- <CliEventsTable
- {...dataSources}
- {...chartFilters}
- hasTenants={hasTenants}
- hasPii={hasPii}
- page={page}
- total={count}
- onPageChange={(newPage) => patchUrlState({ page: newPage })}
- sortingOptions={sortingOptions}
- onSortingOptionsChange={(newSorting) =>
- patchUrlState({
- sort_column: newSorting.sort_column,
- sort_direction: newSorting.sort_direction,
- page: 0,
- })
- }
- />
- </Tabs.Panel>
- </>
- ))}
- </Tabs>
- </Stack>
- </MonitorMain>
- );
-
- return isEventsTab ? (
- <Flex h="100%" wrap="nowrap">
- {content}
- </Flex>
- ) : (
- content
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.unit.spec.tsx
deleted file mode 100644
index 972673db757..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsPage.unit.spec.tsx
+++ /dev/null
@@ -1,244 +0,0 @@
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-
-import { setupEnterprisePlugins } from "__support__/enterprise";
-import {
- setupGroupsEndpoint,
- setupUsersEndpoints,
-} from "__support__/server-mocks";
-import { mockSettings } from "__support__/settings";
-import {
- mockGetBoundingClientRect,
- renderWithProviders,
- screen,
- waitFor,
- within,
-} from "__support__/ui";
-import { createMockState } from "metabase/redux/store/mocks";
-import { Route } from "metabase/router";
-import { registerVisualizations } from "metabase/visualizations/register";
-import { AUDIT_DB_ID } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/constants";
-import type { Database, Dataset, Field } from "metabase-types/api";
-import {
- createMockColumn,
- createMockDatabase,
- createMockDataset,
- createMockDatasetData,
- createMockField,
- createMockGroup,
- createMockTable,
- createMockTokenFeatures,
- createMockUser,
-} from "metabase-types/api/mocks";
-
-import { CliAnalyticsPage } from "./CliAnalyticsPage";
-
-registerVisualizations();
-
-const AGENT_API_CALLS_TABLE_ID = 2001;
-const GROUP_MEMBERS_TABLE_ID = 2002;
-
-const BASE_TYPE = {
- text: "type/Text",
- integer: "type/Integer",
- dateTime: "type/DateTimeWithLocalTZ",
-} as const;
-
-type FieldSpec = [
- type: keyof typeof BASE_TYPE,
- name: string,
- semantic_type: Field["semantic_type"],
-];
-
-/** Build a mock audit-DB table (in `AUDIT_DB_ID`) with the given fields, for the metadata endpoint. */
-const buildTable = (id: number, name: string, fields: FieldSpec[]) =>
- createMockTable({
- id,
- db_id: AUDIT_DB_ID,
- schema: "public",
- name,
- display_name: name,
- fields: fields.map(([type, fieldName, semantic_type], i) =>
- createMockField({
- id: id * 100 + i,
- table_id: id,
- name: fieldName,
- display_name: fieldName,
- fingerprint: null,
- base_type: BASE_TYPE[type],
- effective_type: BASE_TYPE[type],
- semantic_type,
- }),
- ),
- });
-
-const auditDatabase: Database = createMockDatabase({
- id: AUDIT_DB_ID,
- name: "Audit DB",
- tables: [
- buildTable(AGENT_API_CALLS_TABLE_ID, "v_agent_api_calls", [
- ["text", "call_id", "type/PK"],
- ["dateTime", "created_at", "type/CreationTimestamp"],
- ["text", "operation", "type/Category"],
- ["text", "status", "type/Category"],
- ["integer", "duration_ms", "type/Quantity"],
- ["integer", "user_id", "type/FK"],
- ["text", "user_display_name", "type/Name"],
- ["text", "client_display_name", "type/Category"],
- ]),
- buildTable(GROUP_MEMBERS_TABLE_ID, "v_group_members", [
- ["integer", "user_id", "type/Description"],
- ["integer", "group_id", "type/PK"],
- ["text", "group_name", "type/Name"],
- ]),
- ],
-});
-
-// A breakout/count dataset that satisfies both the chart visualizations
-// (breakout + aggregation columns) and the events table (named columns).
-// Aggregation column first so the page's no-breakout count probe (reads rows[0][0]) sees a
-// positive number; the `source` tags still let the breakout charts find the right columns.
-const datasetResponse: Dataset = createMockDataset({
- data: createMockDatasetData({
- rows: [
- [12, "POST /api/agent/v1/query"],
- [7, "GET /api/agent/v1/search"],
- ],
- cols: [
- createMockColumn({
- source: "aggregation",
- name: "count",
- display_name: "Count",
- }),
- createMockColumn({
- source: "breakout",
- name: "operation",
- display_name: "Operation",
- }),
- ],
- }),
- database_id: AUDIT_DB_ID,
- row_count: 2,
- running_time: 1,
-});
-
-// A zero-count aggregation result — what the page's "has any data?" probe gets when the
-// filtered view is empty.
-const emptyDatasetResponse: Dataset = createMockDataset({
- data: createMockDatasetData({
- rows: [[0]],
- cols: [
- createMockColumn({
- source: "aggregation",
- name: "count",
- display_name: "Count",
- }),
- ],
- }),
- database_id: AUDIT_DB_ID,
- row_count: 1,
- running_time: 1,
-});
-
-/** Mock the audit-DB metadata, users/groups, and the `/api/dataset` adhoc endpoint (with the given dataset). */
-function setupEndpoints(dataset: Dataset = datasetResponse) {
- fetchMock.get(`path:/api/database/${AUDIT_DB_ID}/metadata`, auditDatabase);
- // useAuditTable pulls the table's fields (and its FK targets') from here.
- fetchMock.post("path:/api/dataset/query_metadata", {
- databases: [auditDatabase],
- tables: auditDatabase.tables ?? [],
- fields: (auditDatabase.tables ?? []).flatMap((table) => table.fields ?? []),
- });
- setupUsersEndpoints([createMockUser({ id: 1, first_name: "Ada" })]);
- setupGroupsEndpoint([createMockGroup({ id: 1, name: "All Users" })]);
- fetchMock.post("path:/api/dataset", dataset, { name: "dataset" });
-}
-
-/** Render `CliAnalyticsPage` at its route with EE plugins + `audit_app`, optionally overriding the dataset response. */
-function setup({ dataset }: { dataset?: Dataset } = {}) {
- // TreeTable measures column/row sizes via the DOM; jsdom needs a stubbed rect
- // for its virtualized rows to render.
- mockGetBoundingClientRect({ width: 100, height: 100 });
- setupEnterprisePlugins();
- setupEndpoints(dataset);
-
- return renderWithProviders(
- <Route path="/monitor/ai-auditing/cli" element={<CliAnalyticsPage />} />,
- {
- initialRoute: "/monitor/ai-auditing/cli",
- withRouter: true,
- storeInitialState: createMockState({
- settings: mockSettings({
- "token-features": createMockTokenFeatures({ audit_app: true }),
- }),
- }),
- },
- );
-}
-
-describe("CliAnalyticsPage", () => {
- it("renders the header, filters, and charts tab", async () => {
- setup();
-
- expect(
- await screen.findByRole("heading", { name: "CLI analytics" }),
- ).toBeInTheDocument();
- expect(
- screen.getByTestId("conversation-filters-date-select"),
- ).toBeInTheDocument();
- // Tabs appear only after the initial count query resolves (the page shows a loader first).
- expect(
- await screen.findByRole("tab", { name: "Usage" }),
- ).toBeInTheDocument();
-
- // Charts run ad-hoc dataset queries through /api/dataset.
- await waitFor(() => {
- expect(fetchMock.callHistory.called("dataset")).toBe(true);
- });
- expect(await screen.findByText("Calls by operation")).toBeInTheDocument();
- // The errors section renders because the (mocked) error count is > 0.
- expect(await screen.findByText("Errors by operation")).toBeInTheDocument();
- });
-
- it("switches to the calls tab and renders the sortable row-level table", async () => {
- setup();
-
- await screen.findByRole("heading", { name: "CLI analytics" });
- await userEvent.click(await screen.findByRole("tab", { name: "Calls" }));
-
- const eventsPanel = screen.getByRole("tabpanel");
- expect(
- await within(eventsPanel).findByRole("treegrid", { name: "Calls" }),
- ).toBeInTheDocument();
- // a curated column header and a cell value from the mocked page render
- expect(
- await within(eventsPanel).findByRole("columnheader", {
- name: "Operation",
- }),
- ).toBeInTheDocument();
- expect(
- await within(eventsPanel).findByText("POST /api/agent/v1/query"),
- ).toBeInTheDocument();
- });
-
- it("keeps the header, tabs, and filters visible and shows an empty state in place of the tab content when there is no activity", async () => {
- setup({ dataset: emptyDatasetResponse });
-
- expect(
- await screen.findByRole("heading", { name: "CLI analytics" }),
- ).toBeInTheDocument();
- expect(await screen.findByText("No CLI activity")).toBeInTheDocument();
-
- // Tabs and filters stay visible even when the view is empty — only the tab content swaps out.
- const usageTab = screen.getByRole("tab", { name: "Usage" });
- expect(usageTab).toBeInTheDocument();
- expect(screen.getByRole("tab", { name: "Calls" })).toBeInTheDocument();
- expect(
- screen.getByTestId("conversation-filters-date-select"),
- ).toBeInTheDocument();
-
- const panel = screen.getByRole("tabpanel");
- expect(usageTab).toHaveAttribute("aria-controls", panel.id);
- expect(within(panel).getByText("No CLI activity")).toBeInTheDocument();
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.tsx
new file mode 100644
index 00000000000..e02ce47deb1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.tsx
@@ -0,0 +1,157 @@
+import { useMemo } from "react";
+import { t } from "ttag";
+
+import type { PillTab } from "metabase/common/components/PillTabNavigation";
+import { useUrlState } from "metabase/common/hooks/use-url-state";
+import { Outlet, useLocation } from "metabase/router";
+import { useSetting } from "metabase/settings";
+import * as Urls from "metabase/urls";
+import {
+ VIEW_AGENT_API_CALLS,
+ VIEW_GROUP_MEMBERS,
+} from "metabase-enterprise/monitor/ai-auditing/cli-analytics/constants";
+import { useCliHasData } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData";
+import { cliUrlStateConfig } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state";
+import { AiAnalyticsSectionLayout } from "metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout";
+import {
+ ConversationFilters as CliCallsFilter,
+ useFilterOptions,
+} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationFilters";
+import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
+
+import { CliAnalyticsEmptyState } from "./CliAnalyticsEmptyState";
+import {
+ CliAnalyticsContextProvider,
+ type CliAnalyticsContextValue,
+} from "./context";
+
+export function CliAnalyticsSectionLayout() {
+ const location = useLocation();
+ const [
+ { date, user, group, tenant, page, sort_column, sort_direction },
+ { patchUrlState },
+ ] = useUrlState(location, cliUrlStateConfig);
+
+ const {
+ dateFilter,
+ userId,
+ groupId,
+ tenantId,
+ groupNoFilterValue,
+ userOptions,
+ groupOptions,
+ tenantOptions,
+ hasTenants,
+ } = useFilterOptions({ date, user, group, tenant });
+
+ const hasPii = useSetting("analytics-pii-retention-enabled") === true;
+ const callsAudit = useAuditTable(VIEW_AGENT_API_CALLS);
+ const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);
+
+ const dataSources = useMemo(
+ () => ({
+ provider: callsAudit.provider,
+ table: callsAudit.table,
+ groupMembersTable: groupMembersAudit.table,
+ }),
+ [callsAudit.provider, callsAudit.table, groupMembersAudit.table],
+ );
+ const chartFilters = useMemo(
+ () => ({ dateFilter, userId, groupId, tenantId }),
+ [dateFilter, groupId, tenantId, userId],
+ );
+ const sortingOptions = useMemo(
+ () => ({ sort_column, sort_direction }),
+ [sort_column, sort_direction],
+ );
+
+ const { isInitialLoading, isRefetching, hasData, count, error } =
+ useCliHasData({ ...dataSources, ...chartFilters });
+ const { hasData: hasErrors } = useCliHasData({
+ ...dataSources,
+ ...chartFilters,
+ errorsOnly: true,
+ });
+ const showEmpty = !isInitialLoading && !isRefetching && !hasData;
+
+ const usagePath = Urls.monitorAiAuditingCliUsage();
+ const callsPath = Urls.monitorAiAuditingCliCalls();
+ const tabs: PillTab[] = [
+ {
+ label: t`Usage`,
+ to: `${usagePath}${location.search}`,
+ isSelected: (pathname) => pathname === usagePath,
+ },
+ {
+ label: t`Calls`,
+ to: `${callsPath}${location.search}`,
+ isSelected: (pathname) => pathname === callsPath,
+ },
+ ];
+
+ const isCallsRoute = location.pathname === callsPath;
+ const outletContext = useMemo<CliAnalyticsContextValue>(
+ () => ({
+ dataSources,
+ chartFilters,
+ hasTenants,
+ hasPii,
+ hasErrors,
+ page,
+ total: count,
+ onPageChange: (newPage) =>
+ patchUrlState({ page: newPage }, { immediate: true }),
+ sortingOptions,
+ onSortingOptionsChange: (newSorting) =>
+ patchUrlState({
+ sort_column: newSorting.sort_column,
+ sort_direction: newSorting.sort_direction,
+ page: 0,
+ }),
+ }),
+ [
+ chartFilters,
+ count,
+ dataSources,
+ hasErrors,
+ hasPii,
+ hasTenants,
+ page,
+ patchUrlState,
+ sortingOptions,
+ ],
+ );
+
+ return (
+ <AiAnalyticsSectionLayout
+ title={t`CLI analytics`}
+ tabs={tabs}
+ filters={
+ <CliCallsFilter
+ date={date}
+ onDateChange={(val) => patchUrlState({ date: val, page: 0 })}
+ user={user}
+ onUserChange={(val) => patchUrlState({ user: val, page: 0 })}
+ userOptions={userOptions}
+ group={group}
+ onGroupChange={(val) => patchUrlState({ group: val, page: 0 })}
+ groupOptions={groupOptions}
+ groupNoFilterValue={groupNoFilterValue}
+ tenant={tenant}
+ onTenantChange={(val) => patchUrlState({ tenant: val, page: 0 })}
+ tenantOptions={tenantOptions}
+ hasTenants={hasTenants}
+ />
+ }
+ emptyState={<CliAnalyticsEmptyState />}
+ error={error}
+ isInitialLoading={isInitialLoading}
+ isTableRoute={isCallsRoute}
+ showEmpty={showEmpty}
+ >
+ <CliAnalyticsContextProvider value={outletContext}>
+ <Outlet />
+ </CliAnalyticsContextProvider>
+ </AiAnalyticsSectionLayout>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.unit.spec.tsx
new file mode 100644
index 00000000000..1873af81fd5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsSectionLayout.unit.spec.tsx
@@ -0,0 +1,462 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import {
+ setupGroupsEndpoint,
+ setupUsersEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { Route, redirect } from "metabase/router";
+import * as Urls from "metabase/urls";
+import { registerVisualizations } from "metabase/visualizations/register";
+import { AUDIT_DB_ID } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/constants";
+import type { Database, Dataset, Field } from "metabase-types/api";
+import {
+ createMockColumn,
+ createMockDatabase,
+ createMockDataset,
+ createMockDatasetData,
+ createMockField,
+ createMockGroup,
+ createMockTable,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { CliAnalyticsSectionLayout } from "./CliAnalyticsSectionLayout";
+import { CliCallsPage } from "./CliCallsPage";
+import { CliUsagePage } from "./CliUsagePage";
+
+registerVisualizations();
+
+const AGENT_API_CALLS_TABLE_ID = 2001;
+const GROUP_MEMBERS_TABLE_ID = 2002;
+
+// Field ids are deterministic — `table_id * 100 + field index` (see `buildTable`). Indices below
+// match the field order of the `v_agent_api_calls` table defined further down.
+const CALL_ID_FIELD_ID = AGENT_API_CALLS_TABLE_ID * 100 + 0;
+const CREATED_AT_FIELD_ID = AGENT_API_CALLS_TABLE_ID * 100 + 1;
+const OPERATION_FIELD_ID = AGENT_API_CALLS_TABLE_ID * 100 + 2;
+
+const BASE_TYPE = {
+ text: "type/Text",
+ integer: "type/Integer",
+ dateTime: "type/DateTimeWithLocalTZ",
+} as const;
+
+type FieldSpec = [
+ type: keyof typeof BASE_TYPE,
+ name: string,
+ semantic_type: Field["semantic_type"],
+];
+
+/** Build a mock audit-DB table (in `AUDIT_DB_ID`) with the given fields, for the metadata endpoint. */
+const buildTable = (id: number, name: string, fields: FieldSpec[]) =>
+ createMockTable({
+ id,
+ db_id: AUDIT_DB_ID,
+ schema: "public",
+ name,
+ display_name: name,
+ fields: fields.map(([type, fieldName, semantic_type], i) =>
+ createMockField({
+ id: id * 100 + i,
+ table_id: id,
+ name: fieldName,
+ display_name: fieldName,
+ fingerprint: null,
+ base_type: BASE_TYPE[type],
+ effective_type: BASE_TYPE[type],
+ semantic_type,
+ }),
+ ),
+ });
+
+const auditDatabase: Database = createMockDatabase({
+ id: AUDIT_DB_ID,
+ name: "Audit DB",
+ tables: [
+ buildTable(AGENT_API_CALLS_TABLE_ID, "v_agent_api_calls", [
+ ["text", "call_id", "type/PK"],
+ ["dateTime", "created_at", "type/CreationTimestamp"],
+ ["text", "operation", "type/Category"],
+ ["text", "status", "type/Category"],
+ ["integer", "duration_ms", "type/Quantity"],
+ ["integer", "user_id", "type/FK"],
+ ["text", "user_display_name", "type/Name"],
+ ["text", "client_display_name", "type/Category"],
+ ]),
+ buildTable(GROUP_MEMBERS_TABLE_ID, "v_group_members", [
+ ["integer", "user_id", "type/Description"],
+ ["integer", "group_id", "type/PK"],
+ ["text", "group_name", "type/Name"],
+ ]),
+ ],
+});
+
+// A breakout/count dataset that satisfies both the chart visualizations
+// (breakout + aggregation columns) and the events table (named columns).
+const datasetResponse: Dataset = createMockDataset({
+ data: createMockDatasetData({
+ rows: [
+ [12, "POST /api/agent/v1/query"],
+ [7, "GET /api/agent/v1/search"],
+ ],
+ cols: [
+ createMockColumn({
+ source: "aggregation",
+ name: "count",
+ display_name: "Count",
+ }),
+ createMockColumn({
+ source: "breakout",
+ name: "operation",
+ display_name: "Operation",
+ }),
+ ],
+ }),
+ database_id: AUDIT_DB_ID,
+ row_count: 2,
+ running_time: 1,
+});
+
+const multiPageDatasetResponse: Dataset = createMockDataset({
+ data: createMockDatasetData({
+ rows: [
+ [60, "POST /api/agent/v1/query"],
+ [7, "GET /api/agent/v1/search"],
+ ],
+ cols: [
+ createMockColumn({
+ source: "aggregation",
+ name: "count",
+ display_name: "Count",
+ }),
+ createMockColumn({
+ source: "breakout",
+ name: "operation",
+ display_name: "Operation",
+ }),
+ ],
+ }),
+ database_id: AUDIT_DB_ID,
+ row_count: 2,
+ running_time: 1,
+});
+
+// A zero-count aggregation result — what the page's "has any data?" probe gets when the
+// filtered view is empty.
+const emptyDatasetResponse: Dataset = createMockDataset({
+ data: createMockDatasetData({
+ rows: [[0]],
+ cols: [
+ createMockColumn({
+ source: "aggregation",
+ name: "count",
+ display_name: "Count",
+ }),
+ ],
+ }),
+ database_id: AUDIT_DB_ID,
+ row_count: 1,
+ running_time: 1,
+});
+
+function setupEndpoints(
+ dataset: Dataset = datasetResponse,
+ datasetError = false,
+) {
+ fetchMock.get(`path:/api/database/${AUDIT_DB_ID}/metadata`, auditDatabase);
+ fetchMock.post("path:/api/dataset/query_metadata", {
+ databases: [auditDatabase],
+ tables: auditDatabase.tables ?? [],
+ fields: (auditDatabase.tables ?? []).flatMap((table) => table.fields ?? []),
+ });
+ setupUsersEndpoints([createMockUser({ id: 1, first_name: "Ada" })]);
+ setupGroupsEndpoint([createMockGroup({ id: 1, name: "All Users" })]);
+ if (datasetError) {
+ fetchMock.post("path:/api/dataset", {
+ status: 500,
+ body: { message: "Audit query failed" },
+ });
+ } else {
+ fetchMock.post("path:/api/dataset", dataset, { name: "dataset" });
+ }
+}
+
+function setup({
+ dataset,
+ datasetError,
+ initialRoute = Urls.monitorAiAuditingCliUsage(),
+}: {
+ dataset?: Dataset;
+ datasetError?: boolean;
+ initialRoute?: string;
+} = {}) {
+ // TreeTable measures column/row sizes via the DOM; jsdom needs a stubbed rect
+ // for its virtualized rows to render.
+ mockGetBoundingClientRect({ width: 100, height: 100 });
+ setupEnterprisePlugins();
+ setupEndpoints(dataset, datasetError);
+
+ return renderWithProviders(
+ <Route path={Urls.monitorAiAuditingCli()}>
+ <Route index element={redirect("usage")} />
+ <Route element={<CliAnalyticsSectionLayout />}>
+ <Route path="usage" element={<CliUsagePage />} />
+ <Route path="calls" element={<CliCallsPage />} />
+ </Route>
+ </Route>,
+ {
+ initialRoute,
+ withRouter: true,
+ storeInitialState: createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({ audit_app: true }),
+ }),
+ }),
+ },
+ );
+}
+
+// pMBQL order-by clause: [direction, opts, ["field", opts, fieldId]]
+type OrderByClause = [string, unknown, [string, unknown, number]];
+
+type EventsMbqlStage = {
+ page?: { page: number; items: number };
+ "order-by"?: OrderByClause[];
+};
+
+/**
+ * The first MBQL stage of every adhoc `dataset` request issued so far.
+ */
+const eventsDatasetStages = (): EventsMbqlStage[] =>
+ fetchMock.callHistory
+ .calls("dataset")
+ .map((call) => call.options?.body)
+ .filter((body): body is string => typeof body === "string")
+ .map((body) => {
+ // JSON.parse is untyped (`any`); the request body is an MBQL query, so assert its shape.
+ const query = JSON.parse(body) as { stages?: EventsMbqlStage[] };
+ return query.stages?.[0];
+ })
+ .filter((stage): stage is EventsMbqlStage => stage != null);
+
+describe("CliAnalyticsSectionLayout", () => {
+ it("redirects from root route to the /usage sub-route", async () => {
+ const { router } = setup({ initialRoute: Urls.monitorAiAuditingCli() });
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingCliUsage());
+ });
+ expect(
+ await screen.findByRole("heading", { name: "CLI analytics" }),
+ ).toBeInTheDocument();
+ });
+
+ it("redirects from root route even when the section has no data", async () => {
+ const { router } = setup({
+ dataset: emptyDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingCli(),
+ });
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingCliUsage());
+ });
+ expect(await screen.findByText("No CLI activity")).toBeInTheDocument();
+ });
+
+ it("keeps the URL filter params when navigating between /usage and /calls", async () => {
+ const { router } = setup({
+ initialRoute: `${Urls.monitorAiAuditingCliUsage()}?date=past7days~&user=1`,
+ });
+
+ await screen.findByRole("heading", { name: "CLI analytics" });
+ await userEvent.click(await screen.findByRole("link", { name: "Calls" }));
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingCliCalls());
+ });
+ const search = router?.location.search ?? "";
+ expect(search).toContain("date=past7days~");
+ expect(search).toContain("user=1");
+
+ await userEvent.click(await screen.findByRole("link", { name: "Usage" }));
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingCliUsage());
+ });
+ const backSearch = router?.location.search ?? "";
+ expect(backSearch).toContain("date=past7days~");
+ expect(backSearch).toContain("user=1");
+ });
+
+ it("renders the header, filters, and /usage route by default", async () => {
+ setup();
+
+ expect(
+ await screen.findByRole("heading", { name: "CLI analytics" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByRole("link", { name: "Usage" }),
+ ).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("dataset")).toBe(true);
+ });
+ expect(await screen.findByText("Calls by operation")).toBeInTheDocument();
+ // The errors section renders because the (mocked) error count is > 0.
+ expect(await screen.findByText("Errors by operation")).toBeInTheDocument();
+ });
+
+ it("navigates to the /calls route and renders the sortable row-level table", async () => {
+ const { router } = setup();
+
+ await screen.findByRole("heading", { name: "CLI analytics" });
+ await userEvent.click(await screen.findByRole("link", { name: "Calls" }));
+
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingCliCalls());
+ expect(
+ await screen.findByRole("treegrid", { name: "Calls" }),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByRole("columnheader", { name: "Operation" }),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText("POST /api/agent/v1/query"),
+ ).toBeInTheDocument();
+ });
+
+ it("sorts the /calls table server-side when a column header is clicked", async () => {
+ setup({ initialRoute: Urls.monitorAiAuditingCliCalls() });
+
+ await screen.findByRole("treegrid", { name: "Calls" });
+
+ await userEvent.click(
+ await screen.findByRole("columnheader", { name: "Operation" }),
+ );
+
+ await waitFor(() => {
+ const sortedStage = eventsDatasetStages().find(
+ (stage) => stage.page != null && stage["order-by"]?.[0]?.[0] === "asc",
+ );
+ expect(
+ sortedStage?.["order-by"]?.map(([direction, , [, , fieldId]]) => [
+ direction,
+ fieldId,
+ ]),
+ ).toEqual([
+ ["asc", OPERATION_FIELD_ID],
+ ["desc", CALL_ID_FIELD_ID],
+ ]);
+ });
+ });
+
+ it("paginates the /calls table when there are more matching rows than one page", async () => {
+ setup({
+ dataset: multiPageDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingCliCalls(),
+ });
+
+ const pagination = await screen.findByRole("navigation", {
+ name: "pagination",
+ });
+ expect(within(pagination).getByLabelText("Previous page")).toBeDisabled();
+ const nextButton = within(pagination).getByLabelText("Next page");
+ expect(nextButton).toBeEnabled();
+
+ await userEvent.click(nextButton);
+
+ // Advancing issues an adhoc dataset query for the second MBQL page (1-indexed).
+ await waitFor(() => {
+ const requestedPage2 = eventsDatasetStages().some(
+ (stage) => stage.page?.page === 2,
+ );
+ expect(requestedPage2).toBe(true);
+ });
+ });
+
+ it("updates the page URL param when Next is clicked", async () => {
+ const { router } = setup({
+ dataset: multiPageDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingCliCalls(),
+ });
+
+ const pagination = await screen.findByRole("navigation", {
+ name: "pagination",
+ });
+ await userEvent.click(within(pagination).getByLabelText("Next page"));
+ await waitFor(() => {
+ expect(router?.location.search).toContain("page=1");
+ });
+ });
+
+ it("orders the /calls query by a total order (created_at + call_id) for stable paging", async () => {
+ setup({ initialRoute: Urls.monitorAiAuditingCliCalls() });
+
+ // The calls request is the paginated one (carries a `page` clause); its order-by must be
+ // created_at + call_id (PK) tiebreaker, so pages can't skip/duplicate rows on
+ // tied timestamps.
+ await waitFor(() => {
+ const eventsStage = eventsDatasetStages().find(
+ (stage) => stage.page != null,
+ );
+ expect(eventsStage?.["order-by"]?.map((clause) => clause[2][2])).toEqual([
+ CREATED_AT_FIELD_ID,
+ CALL_ID_FIELD_ID,
+ ]);
+ });
+ });
+
+ it("shows an error instead of spinning forever when the count query fails", async () => {
+ setup({ datasetError: true });
+
+ expect(
+ await screen.findByRole("heading", { name: "CLI analytics" }),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Audit query failed")).toBeInTheDocument();
+ expect(screen.queryByText("Calls by operation")).not.toBeInTheDocument();
+ });
+
+ it("keeps the shared filters visible after navigating between /usage and /calls", async () => {
+ setup();
+
+ await screen.findByRole("heading", { name: "CLI analytics" });
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(await screen.findByRole("link", { name: "Calls" }));
+ await screen.findByRole("treegrid", { name: "Calls" });
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps the header, tabs, and filters visible and shows an empty state in place of the tab content when there is no activity", async () => {
+ setup({ dataset: emptyDatasetResponse });
+
+ expect(
+ await screen.findByRole("heading", { name: "CLI analytics" }),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("No CLI activity")).toBeInTheDocument();
+
+ expect(screen.getByRole("link", { name: "Usage" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Calls" })).toBeInTheDocument();
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliCallsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliCallsPage.tsx
new file mode 100644
index 00000000000..a06cc81a617
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliCallsPage.tsx
@@ -0,0 +1,35 @@
+import { CliEventsTable } from "./CliEventsTable";
+import { useCliAnalyticsContext } from "./context";
+
+export function CliCallsPage() {
+ const {
+ dataSources: { provider, table, groupMembersTable },
+ chartFilters: { dateFilter, userId, groupId, tenantId },
+ hasTenants,
+ hasPii,
+ page,
+ total,
+ onPageChange,
+ sortingOptions,
+ onSortingOptionsChange,
+ } = useCliAnalyticsContext();
+
+ return (
+ <CliEventsTable
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ hasTenants={hasTenants}
+ hasPii={hasPii}
+ page={page}
+ total={total}
+ onPageChange={onPageChange}
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliUsagePage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliUsagePage.tsx
new file mode 100644
index 00000000000..0d54898d221
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliUsagePage.tsx
@@ -0,0 +1,117 @@
+import { t } from "ttag";
+
+import { SimpleGrid, Stack, Title } from "metabase/ui";
+import { buildCallsByDayByStatusQuery } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/query-utils";
+
+import { CliBreakoutChart } from "./CliBreakoutChart";
+import { CliCallerLivenessTable } from "./CliCallerLivenessTable";
+import { CliCallsTimelineChart } from "./CliCallsTimelineChart";
+import { useCliAnalyticsContext } from "./context";
+
+export function CliUsagePage() {
+ const {
+ dataSources: { provider, table, groupMembersTable },
+ chartFilters: { dateFilter, userId, groupId, tenantId },
+ hasErrors,
+ } = useCliAnalyticsContext();
+
+ return (
+ <Stack gap="lg">
+ <CliCallsTimelineChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by client over time`}
+ />
+ <SimpleGrid cols={2} spacing="lg">
+ <CliBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by client`}
+ display="pie"
+ breakoutColumn="client_display_name"
+ h={500}
+ />
+ <CliBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by operation`}
+ display="row"
+ breakoutColumn="operation"
+ h={500}
+ />
+ </SimpleGrid>
+ <SimpleGrid cols={2} spacing="lg">
+ <CliBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by user`}
+ display="row"
+ breakoutColumn="user_display_name"
+ h={500}
+ />
+ <CliCallerLivenessTable
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`User activity`}
+ h={500}
+ />
+ </SimpleGrid>
+
+ {hasErrors && (
+ <>
+ <Title order={3} mt="md">{t`Errors`}</Title>
+ <CliCallsTimelineChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by status over time`}
+ buildQuery={buildCallsByDayByStatusQuery}
+ />
+ <CliBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Errors by operation`}
+ display="row"
+ breakoutColumn="operation"
+ errorsOnly
+ h={500}
+ />
+ </>
+ )}
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/context.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/context.tsx
new file mode 100644
index 00000000000..a12a9c85ed7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/context.tsx
@@ -0,0 +1,63 @@
+import { type ReactNode, createContext, useContext } from "react";
+
+import type {
+ CliEventSortColumn,
+ CliFilters,
+} from "metabase-enterprise/monitor/ai-auditing/cli-analytics/query-utils";
+import type {
+ CardMetadata,
+ MetadataProvider,
+ TableMetadata,
+} from "metabase-lib";
+import type { SortingOptions } from "metabase-types/api";
+
+type CliDataSources = {
+ provider: MetadataProvider | null;
+ table: TableMetadata | CardMetadata | null;
+ groupMembersTable: TableMetadata | CardMetadata | null;
+};
+
+export type CliAnalyticsContextValue = {
+ dataSources: CliDataSources;
+ chartFilters: CliFilters;
+ hasTenants: boolean;
+ hasPii: boolean;
+ hasErrors: boolean;
+ page: number;
+ total: number;
+ onPageChange: (page: number) => void;
+ sortingOptions: SortingOptions<CliEventSortColumn>;
+ onSortingOptionsChange: (
+ sortingOptions: SortingOptions<CliEventSortColumn>,
+ ) => void;
+};
+
+const CliAnalyticsContext = createContext<CliAnalyticsContextValue | null>(
+ null,
+);
+
+type CliAnalyticsContextProviderProps = {
+ children: ReactNode;
+ value: CliAnalyticsContextValue;
+};
+
+export function CliAnalyticsContextProvider({
+ children,
+ value,
+}: CliAnalyticsContextProviderProps) {
+ return (
+ <CliAnalyticsContext.Provider value={value}>
+ {children}
+ </CliAnalyticsContext.Provider>
+ );
+}
+
+export function useCliAnalyticsContext(): CliAnalyticsContextValue {
+ const context = useContext(CliAnalyticsContext);
+ if (context === null) {
+ throw new Error(
+ "useCliAnalyticsContext must be used within CliAnalyticsContextProvider",
+ );
+ }
+ return context;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData.ts
index 4d40cdc4467..714bc9902d5 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/hooks/useCliHasData.ts
@@ -24,6 +24,8 @@ type Result = {
hasData: boolean;
/** Total number of calls matching the current filters — drives the events pagination. */
count: number;
+ /** Set when the count query itself failed (e.g. a 500) — the page should show an error, not spin forever. */
+ error: unknown;
};
/**
@@ -67,11 +69,14 @@ export function useCliHasData({
],
);
- const { data, isFetching } = useAdhocBreakoutQuery(query);
+ const { data, isFetching, error } = useAdhocBreakoutQuery(query);
- // Latch once the first count resolves; from then on a fetch is a refetch, not initial load.
+ // Latch once the first count resolves (successfully or not); from then on a fetch is a
+ // refetch, not initial load.
const hasLoadedOnce = useRef(false);
- const resolved = query != null && !isFetching && data != null;
+ const hasError = error != null;
+ const resolved =
+ query !== null && !isFetching && (data !== undefined || hasError);
if (resolved) {
hasLoadedOnce.current = true;
}
@@ -85,5 +90,6 @@ export function useCliHasData({
isRefetching: hasLoadedOnce.current && isFetching,
hasData: count > 0,
count,
+ error,
};
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/index.ts
index 41b271f8ba5..e51a0724599 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/index.ts
@@ -1 +1,3 @@
-export { CliAnalyticsPage } from "./components/CliAnalyticsPage";
+export { CliAnalyticsSectionLayout } from "./components/CliAnalyticsSectionLayout";
+export { CliCallsPage } from "./components/CliCallsPage";
+export { CliUsagePage } from "./components/CliUsagePage";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state.ts
index d01b61ea342..d30bc51e3c4 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/url-state.ts
@@ -1,7 +1,8 @@
import {
- type QueryParam,
type UrlStateConfig,
- getFirstParamValue,
+ parsePage,
+ parseSortColumn,
+ parseSortDirection,
} from "metabase/common/hooks/use-url-state";
import {
type FilterUrlState,
@@ -12,56 +13,32 @@ import type { SortDirection } from "metabase-types/api";
import { CLI_EVENT_SORT_COLUMNS, type CliEventSortColumn } from "./query-utils";
-export type CliTab = "charts" | "events";
-
-type CliPageUrlState = {
- tab: CliTab;
+type CliEventsUrlState = {
/** Current page of the row-level events table, 0-indexed. */
page: number;
sort_column: CliEventSortColumn;
sort_direction: SortDirection;
};
-export type CliUrlState = FilterUrlState & CliPageUrlState;
+export type CliUrlState = FilterUrlState & CliEventsUrlState;
-const DEFAULT_TAB: CliTab = "charts";
const DEFAULT_SORT_COLUMN: CliEventSortColumn = "created_at";
const DEFAULT_SORT_DIRECTION: SortDirection = "desc";
-/** Parse the `tab` query param, defaulting to the charts tab for any unrecognized value. */
-function parseTab(param: QueryParam): CliTab {
- return getFirstParamValue(param) === "events" ? "events" : DEFAULT_TAB;
-}
-
-/** Parse the `page` query param, defaulting to 0 for anything missing or invalid. */
-function parsePage(param: QueryParam): number {
- const parsed = parseInt(getFirstParamValue(param) || "0", 10);
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
-}
-
-function parseSortColumn(param: QueryParam): CliEventSortColumn {
- const value = getFirstParamValue(param);
- return (
- CLI_EVENT_SORT_COLUMNS.find((col) => col === value) ?? DEFAULT_SORT_COLUMN
- );
-}
-
-function parseSortDirection(param: QueryParam): SortDirection {
- const value = getFirstParamValue(param);
- // we don't want to use `value` directly because it may be an invalid sort direction
- // coming from URL params
- return value === "asc" || value === "desc" ? value : DEFAULT_SORT_DIRECTION;
-}
-
-const cliPageUrlStateConfig: UrlStateConfig<CliPageUrlState> = {
+const cliEventsUrlStateConfig: UrlStateConfig<CliEventsUrlState> = {
parse: (query) => ({
- tab: parseTab(query.tab),
page: parsePage(query.page),
- sort_column: parseSortColumn(query.sort_column),
- sort_direction: parseSortDirection(query.sort_direction),
+ sort_column: parseSortColumn(
+ query.sort_column,
+ CLI_EVENT_SORT_COLUMNS,
+ DEFAULT_SORT_COLUMN,
+ ),
+ sort_direction: parseSortDirection(
+ query.sort_direction,
+ DEFAULT_SORT_DIRECTION,
+ ),
}),
- serialize: ({ tab, page, sort_column, sort_direction }) => ({
- tab: tab === DEFAULT_TAB ? undefined : tab,
+ serialize: ({ page, sort_column, sort_direction }) => ({
page: page === 0 ? undefined : String(page),
sort_column: sort_column === DEFAULT_SORT_COLUMN ? undefined : sort_column,
sort_direction:
@@ -70,4 +47,4 @@ const cliPageUrlStateConfig: UrlStateConfig<CliPageUrlState> = {
};
export const cliUrlStateConfig: UrlStateConfig<CliUrlState> =
- mergeUrlStateConfig(filterUrlStateConfig, cliPageUrlStateConfig);
+ mergeUrlStateConfig(filterUrlStateConfig, cliEventsUrlStateConfig);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/AiAnalyticsSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/AiAnalyticsSectionLayout.tsx
new file mode 100644
index 00000000000..158a67dba50
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/AiAnalyticsSectionLayout.tsx
@@ -0,0 +1,113 @@
+import type { ReactNode } from "react";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import {
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
+import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
+import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
+import { Flex, Loader, Stack } from "metabase/ui";
+
+type AiAnalyticsSectionLayoutProps = {
+ children: ReactNode;
+ emptyState: ReactNode;
+ error: unknown;
+ filters: ReactNode;
+ isInitialLoading: boolean;
+ isTableRoute: boolean;
+ showEmpty: boolean;
+ tabs: PillTab[];
+ title: string;
+};
+
+export function AiAnalyticsSectionLayout({
+ children,
+ emptyState,
+ error,
+ filters,
+ isInitialLoading,
+ isTableRoute,
+ showEmpty,
+ tabs,
+ title,
+}: AiAnalyticsSectionLayoutProps) {
+ const sectionContent = (
+ <>
+ <PillTabNavigation tabs={tabs} />
+ {filters}
+ <RouteContent
+ emptyState={emptyState}
+ error={error}
+ isInitialLoading={isInitialLoading}
+ showEmpty={showEmpty}
+ >
+ {children}
+ </RouteContent>
+ </>
+ );
+
+ if (isTableRoute) {
+ return (
+ <Flex h="100%" wrap="nowrap">
+ <MonitorMain>
+ <Stack gap="lg" flex={1} mih={0}>
+ <MonitorHeaderTitle>{title}</MonitorHeaderTitle>
+ <Stack
+ gap="md"
+ flex={1}
+ mih={0}
+ display="flex"
+ style={{ flexDirection: "column" }}
+ >
+ {sectionContent}
+ </Stack>
+ </Stack>
+ </MonitorMain>
+ </Flex>
+ );
+ }
+
+ return (
+ <MonitorMain>
+ <Stack gap="lg">
+ <MonitorHeaderTitle>{title}</MonitorHeaderTitle>
+ <Stack gap="md">{sectionContent}</Stack>
+ </Stack>
+ </MonitorMain>
+ );
+}
+
+type RouteContentProps = {
+ children: ReactNode;
+ emptyState: ReactNode;
+ error: unknown;
+ isInitialLoading: boolean;
+ showEmpty: boolean;
+};
+
+function RouteContent({
+ children,
+ emptyState,
+ error,
+ isInitialLoading,
+ showEmpty,
+}: RouteContentProps) {
+ if (error !== undefined && error !== null) {
+ return (
+ <Flex mih="60vh" align="center" justify="center">
+ <LoadingAndErrorWrapper loading={false} error={error} />
+ </Flex>
+ );
+ }
+
+ if (isInitialLoading) {
+ return (
+ <Flex mih="60vh" align="center" justify="center">
+ <Loader size="lg" />
+ </Flex>
+ );
+ }
+
+ return showEmpty ? emptyState : children;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/index.ts
new file mode 100644
index 00000000000..86c2d93c524
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout/index.ts
@@ -0,0 +1 @@
+export * from "./AiAnalyticsSectionLayout";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.tsx
deleted file mode 100644
index 1fcb07c37cc..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.tsx
+++ /dev/null
@@ -1,263 +0,0 @@
-import { useMemo } from "react";
-import { P, match } from "ts-pattern";
-import { t } from "ttag";
-
-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { useUrlState } from "metabase/common/hooks/use-url-state";
-import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
-import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
-import { useLocation } from "metabase/router";
-import { useSetting } from "metabase/settings";
-import { Flex, Loader, SimpleGrid, Stack, Tabs, Title } from "metabase/ui";
-import {
- VIEW_GROUP_MEMBERS,
- VIEW_MCP_TOOL_CALLS,
-} from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/constants";
-import { useMcpHasData } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData";
-import { buildCallsByDayByStatusQuery } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/query-utils";
-import { mcpUrlStateConfig } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state";
-import {
- // The shared audit filter bar; aliased since it has nothing to do with MCP "conversations".
- ConversationFilters as McpToolCallsFilter,
- useFilterOptions,
-} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationFilters";
-import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
-
-import { McpAnalyticsEmptyState } from "./McpAnalyticsEmptyState";
-import { McpBreakoutChart } from "./McpBreakoutChart";
-import { McpCallsTimelineChart } from "./McpCallsTimelineChart";
-import { McpEventsTable } from "./McpEventsTable";
-
-/**
- * AI Auditing MCP analytics page. Renders live ad-hoc queries over the `v_mcp_tool_calls` audit view
- * across two tabs (Charts and a row-level Events table), sharing URL-state date/user/group
- * filters.
- */
-export function McpAnalyticsPage() {
- const location = useLocation();
- const [
- { date, user, group, tenant, tab, page, sort_column, sort_direction },
- { patchUrlState },
- ] = useUrlState(location, mcpUrlStateConfig);
-
- const {
- dateFilter,
- userId,
- groupId,
- tenantId,
- groupNoFilterValue,
- userOptions,
- groupOptions,
- tenantOptions,
- hasTenants,
- } = useFilterOptions({ date, user, group, tenant });
-
- // IP address and error message are PII (null unless retention is on), so only surface those
- // columns when they're collected.
- const hasPii = useSetting("analytics-pii-retention-enabled") === true;
- const toolCallsAudit = useAuditTable(VIEW_MCP_TOOL_CALLS);
- const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);
-
- const dataSources = {
- provider: toolCallsAudit.provider,
- table: toolCallsAudit.table,
- groupMembersTable: groupMembersAudit.table,
- };
-
- const chartFilters = { dateFilter, userId, groupId, tenantId };
-
- const sortingOptions = useMemo(
- () => ({ sort_column, sort_direction }),
- [sort_column, sort_direction],
- );
-
- const { isInitialLoading, isRefetching, hasData, count, error } =
- useMcpHasData({
- ...dataSources,
- ...chartFilters,
- });
- // Initial load shows a loader (never the empty state). After the first result, a filter
- // change keeps the charts mounted so they show their own skeletons while refetching; the
- // empty state only appears once a load has resolved to zero rows.
- const showEmpty = !isInitialLoading && !isRefetching && !hasData;
-
- // Only surface the errors section when the current filters actually match failed calls, so a
- // healthy instance doesn't show a row of empty error charts.
- const { hasData: hasErrors } = useMcpHasData({
- ...dataSources,
- ...chartFilters,
- errorsOnly: true,
- });
-
- // The events (Tool calls) tab is a data grid that should scroll internally.
- const isEventsTab = tab === "events";
-
- const content = (
- <MonitorMain>
- <Stack gap="lg" {...(isEventsTab ? { flex: 1, mih: 0 } : {})}>
- <MonitorHeaderTitle>{t`MCP analytics`}</MonitorHeaderTitle>
-
- <Tabs
- variant="pills"
- value={tab}
- onChange={(val) =>
- patchUrlState({ tab: val === "events" ? "events" : "charts" })
- }
- keepMounted={false}
- {...(isEventsTab
- ? {
- flex: 1,
- mih: 0,
- display: "flex",
- style: { flexDirection: "column" },
- }
- : {})}
- >
- <Tabs.List mb="md">
- <Tabs.Tab value="charts">{t`Usage`}</Tabs.Tab>
- <Tabs.Tab value="events">{t`Tool calls`}</Tabs.Tab>
- </Tabs.List>
-
- <McpToolCallsFilter
- date={date}
- onDateChange={(val) => patchUrlState({ date: val, page: 0 })}
- user={user}
- onUserChange={(val) => patchUrlState({ user: val, page: 0 })}
- userOptions={userOptions}
- group={group}
- onGroupChange={(val) => patchUrlState({ group: val, page: 0 })}
- groupOptions={groupOptions}
- groupNoFilterValue={groupNoFilterValue}
- tenant={tenant}
- onTenantChange={(val) => patchUrlState({ tenant: val, page: 0 })}
- tenantOptions={tenantOptions}
- hasTenants={hasTenants}
- />
-
- {match({ isInitialLoading, showEmpty, error })
- .with({ error: P.nonNullable }, () => (
- <Tabs.Panel value={tab} mt="md">
- <Flex mih="60vh" align="center" justify="center">
- <LoadingAndErrorWrapper loading={false} error={error} />
- </Flex>
- </Tabs.Panel>
- ))
- .with({ isInitialLoading: true }, () => (
- // Keeps the active tab's panel/tabpanel relationship intact (aria-controls on the
- // selected tab must point at a rendered element) while the initial load is pending.
- <Tabs.Panel value={tab} mt="md">
- <Flex mih="60vh" align="center" justify="center">
- <Loader size="lg" />
- </Flex>
- </Tabs.Panel>
- ))
- .with({ showEmpty: true }, () => (
- <Tabs.Panel value={tab} mt="md">
- <McpAnalyticsEmptyState />
- </Tabs.Panel>
- ))
- .otherwise(() => (
- <>
- <Tabs.Panel value="charts" mt="md">
- <Stack gap="lg">
- <McpCallsTimelineChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by client over time`}
- />
- <SimpleGrid cols={2} spacing="lg">
- <McpBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by tool`}
- display="pie"
- breakoutColumn="tool_name"
- h={500}
- />
- <McpBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by user`}
- display="row"
- breakoutColumn="user_display_name"
- h={500}
- />
- </SimpleGrid>
-
- {hasErrors && (
- <>
- <Title order={3} mt="md">{t`Errors`}</Title>
- <McpCallsTimelineChart
- {...dataSources}
- {...chartFilters}
- title={t`Calls by status over time`}
- buildQuery={buildCallsByDayByStatusQuery}
- />
- <SimpleGrid cols={2} spacing="lg">
- <McpBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Errors by type`}
- display="pie"
- breakoutColumn="error_type"
- errorsOnly
- h={500}
- />
- <McpBreakoutChart
- {...dataSources}
- {...chartFilters}
- title={t`Errors by tool`}
- display="row"
- breakoutColumn="tool_name"
- errorsOnly
- h={500}
- />
- </SimpleGrid>
- </>
- )}
- </Stack>
- </Tabs.Panel>
-
- <Tabs.Panel
- value="events"
- mt="md"
- flex={1}
- mih={0}
- display="flex"
- style={{ flexDirection: "column" }}
- >
- <McpEventsTable
- {...dataSources}
- {...chartFilters}
- hasTenants={hasTenants}
- hasPii={hasPii}
- page={page}
- total={count}
- onPageChange={(newPage) =>
- patchUrlState({ page: newPage }, { immediate: true })
- }
- sortingOptions={sortingOptions}
- onSortingOptionsChange={(newSorting) =>
- patchUrlState({
- sort_column: newSorting.sort_column,
- sort_direction: newSorting.sort_direction,
- page: 0,
- })
- }
- />
- </Tabs.Panel>
- </>
- ))}
- </Tabs>
- </Stack>
- </MonitorMain>
- );
-
- return isEventsTab ? (
- <Flex h="100%" wrap="nowrap">
- {content}
- </Flex>
- ) : (
- content
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.tsx
new file mode 100644
index 00000000000..f718da846e2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.tsx
@@ -0,0 +1,157 @@
+import { useMemo } from "react";
+import { t } from "ttag";
+
+import type { PillTab } from "metabase/common/components/PillTabNavigation";
+import { useUrlState } from "metabase/common/hooks/use-url-state";
+import { Outlet, useLocation } from "metabase/router";
+import { useSetting } from "metabase/settings";
+import * as Urls from "metabase/urls";
+import { AiAnalyticsSectionLayout } from "metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout";
+import {
+ VIEW_GROUP_MEMBERS,
+ VIEW_MCP_TOOL_CALLS,
+} from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/constants";
+import { useMcpHasData } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData";
+import { mcpUrlStateConfig } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state";
+import {
+ ConversationFilters as McpToolCallsFilter,
+ useFilterOptions,
+} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationFilters";
+import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
+
+import { McpAnalyticsEmptyState } from "./McpAnalyticsEmptyState";
+import {
+ McpAnalyticsContextProvider,
+ type McpAnalyticsContextValue,
+} from "./context";
+
+export function McpAnalyticsSectionLayout() {
+ const location = useLocation();
+ const [
+ { date, user, group, tenant, page, sort_column, sort_direction },
+ { patchUrlState },
+ ] = useUrlState(location, mcpUrlStateConfig);
+
+ const {
+ dateFilter,
+ userId,
+ groupId,
+ tenantId,
+ groupNoFilterValue,
+ userOptions,
+ groupOptions,
+ tenantOptions,
+ hasTenants,
+ } = useFilterOptions({ date, user, group, tenant });
+
+ const hasPii = useSetting("analytics-pii-retention-enabled") === true;
+ const toolCallsAudit = useAuditTable(VIEW_MCP_TOOL_CALLS);
+ const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);
+
+ const dataSources = useMemo(
+ () => ({
+ provider: toolCallsAudit.provider,
+ table: toolCallsAudit.table,
+ groupMembersTable: groupMembersAudit.table,
+ }),
+ [groupMembersAudit.table, toolCallsAudit.provider, toolCallsAudit.table],
+ );
+ const chartFilters = useMemo(
+ () => ({ dateFilter, userId, groupId, tenantId }),
+ [dateFilter, groupId, tenantId, userId],
+ );
+ const sortingOptions = useMemo(
+ () => ({ sort_column, sort_direction }),
+ [sort_column, sort_direction],
+ );
+
+ const { isInitialLoading, isRefetching, hasData, count, error } =
+ useMcpHasData({ ...dataSources, ...chartFilters });
+ const { hasData: hasErrors } = useMcpHasData({
+ ...dataSources,
+ ...chartFilters,
+ errorsOnly: true,
+ });
+ const showEmpty = !isInitialLoading && !isRefetching && !hasData;
+
+ const usagePath = Urls.monitorAiAuditingMcpUsage();
+ const eventsPath = Urls.monitorAiAuditingMcpEvents();
+ const tabs: PillTab[] = [
+ {
+ label: t`Usage`,
+ to: `${usagePath}${location.search}`,
+ isSelected: (pathname) => pathname === usagePath,
+ },
+ {
+ label: t`Tool calls`,
+ to: `${eventsPath}${location.search}`,
+ isSelected: (pathname) => pathname === eventsPath,
+ },
+ ];
+
+ const isEventsRoute = location.pathname === eventsPath;
+ const outletContext = useMemo<McpAnalyticsContextValue>(
+ () => ({
+ dataSources,
+ chartFilters,
+ hasTenants,
+ hasPii,
+ hasErrors,
+ page,
+ total: count,
+ onPageChange: (newPage) =>
+ patchUrlState({ page: newPage }, { immediate: true }),
+ sortingOptions,
+ onSortingOptionsChange: (newSorting) =>
+ patchUrlState({
+ sort_column: newSorting.sort_column,
+ sort_direction: newSorting.sort_direction,
+ page: 0,
+ }),
+ }),
+ [
+ chartFilters,
+ count,
+ dataSources,
+ hasErrors,
+ hasPii,
+ hasTenants,
+ page,
+ patchUrlState,
+ sortingOptions,
+ ],
+ );
+
+ return (
+ <AiAnalyticsSectionLayout
+ title={t`MCP analytics`}
+ tabs={tabs}
+ filters={
+ <McpToolCallsFilter
+ date={date}
+ onDateChange={(val) => patchUrlState({ date: val, page: 0 })}
+ user={user}
+ onUserChange={(val) => patchUrlState({ user: val, page: 0 })}
+ userOptions={userOptions}
+ group={group}
+ onGroupChange={(val) => patchUrlState({ group: val, page: 0 })}
+ groupOptions={groupOptions}
+ groupNoFilterValue={groupNoFilterValue}
+ tenant={tenant}
+ onTenantChange={(val) => patchUrlState({ tenant: val, page: 0 })}
+ tenantOptions={tenantOptions}
+ hasTenants={hasTenants}
+ />
+ }
+ emptyState={<McpAnalyticsEmptyState />}
+ error={error}
+ isInitialLoading={isInitialLoading}
+ isTableRoute={isEventsRoute}
+ showEmpty={showEmpty}
+ >
+ <McpAnalyticsContextProvider value={outletContext}>
+ <Outlet />
+ </McpAnalyticsContextProvider>
+ </AiAnalyticsSectionLayout>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.unit.spec.tsx
similarity index 73%
rename from enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx
rename to enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.unit.spec.tsx
index 9d6878ee299..574998bb928 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsSectionLayout.unit.spec.tsx
@@ -15,7 +15,8 @@ import {
within,
} from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import { Route } from "metabase/router";
+import { Route, redirect } from "metabase/router";
+import * as Urls from "metabase/urls";
import { registerVisualizations } from "metabase/visualizations/register";
import { AUDIT_DB_ID } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/constants";
import type { Database, Dataset, Field } from "metabase-types/api";
@@ -31,7 +32,9 @@ import {
createMockUser,
} from "metabase-types/api/mocks";
-import { McpAnalyticsPage } from "./McpAnalyticsPage";
+import { McpAnalyticsSectionLayout } from "./McpAnalyticsSectionLayout";
+import { McpEventsPage } from "./McpEventsPage";
+import { McpUsagePage } from "./McpUsagePage";
registerVisualizations();
@@ -42,6 +45,7 @@ const GROUP_MEMBERS_TABLE_ID = 2002;
// match the field order of the `v_mcp_tool_calls` table defined further down.
const TOOL_CALL_ID_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 0;
const CREATED_AT_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 1;
+const TOOL_NAME_FIELD_ID = MCP_TOOL_CALLS_TABLE_ID * 100 + 2;
const BASE_TYPE = {
text: "type/Text",
@@ -196,11 +200,16 @@ function setupEndpoints(
}
}
-/** Render `McpAnalyticsPage` at its route with EE plugins + `audit_app`, optionally overriding the dataset response. */
+/** Render the MCP analytics section (layout + usage/events sub-routes) with EE plugins + `audit_app`. */
function setup({
dataset,
datasetError,
-}: { dataset?: Dataset; datasetError?: boolean } = {}) {
+ initialRoute = Urls.monitorAiAuditingMcpUsage(),
+}: {
+ dataset?: Dataset;
+ datasetError?: boolean;
+ initialRoute?: string;
+} = {}) {
// TreeTable measures column/row sizes via the DOM; jsdom needs a stubbed rect
// for its virtualized rows to render.
mockGetBoundingClientRect({ width: 100, height: 100 });
@@ -208,9 +217,15 @@ function setup({
setupEndpoints(dataset, datasetError);
return renderWithProviders(
- <Route path="/monitor/ai-auditing/mcp" element={<McpAnalyticsPage />} />,
+ <Route path={Urls.monitorAiAuditingMcp()}>
+ <Route index element={redirect("usage")} />
+ <Route element={<McpAnalyticsSectionLayout />}>
+ <Route path="usage" element={<McpUsagePage />} />
+ <Route path="events" element={<McpEventsPage />} />
+ </Route>
+ </Route>,
{
- initialRoute: "/monitor/ai-auditing/mcp",
+ initialRoute,
withRouter: true,
storeInitialState: createMockState({
settings: mockSettings({
@@ -247,8 +262,30 @@ const eventsDatasetStages = (): EventsMbqlStage[] =>
})
.filter((stage): stage is EventsMbqlStage => stage != null);
-describe("McpAnalyticsPage", () => {
- it("renders the header, filters, and charts tab", async () => {
+describe("McpAnalyticsSectionLayout", () => {
+ it("redirects from root route to the /usage sub-route", async () => {
+ const { router } = setup({ initialRoute: Urls.monitorAiAuditingMcp() });
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
+ });
+ expect(
+ await screen.findByRole("heading", { name: "MCP analytics" }),
+ ).toBeInTheDocument();
+ });
+
+ it("redirects from the root route even when the section has no data", async () => {
+ const { router } = setup({
+ dataset: emptyDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingMcp(),
+ });
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
+ });
+ expect(await screen.findByText("No MCP activity")).toBeInTheDocument();
+ });
+
+ it("renders the header, filters, and /usage route by default", async () => {
setup();
expect(
@@ -259,7 +296,7 @@ describe("McpAnalyticsPage", () => {
).toBeInTheDocument();
// Tabs appear only after the initial count query resolves (the page shows a loader first).
expect(
- await screen.findByRole("tab", { name: "Usage" }),
+ await screen.findByRole("link", { name: "Usage" }),
).toBeInTheDocument();
// Charts run ad-hoc dataset queries through /api/dataset.
@@ -271,53 +308,98 @@ describe("McpAnalyticsPage", () => {
expect(await screen.findByText("Errors by type")).toBeInTheDocument();
});
- it("switches to the events tab and renders the row-level table", async () => {
- setup();
+ it("navigates to the /events route and renders the row-level table", async () => {
+ const { router } = setup();
await screen.findByRole("heading", { name: "MCP analytics" });
await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
+ await screen.findByRole("link", { name: "Tool calls" }),
);
- const eventsPanel = screen.getByRole("tabpanel");
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpEvents());
expect(
- await within(eventsPanel).findByRole("treegrid", { name: "Tool calls" }),
+ await screen.findByRole("treegrid", { name: "Tool calls" }),
).toBeInTheDocument();
// curated column header + a cell value from the mocked dataset row
- expect(within(eventsPanel).getByText("Tool")).toBeInTheDocument();
+ expect(screen.getByText("Tool")).toBeInTheDocument();
+ expect(await screen.findByText("search_data")).toBeInTheDocument();
+ });
+
+ it("keeps the shared filters visible after navigating between /usage and /events", async () => {
+ setup();
+
+ await screen.findByRole("heading", { name: "MCP analytics" });
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ await screen.findByRole("link", { name: "Tool calls" }),
+ );
+ await screen.findByRole("treegrid", { name: "Tool calls" });
expect(
- await within(eventsPanel).findByText("search_data"),
+ screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
});
- it("sorts the events table server-side when a column header is clicked", async () => {
- setup();
+ it("keeps the URL filter params when navigating between /usage and /events", async () => {
+ const { router } = setup({
+ initialRoute: `${Urls.monitorAiAuditingMcpUsage()}?date=past7days~&user=1`,
+ });
await screen.findByRole("heading", { name: "MCP analytics" });
await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
+ await screen.findByRole("link", { name: "Tool calls" }),
);
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpEvents());
+ });
+ const search = router?.location.search ?? "";
+ expect(search).toContain("date=past7days~");
+ expect(search).toContain("user=1");
+
+ await userEvent.click(await screen.findByRole("link", { name: "Usage" }));
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(Urls.monitorAiAuditingMcpUsage());
+ });
+ const backSearch = router?.location.search ?? "";
+ expect(backSearch).toContain("date=past7days~");
+ expect(backSearch).toContain("user=1");
+ });
+
+ it("sorts the events table server-side when a column header is clicked", async () => {
+ setup({ initialRoute: Urls.monitorAiAuditingMcpEvents() });
+
+ await screen.findByRole("treegrid", { name: "Tool calls" });
+
// The Tool header is sortable; clicking it re-sorts ascending (it wasn't the active column).
await userEvent.click(
await screen.findByRole("columnheader", { name: "Tool" }),
);
await waitFor(() => {
- const sortedAscending = eventsDatasetStages().some(
+ const sortedStage = eventsDatasetStages().find(
(stage) => stage.page != null && stage["order-by"]?.[0]?.[0] === "asc",
);
- expect(sortedAscending).toBe(true);
+ expect(
+ sortedStage?.["order-by"]?.map(([direction, , [, , fieldId]]) => [
+ direction,
+ fieldId,
+ ]),
+ ).toEqual([
+ ["asc", TOOL_NAME_FIELD_ID],
+ ["desc", TOOL_CALL_ID_FIELD_ID],
+ ]);
});
});
it("paginates the events table when there are more matching rows than one page", async () => {
- setup({ dataset: multiPageDatasetResponse });
-
- await screen.findByRole("heading", { name: "MCP analytics" });
- await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
- );
+ setup({
+ dataset: multiPageDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingMcpEvents(),
+ });
const pagination = await screen.findByRole("navigation", {
name: "pagination",
@@ -339,12 +421,10 @@ describe("McpAnalyticsPage", () => {
});
it("updates the page URL param immediately when Next is clicked", async () => {
- const { router } = setup({ dataset: multiPageDatasetResponse });
-
- await screen.findByRole("heading", { name: "MCP analytics" });
- await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
- );
+ const { router } = setup({
+ dataset: multiPageDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingMcpEvents(),
+ });
const pagination = await screen.findByRole("navigation", {
name: "pagination",
@@ -355,13 +435,12 @@ describe("McpAnalyticsPage", () => {
});
it("issues exactly one events query per page change (no redundant refetch)", async () => {
- const { router } = setup({ dataset: multiPageDatasetResponse });
+ const { router } = setup({
+ dataset: multiPageDatasetResponse,
+ initialRoute: Urls.monitorAiAuditingMcpEvents(),
+ });
- await screen.findByRole("heading", { name: "MCP analytics" });
- await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
- );
- await within(screen.getByRole("tabpanel")).findByRole("treegrid");
+ await screen.findByRole("treegrid", { name: "Tool calls" });
// Dataset calls for the events query's second page (MBQL `:page` is 1-indexed, so UI page 1).
const page2EventsCalls = () =>
@@ -379,12 +458,7 @@ describe("McpAnalyticsPage", () => {
});
it("orders the events query by a total order (created_at + tool_call_id) for stable paging", async () => {
- setup();
-
- await screen.findByRole("heading", { name: "MCP analytics" });
- await userEvent.click(
- await screen.findByRole("tab", { name: "Tool calls" }),
- );
+ setup({ initialRoute: Urls.monitorAiAuditingMcpEvents() });
// The events request is the paginated one (carries a `page` clause); its order-by must be
// created_at followed by the tool_call_id (PK) tiebreaker, so pages can't skip/duplicate rows
@@ -409,16 +483,13 @@ describe("McpAnalyticsPage", () => {
expect(await screen.findByText("No MCP activity")).toBeInTheDocument();
// Tabs and filters stay visible even when the view is empty — only the tab content swaps out.
- const usageTab = screen.getByRole("tab", { name: "Usage" });
- expect(usageTab).toBeInTheDocument();
- expect(screen.getByRole("tab", { name: "Tool calls" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Usage" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "Tool calls" }),
+ ).toBeInTheDocument();
expect(
screen.getByTestId("conversation-filters-date-select"),
).toBeInTheDocument();
-
- const panel = screen.getByRole("tabpanel");
- expect(usageTab).toHaveAttribute("aria-controls", panel.id);
- expect(within(panel).getByText("No MCP activity")).toBeInTheDocument();
});
it("shows an error instead of spinning forever when the count query fails", async () => {
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpEventsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpEventsPage.tsx
new file mode 100644
index 00000000000..b7d54e3023b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpEventsPage.tsx
@@ -0,0 +1,35 @@
+import { McpEventsTable } from "./McpEventsTable";
+import { useMcpAnalyticsContext } from "./context";
+
+export function McpEventsPage() {
+ const {
+ dataSources: { provider, table, groupMembersTable },
+ chartFilters: { dateFilter, userId, groupId, tenantId },
+ hasTenants,
+ hasPii,
+ page,
+ total,
+ onPageChange,
+ sortingOptions,
+ onSortingOptionsChange,
+ } = useMcpAnalyticsContext();
+
+ return (
+ <McpEventsTable
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ hasTenants={hasTenants}
+ hasPii={hasPii}
+ page={page}
+ total={total}
+ onPageChange={onPageChange}
+ sortingOptions={sortingOptions}
+ onSortingOptionsChange={onSortingOptionsChange}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpUsagePage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpUsagePage.tsx
new file mode 100644
index 00000000000..51c29eed1d7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpUsagePage.tsx
@@ -0,0 +1,106 @@
+import { t } from "ttag";
+
+import { SimpleGrid, Stack, Title } from "metabase/ui";
+import { buildCallsByDayByStatusQuery } from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/query-utils";
+
+import { McpBreakoutChart } from "./McpBreakoutChart";
+import { McpCallsTimelineChart } from "./McpCallsTimelineChart";
+import { useMcpAnalyticsContext } from "./context";
+
+export function McpUsagePage() {
+ const {
+ dataSources: { provider, table, groupMembersTable },
+ chartFilters: { dateFilter, userId, groupId, tenantId },
+ hasErrors,
+ } = useMcpAnalyticsContext();
+
+ return (
+ <Stack gap="lg">
+ <McpCallsTimelineChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by client over time`}
+ />
+ <SimpleGrid cols={2} spacing="lg">
+ <McpBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by tool`}
+ display="pie"
+ breakoutColumn="tool_name"
+ h={500}
+ />
+ <McpBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by user`}
+ display="row"
+ breakoutColumn="user_display_name"
+ h={500}
+ />
+ </SimpleGrid>
+
+ {hasErrors && (
+ <>
+ <Title order={3} mt="md">{t`Errors`}</Title>
+ <McpCallsTimelineChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Calls by status over time`}
+ buildQuery={buildCallsByDayByStatusQuery}
+ />
+ <SimpleGrid cols={2} spacing="lg">
+ <McpBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Errors by type`}
+ display="pie"
+ breakoutColumn="error_type"
+ errorsOnly
+ h={500}
+ />
+ <McpBreakoutChart
+ provider={provider}
+ table={table}
+ groupMembersTable={groupMembersTable}
+ dateFilter={dateFilter}
+ userId={userId}
+ groupId={groupId}
+ tenantId={tenantId}
+ title={t`Errors by tool`}
+ display="row"
+ breakoutColumn="tool_name"
+ errorsOnly
+ h={500}
+ />
+ </SimpleGrid>
+ </>
+ )}
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/context.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/context.tsx
new file mode 100644
index 00000000000..e743702ccff
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/context.tsx
@@ -0,0 +1,63 @@
+import { type ReactNode, createContext, useContext } from "react";
+
+import type {
+ McpEventSortColumn,
+ McpFilters,
+} from "metabase-enterprise/monitor/ai-auditing/mcp-analytics/query-utils";
+import type {
+ CardMetadata,
+ MetadataProvider,
+ TableMetadata,
+} from "metabase-lib";
+import type { SortingOptions } from "metabase-types/api";
+
+type McpDataSources = {
+ provider: MetadataProvider | null;
+ table: TableMetadata | CardMetadata | null;
+ groupMembersTable: TableMetadata | CardMetadata | null;
+};
+
+export type McpAnalyticsContextValue = {
+ dataSources: McpDataSources;
+ chartFilters: McpFilters;
+ hasTenants: boolean;
+ hasPii: boolean;
+ hasErrors: boolean;
+ page: number;
+ total: number;
+ onPageChange: (page: number) => void;
+ sortingOptions: SortingOptions<McpEventSortColumn>;
+ onSortingOptionsChange: (
+ sortingOptions: SortingOptions<McpEventSortColumn>,
+ ) => void;
+};
+
+const McpAnalyticsContext = createContext<McpAnalyticsContextValue | null>(
+ null,
+);
+
+type McpAnalyticsContextProviderProps = {
+ children: ReactNode;
+ value: McpAnalyticsContextValue;
+};
+
+export function McpAnalyticsContextProvider({
+ children,
+ value,
+}: McpAnalyticsContextProviderProps) {
+ return (
+ <McpAnalyticsContext.Provider value={value}>
+ {children}
+ </McpAnalyticsContext.Provider>
+ );
+}
+
+export function useMcpAnalyticsContext(): McpAnalyticsContextValue {
+ const context = useContext(McpAnalyticsContext);
+ if (context === null) {
+ throw new Error(
+ "useMcpAnalyticsContext must be used within McpAnalyticsContextProvider",
+ );
+ }
+ return context;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData.ts
index 7a94d092929..a3f6308b81f 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/hooks/useMcpHasData.ts
@@ -75,8 +75,9 @@ export function useMcpHasData({
// Latch once the first count resolves (successfully or not); from then on a fetch is a
// refetch, not initial load.
const hasLoadedOnce = useRef(false);
+ const hasError = error != null;
const resolved =
- query != null && !isFetching && (data != null || error != null);
+ query !== null && !isFetching && (data !== undefined || hasError);
if (resolved) {
hasLoadedOnce.current = true;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/index.ts
index 0b349df471f..5287b794733 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/index.ts
@@ -1 +1,3 @@
-export { McpAnalyticsPage } from "./components/McpAnalyticsPage";
+export { McpAnalyticsSectionLayout } from "./components/McpAnalyticsSectionLayout";
+export { McpEventsPage } from "./components/McpEventsPage";
+export { McpUsagePage } from "./components/McpUsagePage";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state.ts
index 950b6021c9c..bc68b7e2061 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/url-state.ts
@@ -1,7 +1,8 @@
import {
- type QueryParam,
type UrlStateConfig,
- getFirstParamValue,
+ parsePage,
+ parseSortColumn,
+ parseSortDirection,
} from "metabase/common/hooks/use-url-state";
import type { SortDirection } from "metabase-types/api";
@@ -13,56 +14,32 @@ import {
import { MCP_EVENT_SORT_COLUMNS, type McpEventSortColumn } from "./query-utils";
-export type McpTab = "charts" | "events";
-
-type McpPageUrlState = {
- tab: McpTab;
+type McpEventsUrlState = {
/** Current page of the row-level events table, 0-indexed. */
page: number;
sort_column: McpEventSortColumn;
sort_direction: SortDirection;
};
-export type McpUrlState = FilterUrlState & McpPageUrlState;
+export type McpUrlState = FilterUrlState & McpEventsUrlState;
-const DEFAULT_TAB: McpTab = "charts";
const DEFAULT_SORT_COLUMN: McpEventSortColumn = "created_at";
const DEFAULT_SORT_DIRECTION: SortDirection = "desc";
-/** Parse the `tab` query param, defaulting to the charts tab for any unrecognized value. */
-function parseTab(param: QueryParam): McpTab {
- return getFirstParamValue(param) === "events" ? "events" : DEFAULT_TAB;
-}
-
-/** Parse the `page` query param, defaulting to 0 for anything missing or invalid. */
-function parsePage(param: QueryParam): number {
- const parsed = parseInt(getFirstParamValue(param) || "0", 10);
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
-}
-
-function parseSortColumn(param: QueryParam): McpEventSortColumn {
- const value = getFirstParamValue(param);
- return (
- MCP_EVENT_SORT_COLUMNS.find((col) => col === value) ?? DEFAULT_SORT_COLUMN
- );
-}
-
-function parseSortDirection(param: QueryParam): SortDirection {
- const value = getFirstParamValue(param);
- // we don't want to use `value` directly because it may be an invalid sort direction
- // coming from URL params
- return value === "asc" || value === "desc" ? value : DEFAULT_SORT_DIRECTION;
-}
-
-const mcpPageUrlStateConfig: UrlStateConfig<McpPageUrlState> = {
+const mcpEventsUrlStateConfig: UrlStateConfig<McpEventsUrlState> = {
parse: (query) => ({
- tab: parseTab(query.tab),
page: parsePage(query.page),
- sort_column: parseSortColumn(query.sort_column),
- sort_direction: parseSortDirection(query.sort_direction),
+ sort_column: parseSortColumn(
+ query.sort_column,
+ MCP_EVENT_SORT_COLUMNS,
+ DEFAULT_SORT_COLUMN,
+ ),
+ sort_direction: parseSortDirection(
+ query.sort_direction,
+ DEFAULT_SORT_DIRECTION,
+ ),
}),
- serialize: ({ tab, page, sort_column, sort_direction }) => ({
- tab: tab === DEFAULT_TAB ? undefined : tab,
+ serialize: ({ page, sort_column, sort_direction }) => ({
page: page === 0 ? undefined : String(page),
sort_column: sort_column === DEFAULT_SORT_COLUMN ? undefined : sort_column,
sort_direction:
@@ -71,4 +48,4 @@ const mcpPageUrlStateConfig: UrlStateConfig<McpPageUrlState> = {
};
export const mcpUrlStateConfig: UrlStateConfig<McpUrlState> =
- mergeUrlStateConfig(filterUrlStateConfig, mcpPageUrlStateConfig);
+ mergeUrlStateConfig(filterUrlStateConfig, mcpEventsUrlStateConfig);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
index 531d3a56715..6e378dbb083 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.tsx
@@ -13,16 +13,6 @@ import {
* The plugin registry assigns these routes on every page load, so whatever they
* name is in the initial bundle. The pages carry the charting and data grid
* stack, which no other page needs on first paint.
- *
- * They sit under `components/` rather than a `pages/` directory, which is why
- * the route-file lint rule reaches them by name instead.
- *
- * The route shape stays eager, so matching is unchanged. The availability gates
- * above them still decide what renders, but they now decide a tick later: the
- * router resolves a matched route's `lazy` before it commits, which means a page
- * a gate is about to block is fetched anyway. That is a few tens of kilobytes on
- * an admin page whose feature is switched off, in exchange for one splitting
- * mechanism across the app.
*/
const conversationStatsPage = () =>
import(
@@ -48,24 +38,50 @@ const metabotAnalyticsUpsellPage = () =>
Component: MetabotAnalyticsUpsellPage,
}));
-const mcpAnalyticsPage = () =>
+const mcpAnalyticsSectionLayout = () =>
+ import(
+ /* webpackChunkName: "ai-auditing" */ "./mcp-analytics/components/McpAnalyticsSectionLayout"
+ ).then(({ McpAnalyticsSectionLayout }) => ({
+ Component: McpAnalyticsSectionLayout,
+ }));
+
+const mcpUsagePage = () =>
+ import(
+ /* webpackChunkName: "ai-auditing" */ "./mcp-analytics/components/McpUsagePage"
+ ).then(({ McpUsagePage }) => ({
+ Component: McpUsagePage,
+ }));
+
+const mcpEventsPage = () =>
import(
- /* webpackChunkName: "ai-auditing" */ "./mcp-analytics/components/McpAnalyticsPage"
- ).then(({ McpAnalyticsPage }) => ({ Component: McpAnalyticsPage }));
+ /* webpackChunkName: "ai-auditing" */ "./mcp-analytics/components/McpEventsPage"
+ ).then(({ McpEventsPage }) => ({ Component: McpEventsPage }));
-const cliAnalyticsPage = () =>
+const cliAnalyticsSectionLayout = () =>
import(
- /* webpackChunkName: "ai-auditing" */ "./cli-analytics/components/CliAnalyticsPage"
- ).then(({ CliAnalyticsPage }) => ({ Component: CliAnalyticsPage }));
+ /* webpackChunkName: "ai-auditing" */ "./cli-analytics/components/CliAnalyticsSectionLayout"
+ ).then(({ CliAnalyticsSectionLayout }) => ({
+ Component: CliAnalyticsSectionLayout,
+ }));
+
+const cliUsagePage = () =>
+ import(
+ /* webpackChunkName: "ai-auditing" */ "./cli-analytics/components/CliUsagePage"
+ ).then(({ CliUsagePage }) => ({
+ Component: CliUsagePage,
+ }));
+
+const cliCallsPage = () =>
+ import(
+ /* webpackChunkName: "ai-auditing" */ "./cli-analytics/components/CliCallsPage"
+ ).then(({ CliCallsPage }) => ({
+ Component: CliCallsPage,
+ }));
/**
* Hovering a Monitor sidebar link starts the fetch, so the chunk is usually in
* hand by the time the click lands. These pages share a chunk, so the first
* hover covers the whole section.
- *
- * `/usage` renders the stats page or the upsell page depending on the license,
- * so hovering it asks for both. The conversation detail page takes the trailing
- * slash, which keeps the link to the list from dragging it in as well.
*/
registerPagePrefetch(Urls.monitorAiAuditingUsage(), conversationStatsPage);
registerPagePrefetch(Urls.monitorAiAuditingUsage(), metabotAnalyticsUpsellPage);
@@ -74,8 +90,34 @@ registerPagePrefetch(
`${Urls.monitorAiAuditingConversations()}/`,
conversationDetailPage,
);
-registerPagePrefetch(Urls.monitorAiAuditingMcp(), mcpAnalyticsPage);
-registerPagePrefetch(Urls.monitorAiAuditingCli(), cliAnalyticsPage);
+registerPagePrefetch(Urls.monitorAiAuditingMcp(), mcpAnalyticsSectionLayout);
+registerPagePrefetch(Urls.monitorAiAuditingCli(), cliAnalyticsSectionLayout);
+
+function getMcpAnalyticsRoutes() {
+ return (
+ <Route element={<McpAnalyticsAvailabilityLayout />}>
+ <Route path="mcp">
+ <Route index element={redirect("usage")} />
+ <Route lazy={mcpAnalyticsSectionLayout}>
+ <Route path="usage" lazy={mcpUsagePage} />
+ <Route path="events" lazy={mcpEventsPage} />
+ </Route>
+ </Route>
+ </Route>
+ );
+}
+
+function getCliAnalyticsRoutes() {
+ return (
+ <Route path="cli">
+ <Route index element={redirect("usage")} />
+ <Route lazy={cliAnalyticsSectionLayout}>
+ <Route path="usage" lazy={cliUsagePage} />
+ <Route path="calls" lazy={cliCallsPage} />
+ </Route>
+ </Route>
+ );
+}
export function getAiAuditingRoutes() {
return (
@@ -86,10 +128,8 @@ export function getAiAuditingRoutes() {
<Route path="conversations" lazy={conversationsPage} />
<Route path="conversations/:convoId" lazy={conversationDetailPage} />
</Route>
- <Route element={<McpAnalyticsAvailabilityLayout />}>
- <Route path="mcp" lazy={mcpAnalyticsPage} />
- </Route>
- <Route path="cli" lazy={cliAnalyticsPage} />
+ {getMcpAnalyticsRoutes()}
+ {getCliAnalyticsRoutes()}
</>
);
}
@@ -99,10 +139,8 @@ export function getAiAuditingUpsellRoutes() {
<>
<Route index element={redirect("usage")} />
<Route path="usage" lazy={metabotAnalyticsUpsellPage} />
- <Route element={<McpAnalyticsAvailabilityLayout />}>
- <Route path="mcp" lazy={mcpAnalyticsPage} />
- </Route>
- <Route path="cli" lazy={cliAnalyticsPage} />
+ {getMcpAnalyticsRoutes()}
+ {getCliAnalyticsRoutes()}
</>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.unit.spec.tsx
index 05ca8782dc3..da3846a60ad 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/routes.unit.spec.tsx
@@ -1,6 +1,7 @@
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
+import type * as Router from "metabase/router";
import { Route } from "metabase/router";
import * as Urls from "metabase/urls";
@@ -21,11 +22,39 @@ jest.mock(
MetabotAnalyticsUpsellPage: () => <div>Usage stats upsell</div>,
}),
);
-jest.mock("./mcp-analytics/components/McpAnalyticsPage", () => ({
- McpAnalyticsPage: () => <div>MCP analytics page</div>,
+jest.mock("./mcp-analytics/components/McpAnalyticsSectionLayout", () => {
+ const { Outlet } = jest.requireActual<typeof Router>("metabase/router");
+ return {
+ McpAnalyticsSectionLayout: () => (
+ <div>
+ MCP analytics page
+ <Outlet />
+ </div>
+ ),
+ };
+});
+jest.mock("./cli-analytics/components/CliAnalyticsSectionLayout", () => {
+ const { Outlet } = jest.requireActual<typeof Router>("metabase/router");
+ return {
+ CliAnalyticsSectionLayout: () => (
+ <div>
+ CLI analytics page
+ <Outlet />
+ </div>
+ ),
+ };
+});
+jest.mock("./mcp-analytics/components/McpUsagePage", () => ({
+ McpUsagePage: () => <div>MCP usage page</div>,
+}));
+jest.mock("./mcp-analytics/components/McpEventsPage", () => ({
+ McpEventsPage: () => <div>MCP tool calls page</div>,
}));
-jest.mock("./cli-analytics/components/CliAnalyticsPage", () => ({
- CliAnalyticsPage: () => <div>CLI analytics page</div>,
+jest.mock("./cli-analytics/components/CliUsagePage", () => ({
+ CliUsagePage: () => <div>CLI usage page</div>,
+}));
+jest.mock("./cli-analytics/components/CliCallsPage", () => ({
+ CliCallsPage: () => <div>CLI calls page</div>,
}));
type SetupOpts = {
@@ -160,6 +189,42 @@ describe("AI Auditing routes", () => {
},
);
+ describe.each([false, true])(
+ "MCP and CLI sub-routes (upsell %s)",
+ (upsell) => {
+ it.each([
+ [Urls.monitorAiAuditingMcpUsage(), "MCP usage page"],
+ [Urls.monitorAiAuditingMcpEvents(), "MCP tool calls page"],
+ [Urls.monitorAiAuditingCliUsage(), "CLI usage page"],
+ [Urls.monitorAiAuditingCliCalls(), "CLI calls page"],
+ ])("renders %s", async (route, pageText) => {
+ setup({ route, upsell });
+
+ expect(await screen.findByText(pageText)).toBeInTheDocument();
+ });
+
+ it.each([
+ [Urls.monitorAiAuditingMcp(), Urls.monitorAiAuditingMcpUsage()],
+ [Urls.monitorAiAuditingCli(), Urls.monitorAiAuditingCliUsage()],
+ ])(
+ "redirects %s to its usage sub-route, preserving the query",
+ async (route, target) => {
+ const { router } = setup({
+ route: `${route}?date=past7days~`,
+ upsell,
+ });
+
+ await waitFor(() => {
+ expect(router?.location).toMatchObject({
+ pathname: target,
+ search: "?date=past7days~",
+ });
+ });
+ },
+ );
+ },
+ );
+
it("applies MCP availability to the upsell route set", async () => {
setup({
route: "/monitor/ai-auditing/mcp",
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/components/DiagnosticsHeader/DiagnosticsHeader.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/components/DiagnosticsHeader/DiagnosticsHeader.tsx
index 394f22b38ad..da39f07490a 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/components/DiagnosticsHeader/DiagnosticsHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/components/DiagnosticsHeader/DiagnosticsHeader.tsx
@@ -2,15 +2,15 @@ import { memo } from "react";
import { t } from "ttag";
import {
- type MonitorHeaderTab,
- MonitorHeaderTabs,
-} from "metabase/monitor/components/MonitorHeaderTabs";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { Stack } from "metabase/ui";
import * as Urls from "metabase/urls";
export const DiagnosticsHeader = memo(function DiagnosticsHeader() {
- const tabs: MonitorHeaderTab[] = [
+ const tabs: PillTab[] = [
{
label: t`Broken dependencies`,
to: Urls.brokenDependencies(),
@@ -26,7 +26,7 @@ export const DiagnosticsHeader = memo(function DiagnosticsHeader() {
return (
<Stack gap="lg">
<MonitorHeaderTitle>{t`Dependency diagnostics`}</MonitorHeaderTitle>
- <MonitorHeaderTabs tabs={tabs} />
+ <PillTabNavigation tabs={tabs} />
</Stack>
);
});
diff --git a/frontend/src/metabase/common/components/LinkTab/LinkTab.tsx b/frontend/src/metabase/common/components/LinkTab/LinkTab.tsx
deleted file mode 100644
index 33bd03a220c..00000000000
--- a/frontend/src/metabase/common/components/LinkTab/LinkTab.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { FC } from "react";
-
-import { Link } from "metabase/common/components/Link";
-import { Tabs, type TabsTabProps } from "metabase/ui";
-
-/**
- * Mantine's `Tabs.Tab` is built with the non-polymorphic `factory`, so
- * `component`/`to` aren't in its prop types. However it still accepts the
- * prop and it works as expected, thus type casting.
- */
-const TabsTabAsLink = Tabs.Tab as FC<
- TabsTabProps & { component: typeof Link; to: string }
->;
-
-type LinkTabProps = TabsTabProps & {
- to: string;
-};
-
-/**
- * Mantine tab that navigates as a react-router link.
- */
-export function LinkTab(props: LinkTabProps) {
- return <TabsTabAsLink {...props} component={Link} />;
-}
diff --git a/frontend/src/metabase/common/components/LinkTab/index.ts b/frontend/src/metabase/common/components/LinkTab/index.ts
deleted file mode 100644
index d2a47fe6104..00000000000
--- a/frontend/src/metabase/common/components/LinkTab/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./LinkTab";
diff --git a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.module.css b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.module.css
new file mode 100644
index 00000000000..b0cbf6b3618
--- /dev/null
+++ b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.module.css
@@ -0,0 +1,29 @@
+.tab {
+ border-radius: 999px;
+ padding: 0.6rem 1rem;
+ color: var(--mb-color-text-primary);
+ text-decoration: none;
+
+ &:hover {
+ background-color: var(--mb-color-background_surface-hover);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--mb-color-input-focus);
+ }
+}
+
+.selected {
+ background-color: var(--mb-color-background_surface-selected);
+ color: var(--mb-color-core-brand);
+
+ &:hover {
+ background-color: var(--mb-color-background_surface-selected);
+ }
+}
+
+.label {
+ font-size: var(--mantine-font-size-md);
+ font-weight: bold;
+ line-height: 1.15;
+}
diff --git a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx
new file mode 100644
index 00000000000..d44f110e1c8
--- /dev/null
+++ b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.tsx
@@ -0,0 +1,56 @@
+import cx from "classnames";
+
+import { ForwardRefLink } from "metabase/common/components/Link";
+import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
+import { useLocation } from "metabase/router";
+import { Ellipsified, FixedSizeIcon, Flex } from "metabase/ui";
+import type { IconName } from "metabase-types/api";
+
+import S from "./PillTabNavigation.module.css";
+
+export type PillTab = {
+ label: string;
+ to: string;
+ icon?: IconName;
+ isGated?: boolean;
+ isSelected?: boolean | ((pathname: string) => boolean);
+};
+
+type PillTabNavigationProps = {
+ tabs: PillTab[];
+};
+
+function isTabSelected(tab: PillTab, pathname: string) {
+ const { to, isSelected } = tab;
+ return typeof isSelected === "function"
+ ? isSelected(pathname)
+ : (isSelected ?? to === pathname);
+}
+
+export function PillTabNavigation({ tabs }: PillTabNavigationProps) {
+ const { pathname } = useLocation();
+
+ return (
+ <Flex component="nav" gap="xs" wrap="wrap">
+ {tabs.map((tab) => {
+ const selected = isTabSelected(tab, pathname);
+ return (
+ <Flex
+ key={tab.label}
+ component={ForwardRefLink}
+ to={tab.to}
+ align="center"
+ gap="xs"
+ className={cx(S.tab, { [S.selected]: selected })}
+ aria-label={tab.label}
+ aria-current={selected ? "page" : undefined}
+ >
+ {tab.icon !== undefined && <FixedSizeIcon name={tab.icon} />}
+ <Ellipsified className={S.label}>{tab.label}</Ellipsified>
+ {tab.isGated && <UpsellGem.New size={14} />}
+ </Flex>
+ );
+ })}
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx
new file mode 100644
index 00000000000..a3396a69f47
--- /dev/null
+++ b/frontend/src/metabase/common/components/PillTabNavigation/PillTabNavigation.unit.spec.tsx
@@ -0,0 +1,106 @@
+import { renderWithProviders, screen, within } from "__support__/ui";
+import { Route } from "metabase/router";
+
+import { type PillTab, PillTabNavigation } from "./PillTabNavigation";
+
+const TABS: PillTab[] = [
+ { label: "Usage", to: "/monitor/example/usage", icon: "lineandbar" },
+ { label: "Events", to: "/monitor/example/events" },
+];
+
+function setup({
+ tabs = TABS,
+ initialRoute = "/monitor/example/usage",
+}: { tabs?: PillTab[]; initialRoute?: string } = {}) {
+ renderWithProviders(
+ <Route path="*" element={<PillTabNavigation tabs={tabs} />} />,
+ { withRouter: true, initialRoute },
+ );
+}
+
+describe("PillTabNavigation", () => {
+ it("renders each tab as a real link to its route", () => {
+ setup();
+
+ expect(screen.getByRole("link", { name: "Usage" })).toHaveAttribute(
+ "href",
+ "/monitor/example/usage",
+ );
+ expect(screen.getByRole("link", { name: "Events" })).toHaveAttribute(
+ "href",
+ "/monitor/example/events",
+ );
+ });
+
+ it("marks the tab matching the current pathname as the current page", () => {
+ setup({ initialRoute: "/monitor/example/events" });
+
+ expect(screen.getByRole("link", { name: "Usage" })).not.toHaveAttribute(
+ "aria-current",
+ );
+ expect(screen.getByRole("link", { name: "Events" })).toHaveAttribute(
+ "aria-current",
+ "page",
+ );
+ });
+
+ it("respects an explicit boolean isSelected override", () => {
+ setup({
+ tabs: [
+ { label: "Usage", to: "/monitor/example/usage", isSelected: false },
+ { label: "Events", to: "/monitor/example/events", isSelected: true },
+ ],
+ initialRoute: "/monitor/example/usage",
+ });
+
+ expect(screen.getByRole("link", { name: "Usage" })).not.toHaveAttribute(
+ "aria-current",
+ );
+ expect(screen.getByRole("link", { name: "Events" })).toHaveAttribute(
+ "aria-current",
+ "page",
+ );
+ });
+
+ it("respects a function isSelected override for pathname prefix matching", () => {
+ setup({
+ tabs: [
+ {
+ label: "Broken",
+ to: "/monitor/example/broken",
+ isSelected: (pathname) => pathname.startsWith("/monitor/example/b"),
+ },
+ { label: "Unreferenced", to: "/monitor/example/unreferenced" },
+ ],
+ initialRoute: "/monitor/example/broken/nested",
+ });
+
+ expect(screen.getByRole("link", { name: "Broken" })).toHaveAttribute(
+ "aria-current",
+ "page",
+ );
+ });
+
+ it("shows the tab icon when provided", () => {
+ setup();
+
+ const tab = screen.getByRole("link", { name: "Usage" });
+ expect(
+ within(tab).getByRole("img", { name: "lineandbar icon" }),
+ ).toBeInTheDocument();
+ });
+
+ it("renders an upsell gem for a gated tab", () => {
+ setup({
+ tabs: [{ label: "Usage", to: "/monitor/example/usage", isGated: true }],
+ });
+
+ expect(screen.getByTestId("upsell-gem")).toBeInTheDocument();
+ });
+
+ it("does not render an upsell gem for an ungated tab", () => {
+ setup();
+
+ expect(screen.queryByTestId("upsell-gem")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/common/components/PillTabNavigation/index.ts b/frontend/src/metabase/common/components/PillTabNavigation/index.ts
new file mode 100644
index 00000000000..193dba906bd
--- /dev/null
+++ b/frontend/src/metabase/common/components/PillTabNavigation/index.ts
@@ -0,0 +1 @@
+export * from "./PillTabNavigation";
diff --git a/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx b/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
index dd20ef3986b..f3c864b328b 100644
--- a/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
+++ b/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
@@ -2,11 +2,8 @@ import type { ReactNode } from "react";
import { t } from "ttag";
import { EditableText } from "metabase/common/components/EditableText";
-import { LinkTab } from "metabase/common/components/LinkTab";
-import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { MetabotDataStudioButton } from "metabase/metabot/components/MetabotDataStudioButton";
import { AppSwitcher } from "metabase/nav/components/AppSwitcher";
-import { useLocation } from "metabase/router";
import {
Box,
Button,
@@ -15,13 +12,11 @@ import {
Group,
Stack,
type StackProps,
- Tabs,
Tooltip,
} from "metabase/ui";
import type { IconName } from "metabase-types/api";
import S from "./PaneHeader.module.css";
-import type { PaneHeaderTab } from "./types";
export interface PaneHeaderProps extends Omit<StackProps, "title"> {
title?: ReactNode;
@@ -132,40 +127,6 @@ export function PaneHeaderInput({
);
}
-type PaneHeaderTabsProps = {
- tabs: PaneHeaderTab[];
-};
-
-function isTabSelected(tab: PaneHeaderTab, pathname: string) {
- const { to, isSelected } = tab;
- return typeof isSelected === "function"
- ? isSelected(pathname)
- : (isSelected ?? to === pathname);
-}
-
-export function PaneHeaderTabs({ tabs }: PaneHeaderTabsProps) {
- const { pathname } = useLocation();
- const activeTab = tabs.find((tab) => isTabSelected(tab, pathname));
-
- return (
- <Tabs variant="pills" value={activeTab?.to ?? null}>
- <Tabs.List>
- {tabs.map(({ label, to, icon, isGated }) => (
- <LinkTab
- key={label}
- value={to}
- to={to}
- leftSection={icon != null ? <FixedSizeIcon name={icon} /> : null}
- rightSection={isGated ? <UpsellGem.New size={14} /> : null}
- >
- {label}
- </LinkTab>
- ))}
- </Tabs.List>
- </Tabs>
- );
-}
-
type PaneHeaderActionsProps = {
errorMessage?: string;
isValid?: boolean;
diff --git a/frontend/src/metabase/common/data-studio/components/PaneHeader/index.ts b/frontend/src/metabase/common/data-studio/components/PaneHeader/index.ts
index 0414c457bca..ff730b16956 100644
--- a/frontend/src/metabase/common/data-studio/components/PaneHeader/index.ts
+++ b/frontend/src/metabase/common/data-studio/components/PaneHeader/index.ts
@@ -1,2 +1 @@
export * from "./PaneHeader";
-export * from "./types";
diff --git a/frontend/src/metabase/common/data-studio/components/PaneHeader/types.ts b/frontend/src/metabase/common/data-studio/components/PaneHeader/types.ts
deleted file mode 100644
index 1d68f827cc7..00000000000
--- a/frontend/src/metabase/common/data-studio/components/PaneHeader/types.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { IconName } from "metabase-types/api";
-export type PaneHeaderTab = {
- label: string;
- to: string;
- icon?: IconName;
- isGated?: boolean;
- isSelected?: boolean | ((pathname: string) => boolean);
-};
diff --git a/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx b/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
index 852315df278..dd6e1b88051 100644
--- a/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
+++ b/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
@@ -1,9 +1,9 @@
import { t } from "ttag";
import {
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
import { useLocation } from "metabase/router";
@@ -20,7 +20,7 @@ type EntityDetailTabsProps = {
export function EntityDetailTabs({ urls }: EntityDetailTabsProps) {
const location = useLocation();
- const tabs: PaneHeaderTab[] = [
+ const tabs: PillTab[] = [
{
label: t`Definition`,
to: urls.definition,
@@ -40,5 +40,5 @@ export function EntityDetailTabs({ urls }: EntityDetailTabsProps) {
});
}
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
}
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
index e81f26bd930..5fce7943f2e 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
@@ -3,9 +3,9 @@ import { t } from "ttag";
import { useGetMetricQuery } from "metabase/api/metric";
import {
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import type { MetricUrls } from "metabase/common/metrics/types";
import { getUserIsAdmin, getUserIsAnalyst } from "metabase/current-user";
import { isNumericMetric } from "metabase/metrics/utils/validation";
@@ -33,7 +33,7 @@ export function MetricTabs({ card, urls }: MetricTabsProps) {
() => getTabs(card, metadata, urls, hasDimensions, canSeeDependencies),
[card, metadata, urls, hasDimensions, canSeeDependencies],
);
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
}
function getTabs(
@@ -42,8 +42,8 @@ function getTabs(
urls: MetricUrls,
hasDimensions: boolean,
canSeeDependencies: boolean,
-): PaneHeaderTab[] {
- const tabs: PaneHeaderTab[] = [
+): PillTab[] {
+ const tabs: PillTab[] = [
{
label: t`About`,
to: urls.about(card.id),
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
index fccdafc0361..745a3015d18 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
@@ -88,9 +88,7 @@ describe("MetricTabs", () => {
}
function getTabLabels() {
- return Array.from(
- document.querySelectorAll(".mb-mantine-Tabs-tabLabel"),
- ).map((element) => element.textContent);
+ return screen.queryAllByRole("link").map((link) => link.textContent);
}
it("does not show the caching tab in the tabs row regardless of write access", async () => {
diff --git a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx b/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx
deleted file mode 100644
index 01a932eedfd..00000000000
--- a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { LinkTab } from "metabase/common/components/LinkTab";
-import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
-import { useLocation } from "metabase/router";
-import { FixedSizeIcon, Tabs } from "metabase/ui";
-import type { IconName } from "metabase-types/api";
-
-export type MonitorHeaderTab = {
- label: string;
- to: string;
- icon?: IconName;
- isGated?: boolean;
- isSelected?: boolean | ((pathname: string) => boolean);
-};
-
-type MonitorHeaderTabsProps = {
- tabs: MonitorHeaderTab[];
-};
-
-function isTabSelected(tab: MonitorHeaderTab, pathname: string) {
- const { to, isSelected } = tab;
- return typeof isSelected === "function"
- ? isSelected(pathname)
- : (isSelected ?? to === pathname);
-}
-
-export function MonitorHeaderTabs({ tabs }: MonitorHeaderTabsProps) {
- const { pathname } = useLocation();
- const activeTab = tabs.find((tab) => isTabSelected(tab, pathname));
-
- return (
- <Tabs variant="pills" value={activeTab?.to ?? null}>
- <Tabs.List>
- {tabs.map(({ label, to, icon, isGated }) => (
- <LinkTab
- key={label}
- value={to}
- to={to}
- leftSection={
- icon !== undefined ? <FixedSizeIcon name={icon} /> : null
- }
- rightSection={isGated ? <UpsellGem.New size={14} /> : null}
- >
- {label}
- </LinkTab>
- ))}
- </Tabs.List>
- </Tabs>
- );
-}
diff --git a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/index.ts b/frontend/src/metabase/monitor/components/MonitorHeaderTabs/index.ts
deleted file mode 100644
index de090a42bee..00000000000
--- a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./MonitorHeaderTabs";
diff --git a/frontend/src/metabase/monitor/tools/components/TasksTabs/TasksTabs.tsx b/frontend/src/metabase/monitor/tools/components/TasksTabs/TasksTabs.tsx
index b1888dedb12..64d9db2533d 100644
--- a/frontend/src/metabase/monitor/tools/components/TasksTabs/TasksTabs.tsx
+++ b/frontend/src/metabase/monitor/tools/components/TasksTabs/TasksTabs.tsx
@@ -2,9 +2,9 @@ import type { ReactNode } from "react";
import { t } from "ttag";
import {
- type MonitorHeaderTab,
- MonitorHeaderTabs,
-} from "metabase/monitor/components/MonitorHeaderTabs";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
import { Flex, Stack } from "metabase/ui";
@@ -15,7 +15,7 @@ type TasksTabsProps = {
};
export const TasksTabs = ({ children }: TasksTabsProps) => {
- const tabs: MonitorHeaderTab[] = [
+ const tabs: PillTab[] = [
{ label: t`Tasks`, to: Urls.monitorTasksList() },
{ label: t`Runs`, to: Urls.monitorTasksRuns() },
];
@@ -25,7 +25,7 @@ export const TasksTabs = ({ children }: TasksTabsProps) => {
<MonitorMain>
<Stack gap="lg">
<MonitorHeaderTitle>{t`Background tasks`}</MonitorHeaderTitle>
- <MonitorHeaderTabs tabs={tabs} />
+ <PillTabNavigation tabs={tabs} />
</Stack>
{children}
</MonitorMain>
diff --git a/frontend/src/metabase/transforms/components/JobTabs/JobTabs.tsx b/frontend/src/metabase/transforms/components/JobTabs/JobTabs.tsx
index a1051841f36..6deca6953e6 100644
--- a/frontend/src/metabase/transforms/components/JobTabs/JobTabs.tsx
+++ b/frontend/src/metabase/transforms/components/JobTabs/JobTabs.tsx
@@ -1,9 +1,9 @@
import { t } from "ttag";
import {
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import * as Urls from "metabase/urls";
import type { TransformJobId } from "metabase-types/api";
@@ -13,10 +13,10 @@ type JobTabsProps = {
export const JobTabs = ({ jobId }: JobTabsProps) => {
const tabs = getTabs(jobId);
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
};
-function getTabs(jobId: TransformJobId): PaneHeaderTab[] {
+function getTabs(jobId: TransformJobId): PillTab[] {
return [
{
label: t`Overview`,
diff --git a/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx b/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
index f57e91c7356..5ba03123395 100644
--- a/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
+++ b/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
@@ -60,23 +60,25 @@ describe("TransformHeader", () => {
setup({ isEditMode: false });
expect(
- screen.getByRole("tab", { name: "Definition" }),
+ screen.getByRole("link", { name: "Definition" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Run" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "Settings" }),
).toBeInTheDocument();
- expect(screen.getByRole("tab", { name: "Run" })).toBeInTheDocument();
- expect(screen.getByRole("tab", { name: "Settings" })).toBeInTheDocument();
});
it("should not render tabs when isEditMode is true", () => {
setup({ isEditMode: true });
expect(
- screen.queryByRole("tab", { name: "Definition" }),
+ screen.queryByRole("link", { name: "Definition" }),
).not.toBeInTheDocument();
expect(
- screen.queryByRole("tab", { name: "Run" }),
+ screen.queryByRole("link", { name: "Run" }),
).not.toBeInTheDocument();
expect(
- screen.queryByRole("tab", { name: "Target" }),
+ screen.queryByRole("link", { name: "Settings" }),
).not.toBeInTheDocument();
});
});
@@ -92,7 +94,7 @@ describe("TransformHeader", () => {
setupEnterprisePlugins();
setup();
- const inspectLink = screen.getByRole("tab", { name: /Inspect/ });
+ const inspectLink = screen.getByRole("link", { name: /Inspect/ });
expect(inspectLink).toBeInTheDocument();
expect(within(inspectLink).getByTestId("upsell-gem")).toBeInTheDocument();
@@ -104,7 +106,7 @@ describe("TransformHeader", () => {
setup();
- const inspectLink = screen.getByRole("tab", { name: "Inspect" });
+ const inspectLink = screen.getByRole("link", { name: "Inspect" });
expect(inspectLink).toBeInTheDocument();
expect(
diff --git a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx
index 0c0e7e64ab1..dec915e1a3b 100644
--- a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx
+++ b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx
@@ -1,9 +1,9 @@
import { t } from "ttag";
import {
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
import {
PLUGIN_DEPENDENCIES,
PLUGIN_TRANSFORMS_PYTHON,
@@ -17,12 +17,12 @@ type TransformTabsProps = {
export const TransformTabs = ({ transform }: TransformTabsProps) => {
const tabs = getTabs(transform.id);
- return <PaneHeaderTabs tabs={tabs} />;
+ return <PillTabNavigation tabs={tabs} />;
};
-function getTabs(id: TransformId): PaneHeaderTab[] {
+function getTabs(id: TransformId): PillTab[] {
const inspectUrl = Urls.transformInspect(id);
- const tabs: PaneHeaderTab[] = [
+ const tabs: PillTab[] = [
{
label: t`Definition`,
to: Urls.transform(id),
diff --git a/frontend/src/metabase/transforms/components/TransformsHeader/TransformsHeader.tsx b/frontend/src/metabase/transforms/components/TransformsHeader/TransformsHeader.tsx
index c89a9b44cb5..30561ec8d9e 100644
--- a/frontend/src/metabase/transforms/components/TransformsHeader/TransformsHeader.tsx
+++ b/frontend/src/metabase/transforms/components/TransformsHeader/TransformsHeader.tsx
@@ -1,12 +1,12 @@
import { memo } from "react";
import { t } from "ttag";
-import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";
import {
- PaneHeader,
- type PaneHeaderTab,
- PaneHeaderTabs,
-} from "metabase/common/data-studio/components/PaneHeader";
+ type PillTab,
+ PillTabNavigation,
+} from "metabase/common/components/PillTabNavigation";
+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";
+import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";
import * as Urls from "metabase/urls";
import {
@@ -24,7 +24,7 @@ export const TransformsHeader = memo(function TransformsHeader({
showMetabotButton,
showTabs = true,
}: TransformsHeaderProps) {
- const tabs: PaneHeaderTab[] = [
+ const tabs: PillTab[] = [
{
label: t`Transforms`,
to: Urls.transformList(),
@@ -51,7 +51,7 @@ export const TransformsHeader = memo(function TransformsHeader({
breadcrumbs={
<DataStudioBreadcrumbs>{t`Data transformation`}</DataStudioBreadcrumbs>
}
- tabs={showTabs ? <PaneHeaderTabs tabs={tabs} /> : undefined}
+ tabs={showTabs ? <PillTabNavigation tabs={tabs} /> : undefined}
py={0}
mb="md"
showMetabotButton={showMetabotButton}
diff --git a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.unit.spec.tsx
index bfa268bceaf..1b6d8acb5a7 100644
--- a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.unit.spec.tsx
+++ b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunListPage.unit.spec.tsx
@@ -103,7 +103,7 @@ describe("JobRunListPage", () => {
expect(await screen.findAllByText("Nightly job")).not.toHaveLength(0);
expect(
- screen.getByRole("tab", { name: "Run history" }),
+ screen.getByRole("link", { name: "Run history" }),
).toBeInTheDocument();
expect(await screen.findByText("Success")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/urls/monitor.ts b/frontend/src/metabase/urls/monitor.ts
index 4e96677c94c..f5bb11848df 100644
--- a/frontend/src/metabase/urls/monitor.ts
+++ b/frontend/src/metabase/urls/monitor.ts
@@ -109,6 +109,22 @@ export function monitorAiAuditingMcp() {
return `${monitorAiAuditing()}/mcp`;
}
+export function monitorAiAuditingMcpUsage() {
+ return `${monitorAiAuditingMcp()}/usage`;
+}
+
+export function monitorAiAuditingMcpEvents() {
+ return `${monitorAiAuditingMcp()}/events`;
+}
+
export function monitorAiAuditingCli() {
return `${monitorAiAuditing()}/cli`;
}
+
+export function monitorAiAuditingCliUsage() {
+ return `${monitorAiAuditingCli()}/usage`;
+}
+
+export function monitorAiAuditingCliCalls() {
+ return `${monitorAiAuditingCli()}/calls`;
+}