Skip to content

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

Show an empty state when Usage stats has no data (#83862)

Andrei Simionescucb095b3ec6a8
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsEmptyState.tsx
deleted file mode 100644
index 93fcdf3fe38..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/cli-analytics/components/CliAnalyticsEmptyState.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { t } from "ttag";
-
-import { EmptyState } from "metabase/common/components/EmptyState";
-import { Flex } from "metabase/ui";
-
-/** Centered placeholder shown (in place of the tabs/charts) when the filtered view has no calls. */
-export function CliAnalyticsEmptyState() {
- return (
- <Flex flex={1} mih="60vh" align="center" justify="center">
- <EmptyState
- icon="audit"
- title={t`No CLI activity`}
- message={t`Calls from the CLI and other Agent API clients will show up here. Try widening the date range or check back once clients start making requests.`}
- />
- </Flex>
- );
-}
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
index e02ce47deb1..47e68320709 100644
--- 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
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { t } from "ttag";
+import { EmptyState } from "metabase/common/components/EmptyState";
import type { PillTab } from "metabase/common/components/PillTabNavigation";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { Outlet, useLocation } from "metabase/router";
@@ -19,7 +20,6 @@ import {
} 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,
@@ -143,7 +143,13 @@ export function CliAnalyticsSectionLayout() {
hasTenants={hasTenants}
/>
}
- emptyState={<CliAnalyticsEmptyState />}
+ emptyState={
+ <EmptyState
+ icon="audit"
+ title={t`No CLI activity`}
+ message={t`Calls from the CLI and other Agent API clients will show up here. Try widening the date range or check back once clients start making requests.`}
+ />
+ }
error={error}
isInitialLoading={isInitialLoading}
isTableRoute={isCallsRoute}
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 714bc9902d5..b282e4cf007 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
@@ -1,8 +1,9 @@
-import { useMemo, useRef } from "react";
+import { useMemo } from "react";
import type { CliFilters } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/query-utils";
import { buildTotalCountQuery } from "metabase-enterprise/monitor/ai-auditing/cli-analytics/query-utils";
-import { useAdhocBreakoutQuery } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAdhocBreakoutQuery";
+import type { UseHasDataResult } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData";
+import { useHasData } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData";
import type {
CardMetadata,
MetadataProvider,
@@ -15,24 +16,6 @@ type DataSources = {
groupMembersTable: TableMetadata | CardMetadata | null;
};
-type Result = {
- /** First load, before the count has ever resolved — show a loader, never the empty state. */
- isInitialLoading: boolean;
- /** A subsequent load triggered by a filter change — let the charts show their own skeletons. */
- isRefetching: boolean;
- /** Whether the current (resolved) filters match any calls. */
- 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;
-};
-
-/**
- * Runs a single count query over the filtered view to drive the page's load/empty/data states.
- * Distinguishes the initial load (loader) from a filter-change refetch (skeletons) so the page
- * never flashes the empty state before the first result has resolved.
- */
export function useCliHasData({
provider,
table,
@@ -42,7 +25,7 @@ export function useCliHasData({
groupId,
tenantId,
errorsOnly = false,
-}: DataSources & CliFilters & { errorsOnly?: boolean }): Result {
+}: DataSources & CliFilters & { errorsOnly?: boolean }): UseHasDataResult {
const query = useMemo(
() =>
provider && table && groupMembersTable
@@ -69,27 +52,5 @@ export function useCliHasData({
],
);
- const { data, isFetching, error } = useAdhocBreakoutQuery(query);
-
- // 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 !== undefined || hasError);
- if (resolved) {
- hasLoadedOnce.current = true;
- }
-
- // The query is a single count aggregation with no breakout, so the result is exactly one row
- // with one column — the scalar total. `rows[0][0]` is that count.
- const count = Number(data?.data?.rows?.[0]?.[0] ?? 0);
-
- return {
- isInitialLoading: !hasLoadedOnce.current,
- isRefetching: hasLoadedOnce.current && isFetching,
- hasData: count > 0,
- count,
- error,
- };
+ return useHasData(query);
}
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
index 11f2c97fd26..db62cf0f7f9 100644
--- 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
@@ -86,7 +86,7 @@ type RouteContentProps = {
showEmpty: boolean;
};
-function RouteContent({
+export function RouteContent({
children,
emptyState,
error,
@@ -109,5 +109,13 @@ function RouteContent({
);
}
- return showEmpty ? emptyState : children;
+ if (showEmpty) {
+ return (
+ <Flex flex={1} mih="60vh" align="center" justify="center">
+ {emptyState}
+ </Flex>
+ );
+ }
+
+ return children;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsEmptyState.tsx
deleted file mode 100644
index 6a0e8e781ed..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/mcp-analytics/components/McpAnalyticsEmptyState.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { t } from "ttag";
-
-import { EmptyState } from "metabase/common/components/EmptyState";
-import { Flex } from "metabase/ui";
-
-/** Centered placeholder shown (in place of the tabs/charts) when the filtered view has no tool calls. */
-export function McpAnalyticsEmptyState() {
- return (
- <Flex flex={1} mih="60vh" align="center" justify="center">
- <EmptyState
- icon="audit"
- title={t`No MCP activity`}
- message={t`Tool calls from MCP clients will show up here. Try widening the date range or check back once clients start using the server.`}
- />
- </Flex>
- );
-}
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
index f718da846e2..9eae9c9e91e 100644
--- 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
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { t } from "ttag";
+import { EmptyState } from "metabase/common/components/EmptyState";
import type { PillTab } from "metabase/common/components/PillTabNavigation";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { Outlet, useLocation } from "metabase/router";
@@ -19,7 +20,6 @@ import {
} 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,
@@ -143,7 +143,13 @@ export function McpAnalyticsSectionLayout() {
hasTenants={hasTenants}
/>
}
- emptyState={<McpAnalyticsEmptyState />}
+ emptyState={
+ <EmptyState
+ icon="audit"
+ title={t`No MCP activity`}
+ message={t`Tool calls from MCP clients will show up here. Try widening the date range or check back once clients start using the server.`}
+ />
+ }
error={error}
isInitialLoading={isInitialLoading}
isTableRoute={isEventsRoute}
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 a3f6308b81f..e9e29978906 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
@@ -1,4 +1,4 @@
-import { useMemo, useRef } from "react";
+import { useMemo } from "react";
import type {
CardMetadata,
@@ -6,7 +6,8 @@ import type {
TableMetadata,
} from "metabase-lib";
-import { useAdhocBreakoutQuery } from "../../metabot-analytics/hooks/useAdhocBreakoutQuery";
+import type { UseHasDataResult } from "../../metabot-analytics/hooks/useHasData";
+import { useHasData } from "../../metabot-analytics/hooks/useHasData";
import type { McpFilters } from "../query-utils";
import { buildTotalCountQuery } from "../query-utils";
@@ -16,24 +17,6 @@ type DataSources = {
groupMembersTable: TableMetadata | CardMetadata | null;
};
-type Result = {
- /** First load, before the count has ever resolved — show a loader, never the empty state. */
- isInitialLoading: boolean;
- /** A subsequent load triggered by a filter change — let the charts show their own skeletons. */
- isRefetching: boolean;
- /** Whether the current (resolved) filters match any tool calls. */
- hasData: boolean;
- /** Total number of tool 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;
-};
-
-/**
- * Runs a single count query over the filtered view to drive the page's load/empty/data states.
- * Distinguishes the initial load (loader) from a filter-change refetch (skeletons) so the page
- * never flashes the empty state before the first result has resolved.
- */
export function useMcpHasData({
provider,
table,
@@ -43,7 +26,7 @@ export function useMcpHasData({
groupId,
tenantId,
errorsOnly = false,
-}: DataSources & McpFilters & { errorsOnly?: boolean }): Result {
+}: DataSources & McpFilters & { errorsOnly?: boolean }): UseHasDataResult {
const query = useMemo(
() =>
provider && table && groupMembersTable
@@ -70,27 +53,5 @@ export function useMcpHasData({
],
);
- const { data, isFetching, error } = useAdhocBreakoutQuery(query);
-
- // 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 !== undefined || hasError);
- if (resolved) {
- hasLoadedOnce.current = true;
- }
-
- // The query is a single count aggregation with no breakout, so the result is exactly one row
- // with one column — the scalar total. `rows[0][0]` is that count.
- const count = Number(data?.data?.rows?.[0]?.[0] ?? 0);
-
- return {
- isInitialLoading: !hasLoadedOnce.current,
- isRefetching: hasLoadedOnce.current && isFetching,
- hasData: count > 0,
- count,
- error,
- };
+ return useHasData(query);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
index d2df02e3a79..05146c73e7a 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from "react";
import { t } from "ttag";
import { getErrorMessage } from "metabase/api/utils";
+import { EmptyState } from "metabase/common/components/EmptyState";
import { useToast } from "metabase/common/hooks";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { dayjs } from "metabase/dayjs";
@@ -25,6 +26,7 @@ import {
Title,
} from "metabase/ui";
import * as Urls from "metabase/urls";
+import { RouteContent } from "metabase-enterprise/monitor/ai-auditing/components/AiAnalyticsSectionLayout";
import {
useGetDataComplexityScoresQuery,
useRefreshDataComplexityScoresMutation,
@@ -44,6 +46,7 @@ import {
VIEW_USAGE_LOG,
} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/constants";
import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
+import { useHasData } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { BreakoutChart } from "./BreakoutChart";
@@ -55,6 +58,7 @@ import { DataComplexityCards } from "./DataComplexityCards";
import {
type StatsFilters,
type UsageStatsMetric,
+ buildCountQuery,
buildGroupBreakoutQuery,
buildSourceBreakoutQuery,
buildTenantBreakoutQuery,
@@ -135,6 +139,18 @@ const tenantTitles: Record<UsageStatsMetric, string> = {
},
};
+const emptyStateTitles: Record<UsageStatsMetric, string> = {
+ get conversations() {
+ return t`No conversations`;
+ },
+ get messages() {
+ return t`No messages`;
+ },
+ get tokens() {
+ return t`No token usage`;
+ },
+};
+
const buildSourceQuery = (opts: StatsFilters & ChartDataSources) =>
buildSourceBreakoutQuery({ ...opts, breakoutColumn: "source_name" });
@@ -212,6 +228,24 @@ function UsageStats({ metric }: UsageStatsProps) {
metric,
};
+ const { provider, table, groupMembersTable } = sharedChartProps;
+ const countQuery = useMemo(
+ () =>
+ provider && table && groupMembersTable
+ ? buildCountQuery({
+ provider,
+ table,
+ groupMembersTable,
+ dateFilter,
+ userId,
+ groupId,
+ tenantId,
+ })
+ : null,
+ [provider, table, groupMembersTable, dateFilter, userId, groupId, tenantId],
+ );
+ const { currentCount, error } = useHasData(countQuery);
+
const tenantNameById = useMemo(() => {
const map = new Map<string, string>();
for (const opt of tenantOptions) {
@@ -338,65 +372,81 @@ function UsageStats({ metric }: UsageStatsProps) {
/>
<Stack gap="xl">
- <ConversationsByDayChart
- {...sharedChartProps}
- onDimensionClick={handleDayClick}
- />
-
- <SimpleGrid cols={2} spacing="xl">
- <BreakoutChart
- {...sharedChartProps}
- titles={sourceTitles}
- display="bar"
- buildQuery={buildSourceQuery}
- />
- <BreakoutChart
+ <RouteContent
+ emptyState={
+ <EmptyState
+ icon="audit"
+ title={emptyStateTitles[metric]}
+ message={t`Try widening the date range or check back once people start using Metabot.`}
+ />
+ }
+ error={error}
+ isInitialLoading={currentCount === undefined}
+ showEmpty={currentCount === 0}
+ >
+ <ConversationsByDayChart
{...sharedChartProps}
- titles={profileTitles}
- display="bar"
- buildQuery={buildProfileQuery}
+ onDimensionClick={handleDayClick}
/>
- </SimpleGrid>
- <SimpleGrid cols={hasTenants ? 2 : 3} spacing="xl">
- {hasTenants && (
+ <SimpleGrid cols={2} spacing="xl">
+ <BreakoutChart
+ {...sharedChartProps}
+ titles={sourceTitles}
+ display="bar"
+ buildQuery={buildSourceQuery}
+ />
<BreakoutChart
{...sharedChartProps}
- titles={tenantTitles}
+ titles={profileTitles}
+ display="bar"
+ buildQuery={buildProfileQuery}
+ />
+ </SimpleGrid>
+
+ <SimpleGrid cols={hasTenants ? 2 : 3} spacing="xl">
+ {hasTenants && (
+ <BreakoutChart
+ {...sharedChartProps}
+ titles={tenantTitles}
+ display="row"
+ buildQuery={buildTenantBreakoutQuery}
+ labelMapper={labelTenantName}
+ onDimensionClick={handleTenantClick}
+ h={500}
+ />
+ )}
+ <BreakoutChart
+ {...sharedChartProps}
+ titles={groupTitles}
display="row"
- buildQuery={buildTenantBreakoutQuery}
- labelMapper={labelTenantName}
- onDimensionClick={handleTenantClick}
+ buildQuery={(opts) =>
+ buildGroupBreakoutQuery({
+ ...opts,
+ excludeAllUsers: !hasTenants,
+ })
+ }
+ onDimensionClick={handleGroupClick}
h={500}
/>
- )}
- <BreakoutChart
- {...sharedChartProps}
- titles={groupTitles}
- display="row"
- buildQuery={(opts) =>
- buildGroupBreakoutQuery({ ...opts, excludeAllUsers: !hasTenants })
- }
- onDimensionClick={handleGroupClick}
- h={500}
- />
- <BreakoutChart
- {...sharedChartProps}
- titles={userTitles}
- display="row"
- buildQuery={buildUserQuery}
- onDimensionClick={handleUserClick}
- h={500}
- />
- <BreakoutChart
- {...sharedChartProps}
- titles={ipAddressTitles}
- display="row"
- buildQuery={buildIpAddressQuery}
- labelMapper={labelUnknownIpAddress}
- h={500}
- />
- </SimpleGrid>
+ <BreakoutChart
+ {...sharedChartProps}
+ titles={userTitles}
+ display="row"
+ buildQuery={buildUserQuery}
+ onDimensionClick={handleUserClick}
+ h={500}
+ />
+ <BreakoutChart
+ {...sharedChartProps}
+ titles={ipAddressTitles}
+ display="row"
+ buildQuery={buildIpAddressQuery}
+ labelMapper={labelUnknownIpAddress}
+ h={500}
+ />
+ </SimpleGrid>
+ </RouteContent>
<DataComplexitySection />
</Stack>
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
index ec16afc7d5f..81e7b98c388 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
@@ -13,7 +13,11 @@ import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { Route } from "metabase/router";
import * as Urls from "metabase/urls";
import { parseSearchQuery } from "metabase/utils/browser";
-import { AUDIT_DB_ID } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/constants";
+import {
+ AUDIT_DB_ID,
+ VIEW_CONVERSATIONS,
+ VIEW_USAGE_LOG,
+} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/constants";
import {
ADMIN_GROUP,
ALL_USERS_GROUP,
@@ -84,6 +88,12 @@ const CONVERSATIONS_PATH = Urls.monitorAiAuditingConversations();
const { database: auditDatabase } = buildAuditViewsFixture();
+const TABLE_NAME_BY_ID = new Map(
+ (auditDatabase.tables ?? []).map(
+ (table) => [Number(table.id), table.name] as const,
+ ),
+);
+
const FIELD_NAME_BY_ID = new Map(
(auditDatabase.tables ?? []).flatMap((table) =>
(table.fields ?? []).map(
@@ -126,6 +136,7 @@ const BREAKOUT_VALUES: Record<string, RowValue[]> = {
type FieldRef = [string, { "temporal-unit"?: string }, number];
type FilterClause = [string, object, FieldRef, ...unknown[]];
type RequestStage = {
+ "source-table": number;
aggregation?: unknown[];
breakout?: FieldRef[];
filters?: FilterClause[];
@@ -159,8 +170,26 @@ function getBreakoutValues(stage: RequestStage): RowValue[] {
return values;
}
-function buildDatasetResponse(body: unknown): Dataset {
+function buildCountResponse(count: number): Dataset {
+ return createMockDataset({
+ data: createMockDatasetData({
+ cols: [createMockColumn({ source: "aggregation", name: "count" })],
+ rows: [[count]],
+ }),
+ database_id: AUDIT_DB_ID,
+ row_count: 1,
+ });
+}
+
+function getViewName(stage: RequestStage): string {
+ return TABLE_NAME_BY_ID.get(stage["source-table"]) ?? "";
+}
+
+function buildDatasetResponse(body: unknown, emptyViews: string[]): Dataset {
const stage = parseStage(body);
+ if (stage && !stage.breakout) {
+ return buildCountResponse(emptyViews.includes(getViewName(stage)) ? 0 : 2);
+ }
const values = stage ? getBreakoutValues(stage) : [];
const aggregationNames =
(stage?.aggregation ?? []).length > 1 ? ["sum", "sum_2"] : ["count"];
@@ -199,31 +228,52 @@ function getFilteredFieldIds(): number[] {
type SetupOpts = {
initialRoute?: string;
hasTenants?: boolean;
+ emptyViews?: string[];
+ heldView?: string;
};
function setup({
initialRoute = STATS_PATH,
hasTenants = false,
+ emptyViews = [],
+ heldView,
}: SetupOpts = {}) {
setupEnterprisePlugins();
+ const heldMetadata = Promise.withResolvers<void>();
+ const heldCount = Promise.withResolvers<void>();
+
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 ?? []),
+ fetchMock.post("path:/api/dataset/query_metadata", async (call) => {
+ const stage = parseStage(call.options.body);
+ if (stage && getViewName(stage) === heldView) {
+ await heldMetadata.promise;
+ }
+ return {
+ databases: [auditDatabase],
+ tables: auditDatabase.tables ?? [],
+ fields: (auditDatabase.tables ?? []).flatMap(
+ (table) => table.fields ?? [],
+ ),
+ };
});
fetchMock.post(
"path:/api/dataset",
- (call) => buildDatasetResponse(call?.options.body),
+ async (call) => {
+ const stage = parseStage(call.options.body);
+ if (stage && !stage.breakout && getViewName(stage) === heldView) {
+ await heldCount.promise;
+ }
+ return buildDatasetResponse(call.options.body, emptyViews);
+ },
{ name: "dataset" },
);
setupUsersEndpoints([BOBBY, ROBERT]);
setupGroupsEndpoint([ALL_USERS_GROUP, ADMIN_GROUP, DATA_GROUP]);
setupTenantEntpoints([BOBBY_TENANT, ROBERT_TENANT]);
- return renderWithProviders(
+ const view = renderWithProviders(
<>
<Route
path={`${Urls.monitorAiAuditingUsage()}/:metric`}
@@ -248,6 +298,12 @@ function setup({
}),
},
);
+
+ return {
+ ...view,
+ releaseHeldMetadata: heldMetadata.resolve,
+ releaseHeldCount: heldCount.resolve,
+ };
}
async function findChartCard(title: string): Promise<HTMLElement> {
@@ -379,6 +435,60 @@ describe("ConversationStatsPage", () => {
});
});
+ describe("empty state", () => {
+ it("shows one empty state instead of the charts when nothing matches the filters", async () => {
+ setup({ emptyViews: [VIEW_CONVERSATIONS] });
+
+ expect(await screen.findByText("No conversations")).toBeInTheDocument();
+ expect(
+ screen.getByRole("tab", { name: "Conversations" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("conversation-filters-date-select"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Conversations by day"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the token charts when there is token usage but no conversations", async () => {
+ setup({
+ initialRoute: Urls.monitorAiAuditingUsageMetric("tokens"),
+ emptyViews: [VIEW_CONVERSATIONS],
+ });
+
+ expect(await screen.findByText("Tokens by day")).toBeInTheDocument();
+ });
+
+ it("keeps the loader up until the Tokens count comes back", async () => {
+ const { releaseHeldMetadata, releaseHeldCount } = setup({
+ emptyViews: [VIEW_CONVERSATIONS, VIEW_USAGE_LOG],
+ heldView: VIEW_USAGE_LOG,
+ });
+
+ await screen.findByText("No conversations");
+ await userEvent.click(screen.getByRole("tab", { name: "Tokens" }));
+
+ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
+ expect(screen.queryByText("No token usage")).not.toBeInTheDocument();
+
+ releaseHeldMetadata();
+ await waitFor(() =>
+ expect(
+ getDatasetStages().some(
+ (stage) => !stage.breakout && getViewName(stage) === VIEW_USAGE_LOG,
+ ),
+ ).toBe(true),
+ );
+
+ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
+
+ releaseHeldCount();
+
+ expect(await screen.findByText("No token usage")).toBeInTheDocument();
+ });
+ });
+
describe("tenants", () => {
it("hides the tenant filter and tenant chart when tenants are disabled", async () => {
setup();
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationsByDayChart.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationsByDayChart.tsx
index 80f56eca2ce..546215cffc8 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationsByDayChart.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/ConversationsByDayChart.tsx
@@ -14,12 +14,10 @@ import {
type GetColor,
type StatsFilters,
type UsageStatsMetric,
- applyDateFilter,
- applyIdFilter,
applyUsageStatsAggregation,
+ buildFilteredQuery,
findColumn,
getMetricSeriesSettings,
- joinGroupMembers,
} from "./query-utils";
import {
type ChartDataSources,
@@ -157,22 +155,11 @@ type BuildQueryOpts = StatsFilters &
ChartDataSources & { bucketName: BucketName };
export function buildTimeseriesBreakoutQuery({
- provider,
- table,
- groupMembersTable,
- dateFilter,
- userId,
- groupId,
- tenantId,
metric,
bucketName,
+ ...filteredQueryOpts
}: BuildQueryOpts): Query {
- let q = Lib.queryFromTableOrCardMetadata(provider, table);
- q = applyDateFilter(q, dateFilter);
- q = applyIdFilter(q, "user_id", userId);
- q = applyIdFilter(q, "tenant_id", tenantId);
- q = groupId != null ? joinGroupMembers(q, groupMembersTable) : q;
- q = groupId != null ? applyIdFilter(q, "group_id", groupId) : q;
+ let q = buildFilteredQuery(filteredQueryOpts);
q = applyUsageStatsAggregation(q, metric);
q = breakoutByCreatedAtBucket(q, bucketName);
return q;
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/__snapshots__/query-snapshots.unit.spec.ts.snap b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/__snapshots__/query-snapshots.unit.spec.ts.snap
index a00d4305d99..b9d80c4b9c3 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/__snapshots__/query-snapshots.unit.spec.ts.snap
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/__snapshots__/query-snapshots.unit.spec.ts.snap
@@ -1,5 +1,11 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
+exports[`buildCountQuery all filters 1`] = `
+"filters: ["created_at is in the previous 30 days or today", "user_id is 42", "tenant_id is 7", "group_id is 5"]
+joins: ["inner-join v_group_members on user_id = v_group_members.user_id"]
+aggregations: ["count()"]"
+`;
+
exports[`buildGroupBreakoutQuery all filters 1`] = `
"filters: ["created_at is in the previous 30 days or today", "user_id is 42", "tenant_id is 7", "group_id is not 1", "group_id is 5"]
joins: ["inner-join v_group_members on user_id = v_group_members.user_id"]
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-snapshots.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-snapshots.unit.spec.ts
index fc6eb5aead2..6165ed52745 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-snapshots.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-snapshots.unit.spec.ts
@@ -7,6 +7,7 @@ import { buildAuditViewsFixture } from "./audit-views-fixture";
import { summarize } from "./query-summary";
import {
type StatsFilters,
+ buildCountQuery,
buildGroupBreakoutQuery,
buildSourceBreakoutQuery,
buildTenantBreakoutQuery,
@@ -118,6 +119,16 @@ describe("buildSourceBreakoutQuery", () => {
));
});
+describe("buildCountQuery", () => {
+ it("all filters", () =>
+ snapshotQuery(
+ buildCountQuery({
+ ...filtersFor("tokens", ALL_FILTERS),
+ ...dataSources("tokens"),
+ }),
+ ));
+});
+
describe("buildGroupBreakoutQuery", () => {
describe("by metric", () => {
it.each(METRICS)("%s", (metric) =>
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-utils.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-utils.ts
index f8d82aff2e3..ffcb80c9dc7 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/query-utils.ts
@@ -237,14 +237,9 @@ export function applyMetricOrderBy(
return Lib.orderBy(query, 0, orderCol, "desc");
}
-type SourceBreakoutQueryOpts = StatsFilters & {
- provider: MetadataProvider;
- table: TableMetadata | CardMetadata;
- groupMembersTable: TableMetadata | CardMetadata;
- breakoutColumn: string;
-};
+type FilteredQueryOpts = Omit<BreakoutQueryOpts, "metric">;
-export function buildSourceBreakoutQuery({
+export function buildFilteredQuery({
provider,
table,
groupMembersTable,
@@ -252,15 +247,33 @@ export function buildSourceBreakoutQuery({
userId,
groupId,
tenantId,
- metric,
- breakoutColumn,
-}: SourceBreakoutQueryOpts): Query {
+}: FilteredQueryOpts): Query {
let q = Lib.queryFromTableOrCardMetadata(provider, table);
q = applyDateFilter(q, dateFilter);
q = applyIdFilter(q, "user_id", userId);
q = applyIdFilter(q, "tenant_id", tenantId);
q = groupId != null ? joinGroupMembers(q, groupMembersTable) : q;
q = groupId != null ? applyIdFilter(q, "group_id", groupId) : q;
+ return q;
+}
+
+export function buildCountQuery(opts: FilteredQueryOpts): Query {
+ return Lib.aggregateByCount(buildFilteredQuery(opts), 0);
+}
+
+type SourceBreakoutQueryOpts = StatsFilters & {
+ provider: MetadataProvider;
+ table: TableMetadata | CardMetadata;
+ groupMembersTable: TableMetadata | CardMetadata;
+ breakoutColumn: string;
+};
+
+export function buildSourceBreakoutQuery({
+ metric,
+ breakoutColumn,
+ ...filteredQueryOpts
+}: SourceBreakoutQueryOpts): Query {
+ let q = buildFilteredQuery(filteredQueryOpts);
q = applyUsageStatsAggregation(q, metric);
q = breakoutByColumn(q, breakoutColumn);
q = applyMetricOrderBy(q, metric);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAdhocBreakoutQuery.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAdhocBreakoutQuery.ts
index 90d84f28ee2..427bedd0c03 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAdhocBreakoutQuery.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAdhocBreakoutQuery.ts
@@ -7,6 +7,7 @@ import type { Dataset, DatasetQuery } from "metabase-types/api";
type AdhocQueryResult = {
data: Dataset | undefined;
+ currentData: Dataset | undefined;
jsQuery: DatasetQuery | null;
isFetching: boolean;
error: unknown;
@@ -19,11 +20,11 @@ export function useAdhocBreakoutQuery(query: Query | null): AdhocQueryResult {
[query],
);
- const { data, isFetching, error } = useGetAdhocQueryQuery(
+ const { data, currentData, isFetching, error } = useGetAdhocQueryQuery(
// Unjustified type cast. FIXME
jsQuery ?? ({} as DatasetQuery),
{ skip: !jsQuery },
);
- return { data, jsQuery, isFetching, error };
+ return { data, currentData, jsQuery, isFetching, error };
}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData.ts
new file mode 100644
index 00000000000..59e0597372b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useHasData.ts
@@ -0,0 +1,55 @@
+import { useRef } from "react";
+
+import type { Query } from "metabase-lib";
+import type { Dataset } from "metabase-types/api";
+
+import { useAdhocBreakoutQuery } from "./useAdhocBreakoutQuery";
+
+export type UseHasDataResult = {
+ /** No count has resolved yet, or the view's metadata is still loading: show a loader, never the empty state. */
+ isInitialLoading: boolean;
+ /** A later load triggered by a filter change: let the charts show their own skeletons. */
+ isRefetching: boolean;
+ hasData: boolean;
+ count: number;
+ /** The count for the current query only: `undefined` while its metadata or its count is loading. */
+ currentCount: number | undefined;
+ /** Set when the count query itself failed (e.g. a 500), so the page can show an error instead of spinning forever. */
+ error: unknown;
+};
+
+// A count aggregation with no breakout returns exactly one row with one column: the total.
+function getCount(dataset: Dataset | undefined): number {
+ return Number(dataset?.data?.rows?.[0]?.[0] ?? 0);
+}
+
+/**
+ * Runs a single count query over the filtered view to drive the page's load/empty/data states.
+ * Distinguishes the initial load (loader) from a filter-change refetch (skeletons) so the page
+ * never flashes the empty state before the first result has resolved.
+ */
+export function useHasData(countQuery: Query | null): UseHasDataResult {
+ const { data, currentData, isFetching, error } =
+ useAdhocBreakoutQuery(countQuery);
+
+ // 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 =
+ countQuery !== null && !isFetching && (data !== undefined || hasError);
+ if (resolved) {
+ hasLoadedOnce.current = true;
+ }
+
+ const count = getCount(data);
+
+ return {
+ isInitialLoading: !hasLoadedOnce.current || countQuery === null,
+ isRefetching: hasLoadedOnce.current && isFetching,
+ hasData: count > 0,
+ count,
+ currentCount: currentData ? getCount(currentData) : undefined,
+ error,
+ };
+}