Skip to content

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

feat(sdk-package, sdk-bundle): Introduce `useMetabot` hook (#73075)

Mahatthana (Kelvin) Nomsawadi673ee6158989
diff --git a/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx
new file mode 100644
index 00000000000..8e59d2b0427
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx
@@ -0,0 +1,157 @@
+const { H } = cy;
+
+import { useMetabot } from "@metabase/embedding-sdk-react";
+
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+
+const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;
+
+const buildAdHocPath = (query: Record<string, unknown>) =>
+ `/question#${btoa(
+ JSON.stringify({
+ dataset_query: { database: SAMPLE_DB_ID, type: "query", query },
+ display: "table",
+ displayIsLocked: true,
+ visualization_settings: {},
+ }),
+ )}`;
+
+const adHocQuestionPathOrders = buildAdHocPath({
+ "source-table": ORDERS_ID,
+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],
+ breakout: [["field", ORDERS.PRODUCT_ID, null]],
+ limit: 2,
+});
+
+const adHocQuestionPathProducts = buildAdHocPath({
+ "source-table": PRODUCTS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", PRODUCTS.CATEGORY, null]],
+ limit: 2,
+});
+
+const buildNavigateToResponse = (path: string) =>
+ `0:"Here is the [question link](${path})"
+2:{"type":"navigate_to","version":1,"value":"${path}"}`;
+
+type MetabotConsumerProps = {
+ prompts: string[];
+};
+
+const MetabotConsumer = ({ prompts }: MetabotConsumerProps) => {
+ const metabot = useMetabot();
+
+ if (!metabot) {
+ return null;
+ }
+
+ return (
+ <div>
+ <div style={{ display: "flex", gap: 4, padding: 8 }}>
+ {prompts.map((prompt) => (
+ <button
+ key={prompt}
+ type="button"
+ onClick={() => {
+ void metabot.submitMessage(prompt);
+ }}
+ // I don't like ugly buttons
+ style={{
+ padding: "2px 8px",
+ fontSize: 12,
+ border: "1px solid #ccc",
+ borderRadius: 3,
+ background: "#f5f5f5",
+ cursor: "pointer",
+ }}
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+
+ {metabot.CurrentChart && (
+ <div data-testid="metabot-current-chart">
+ <metabot.CurrentChart />
+ </div>
+ )}
+ </div>
+ );
+};
+
+describe("scenarios > embedding-sdk > use-metabot hook", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ H.updateSetting("llm-anthropic-api-key", "sk-ant-test-key");
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ it("exposes Metabot and renders CurrentChart after navigate_to", () => {
+ H.mockMetabotResponse({
+ statusCode: 200,
+ body: buildNavigateToResponse(adHocQuestionPathOrders),
+ });
+
+ mountSdkContent(<MetabotConsumer prompts={["Show me orders"]} />);
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("metabot-current-chart").should("not.exist");
+ cy.button("Show me orders").click();
+ });
+
+ cy.wait("@metabotAgent", { timeout: 20_000 });
+
+ getSdkRoot().within(() => {
+ cy.findByTestId("metabot-current-chart").should("exist");
+ cy.findByTestId("visualization-root")
+ .should("contain", "Product ID")
+ .and("contain", "1")
+ .and("contain", "Max of Quantity")
+ .and("contain", "30");
+ });
+ });
+
+ it("swaps CurrentChart when a second navigate_to reaction arrives with a new path", () => {
+ cy.intercept("POST", "/api/metabot/agent-streaming", (request) => {
+ const path =
+ request.body.message === "Show me products"
+ ? adHocQuestionPathProducts
+ : adHocQuestionPathOrders;
+ request.reply({
+ statusCode: 200,
+ body: buildNavigateToResponse(path),
+ headers: { "content-type": "text/event-stream; charset=utf-8" },
+ });
+ }).as("metabotAgent");
+
+ mountSdkContent(
+ <MetabotConsumer prompts={["Show me orders", "Show me products"]} />,
+ );
+
+ getSdkRoot().within(() => {
+ cy.button("Show me orders").click();
+ cy.wait("@metabotAgent", { timeout: 20_000 });
+ cy.findByTestId("visualization-root")
+ .should("contain", "Product ID")
+ .and("contain", "1")
+ .and("contain", "Max of Quantity")
+ .and("contain", "30");
+
+ cy.button("Show me products").click();
+ cy.wait("@metabotAgent", { timeout: 20_000 });
+
+ cy.findByTestId("visualization-root")
+ .should("contain", "Category")
+ .and("contain", "Doohickey")
+ .and("contain", "Count")
+ .and("contain", "42");
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
index 0694ca5442c..636126b5d0d 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { Messages } from "metabase/metabot/components/MetabotChat/MetabotChatMessage";
import { MetabotResetLongChatButton } from "metabase/metabot/components/MetabotChat/MetabotResetLongChatButton";
@@ -14,6 +14,11 @@ export function MetabotChatHistory() {
const { setNavigateToPath } = useMetabotReactions();
const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const visibleMessages = useMemo(
+ () => messages.filter((message) => message.type !== "chart"),
+ [messages],
+ );
+
const hasMessages = messages.length > 0 || errorMessages.length > 0;
// Auto-scroll to bottom when new messages are received
@@ -35,7 +40,7 @@ export function MetabotChatHistory() {
>
{hasMessages ? (
<Messages
- messages={messages}
+ messages={visibleMessages}
errorMessages={errorMessages}
onRetryMessage={metabot.retryMessage}
isDoingScience={metabot.isDoingScience}
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx
new file mode 100644
index 00000000000..d69735ee655
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx
@@ -0,0 +1,53 @@
+import { assocIn } from "icepick";
+
+import { screen } from "__support__/ui";
+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
+import type { MetabotChatMessage } from "metabase/metabot/state/types";
+import { setup } from "metabase/metabot/tests/utils";
+
+import { MetabotChatHistory } from "./MetabotChatHistory";
+
+const makeVisibleState = (messages: MetabotChatMessage[]) =>
+ assocIn(
+ assocIn(
+ getMetabotInitialState(),
+ ["conversations", "omnibot", "visible"],
+ true,
+ ),
+ ["conversations", "omnibot", "messages"],
+ messages,
+ );
+
+describe("MetabotChatHistory", () => {
+ it("should not render chart messages in the message list", () => {
+ setup({
+ ui: <MetabotChatHistory />,
+ metabotInitialState: makeVisibleState([
+ {
+ id: "1",
+ role: "agent",
+ type: "chart",
+ navigateTo: "/question#abc",
+ },
+ ]),
+ });
+
+ expect(
+ screen.queryByTestId("metabot-chat-message"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should render non-chart messages normally", async () => {
+ setup({
+ ui: <MetabotChatHistory />,
+ metabotInitialState: makeVisibleState([
+ { id: "1", role: "agent", type: "text", message: "Hello world" },
+ ]),
+ });
+
+ expect(
+ await screen.findByTestId("metabot-chat-message"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Hello world")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-crm.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-crm.stories.tsx
new file mode 100644
index 00000000000..93f6b76384f
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-crm.stories.tsx
@@ -0,0 +1,384 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMetabot } from "./use-metabot";
+import {
+ BotIcon,
+ Composer,
+ MessageList,
+ SharedKeyframes,
+ makeSdkWrapper,
+} from "./use-metabot.stories.utils";
+
+// ============================================================================
+// CRM (AcmeCRM) palette
+// ============================================================================
+
+const crm = {
+ bg: "#16325c",
+ surface: "#1b3d72",
+ surfaceRaised: "#214886",
+ surfaceHover: "#27529a",
+ border: "#2b5dae",
+ borderSubtle: "#1f4480",
+ text: "#e8f0fe",
+ textSecondary: "#7faad4",
+ textMuted: "#4d7ab0",
+ accent: "#0176d3",
+ accentLight: "#58b0ff",
+ accentDim: "#0176d325",
+ gradient: "linear-gradient(135deg, #0176d3 0%, #58b0ff 100%)",
+ red: "#f87171",
+ redDim: "#f8717120",
+};
+
+// ============================================================================
+// Fake AcmeCRM background
+// ============================================================================
+
+const deals = [
+ { name: "Acme Corp", stage: "Proposal", amount: "$48,000", owner: "Sarah" },
+ {
+ name: "TechStart Inc",
+ stage: "Negotiation",
+ amount: "$92,000",
+ owner: "James",
+ },
+ { name: "Global Retail", stage: "Demo", amount: "$24,500", owner: "Priya" },
+ {
+ name: "FinCo Ltd",
+ stage: "Prospecting",
+ amount: "$130,000",
+ owner: "Alex",
+ },
+ { name: "CloudSoft", stage: "Closed Won", amount: "$76,000", owner: "Maria" },
+];
+
+const stageColor = (stage: string) => {
+ if (stage === "Closed Won") {
+ return crm.accentLight;
+ }
+ if (stage === "Negotiation") {
+ return "#fbbf24";
+ }
+ if (stage === "Proposal") {
+ return "#a78bfa";
+ }
+ return crm.textMuted;
+};
+
+const AcmeCRMBg = () => (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: crm.bg,
+ overflow: "hidden",
+ zIndex: 0,
+ }}
+ >
+ {/* Top nav */}
+ <div
+ style={{
+ height: 44,
+ borderBottom: `1px solid ${crm.border}`,
+ display: "flex",
+ alignItems: "center",
+ padding: "0 20px",
+ gap: 20,
+ }}
+ >
+ <span style={{ fontWeight: 800, fontSize: 14, color: crm.text }}>
+ <span style={{ color: crm.accentLight }}>Acme</span>CRM
+ </span>
+ {["Home", "Leads", "Opportunities", "Accounts", "Reports"].map((tab) => (
+ <span
+ key={tab}
+ style={{ fontSize: 12, color: crm.textSecondary, cursor: "pointer" }}
+ >
+ {tab}
+ </span>
+ ))}
+ </div>
+ {/* Pipeline header */}
+ <div style={{ padding: "16px 20px 0" }}>
+ <div
+ style={{
+ fontSize: 16,
+ fontWeight: 700,
+ color: crm.text,
+ marginBottom: 4,
+ }}
+ >
+ Pipeline Q2 2025
+ </div>
+ <div style={{ fontSize: 12, color: crm.textMuted, marginBottom: 16 }}>
+ Total: $370,500 · 5 open deals
+ </div>
+ {/* Deal list */}
+ <div
+ style={{
+ background: crm.surface,
+ border: `1px solid ${crm.border}`,
+ borderRadius: 10,
+ overflow: "hidden",
+ }}
+ >
+ <div
+ style={{
+ padding: "10px 14px",
+ borderBottom: `1px solid ${crm.border}`,
+ display: "grid",
+ gridTemplateColumns: "2fr 1fr 1fr 1fr",
+ fontSize: 11,
+ fontWeight: 600,
+ color: crm.textMuted,
+ }}
+ >
+ <span>Account</span>
+ <span>Stage</span>
+ <span>Amount</span>
+ <span>Owner</span>
+ </div>
+ {deals.map((deal, i) => (
+ <div
+ key={deal.name}
+ style={{
+ padding: "10px 14px",
+ display: "grid",
+ gridTemplateColumns: "2fr 1fr 1fr 1fr",
+ fontSize: 13,
+ color: crm.textSecondary,
+ borderBottom:
+ i < deals.length - 1 ? `1px solid ${crm.borderSubtle}` : "none",
+ alignItems: "center",
+ }}
+ >
+ <span style={{ color: crm.text, fontWeight: 500 }}>
+ {deal.name}
+ </span>
+ <span style={{ color: stageColor(deal.stage) }}>{deal.stage}</span>
+ <span style={{ fontWeight: 600, color: crm.text }}>
+ {deal.amount}
+ </span>
+ <span style={{ color: crm.textMuted }}>{deal.owner}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+);
+
+// ============================================================================
+// Story — persistent right side panel (always visible)
+// ============================================================================
+
+const CrmDemo = () => {
+ const metabot = useMetabot();
+ const [inputValue, setInputValue] = useState("");
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [metabot.messages, metabot.isProcessing]);
+
+ const handleSubmit = () => {
+ if (inputValue.trim() && !metabot.isProcessing) {
+ metabot.submitMessage(inputValue.trim());
+ setInputValue("");
+ }
+ };
+
+ const canSend = inputValue.trim().length > 0 && !metabot.isProcessing;
+
+ return (
+ <div
+ style={{
+ display: "flex",
+ width: "100%",
+ height: "100vh",
+ overflow: "hidden",
+ fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
+ }}
+ >
+ <SharedKeyframes />
+ <div style={{ flex: 1, position: "relative" }}>
+ {metabot.CurrentChart ? (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: crm.bg,
+ }}
+ >
+ <metabot.CurrentChart drills isSaveEnabled={false} height="100%" />
+ </div>
+ ) : (
+ <AcmeCRMBg />
+ )}
+ </div>
+
+ {/* Persistent right panel — pinned alongside the deal list */}
+ <div
+ style={{
+ width: 320,
+ height: "100%",
+ background: crm.surface,
+ borderLeft: `1px solid ${crm.border}`,
+ display: "flex",
+ flexDirection: "column",
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ padding: "12px 14px",
+ background: crm.surfaceRaised,
+ borderBottom: `1px solid ${crm.border}`,
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ flexShrink: 0,
+ }}
+ >
+ <div
+ style={{
+ width: 28,
+ height: 28,
+ borderRadius: 7,
+ background: crm.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ }}
+ >
+ <BotIcon size={14} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div style={{ fontSize: 13, fontWeight: 700, color: crm.text }}>
+ Metabot
+ </div>
+ <div
+ style={{
+ fontSize: 10,
+ color: metabot.isProcessing ? crm.accentLight : crm.textMuted,
+ }}
+ >
+ {metabot.isProcessing ? "Analyzing pipeline..." : "CRM analytics"}
+ </div>
+ </div>
+ {metabot.messages.length > 0 && (
+ <button
+ onClick={() => metabot.resetConversation()}
+ style={{
+ background: "none",
+ border: "none",
+ color: crm.textMuted,
+ fontSize: 11,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ }}
+ >
+ Clear
+ </button>
+ )}
+ </div>
+
+ {/* Errors */}
+ {metabot.errorMessages.map((errorMessage, index) => (
+ <div
+ key={index}
+ style={{
+ padding: "5px 14px",
+ fontSize: 12,
+ color: crm.red,
+ background: crm.redDim,
+ }}
+ >
+ {errorMessage.message}
+ </div>
+ ))}
+
+ {/* Messages */}
+ <div style={{ flex: 1, overflowY: "auto", padding: "10px 12px" }}>
+ {metabot.messages.length === 0 && !metabot.isProcessing && (
+ <div style={{ padding: "8px 0" }}>
+ <div
+ style={{
+ fontSize: 11,
+ color: crm.textMuted,
+ fontWeight: 600,
+ marginBottom: 8,
+ }}
+ >
+ SUGGESTED QUESTIONS
+ </div>
+ {[
+ "Which customers have the highest total spend?",
+ "Show orders by acquisition source",
+ "Average order value by state",
+ ].map((prompt) => (
+ <button
+ key={prompt}
+ onClick={() => {
+ if (!metabot.isProcessing) {
+ metabot.submitMessage(prompt);
+ }
+ }}
+ style={{
+ display: "block",
+ width: "100%",
+ textAlign: "left",
+ background: crm.surfaceRaised,
+ border: `1px solid ${crm.border}`,
+ borderRadius: 7,
+ padding: "8px 10px",
+ fontSize: 12,
+ color: crm.textSecondary,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ marginBottom: 6,
+ }}
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+ )}
+ <MessageList
+ messages={metabot.messages.filter(
+ (message) => message.type !== "chart",
+ )}
+ isProcessing={metabot.isProcessing}
+ scrollRef={scrollRef}
+ palette={crm}
+ onRetry={metabot.retryMessage}
+ />
+ </div>
+
+ <Composer
+ value={inputValue}
+ onChange={setInputValue}
+ onSubmit={handleSubmit}
+ canSend={canSend}
+ placeholder="Ask about customers, orders..."
+ onCancel={metabot.cancelRequest}
+ isProcessing={metabot.isProcessing}
+ palette={crm}
+ />
+ </div>
+ </div>
+ );
+};
+
+const meta: Meta<typeof CrmDemo> = {
+ title: "EmbeddingSDK/useMetabot/CRM (AcmeCRM)",
+ component: CrmDemo,
+ parameters: { layout: "fullscreen" },
+ decorators: [makeSdkWrapper()],
+};
+
+export default meta;
+
+export const AcmeCRM: StoryFn = () => <CrmDemo />;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-devops.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-devops.stories.tsx
new file mode 100644
index 00000000000..62641e9bbca
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-devops.stories.tsx
@@ -0,0 +1,446 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMetabot } from "./use-metabot";
+import {
+ CloseIcon,
+ MessageList,
+ SharedKeyframes,
+ SparkleIcon,
+ makeSdkWrapper,
+} from "./use-metabot.stories.utils";
+
+// ============================================================================
+// DevOps (InfraWatch) palette
+// ============================================================================
+
+const dv = {
+ bg: "#1b1e2e",
+ surface: "#20243a",
+ surfaceRaised: "#272b42",
+ surfaceHover: "#2f3450",
+ border: "#363b5a",
+ borderSubtle: "#2a2f4a",
+ text: "#e2e4f0",
+ textSecondary: "#8b90b0",
+ textMuted: "#585d7e",
+ accent: "#774aa4",
+ accentLight: "#b39ddb",
+ accentDim: "#774aa425",
+ gradient: "linear-gradient(135deg, #774aa4 0%, #b39ddb 100%)",
+ red: "#f87171",
+ redDim: "#f8717120",
+};
+
+// ============================================================================
+// Fake InfraWatch monitoring background
+// ============================================================================
+
+const InfraWatchBg = () => (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: dv.bg,
+ overflow: "hidden",
+ zIndex: 0,
+ }}
+ >
+ {/* Top nav */}
+ <div
+ style={{
+ height: 44,
+ borderBottom: `1px solid ${dv.border}`,
+ display: "flex",
+ alignItems: "center",
+ padding: "0 20px",
+ gap: 20,
+ }}
+ >
+ <span style={{ fontWeight: 800, fontSize: 14, color: dv.accentLight }}>
+ InfraWatch
+ </span>
+ {["Dashboards", "Monitors", "APM", "Logs", "Infrastructure"].map(
+ (tab) => (
+ <span
+ key={tab}
+ style={{ fontSize: 12, color: dv.textSecondary, cursor: "pointer" }}
+ >
+ {tab}
+ </span>
+ ),
+ )}
+ <span style={{ marginLeft: "auto", fontSize: 12, color: dv.textMuted }}>
+ Press ⌘K to open Metabot
+ </span>
+ </div>
+ {/* Alert list */}
+ <div style={{ padding: "20px 24px" }}>
+ <div
+ style={{
+ fontSize: 15,
+ fontWeight: 700,
+ color: dv.text,
+ marginBottom: 16,
+ }}
+ >
+ Active monitors
+ </div>
+ {[
+ ["P1", "API error rate > 5%", "web-api", "3m ago", true],
+ ["P2", "CPU usage > 90%", "worker-fleet", "12m ago", true],
+ ["P3", "Memory spike", "cache-cluster", "1h ago", false],
+ ["P3", "Latency p99 > 800ms", "checkout-service", "2h ago", false],
+ ].map(([prio, name, service, time, active]) => (
+ <div
+ key={String(name)}
+ style={{
+ background: dv.surface,
+ border: `1px solid ${active ? dv.red + "50" : dv.border}`,
+ borderLeft: `4px solid ${active ? dv.red : dv.textMuted}`,
+ borderRadius: 8,
+ padding: "10px 14px",
+ marginBottom: 8,
+ display: "flex",
+ alignItems: "center",
+ gap: 12,
+ fontSize: 13,
+ }}
+ >
+ <span
+ style={{
+ fontSize: 11,
+ fontWeight: 700,
+ color: active ? dv.red : dv.textMuted,
+ background: dv.surfaceRaised,
+ padding: "2px 6px",
+ borderRadius: 4,
+ }}
+ >
+ {String(prio)}
+ </span>
+ <span style={{ flex: 1, color: dv.text }}>{String(name)}</span>
+ <span style={{ color: dv.textMuted }}>{String(service)}</span>
+ <span style={{ color: dv.textMuted, fontSize: 11 }}>
+ {String(time)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+);
+
+// ============================================================================
+// Story — command palette (Cmd+K modal)
+// ============================================================================
+
+const DevopsDemo = () => {
+ const metabot = useMetabot();
+ const [open, setOpen] = useState(false);
+ const [inputValue, setInputValue] = useState("");
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [metabot.messages, metabot.isProcessing]);
+
+ // Open/close with Cmd+K
+ useEffect(() => {
+ const handler = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === "k") {
+ event.preventDefault();
+ setOpen((isOpen) => !isOpen);
+ }
+ if (event.key === "Escape") {
+ setOpen(false);
+ }
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, []);
+
+ const handleSubmit = () => {
+ if (inputValue.trim() && !metabot.isProcessing) {
+ metabot.submitMessage(inputValue.trim());
+ setInputValue("");
+ }
+ };
+
+ const canSend = inputValue.trim().length > 0 && !metabot.isProcessing;
+
+ return (
+ <div
+ style={{
+ position: "relative",
+ width: "100%",
+ height: "100vh",
+ overflow: "hidden",
+ fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
+ }}
+ >
+ <SharedKeyframes />
+ <InfraWatchBg />
+
+ {/* Command palette overlay */}
+ {open && (
+ <>
+ {/* Backdrop */}
+ <div
+ onClick={() => setOpen(false)}
+ style={{
+ position: "fixed",
+ inset: 0,
+ background: "rgba(0,0,0,0.6)",
+ zIndex: 999,
+ }}
+ />
+ {/* Modal */}
+ <div
+ style={{
+ position: "fixed",
+ top: "10%",
+ left: "50%",
+ transform: "translateX(-50%)",
+ width: 600,
+ maxHeight: 480,
+ background: dv.surface,
+ border: `1px solid ${dv.border}`,
+ borderRadius: 14,
+ boxShadow: "0 32px 80px rgba(0,0,0,0.6)",
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ zIndex: 1000,
+ animation: "metabotFadeUp 0.2s ease",
+ }}
+ >
+ {/* Search bar */}
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ padding: "12px 16px",
+ borderBottom: `1px solid ${dv.border}`,
+ flexShrink: 0,
+ color: dv.accentLight,
+ }}
+ >
+ <SparkleIcon size={16} />
+ <style>{`.dv-search-input::placeholder { color: ${dv.textSecondary}; opacity: 1; }`}</style>
+ <input
+ autoFocus
+ className="dv-search-input"
+ style={{
+ flex: 1,
+ background: "none",
+ border: "none",
+ outline: "none",
+ fontSize: 15,
+ color: dv.text,
+ fontFamily: "inherit",
+ }}
+ value={inputValue}
+ onChange={(event) => setInputValue(event.target.value)}
+ onKeyDown={(event) => event.key === "Enter" && handleSubmit()}
+ placeholder="Ask about products, orders..."
+ />
+ <button
+ onClick={() => setOpen(false)}
+ style={{
+ background: "none",
+ border: "none",
+ color: dv.textMuted,
+ cursor: "pointer",
+ padding: 4,
+ display: "flex",
+ }}
+ >
+ <CloseIcon />
+ </button>
+ </div>
+
+ {/* Errors */}
+ {metabot.errorMessages.map((errorMessage, index) => (
+ <div
+ key={index}
+ style={{
+ padding: "6px 16px",
+ fontSize: 12,
+ color: dv.red,
+ background: dv.redDim,
+ }}
+ >
+ {errorMessage.message}
+ </div>
+ ))}
+
+ {/* Messages */}
+ <div
+ style={{
+ flex: 1,
+ overflowY: "auto",
+ padding: "10px 14px",
+ minHeight: 0,
+ }}
+ >
+ {metabot.messages.length === 0 && !metabot.isProcessing && (
+ <div
+ style={{
+ color: dv.textMuted,
+ fontSize: 13,
+ padding: "16px 0",
+ }}
+ >
+ <div
+ style={{
+ marginBottom: 8,
+ fontWeight: 600,
+ color: dv.textSecondary,
+ }}
+ >
+ Suggested
+ </div>
+ {[
+ "Which products have the lowest ratings?",
+ "Show order volume over time",
+ "Average review rating by category",
+ ].map((prompt) => (
+ <div
+ key={prompt}
+ onClick={() => {
+ if (!metabot.isProcessing) {
+ metabot.submitMessage(prompt);
+ }
+ }}
+ style={{
+ padding: "8px 10px",
+ borderRadius: 6,
+ cursor: "pointer",
+ fontSize: 13,
+ color: dv.text,
+ marginBottom: 4,
+ background: dv.surfaceRaised,
+ border: `1px solid ${dv.border}`,
+ }}
+ >
+ {prompt}
+ </div>
+ ))}
+ </div>
+ )}
+ <MessageList
+ messages={metabot.messages}
+ isProcessing={metabot.isProcessing}
+ scrollRef={scrollRef}
+ palette={dv}
+ />
+ </div>
+
+ {/* Footer controls */}
+ <div
+ style={{
+ borderTop: `1px solid ${dv.border}`,
+ padding: "6px 16px",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ flexShrink: 0,
+ }}
+ >
+ <div style={{ fontSize: 11, color: dv.textMuted }}>
+ {metabot.messages.length > 0 && (
+ <button
+ onClick={() => metabot.resetConversation()}
+ style={{
+ background: "none",
+ border: "none",
+ color: dv.textMuted,
+ cursor: "pointer",
+ fontSize: 11,
+ fontFamily: "inherit",
+ }}
+ >
+ Clear conversation
+ </button>
+ )}
+ </div>
+ <button
+ onClick={handleSubmit}
+ disabled={!canSend}
+ style={{
+ background: canSend ? dv.accent : dv.surfaceRaised,
+ border: "none",
+ borderRadius: 6,
+ padding: "5px 14px",
+ color: canSend ? "#fff" : dv.textMuted,
+ fontSize: 12,
+ fontWeight: 600,
+ cursor: canSend ? "pointer" : "default",
+ fontFamily: "inherit",
+ }}
+ >
+ {metabot.isProcessing ? "Stop" : "Ask →"}
+ </button>
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Cmd+K hint button */}
+ {!open && (
+ <button
+ onClick={() => setOpen(true)}
+ style={{
+ position: "fixed",
+ bottom: 24,
+ right: 24,
+ background: dv.surface,
+ border: `1px solid ${dv.border}`,
+ borderRadius: 10,
+ padding: "8px 14px",
+ color: dv.textSecondary,
+ fontSize: 13,
+ fontWeight: 600,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ fontFamily: "inherit",
+ boxShadow: "0 4px 20px rgba(0,0,0,0.4)",
+ zIndex: 100,
+ }}
+ >
+ <SparkleIcon size={14} />
+ Ask Metabot
+ <kbd
+ style={{
+ background: dv.surfaceRaised,
+ padding: "1px 6px",
+ borderRadius: 4,
+ fontSize: 11,
+ color: dv.textMuted,
+ }}
+ >
+ ⌘K
+ </kbd>
+ </button>
+ )}
+ </div>
+ );
+};
+
+const meta: Meta<typeof DevopsDemo> = {
+ title: "EmbeddingSDK/useMetabot/DevOps (InfraWatch Monitoring)",
+ component: DevopsDemo,
+ parameters: {
+ layout: "fullscreen",
+ // Raise SDK popovers above the command palette modal (z-index: 1000)
+ sdkThemeOverride: { components: { popover: { zIndex: 1001 } } },
+ },
+ decorators: [makeSdkWrapper()],
+};
+
+export default meta;
+
+export const InfraWatchMonitoring: StoryFn = () => <DevopsDemo />;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-ecommerce.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-ecommerce.stories.tsx
new file mode 100644
index 00000000000..bc9573c581b
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-ecommerce.stories.tsx
@@ -0,0 +1,526 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMetabot } from "./use-metabot";
+import {
+ BotIcon,
+ CloseIcon,
+ Composer,
+ MessageList,
+ SharedKeyframes,
+ makeSdkWrapper,
+} from "./use-metabot.stories.utils";
+
+// ============================================================================
+// E-commerce (Storefront) palette
+// ============================================================================
+
+const ec = {
+ bg: "#1a1c1e",
+ surface: "#202325",
+ surfaceRaised: "#282b2d",
+ surfaceHover: "#303336",
+ border: "#3d4144",
+ borderSubtle: "#2d3033",
+ text: "#e3e5e8",
+ textSecondary: "#9ba3a8",
+ textMuted: "#5e666b",
+ accent: "#008060",
+ accentLight: "#34d399",
+ accentDim: "#00806025",
+ gradient: "linear-gradient(135deg, #008060 0%, #34d399 100%)",
+ red: "#f87171",
+ redDim: "#f8717120",
+};
+
+// ============================================================================
+// Fake Storefront Admin background
+// ============================================================================
+
+const StorefrontBg = () => (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: ec.bg,
+ overflow: "hidden",
+ zIndex: 0,
+ display: "flex",
+ }}
+ >
+ {/* Left sidebar */}
+ <div
+ style={{
+ width: 200,
+ background: "#111314",
+ borderRight: `1px solid ${ec.border}`,
+ padding: "16px 0",
+ flexShrink: 0,
+ }}
+ >
+ <div
+ style={{
+ padding: "0 16px 16px",
+ fontWeight: 800,
+ fontSize: 15,
+ color: ec.text,
+ }}
+ >
+ Storefront
+ </div>
+ {[
+ "Orders",
+ "Products",
+ "Customers",
+ "Analytics",
+ "Marketing",
+ "Discounts",
+ ].map((item, i) => (
+ <div
+ key={item}
+ style={{
+ padding: "8px 16px",
+ fontSize: 13,
+ color: i === 2 ? ec.text : ec.textSecondary,
+ background: i === 2 ? ec.surfaceRaised : "none",
+ borderLeft:
+ i === 2 ? `3px solid ${ec.accent}` : "3px solid transparent",
+ cursor: "pointer",
+ }}
+ >
+ {item}
+ </div>
+ ))}
+ </div>
+
+ {/* Main content */}
+ <div style={{ flex: 1, padding: 24, overflowY: "auto" }}>
+ {/* Top bar */}
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ marginBottom: 24,
+ }}
+ >
+ <div style={{ fontSize: 20, fontWeight: 700, color: ec.text }}>
+ Customers
+ </div>
+ <button
+ style={{
+ background: ec.accent,
+ border: "none",
+ borderRadius: 6,
+ padding: "8px 16px",
+ color: "#fff",
+ fontSize: 13,
+ fontWeight: 600,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ }}
+ >
+ Export
+ </button>
+ </div>
+ {/* Stat cards */}
+ <div
+ style={{
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr 1fr",
+ gap: 16,
+ marginBottom: 24,
+ }}
+ >
+ {[
+ ["Total customers", "48,291", "+8.3%"],
+ ["Returning", "61%", "+2.1%"],
+ ["Avg. order value", "$84.20", "+12%"],
+ ].map(([label, value, delta]) => (
+ <div
+ key={label}
+ style={{
+ background: ec.surface,
+ border: `1px solid ${ec.border}`,
+ borderRadius: 10,
+ padding: 16,
+ }}
+ >
+ <div style={{ fontSize: 12, color: ec.textMuted }}>{label}</div>
+ <div
+ style={{
+ fontSize: 24,
+ fontWeight: 800,
+ color: ec.text,
+ margin: "4px 0",
+ }}
+ >
+ {value}
+ </div>
+ <div style={{ fontSize: 12, color: ec.accentLight }}>{delta}</div>
+ </div>
+ ))}
+ </div>
+ {/* Order table */}
+ <div
+ style={{
+ background: ec.surface,
+ border: `1px solid ${ec.border}`,
+ borderRadius: 10,
+ overflow: "hidden",
+ }}
+ >
+ <div
+ style={{
+ padding: "12px 16px",
+ borderBottom: `1px solid ${ec.border}`,
+ fontWeight: 600,
+ fontSize: 13,
+ color: ec.text,
+ }}
+ >
+ Recent orders
+ </div>
+ {[
+ ["#1204", "Sarah Chen", "$142.00", "Fulfilled"],
+ ["#1203", "James Park", "$89.50", "Pending"],
+ ["#1202", "Maria Santos", "$214.00", "Fulfilled"],
+ ["#1201", "Alex Kim", "$56.80", "Cancelled"],
+ ].map(([id, name, amount, status], i) => (
+ <div
+ key={id}
+ style={{
+ padding: "12px 16px",
+ display: "flex",
+ gap: 16,
+ fontSize: 13,
+ color: ec.textSecondary,
+ borderBottom: i < 3 ? `1px solid ${ec.borderSubtle}` : "none",
+ }}
+ >
+ <span style={{ color: ec.accentLight, fontWeight: 600 }}>{id}</span>
+ <span style={{ flex: 1 }}>{name}</span>
+ <span>{amount}</span>
+ <span
+ style={{
+ color:
+ status === "Fulfilled"
+ ? ec.accentLight
+ : status === "Cancelled"
+ ? ec.red
+ : ec.textMuted,
+ }}
+ >
+ {status}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+);
+
+// ============================================================================
+// Story
+// ============================================================================
+
+const EcommerceDemo = () => {
+ const metabot = useMetabot();
+ const [open, setOpen] = useState(false);
+ const [inputValue, setInputValue] = useState("");
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [metabot.messages, metabot.isProcessing]);
+
+ const handleSubmit = () => {
+ if (inputValue.trim() && !metabot.isProcessing) {
+ metabot.submitMessage(inputValue.trim());
+ setInputValue("");
+ }
+ };
+
+ const canSend = inputValue.trim().length > 0 && !metabot.isProcessing;
+
+ return (
+ <div
+ style={{
+ position: "relative",
+ width: "100%",
+ height: "100vh",
+ overflow: "hidden",
+ fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
+ }}
+ >
+ <SharedKeyframes />
+ <StorefrontBg />
+
+ {/* Slide-in drawer from right */}
+ {open && (
+ <div
+ style={{
+ position: "fixed",
+ top: 0,
+ right: 0,
+ width: 400,
+ height: "100%",
+ background: ec.surface,
+ borderLeft: `1px solid ${ec.border}`,
+ boxShadow: "-24px 0 80px rgba(0,0,0,0.5)",
+ display: "flex",
+ flexDirection: "column",
+ zIndex: 1000,
+ animation: "metabotFadeUp 0.25s ease",
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ padding: "14px 16px",
+ background: ec.surfaceRaised,
+ borderBottom: `1px solid ${ec.border}`,
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ flexShrink: 0,
+ }}
+ >
+ <div
+ style={{
+ width: 32,
+ height: 32,
+ borderRadius: 8,
+ background: ec.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ }}
+ >
+ <BotIcon size={16} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div style={{ fontSize: 14, fontWeight: 700, color: ec.text }}>
+ Metabot
+ </div>
+ <div
+ style={{
+ fontSize: 11,
+ color: metabot.isProcessing ? ec.accentLight : ec.textMuted,
+ }}
+ >
+ {metabot.isProcessing
+ ? "Thinking..."
+ : "Ask about your store data"}
+ </div>
+ </div>
+ <button
+ onClick={() => metabot.resetConversation()}
+ style={{
+ background: "none",
+ border: "none",
+ color: ec.textMuted,
+ fontSize: 11,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ }}
+ >
+ Clear
+ </button>
+ <button
+ onClick={() => setOpen(false)}
+ style={{
+ background: "none",
+ border: "none",
+ color: ec.textSecondary,
+ cursor: "pointer",
+ padding: 4,
+ display: "flex",
+ }}
+ >
+ <CloseIcon />
+ </button>
+ </div>
+
+ {/* Errors */}
+ {metabot.errorMessages.map((errorMessage, index) => (
+ <div
+ key={index}
+ style={{
+ padding: "6px 16px",
+ fontSize: 12,
+ color: ec.red,
+ background: ec.redDim,
+ }}
+ >
+ {errorMessage.message}
+ </div>
+ ))}
+
+ {/* Pinned latest chart */}
+ {metabot.CurrentChart && (
+ <div
+ style={{
+ height: 260,
+ borderBottom: `1px solid ${ec.border}`,
+ background: ec.surfaceRaised,
+ flexShrink: 0,
+ }}
+ >
+ <metabot.CurrentChart
+ drills
+ isSaveEnabled={false}
+ height="100%"
+ />
+ </div>
+ )}
+
+ {/* Messages */}
+ <div style={{ flex: 1, overflowY: "auto", padding: "12px 14px" }}>
+ {metabot.messages.length === 0 && !metabot.isProcessing && (
+ <div
+ style={{
+ textAlign: "center",
+ padding: "40px 20px",
+ color: ec.textMuted,
+ }}
+ >
+ <div
+ style={{
+ width: 48,
+ height: 48,
+ borderRadius: 12,
+ background: ec.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ margin: "0 auto 12px",
+ }}
+ >
+ <BotIcon size={24} />
+ </div>
+ <div
+ style={{
+ fontSize: 14,
+ fontWeight: 700,
+ color: ec.text,
+ marginBottom: 8,
+ }}
+ >
+ Ask about your store
+ </div>
+ <div
+ style={{ marginTop: 16, width: "100%", textAlign: "left" }}
+ >
+ <div
+ style={{
+ fontSize: 11,
+ color: ec.textMuted,
+ fontWeight: 600,
+ marginBottom: 8,
+ textAlign: "center",
+ }}
+ >
+ SUGGESTED QUESTIONS
+ </div>
+ {[
+ "Show top products by revenue this month",
+ "Why did orders drop last Tuesday?",
+ "Which customers ordered the most?",
+ ].map((prompt) => (
+ <button
+ key={prompt}
+ onClick={() => {
+ if (!metabot.isProcessing) {
+ metabot.submitMessage(prompt);
+ }
+ }}
+ style={{
+ display: "block",
+ width: "100%",
+ textAlign: "left",
+ background: ec.surfaceRaised,
+ border: `1px solid ${ec.border}`,
+ borderRadius: 7,
+ padding: "8px 10px",
+ fontSize: 12,
+ color: ec.textSecondary,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ marginBottom: 6,
+ }}
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ <MessageList
+ messages={metabot.messages.filter(
+ (message) => message.type !== "chart",
+ )}
+ isProcessing={metabot.isProcessing}
+ scrollRef={scrollRef}
+ palette={ec}
+ />
+ </div>
+
+ <Composer
+ value={inputValue}
+ onChange={setInputValue}
+ onSubmit={handleSubmit}
+ canSend={canSend}
+ placeholder="Ask about orders, products..."
+ onCancel={metabot.cancelRequest}
+ isProcessing={metabot.isProcessing}
+ palette={ec}
+ />
+ </div>
+ )}
+
+ {/* FAB to open drawer */}
+ {!open && (
+ <button
+ onClick={() => setOpen(true)}
+ style={{
+ position: "fixed",
+ bottom: 24,
+ right: 24,
+ width: 52,
+ height: 52,
+ borderRadius: 14,
+ border: "none",
+ background: ec.gradient,
+ color: "#fff",
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ boxShadow: `0 4px 24px ${ec.accent}50`,
+ zIndex: 1000,
+ }}
+ >
+ <BotIcon size={24} />
+ </button>
+ )}
+ </div>
+ );
+};
+
+const meta: Meta<typeof EcommerceDemo> = {
+ title: "EmbeddingSDK/useMetabot/Ecommerce (Storefront)",
+ component: EcommerceDemo,
+ parameters: {
+ layout: "fullscreen",
+ // Raise SDK popovers above the slide-in drawer (z-index: 1000)
+ sdkThemeOverride: { components: { popover: { zIndex: 1001 } } },
+ },
+ decorators: [makeSdkWrapper()],
+};
+
+export default meta;
+
+export const Storefront: StoryFn = () => <EcommerceDemo />;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-fintech.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-fintech.stories.tsx
new file mode 100644
index 00000000000..8523a123a4a
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-fintech.stories.tsx
@@ -0,0 +1,383 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMetabot } from "./use-metabot";
+import {
+ BotIcon,
+ Composer,
+ MessageList,
+ SharedKeyframes,
+ makeSdkWrapper,
+} from "./use-metabot.stories.utils";
+
+// ============================================================================
+// FinTech (PayFlow) palette
+// ============================================================================
+
+const ft = {
+ bg: "#0a2540",
+ surface: "#0d2d4a",
+ surfaceRaised: "#133558",
+ surfaceHover: "#1a3f67",
+ border: "#1e4976",
+ borderSubtle: "#153560",
+ text: "#e8f0fe",
+ textSecondary: "#8bafd4",
+ textMuted: "#4a7499",
+ accent: "#635bff",
+ accentLight: "#a29bfe",
+ accentDim: "#635bff25",
+ gradient: "linear-gradient(135deg, #635bff 0%, #a29bfe 100%)",
+ red: "#f87171",
+ redDim: "#f8717120",
+};
+
+// ============================================================================
+// Fake PayFlow Dashboard background
+// ============================================================================
+
+const PayFlowBg = () => (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: ft.bg,
+ overflow: "hidden",
+ zIndex: 0,
+ }}
+ >
+ {/* Top nav */}
+ <div
+ style={{
+ height: 48,
+ borderBottom: `1px solid ${ft.border}`,
+ display: "flex",
+ alignItems: "center",
+ padding: "0 24px",
+ gap: 24,
+ }}
+ >
+ <span style={{ fontWeight: 800, fontSize: 15, color: ft.text }}>
+ <span style={{ color: ft.accentLight }}>Pay</span>Flow
+ </span>
+ {["Home", "Payments", "Customers", "Reports", "Developers"].map((tab) => (
+ <span
+ key={tab}
+ style={{ fontSize: 13, color: ft.textSecondary, cursor: "pointer" }}
+ >
+ {tab}
+ </span>
+ ))}
+ </div>
+ {/* Stat cards */}
+ <div
+ style={{
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr 1fr 1fr",
+ gap: 16,
+ padding: 24,
+ }}
+ >
+ {[
+ ["Gross volume", "$2.41M", "+18.2%"],
+ ["MRR", "$142K", "+6.4%"],
+ ["Churn", "2.8%", "-0.3%"],
+ ["Active subs", "8,214", "+12.1%"],
+ ].map(([label, value, delta]) => (
+ <div
+ key={label}
+ style={{
+ background: ft.surface,
+ border: `1px solid ${ft.border}`,
+ borderRadius: 10,
+ padding: 16,
+ }}
+ >
+ <div style={{ fontSize: 12, color: ft.textMuted }}>{label}</div>
+ <div
+ style={{
+ fontSize: 22,
+ fontWeight: 800,
+ color: ft.text,
+ margin: "6px 0 4px",
+ }}
+ >
+ {value}
+ </div>
+ <div
+ style={{
+ fontSize: 12,
+ color: delta?.startsWith("-") ? ft.red : ft.accentLight,
+ }}
+ >
+ {delta}
+ </div>
+ </div>
+ ))}
+ </div>
+ {/* Payments table */}
+ <div style={{ padding: "0 24px" }}>
+ <div
+ style={{
+ background: ft.surface,
+ border: `1px solid ${ft.border}`,
+ borderRadius: 10,
+ overflow: "hidden",
+ }}
+ >
+ <div
+ style={{
+ padding: "12px 16px",
+ borderBottom: `1px solid ${ft.border}`,
+ fontWeight: 600,
+ fontSize: 13,
+ color: ft.text,
+ }}
+ >
+ Recent payments
+ </div>
+ {[
+ ["Jane Cooper", "Enterprise plan", "$2,400", "Succeeded"],
+ ["Acme Corp", "Starter plan", "$149", "Succeeded"],
+ ["Bob Martin", "Pro plan", "$490", "Failed"],
+ ["TechCo Ltd", "Enterprise plan", "$2,400", "Refunded"],
+ ].map(([name, plan, amount, status], i) => (
+ <div
+ key={name}
+ style={{
+ padding: "12px 16px",
+ display: "flex",
+ gap: 16,
+ fontSize: 13,
+ color: ft.textSecondary,
+ borderBottom: i < 3 ? `1px solid ${ft.borderSubtle}` : "none",
+ }}
+ >
+ <span style={{ flex: 1 }}>{name}</span>
+ <span style={{ color: ft.textMuted }}>{plan}</span>
+ <span style={{ fontWeight: 600, color: ft.text }}>{amount}</span>
+ <span
+ style={{
+ color:
+ status === "Succeeded"
+ ? ft.accentLight
+ : status === "Failed"
+ ? ft.red
+ : ft.textMuted,
+ }}
+ >
+ {status}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+);
+
+// ============================================================================
+// Story
+// ============================================================================
+
+const FintechDemo = () => {
+ const metabot = useMetabot();
+ const [inputValue, setInputValue] = useState("");
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [metabot.messages, metabot.isProcessing]);
+
+ const handleSubmit = () => {
+ if (inputValue.trim() && !metabot.isProcessing) {
+ metabot.submitMessage(inputValue.trim());
+ setInputValue("");
+ }
+ };
+
+ const canSend = inputValue.trim().length > 0 && !metabot.isProcessing;
+
+ return (
+ <div
+ style={{
+ display: "flex",
+ width: "100%",
+ height: "100vh",
+ overflow: "hidden",
+ fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
+ }}
+ >
+ <SharedKeyframes />
+ <div style={{ flex: 1, position: "relative" }}>
+ {metabot.CurrentChart ? (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: ft.bg,
+ }}
+ >
+ <metabot.CurrentChart drills isSaveEnabled={false} height="100%" />
+ </div>
+ ) : (
+ <PayFlowBg />
+ )}
+ </div>
+
+ {/* Inline side panel — always visible on the right */}
+ <div
+ style={{
+ width: 360,
+ height: "100%",
+ background: ft.surface,
+ borderLeft: `1px solid ${ft.border}`,
+ display: "flex",
+ flexDirection: "column",
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ padding: "14px 16px",
+ background: ft.surfaceRaised,
+ borderBottom: `1px solid ${ft.border}`,
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ flexShrink: 0,
+ }}
+ >
+ <div
+ style={{
+ width: 30,
+ height: 30,
+ borderRadius: 8,
+ background: ft.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ }}
+ >
+ <BotIcon size={14} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div style={{ fontSize: 14, fontWeight: 700, color: ft.text }}>
+ Metabot
+ </div>
+ <div
+ style={{
+ fontSize: 11,
+ color: metabot.isProcessing ? ft.accentLight : ft.textMuted,
+ }}
+ >
+ {metabot.isProcessing ? "Analyzing..." : "Financial analytics"}
+ </div>
+ </div>
+ <button
+ onClick={() => metabot.resetConversation()}
+ style={{
+ background: "none",
+ border: "none",
+ color: ft.textMuted,
+ fontSize: 11,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ }}
+ >
+ Clear
+ </button>
+ </div>
+
+ {/* Errors */}
+ {metabot.errorMessages.map((errorMessage, index) => (
+ <div
+ key={index}
+ style={{
+ padding: "6px 16px",
+ fontSize: 12,
+ color: ft.red,
+ background: ft.redDim,
+ }}
+ >
+ {errorMessage.message}
+ </div>
+ ))}
+
+ {/* Messages */}
+ <div style={{ flex: 1, overflowY: "auto", padding: "12px 14px" }}>
+ {metabot.messages.length === 0 && !metabot.isProcessing && (
+ <div
+ style={{
+ textAlign: "center",
+ padding: "40px 16px",
+ color: ft.textMuted,
+ }}
+ >
+ <div
+ style={{
+ width: 44,
+ height: 44,
+ borderRadius: 12,
+ background: ft.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ margin: "0 auto 12px",
+ }}
+ >
+ <BotIcon size={22} />
+ </div>
+ <div
+ style={{
+ fontSize: 13,
+ fontWeight: 700,
+ color: ft.text,
+ marginBottom: 8,
+ }}
+ >
+ Revenue insights
+ </div>
+ <div style={{ fontSize: 12, lineHeight: 1.5 }}>
+ {
+ 'Try: "What\'s the total revenue this month?" or "Show revenue trend over time"'
+ }
+ </div>
+ </div>
+ )}
+ <MessageList
+ messages={metabot.messages.filter(
+ (message) => message.type !== "chart",
+ )}
+ isProcessing={metabot.isProcessing}
+ scrollRef={scrollRef}
+ palette={ft}
+ />
+ </div>
+
+ <Composer
+ value={inputValue}
+ onChange={setInputValue}
+ onSubmit={handleSubmit}
+ canSend={canSend}
+ placeholder="Ask about revenue, orders..."
+ onCancel={metabot.cancelRequest}
+ isProcessing={metabot.isProcessing}
+ palette={ft}
+ />
+ </div>
+ </div>
+ );
+};
+
+const meta: Meta<typeof FintechDemo> = {
+ title: "EmbeddingSDK/useMetabot/FinTech (PayFlow)",
+ component: FintechDemo,
+ parameters: { layout: "fullscreen" },
+ decorators: [makeSdkWrapper()],
+};
+
+export default meta;
+
+export const PayFlow: StoryFn = () => <FintechDemo />;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-hr.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-hr.stories.tsx
new file mode 100644
index 00000000000..8e2865bd10e
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot-hr.stories.tsx
@@ -0,0 +1,501 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import { useEffect, useRef, useState } from "react";
+
+import { useMetabot } from "./use-metabot";
+import {
+ BotIcon,
+ CloseIcon,
+ Composer,
+ MessageList,
+ SharedKeyframes,
+ SparkleIcon,
+ makeSdkWrapper,
+} from "./use-metabot.stories.utils";
+
+// ============================================================================
+// HR / People Analytics (PeopleHQ) palette
+// ============================================================================
+
+const hr = {
+ bg: "#1c1c1e",
+ surface: "#232325",
+ surfaceRaised: "#2c2c2e",
+ surfaceHover: "#363638",
+ border: "#3a3a3c",
+ borderSubtle: "#2c2c2e",
+ text: "#f0f0f2",
+ textSecondary: "#98989e",
+ textMuted: "#636366",
+ accent: "#e35b00",
+ accentLight: "#ff9f5a",
+ accentDim: "#e35b0025",
+ gradient: "linear-gradient(135deg, #e35b00 0%, #ff9f5a 100%)",
+ red: "#f87171",
+ redDim: "#f8717120",
+};
+
+// ============================================================================
+// Fake PeopleHQ background
+// ============================================================================
+
+const PeopleHQBg = () => (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ background: hr.bg,
+ overflow: "hidden",
+ zIndex: 0,
+ }}
+ >
+ {/* Top nav */}
+ <div
+ style={{
+ height: 48,
+ borderBottom: `1px solid ${hr.border}`,
+ display: "flex",
+ alignItems: "center",
+ padding: "0 24px",
+ gap: 24,
+ }}
+ >
+ <span style={{ fontWeight: 800, fontSize: 15, color: hr.text }}>
+ PeopleHQ
+ </span>
+ {["People", "Time Off", "Performance", "Reports", "Hiring"].map((tab) => (
+ <span
+ key={tab}
+ style={{ fontSize: 13, color: hr.textSecondary, cursor: "pointer" }}
+ >
+ {tab}
+ </span>
+ ))}
+ </div>
+ {/* People metrics header */}
+ <div style={{ padding: "20px 24px 0" }}>
+ <div
+ style={{
+ fontSize: 18,
+ fontWeight: 700,
+ color: hr.text,
+ marginBottom: 16,
+ }}
+ >
+ People Overview
+ </div>
+ <div
+ style={{
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr 1fr 1fr",
+ gap: 14,
+ marginBottom: 24,
+ }}
+ >
+ {[
+ ["Headcount", "1,284", "+18 this month"],
+ ["Avg. tenure", "3.2 yrs", ""],
+ ["Attrition", "8.4%", "-1.2% YoY"],
+ ["Open roles", "42", "+7 this week"],
+ ].map(([label, value, note]) => (
+ <div
+ key={label}
+ style={{
+ background: hr.surface,
+ border: `1px solid ${hr.border}`,
+ borderRadius: 10,
+ padding: 14,
+ }}
+ >
+ <div style={{ fontSize: 11, color: hr.textMuted }}>{label}</div>
+ <div
+ style={{
+ fontSize: 22,
+ fontWeight: 800,
+ color: hr.text,
+ margin: "4px 0 2px",
+ }}
+ >
+ {value}
+ </div>
+ {note && (
+ <div style={{ fontSize: 11, color: hr.accentLight }}>{note}</div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ {/* Employee table */}
+ <div style={{ padding: "0 24px" }}>
+ <div
+ style={{
+ background: hr.surface,
+ border: `1px solid ${hr.border}`,
+ borderRadius: 10,
+ overflow: "hidden",
+ }}
+ >
+ <div
+ style={{
+ padding: "12px 16px",
+ borderBottom: `1px solid ${hr.border}`,
+ fontWeight: 600,
+ fontSize: 13,
+ color: hr.text,
+ }}
+ >
+ Employees
+ </div>
+ {[
+ ["Alice Wang", "Engineering", "Senior IC", "4.2 yrs"],
+ ["James Torres", "Sales", "Account Exec", "1.8 yrs"],
+ ["Priya Sharma", "Product", "PM II", "3.1 yrs"],
+ ["Marcus Lee", "Design", "Lead Designer", "5.6 yrs"],
+ ].map(([name, dept, title, tenure], i) => (
+ <div
+ key={name}
+ style={{
+ padding: "10px 16px",
+ display: "flex",
+ gap: 16,
+ fontSize: 13,
+ color: hr.textSecondary,
+ borderBottom: i < 3 ? `1px solid ${hr.borderSubtle}` : "none",
+ alignItems: "center",
+ }}
+ >
+ <div
+ style={{
+ width: 28,
+ height: 28,
+ borderRadius: "50%",
+ background: hr.gradient,
+ color: "#fff",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: 11,
+ fontWeight: 700,
+ flexShrink: 0,
+ }}
+ >
+ {String(name)[0]}
+ </div>
+ <span style={{ flex: 1, color: hr.text }}>{name}</span>
+ <span>{dept}</span>
+ <span style={{ color: hr.textMuted }}>{title}</span>
+ <span style={{ fontSize: 11, color: hr.textMuted }}>{tenure}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+);
+
+// ============================================================================
+// Story — bottom drawer that slides up
+// ============================================================================
+
+const HrDemo = () => {
+ const metabot = useMetabot();
+ const [open, setOpen] = useState(false);
+ const [inputValue, setInputValue] = useState("");
+ const [drawerHeight, setDrawerHeight] = useState(340);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const dragRef = useRef<{ startY: number; startHeight: number } | null>(null);
+
+ const handleDragStart = (event: React.MouseEvent) => {
+ dragRef.current = { startY: event.clientY, startHeight: drawerHeight };
+ const onMove = (moveEvent: MouseEvent) => {
+ if (!dragRef.current) {
+ return;
+ }
+ const delta = dragRef.current.startY - moveEvent.clientY;
+ const next = Math.max(
+ 120,
+ Math.min(
+ window.innerHeight * 0.85,
+ dragRef.current.startHeight + delta,
+ ),
+ );
+ setDrawerHeight(next);
+ };
+ const onUp = () => {
+ dragRef.current = null;
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", onUp);
+ };
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", onUp);
+ };
+
+ useEffect(() => {
+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [metabot.messages, metabot.isProcessing]);
+
+ const handleSubmit = () => {
+ if (inputValue.trim() && !metabot.isProcessing) {
+ metabot.submitMessage(inputValue.trim());
+ setInputValue("");
+ }
+ };
+
+ const canSend = inputValue.trim().length > 0 && !metabot.isProcessing;
+
+ return (
+ <div
+ style={{
+ position: "relative",
+ width: "100%",
+ height: "100vh",
+ overflow: "hidden",
+ fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
+ }}
+ >
+ <SharedKeyframes />
+ <PeopleHQBg />
+
+ {/* Bottom drawer */}
+ {open && (
+ <div
+ style={{
+ position: "fixed",
+ bottom: 0,
+ left: 0,
+ right: 0,
+ height: drawerHeight,
+ background: hr.surface,
+ borderTop: `1px solid ${hr.border}`,
+ boxShadow: "0 -16px 60px rgba(0,0,0,0.5)",
+ display: "flex",
+ flexDirection: "column",
+ zIndex: 1000,
+ animation: "metabotFadeUp 0.25s ease",
+ }}
+ >
+ {/* Drag handle */}
+ <div
+ onMouseDown={handleDragStart}
+ style={{
+ height: 16,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ cursor: "row-resize",
+ flexShrink: 0,
+ background: hr.surfaceRaised,
+ }}
+ >
+ <div
+ style={{
+ width: 32,
+ height: 3,
+ borderRadius: 2,
+ background: hr.border,
+ }}
+ />
+ </div>
+
+ {/* Header */}
+ <div
+ style={{
+ padding: "10px 16px",
+ background: hr.surfaceRaised,
+ borderBottom: `1px solid ${hr.border}`,
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ flexShrink: 0,
+ }}
+ >
+ <div
+ style={{
+ width: 28,
+ height: 28,
+ borderRadius: 7,
+ background: hr.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ }}
+ >
+ <BotIcon size={14} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div style={{ fontSize: 13, fontWeight: 700, color: hr.text }}>
+ Metabot
+ </div>
+ <div
+ style={{
+ fontSize: 11,
+ color: metabot.isProcessing ? hr.accentLight : hr.textMuted,
+ }}
+ >
+ {metabot.isProcessing
+ ? "Thinking..."
+ : "People analytics assistant"}
+ </div>
+ </div>
+ <button
+ onClick={() => metabot.resetConversation()}
+ style={{
+ background: "none",
+ border: "none",
+ color: hr.textMuted,
+ fontSize: 11,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ }}
+ >
+ Clear
+ </button>
+ <button
+ onClick={() => setOpen(false)}
+ style={{
+ background: "none",
+ border: "none",
+ color: hr.textSecondary,
+ cursor: "pointer",
+ padding: 4,
+ display: "flex",
+ }}
+ >
+ <CloseIcon />
+ </button>
+ </div>
+
+ {/* Errors */}
+ {metabot.errorMessages.map((errorMessage, index) => (
+ <div
+ key={index}
+ style={{
+ padding: "5px 16px",
+ fontSize: 12,
+ color: hr.red,
+ background: hr.redDim,
+ }}
+ >
+ {errorMessage.message}
+ </div>
+ ))}
+
+ {/* Pinned latest chart */}
+ {metabot.CurrentChart && (
+ <div
+ style={{
+ height: 240,
+ borderBottom: `1px solid ${hr.border}`,
+ background: hr.surfaceRaised,
+ flexShrink: 0,
+ }}
+ >
+ <metabot.CurrentChart
+ drills
+ isSaveEnabled={false}
+ height="100%"
+ />
+ </div>
+ )}
+
+ {/* Messages */}
+ <div style={{ flex: 1, overflowY: "auto", padding: "8px 16px" }}>
+ {metabot.messages.length === 0 && !metabot.isProcessing && (
+ <div style={{ display: "flex", gap: 10, paddingTop: 8 }}>
+ {[
+ "How many customers joined each month?",
+ "Show customer distribution by state",
+ "What's the most common acquisition source?",
+ ].map((prompt) => (
+ <button
+ key={prompt}
+ onClick={() => {
+ if (!metabot.isProcessing) {
+ metabot.submitMessage(prompt);
+ }
+ }}
+ style={{
+ background: hr.surfaceRaised,
+ border: `1px solid ${hr.border}`,
+ borderRadius: 8,
+ padding: "6px 12px",
+ fontSize: 12,
+ color: hr.textSecondary,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+ )}
+ <MessageList
+ messages={metabot.messages.filter(
+ (message) => message.type !== "chart",
+ )}
+ isProcessing={metabot.isProcessing}
+ scrollRef={scrollRef}
+ palette={hr}
+ />
+ </div>
+
+ <Composer
+ value={inputValue}
+ onChange={setInputValue}
+ onSubmit={handleSubmit}
+ canSend={canSend}
+ placeholder="Ask about people data..."
+ onCancel={metabot.cancelRequest}
+ isProcessing={metabot.isProcessing}
+ palette={hr}
+ />
+ </div>
+ )}
+
+ {/* Trigger button */}
+ {!open && (
+ <button
+ onClick={() => setOpen(true)}
+ style={{
+ position: "fixed",
+ bottom: 24,
+ right: 24,
+ background: hr.gradient,
+ border: "none",
+ borderRadius: 12,
+ padding: "10px 18px",
+ color: "#fff",
+ fontSize: 13,
+ fontWeight: 600,
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ fontFamily: "inherit",
+ boxShadow: `0 4px 20px ${hr.accent}40`,
+ zIndex: 100,
+ }}
+ >
+ <SparkleIcon size={14} />
+ Ask Metabot
+ </button>
+ )}
+ </div>
+ );
+};
+
+const meta: Meta<typeof HrDemo> = {
+ title: "EmbeddingSDK/useMetabot/HR (PeopleHQ)",
+ component: HrDemo,
+ parameters: {
+ layout: "fullscreen",
+ // Raise SDK popovers above the bottom drawer (z-index: 1000)
+ sdkThemeOverride: { components: { popover: { zIndex: 1001 } } },
+ },
+ decorators: [makeSdkWrapper()],
+};
+
+export default meta;
+
+export const PeopleHQ: StoryFn = () => <HrDemo />;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.stories.utils.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.stories.utils.tsx
new file mode 100644
index 00000000000..431ef24f41d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.stories.utils.tsx
@@ -0,0 +1,400 @@
+import type { ReactNode } from "react";
+
+import { CommonSdkStoryWrapper } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";
+import type { MetabotMessage } from "embedding-sdk-bundle/types/metabot";
+import type { defineMetabaseTheme } from "metabase/embedding-sdk/theme";
+
+type ChartComponent = Extract<MetabotMessage, { type: "chart" }>["Chart"];
+
+// ============================================================================
+// Shared keyframes
+// ============================================================================
+
+export const SharedKeyframes = () => (
+ <style>{`
+ @keyframes metabotPulse {
+ 0%, 100% { opacity: 0.4; transform: scale(1); }
+ 50% { opacity: 1; transform: scale(1.15); }
+ }
+ @keyframes metabotFadeUp {
+ from { opacity: 0; transform: translateY(8px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+ @keyframes metabotShimmer {
+ 0% { background-position: -200% center; }
+ 100% { background-position: 200% center; }
+ }
+ @keyframes metabotGlow {
+ 0%, 100% { opacity: 0.4; }
+ 50% { opacity: 0.8; }
+ }
+ `}</style>
+);
+
+// ============================================================================
+// Icons
+// ============================================================================
+
+export const BotIcon = ({ size = 18 }: { size?: number }) => (
+ <svg width={size} height={size} viewBox="0 0 20 20" fill="none">
+ <circle cx="7" cy="8.5" r="1.4" fill="currentColor" />
+ <circle cx="13" cy="8.5" r="1.4" fill="currentColor" />
+ <path
+ d="M7 13c0 0 1.5 1.8 3 1.8s3-1.8 3-1.8"
+ stroke="currentColor"
+ strokeWidth="1.3"
+ strokeLinecap="round"
+ />
+ </svg>
+);
+
+export const SendIcon = () => (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
+ <path d="M14.5 8L2 14V9.5L9 8L2 6.5V2L14.5 8Z" fill="currentColor" />
+ </svg>
+);
+
+export const CloseIcon = () => (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
+ <path
+ d="M11 3L3 11M3 3L11 11"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ strokeLinecap="round"
+ />
+ </svg>
+);
+
+export const SparkleIcon = ({ size = 14 }: { size?: number }) => (
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
+ <path
+ d="M8 1L9.5 6.5L15 8L9.5 9.5L8 15L6.5 9.5L1 8L6.5 6.5L8 1Z"
+ fill="currentColor"
+ />
+ </svg>
+);
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+export const stripMarkdownLinks = (text: string) =>
+ text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1");
+
+const formatTime = () => {
+ const d = new Date();
+ return `${d.getHours() % 12 || 12}:${d.getMinutes().toString().padStart(2, "0")} ${d.getHours() >= 12 ? "PM" : "AM"}`;
+};
+
+// ============================================================================
+// InlineChart
+// ============================================================================
+
+export const InlineChart = ({ Component }: { Component: ChartComponent }) => (
+ <div
+ style={{
+ height: 500,
+ width: "100%",
+ flexShrink: 0,
+ borderRadius: 8,
+ overflow: "hidden",
+ margin: "6px 0",
+ background: "var(--mb-color-background-secondary)",
+ }}
+ >
+ <Component drills isSaveEnabled={false} height="500px" />
+ </div>
+);
+
+// ============================================================================
+// MessageList
+// ============================================================================
+
+export type MessageListPalette = {
+ accent: string;
+ accentLight: string;
+ accentDim: string;
+ surface: string;
+ surfaceRaised: string;
+ border: string;
+ text: string;
+ textMuted: string;
+ textSecondary: string;
+ gradient: string;
+ red: string;
+ redDim: string;
+};
+
+export const MessageList = ({
+ messages,
+ isProcessing,
+ scrollRef,
+ palette,
+ onRetry,
+}: {
+ messages: MetabotMessage[];
+ isProcessing: boolean;
+ scrollRef: React.RefObject<HTMLDivElement>;
+ palette: MessageListPalette;
+ onRetry?: (messageId: string) => void;
+}) => (
+ <>
+ {messages.map((message) => {
+ const isUser = message.role === "user";
+
+ if (message.type === "chart") {
+ return <InlineChart key={message.id} Component={message.Chart} />;
+ }
+
+ const content: ReactNode =
+ message.type === "text" && message.message
+ ? stripMarkdownLinks(message.message)
+ : null;
+
+ if (!content) {
+ return null;
+ }
+
+ return (
+ <div
+ key={message.id}
+ style={{
+ display: "flex",
+ gap: 8,
+ padding: "6px 0",
+ animation: "metabotFadeUp 0.25s ease",
+ }}
+ >
+ {!isUser && (
+ <div
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: 6,
+ background: palette.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ flexShrink: 0,
+ marginTop: 1,
+ }}
+ >
+ <BotIcon size={13} />
+ </div>
+ )}
+ <div
+ style={{
+ flex: 1,
+ minWidth: 0,
+ ...(isUser ? { textAlign: "right" as const } : {}),
+ }}
+ >
+ <div
+ style={{
+ display: "inline-block",
+ maxWidth: "85%",
+ textAlign: "left",
+ padding: "7px 12px",
+ borderRadius: 12,
+ fontSize: 13,
+ lineHeight: 1.45,
+ ...(isUser
+ ? {
+ background: palette.accent,
+ color: "#fff",
+ borderBottomRightRadius: 4,
+ }
+ : {
+ background: palette.surfaceRaised,
+ color: palette.text,
+ border: `1px solid ${palette.border}`,
+ borderBottomLeftRadius: 4,
+ }),
+ }}
+ >
+ {content}
+ </div>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ fontSize: 10,
+ color: palette.textMuted,
+ marginTop: 2,
+ ...(isUser
+ ? { justifyContent: "flex-end", paddingRight: 2 }
+ : { paddingLeft: 2 }),
+ }}
+ >
+ <span>{formatTime()}</span>
+ {!isUser && onRetry && !isProcessing && (
+ <button
+ onClick={() => onRetry(message.id)}
+ style={{
+ background: "none",
+ border: "none",
+ color: palette.textMuted,
+ cursor: "pointer",
+ fontSize: 10,
+ fontFamily: "inherit",
+ padding: 0,
+ textDecoration: "underline",
+ }}
+ >
+ Retry
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+
+ {isProcessing && (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "6px 0",
+ animation: "metabotFadeUp 0.2s ease",
+ }}
+ >
+ <div
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: 6,
+ background: palette.gradient,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#fff",
+ flexShrink: 0,
+ }}
+ >
+ <BotIcon size={13} />
+ </div>
+ <div style={{ display: "flex", gap: 4, padding: "4px 0" }}>
+ {[0, 0.15, 0.3].map((delay) => (
+ <div
+ key={delay}
+ style={{
+ width: 6,
+ height: 6,
+ borderRadius: "50%",
+ background: palette.accentLight,
+ animation: `metabotPulse 1.4s ${delay}s infinite`,
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div ref={scrollRef} />
+ </>
+);
+
+// ============================================================================
+// Composer
+// ============================================================================
+
+export const Composer = ({
+ value,
+ onChange,
+ onSubmit,
+ canSend,
+ placeholder,
+ onCancel,
+ isProcessing,
+ palette,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+ canSend: boolean;
+ placeholder?: string;
+ onCancel?: () => void;
+ isProcessing: boolean;
+ palette: MessageListPalette;
+}) => (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "8px 12px",
+ borderTop: `1px solid ${palette.border}`,
+ background: palette.surface,
+ }}
+ >
+ <input
+ style={{
+ flex: 1,
+ background: palette.surfaceRaised,
+ border: `1px solid ${palette.border}`,
+ borderRadius: 8,
+ padding: "8px 12px",
+ fontSize: 13,
+ color: palette.text,
+ outline: "none",
+ fontFamily: "inherit",
+ }}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={(event) => event.key === "Enter" && onSubmit()}
+ placeholder={placeholder ?? "Ask something..."}
+ />
+ {isProcessing && onCancel && (
+ <button
+ onClick={onCancel}
+ style={{
+ background: palette.redDim,
+ border: `1px solid ${palette.red}40`,
+ borderRadius: 6,
+ padding: "6px 8px",
+ color: palette.red,
+ cursor: "pointer",
+ fontSize: 11,
+ fontWeight: 600,
+ fontFamily: "inherit",
+ }}
+ >
+ Stop
+ </button>
+ )}
+ <button
+ onClick={onSubmit}
+ disabled={!canSend}
+ style={{
+ width: 32,
+ height: 32,
+ borderRadius: 8,
+ border: "none",
+ background: canSend ? palette.accent : palette.surfaceRaised,
+ color: canSend ? "#fff" : palette.textMuted,
+ cursor: canSend ? "pointer" : "default",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ transition: "all 0.15s",
+ }}
+ >
+ <SendIcon />
+ </button>
+ </div>
+);
+
+// ============================================================================
+// SDK Wrapper factory
+// ============================================================================
+
+// CommonSdkStoryWrapper already handles auth + ComponentProvider + theme via
+// Storybook globals. makeSdkWrapper returns it directly; the theme param is
+// accepted for call-site compatibility but theme selection is done via globals.
+export const makeSdkWrapper = (
+ _theme?: ReturnType<typeof defineMetabaseTheme>,
+) => CommonSdkStoryWrapper;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx
new file mode 100644
index 00000000000..11d81584c24
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx
@@ -0,0 +1,190 @@
+import { useCallback, useMemo, useRef } from "react";
+import { match } from "ts-pattern";
+
+import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
+import { InteractiveQuestionInternal } from "embedding-sdk-bundle/components/public/InteractiveQuestion";
+import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";
+import { StaticQuestionInternal } from "embedding-sdk-bundle/components/public/StaticQuestion";
+import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";
+import type {
+ MetabotChartProps,
+ MetabotMessage,
+ UseMetabotResult,
+} from "embedding-sdk-bundle/types/metabot";
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { useMetabotAgent } from "metabase/metabot/hooks";
+import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";
+import type { MetabotChatMessage } from "metabase/metabot/state/types";
+
+/**
+ * Public-facing hook for interacting with Metabot in the SDK.
+ *
+ * Provides a stable, SDK-friendly API for sending messages, managing
+ * conversation state, and reading Metabot responses.
+ *
+ * Note: all `useMetabot` instances in the same app share conversation state.
+ * Mounting the hook in two components reads the same Redux state.
+ * The backend exposes only a finite set of metabot agent types
+ * (e.g. `default`, `embedded`, `slackbot`).
+ */
+export const useMetabot = (): UseMetabotResult => {
+ const agent = useMetabotAgent();
+ const { navigateToPath } = useMetabotReactions();
+ const chartComponentsCache = useRef(
+ new Map<string, ReturnType<typeof createChartComponent>>(),
+ );
+
+ const {
+ state: { props: metabaseProviderProps },
+ } = useMetabaseProviderPropsStore();
+
+ const authConfig = metabaseProviderProps?.authConfig;
+
+ const CurrentChart = useMemo(
+ () =>
+ navigateToPath && authConfig
+ ? getCachedChartComponent(
+ navigateToPath,
+ chartComponentsCache.current,
+ authConfig,
+ )
+ : null,
+ [navigateToPath, authConfig],
+ );
+
+ const agentSubmitMessage = agent.submitInput;
+ const submitMessage = useCallback(
+ (message: string): Promise<void> => {
+ return agentSubmitMessage(message, { preventOpenSidebar: true }).then(
+ () => undefined,
+ );
+ },
+ [agentSubmitMessage],
+ );
+
+ const agentRetryMessage = agent.retryMessage;
+ const retryMessage = useCallback(
+ (messageId: string): Promise<void> => {
+ return agentRetryMessage(messageId);
+ },
+ [agentRetryMessage],
+ );
+
+ const agentResetConversation = agent.resetConversation;
+ const resetConversation = useCallback(() => {
+ chartComponentsCache.current.clear();
+ agentResetConversation();
+ }, [agentResetConversation]);
+
+ const messages = useMemo<MetabotMessage[]>(
+ () =>
+ agent.messages
+ .filter(isPublicMessage)
+ .map((message) =>
+ mapMessage(message, chartComponentsCache.current, authConfig),
+ ),
+ [agent.messages, authConfig],
+ );
+
+ return {
+ submitMessage,
+ retryMessage,
+ cancelRequest: agent.cancelRequest,
+ resetConversation,
+
+ messages,
+ errorMessages: agent.errorMessages,
+ isProcessing: agent.isDoingScience,
+
+ CurrentChart,
+ };
+};
+
+/**
+ * Creates a chart component bound to a `navigateTo` path.
+ * `drills={false}` (default) renders a StaticQuestion;
+ * `drills={true}` renders an InteractiveQuestion.
+ *
+ * Wrapped in `ComponentProvider` so it behaves like other public SDK components.
+ */
+function createChartComponent(
+ questionPath: string,
+ authConfig: MetabaseAuthConfig,
+) {
+ return function MetabotChart({ drills, ...rest }: MetabotChartProps) {
+ return (
+ <ComponentProvider authConfig={authConfig}>
+ {drills ? (
+ <InteractiveQuestionInternal query={questionPath} {...rest} />
+ ) : (
+ <StaticQuestionInternal query={questionPath} {...rest} />
+ )}
+ </ComponentProvider>
+ );
+ };
+}
+
+function getCachedChartComponent(
+ questionPath: string,
+ cache: Map<string, ReturnType<typeof createChartComponent>>,
+ authConfig: MetabaseAuthConfig,
+) {
+ if (!cache.has(questionPath)) {
+ cache.set(questionPath, createChartComponent(questionPath, authConfig));
+ }
+ return cache.get(questionPath)!;
+}
+
+// These internal variants are intentionally not surfaced in the public SDK —
+// see the comment on `MetabotMessage` in `embedding-sdk-bundle/types/metabot.ts`
+// for the full rationale.
+type PublicChatMessage = Exclude<
+ MetabotChatMessage,
+ { type: "tool_call" | "edit_suggestion" | "action" | "todo_list" }
+>;
+
+const isPublicMessage = (
+ message: MetabotChatMessage,
+): message is PublicChatMessage =>
+ message.type !== "tool_call" &&
+ message.type !== "edit_suggestion" &&
+ message.type !== "action" &&
+ message.type !== "todo_list";
+
+const mapMessage = (
+ message: PublicChatMessage,
+ cache: Map<string, ReturnType<typeof createChartComponent>>,
+ authConfig: MetabaseAuthConfig | undefined,
+): MetabotMessage =>
+ match(message)
+ .with(
+ { role: "user", type: "text" },
+ ({ id, message }) =>
+ ({ id, role: "user", type: "text", message }) as const,
+ )
+ .with(
+ { role: "agent", type: "text" },
+ ({ id, message }) =>
+ ({ id, role: "agent", type: "text", message }) as const,
+ )
+ .with({ role: "agent", type: "chart" }, ({ id, navigateTo }) => {
+ const Chart = authConfig
+ ? getCachedChartComponent(navigateTo, cache, authConfig)
+ : FallbackChartComponent;
+ return {
+ id,
+ role: "agent",
+ type: "chart",
+ questionPath: navigateTo,
+ Chart,
+ } as const;
+ })
+ .exhaustive();
+
+// Rendered only when `useMetabot` is called outside a `MetabaseProvider`
+// with authConfig populated. In normal usage this branch is unreachable;
+// keeping a placeholder satisfy message type.
+const FallbackChartComponent = () => null;
+
+// side effect that activates the plugin
+METABOT_SDK_EE_PLUGIN.useMetabot = useMetabot;
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx
new file mode 100644
index 00000000000..e782cc4b9fe
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx
@@ -0,0 +1,510 @@
+import userEvent from "@testing-library/user-event";
+import type { ReactNode } from "react";
+import { useState } from "react";
+
+import { act, screen, waitFor } from "__support__/ui";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import { metabotActions } from "metabase/metabot/state";
+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
+import {
+ lastReqBody,
+ mockAgentEndpoint,
+ setup,
+ whoIsYourFavoriteResponse,
+} from "metabase/metabot/tests/utils";
+
+import { useMetabot } from "./use-metabot";
+
+/**
+ * Covers `useMetabot()` non-passthrough wiring: `CurrentChart`,
+ * `messages[n].Chart`, `submitMessage`, `messages` mapping. Chart mocks
+ * expose `data-testid` + `data-query`; real rendering lives in the
+ * StaticQuestion/InteractiveQuestion specs. `ComponentProvider` is stubbed —
+ * provider init is out of scope. Pure passthroughs (retry/cancel/reset/
+ * errorMessages/isProcessing) skipped.
+ */
+jest.mock("embedding-sdk-bundle/components/public/ComponentProvider", () => ({
+ ComponentProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+jest.mock("embedding-sdk-bundle/components/public/StaticQuestion", () => {
+ const Component = ({ query }: { query?: string }) => (
+ <div data-testid="mock-static-question" data-query={query} />
+ );
+ return { StaticQuestionInternal: Component };
+});
+
+jest.mock("embedding-sdk-bundle/components/public/InteractiveQuestion", () => {
+ const Component = ({ query }: { query?: string }) => (
+ <div data-testid="mock-interactive-question" data-query={query} />
+ );
+ return { InteractiveQuestionInternal: Component };
+});
+
+describe("useMetabot", () => {
+ beforeEach(() => {
+ ensureMetabaseProviderPropsStore().cleanup();
+ const seededStore = ensureMetabaseProviderPropsStore();
+ seededStore.setProps({
+ authConfig: {
+ metabaseInstanceUrl: "http://localhost:3000",
+ jwtProviderUri: "http://localhost:3000/sso",
+ },
+ });
+ });
+
+ describe("CurrentChart", () => {
+ const TestCurrentChart = ({ drills }: { drills?: true }) => {
+ const { CurrentChart } = useMetabot();
+ return CurrentChart ? <CurrentChart drills={drills} /> : null;
+ };
+
+ it("renders nothing before navigate_to fires", () => {
+ setup({ ui: <TestCurrentChart /> });
+
+ expect(
+ screen.queryByTestId("mock-static-question"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders a chart after navigate_to fires", async () => {
+ const { store } = setup({ ui: <TestCurrentChart /> });
+
+ expect(
+ screen.queryByTestId("mock-static-question"),
+ ).not.toBeInTheDocument();
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#base64"));
+ });
+
+ expect(await screen.findByTestId("mock-static-question")).toBeVisible();
+ });
+
+ it("renders StaticQuestion when drills is absent", async () => {
+ const { store } = setup({ ui: <TestCurrentChart /> });
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#base64"));
+ });
+
+ expect(await screen.findByTestId("mock-static-question")).toBeVisible();
+ });
+
+ it("renders InteractiveQuestion when drills is true", async () => {
+ const { store } = setup({ ui: <TestCurrentChart drills /> });
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#base64"));
+ });
+
+ expect(
+ await screen.findByTestId("mock-interactive-question"),
+ ).toBeVisible();
+ });
+
+ it("keeps CurrentChart identity stable across unrelated parent re-renders", async () => {
+ let capturedChart: unknown = null;
+ let identityChanges = 0;
+
+ const TestIdentity = ({ tick }: { tick: number }) => {
+ const { CurrentChart } = useMetabot();
+ if (CurrentChart) {
+ if (capturedChart && capturedChart !== CurrentChart) {
+ identityChanges += 1;
+ }
+ capturedChart = CurrentChart;
+ }
+ return (
+ <div data-testid="tick" data-tick={tick}>
+ {CurrentChart ? <CurrentChart /> : null}
+ </div>
+ );
+ };
+
+ const Harness = () => {
+ const [tick, setTick] = useState(0);
+ return (
+ <>
+ <button data-testid="bump" onClick={() => setTick((n) => n + 1)}>
+ bump
+ </button>
+ <TestIdentity tick={tick} />
+ </>
+ );
+ };
+
+ const { store } = setup({ ui: <Harness /> });
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#base64"));
+ });
+
+ expect(await screen.findByTestId("mock-static-question")).toBeVisible();
+ expect(capturedChart).not.toBeNull();
+
+ await userEvent.click(screen.getByTestId("bump"));
+ await userEvent.click(screen.getByTestId("bump"));
+ await userEvent.click(screen.getByTestId("bump"));
+
+ expect(screen.getByTestId("tick")).toHaveAttribute("data-tick", "3");
+ expect(identityChanges).toBe(0);
+ });
+
+ it("updates when a second navigate_to fires", async () => {
+ const { store } = setup({ ui: <TestCurrentChart /> });
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#first"));
+ });
+
+ const chart = await screen.findByTestId("mock-static-question");
+ expect(chart).toHaveAttribute("data-query", "/question#first");
+
+ act(() => {
+ store.dispatch(metabotActions.setNavigateToPath("/question#second"));
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("mock-static-question")).toHaveAttribute(
+ "data-query",
+ "/question#second",
+ );
+ });
+ });
+ });
+
+ describe("messages", () => {
+ const TestMessages = () => {
+ const { messages } = useMetabot();
+ return (
+ <div data-testid="messages" data-json={JSON.stringify(messages)} />
+ );
+ };
+
+ const readMessages = async () => {
+ let parsed: any[] = [];
+ await waitFor(() => {
+ const messages = screen.getByTestId("messages");
+ parsed = JSON.parse(messages.getAttribute("data-json") ?? "[]");
+ expect(parsed.length).toBeGreaterThan(0);
+ });
+ return parsed;
+ };
+
+ it("maps user.text passthrough", async () => {
+ const { store } = setup({ ui: <TestMessages /> });
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addUserMessage({
+ agentId: "omnibot",
+ id: "u1",
+ type: "text",
+ message: "hi",
+ }),
+ );
+ });
+
+ expect(await readMessages()).toEqual([
+ { id: "u1", role: "user", type: "text", message: "hi" },
+ ]);
+ });
+
+ it("maps agent.text passthrough", async () => {
+ const { store } = setup({ ui: <TestMessages /> });
+
+ act(() => {
+ store.dispatch(
+ // `addAgentMessage`/`addUserMessage` in reducer.ts type their payload
+ // as `Omit<UnionType, ...>`. Non-distributive `Omit` collapses the
+ // discriminated union to common keys only, so branch-specific fields
+ // (message, navigateTo, payload, ...) fail excess-property checks
+ // without `as any`. Switching to a DistributiveOmit would unblock
+ // call sites here but surfaces more errors elsewhere (e.g. the
+ // edit_suggestion payload hits the "infinite TS errors" noted in
+ // reducer.ts). Keeping `as any` for now — applies to every dispatch
+ // below.
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "text",
+ message: "ok",
+ } as any),
+ );
+ });
+
+ const [message] = await readMessages();
+ expect(message).toEqual({
+ id: expect.any(String),
+ role: "agent",
+ type: "text",
+ message: "ok",
+ });
+ });
+
+ it("renames `navigateTo` to `questionPath` on agent.chart", async () => {
+ const { store } = setup({ ui: <TestMessages /> });
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "chart",
+ navigateTo: "/question#base64",
+ } as any),
+ );
+ });
+
+ const [message] = await readMessages();
+ // `Chart` is a React component reference — JSON.stringify drops
+ // functions, so it appears as `undefined` in the serialized snapshot
+ // the harness reads. We assert only the serializable fields here;
+ // `Chart` wiring is covered by the `messages[n].Chart` describe.
+ expect(message).toEqual({
+ id: expect.any(String),
+ role: "agent",
+ type: "chart",
+ questionPath: "/question#base64",
+ });
+ });
+
+ it("filters out internal-only variants (tool_call, edit_suggestion, user action, todo_list)", async () => {
+ const { store } = setup({ ui: <TestMessages /> });
+
+ act(() => {
+ store.dispatch(metabotActions.setDebugMode(true));
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "tool_call",
+ name: "fn",
+ status: "started",
+ } as any),
+ );
+ store.dispatch(
+ metabotActions.addUserMessage({
+ agentId: "omnibot",
+ id: "u-action",
+ type: "action",
+ message: "5 rows",
+ userMessage: "Run Query",
+ } as any),
+ );
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "edit_suggestion",
+ model: "transform",
+ payload: {
+ editorTransform: undefined,
+ suggestedTransform: {
+ name: "Transform A",
+ description: "Does X",
+ source: "SRC",
+ target: "TGT",
+ active: true,
+ suggestionId: "s1",
+ },
+ },
+ } as any),
+ );
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "todo_list",
+ payload: [
+ {
+ id: "t1",
+ content: "work",
+ status: "pending",
+ priority: "high",
+ },
+ ],
+ } as any),
+ );
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "text",
+ message: "ok",
+ } as any),
+ );
+ });
+
+ const messages = await readMessages();
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toEqual({
+ id: expect.any(String),
+ role: "agent",
+ type: "text",
+ message: "ok",
+ });
+ });
+ });
+
+ describe("submitMessage", () => {
+ const TestSubmit = ({
+ onResolved,
+ }: {
+ onResolved?: (value: unknown) => void;
+ }) => {
+ const { submitMessage } = useMetabot();
+ const handleClick = async () => {
+ const result = await submitMessage("hi");
+ onResolved?.(result);
+ };
+ return (
+ <button data-testid="submit-btn" onClick={handleClick}>
+ submit
+ </button>
+ );
+ };
+
+ it("forwards the message to the underlying agent request", async () => {
+ const agentSpy = mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
+ setup({ ui: <TestSubmit /> });
+
+ await userEvent.click(screen.getByTestId("submit-btn"));
+
+ const reqBody = await lastReqBody(agentSpy);
+ expect(reqBody?.message).toBe("hi");
+ });
+
+ it("does not open the metabot sidebar (preventOpenSidebar)", async () => {
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
+ // default setup() forces omnibot.visible = true; override so we can
+ // observe whether submitMessage would flip it back on.
+ const { store } = setup({
+ ui: <TestSubmit />,
+ metabotInitialState: getMetabotInitialState(),
+ });
+
+ expect(
+ store.getState().metabot?.conversations?.omnibot?.messages.length,
+ ).toBe(0);
+ expect(store.getState().metabot?.conversations?.omnibot?.visible).toBe(
+ false,
+ );
+
+ await userEvent.click(screen.getByTestId("submit-btn"));
+
+ await waitFor(() => {
+ expect(
+ store.getState().metabot?.conversations?.omnibot?.messages.length,
+ ).toBeGreaterThan(0);
+ });
+
+ expect(store.getState().metabot?.conversations?.omnibot?.visible).toBe(
+ false,
+ );
+ });
+
+ it("resolves to undefined even though agent.submitInput returns an action", async () => {
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
+ const onResolved = jest.fn();
+ setup({ ui: <TestSubmit onResolved={onResolved} /> });
+
+ await userEvent.click(screen.getByTestId("submit-btn"));
+
+ await waitFor(() => expect(onResolved).toHaveBeenCalled());
+ expect(onResolved).toHaveBeenCalledWith(undefined);
+ });
+ });
+
+ describe("messages[n].Chart", () => {
+ const TestChart = ({ drills }: { drills?: true }) => {
+ const { messages } = useMetabot();
+ const chartMessage = messages.find((message) => message.type === "chart");
+ if (!chartMessage) {
+ return null;
+ }
+ const { Chart } = chartMessage;
+ return <Chart drills={drills} />;
+ };
+
+ it("renders StaticQuestion when drills is absent", async () => {
+ const { store } = setup({ ui: <TestChart /> });
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "chart",
+ navigateTo: "/question#base64",
+ } as any),
+ );
+ });
+
+ expect(await screen.findByTestId("mock-static-question")).toBeVisible();
+ });
+
+ it("renders InteractiveQuestion when drills is true", async () => {
+ const { store } = setup({ ui: <TestChart drills /> });
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "chart",
+ navigateTo: "/question#base64",
+ } as any),
+ );
+ });
+
+ expect(
+ await screen.findByTestId("mock-interactive-question"),
+ ).toBeVisible();
+ });
+
+ it("Chart reference is stable after a second chart message arrives", async () => {
+ let firstChart: unknown = null;
+
+ const TestCapture = () => {
+ const { messages } = useMetabot();
+ const chartMessages = messages.filter(
+ (message) => message.type === "chart",
+ );
+ if (chartMessages[0]) {
+ firstChart = chartMessages[0].Chart;
+ }
+ return <div data-testid="chart-count">{chartMessages.length}</div>;
+ };
+
+ const { store } = setup({ ui: <TestCapture /> });
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "chart",
+ navigateTo: "/question#abc",
+ } as any),
+ );
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("chart-count")).toHaveTextContent("1");
+ });
+ const capturedChart = firstChart;
+ expect(capturedChart).not.toBeNull();
+
+ act(() => {
+ store.dispatch(
+ metabotActions.addAgentMessage({
+ agentId: "omnibot",
+ type: "chart",
+ navigateTo: "/question#xyz",
+ } as any),
+ );
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("chart-count")).toHaveTextContent("2");
+ });
+
+ expect(firstChart).toBe(capturedChart);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/index.ts b/enterprise/frontend/src/embedding-sdk-ee/metabot/index.ts
index adca540961f..5ea7e8615de 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/index.ts
@@ -1,5 +1,6 @@
-// Contains side effects that puts `MetabotQuestion` in the plugin
+// Contains side effects that puts `MetabotQuestion` and `useMetabot` in the plugin
import "./MetabotQuestion";
+import "./hooks/use-metabot";
import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";
import { MetabotProvider } from "metabase/metabot/context";
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx
index 7970e122c79..fd98a4ae4e4 100644
--- a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx
@@ -87,7 +87,15 @@ const MetabaseProviderInner = memo(function MetabaseProviderInner(
return null;
}
- return <MetabaseProviderInitDataWrapper />;
+ const MetabotSubscriber =
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.MetabotSubscriber;
+
+ return (
+ <>
+ <MetabaseProviderInitDataWrapper />
+ {MetabotSubscriber && <MetabotSubscriber store={reduxStore} />}
+ </>
+ );
});
/**
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.ts
new file mode 100644
index 00000000000..46bfd8066bd
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.ts
@@ -0,0 +1,32 @@
+import { useSyncExternalStore } from "react";
+
+import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";
+import {
+ getMetabotStateSnapshot,
+ subscribeMetabotState,
+} from "embedding-sdk-shared/lib/metabot-state-channel";
+
+const getServerSnapshot = (): UseMetabotResult | null => null;
+
+/**
+ * Returns the Metabot conversation API.
+ *
+ * Returns `null` until the SDK bundle has loaded and `<MetabaseProvider>`
+ * has mounted its internal subscriber. Guard before use:
+ *
+ * @example
+ * const metabot = useMetabot();
+ * if (!metabot) {
+ * return <Spinner />;
+ * }
+ * metabot.submitMessage("Show me orders");
+ *
+ * @function
+ * @category useMetabot
+ */
+export const useMetabot = (): UseMetabotResult | null =>
+ useSyncExternalStore(
+ subscribeMetabotState,
+ getMetabotStateSnapshot,
+ getServerSnapshot,
+ );
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.unit.spec.tsx
new file mode 100644
index 00000000000..e95f0038808
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabot.unit.spec.tsx
@@ -0,0 +1,77 @@
+import { act, renderHook } from "@testing-library/react";
+
+import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";
+import { publishMetabotState } from "embedding-sdk-shared/lib/metabot-state-channel";
+
+import { useMetabot } from "./use-metabot";
+
+const makeMetabotResult = (
+ overrides: Partial<UseMetabotResult> = {},
+): UseMetabotResult => ({
+ submitMessage: jest.fn().mockResolvedValue(undefined),
+ retryMessage: jest.fn().mockResolvedValue(undefined),
+ cancelRequest: jest.fn(),
+ resetConversation: jest.fn(),
+ messages: [],
+ errorMessages: [],
+ isProcessing: false,
+ CurrentChart: null,
+ ...overrides,
+});
+
+describe("useMetabot", () => {
+ afterEach(() => {
+ act(() => {
+ publishMetabotState(null);
+ });
+ });
+
+ it("returns null before the subscriber publishes", () => {
+ const { result } = renderHook(() => useMetabot());
+
+ expect(result.current).toBeNull();
+ });
+
+ it("returns the published value when the subscriber publishes", () => {
+ const published = makeMetabotResult({ isProcessing: true });
+ const { result } = renderHook(() => useMetabot());
+
+ act(() => {
+ publishMetabotState(published);
+ });
+
+ expect(result.current).toBe(published);
+ });
+
+ it("resets to null when the subscriber publishes null", () => {
+ const published = makeMetabotResult();
+ const { result } = renderHook(() => useMetabot());
+
+ act(() => {
+ publishMetabotState(published);
+ });
+ expect(result.current).toBe(published);
+
+ act(() => {
+ publishMetabotState(null);
+ });
+ expect(result.current).toBeNull();
+ });
+
+ it("unsubscribes on unmount", () => {
+ const { result, unmount } = renderHook(() => useMetabot());
+ const published = makeMetabotResult();
+
+ unmount();
+
+ // If unsubscribe did not run, the render count would still update the
+ // unmounted hook's internal state. Publishing after unmount must not
+ // throw and must not affect the last-seen value.
+ expect(() => {
+ act(() => {
+ publishMetabotState(published);
+ });
+ }).not.toThrow();
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.ts
index 35b7802487f..0891acfc731 100644
--- a/enterprise/frontend/src/embedding-sdk-package/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts
@@ -26,6 +26,7 @@ export * from "./components/public/debug/SdkDebugInfo";
export { useApplicationName } from "./hooks/public/use-application-name";
export { useAvailableFonts } from "./hooks/public/use-available-fonts";
export { useCurrentUser } from "./hooks/public/use-current-user";
+export { useMetabot } from "./hooks/public/use-metabot";
export { useCreateDashboardApi } from "./hooks/public/use-create-dashboard-api";
export { useMetabaseAuthStatus } from "./hooks/public/use-metabase-auth-status";
@@ -118,6 +119,14 @@ export type {
MetabaseTheme,
MetabaseThemePreset,
MetabaseUser,
+ MetabotAgentChartMessage,
+ MetabotAgentMessage,
+ MetabotAgentTextMessage,
+ MetabotChartProps,
+ MetabotErrorMessage,
+ MetabotMessage,
+ MetabotUserTextMessage,
+ UseMetabotResult,
SdkEntityToken,
SdkCollectionId,
SdkDashboardId,
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 68b51198b1e..71ecf212be1 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -345,7 +345,7 @@ const configs = [
},
{
files: [
- "**/*.unit.spec.*",
+ "**/*.spec.*",
"frontend/lint/**/*",
"**/*.stories.*",
"**/stories-data.*",
diff --git a/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx b/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx
new file mode 100644
index 00000000000..7bd47e76cdd
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx
@@ -0,0 +1,28 @@
+import { useEffect } from "react";
+
+import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";
+import { useMetabot } from "embedding-sdk-bundle/hooks/public/use-metabot";
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import { publishMetabotState } from "embedding-sdk-shared/lib/metabot-state-channel";
+import { MetabaseReduxProvider } from "metabase/redux";
+
+type Props = {
+ store: SdkStore;
+};
+
+const MetabotStatePublisher = () => {
+ const metabot = useMetabot();
+ useEffect(() => {
+ publishMetabotState(metabot);
+ return () => publishMetabotState(null);
+ }, [metabot]);
+ return null;
+};
+
+export const MetabotSubscriber = ({ store }: Props) => (
+ <MetabaseReduxProvider store={store}>
+ <METABOT_SDK_EE_PLUGIN.MetabotProvider>
+ <MetabotStatePublisher />
+ </METABOT_SDK_EE_PLUGIN.MetabotProvider>
+ </MetabaseReduxProvider>
+);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx
index 41f07ffbd38..2e865095d88 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateQuestion/CreateQuestion.tsx
@@ -2,7 +2,7 @@ import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/priv
import {
InteractiveQuestion,
- type InteractiveQuestionProps,
+ type InteractiveQuestionBaseProps,
} from "../InteractiveQuestion";
/**
@@ -11,8 +11,8 @@ import {
* @category CreateQuestion
*/
export type CreateQuestionProps = Omit<
- Partial<InteractiveQuestionProps>,
- "questionId" | "children"
+ Partial<InteractiveQuestionBaseProps>,
+ "children"
>;
const CreateQuestionInner = (props: CreateQuestionProps = {}) => (
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
index 9630ad0e3ea..2753e814d13 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
@@ -2,9 +2,12 @@ import * as Yup from "yup";
import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
-import type { InteractiveQuestionProps } from "./InteractiveQuestion";
+import type { InteractiveQuestionInternalProps } from "./InteractiveQuestion";
-const propsSchema: Yup.SchemaOf<InteractiveQuestionProps> = Yup.object({
+// Typed against the internal shape so runtime validation still accepts the
+// `query` prop used by the `useMetabot` hook. The public API (see
+// `InteractiveQuestionProps`) intentionally doesn't expose `query` to users.
+const propsSchema: Yup.SchemaOf<InteractiveQuestionInternalProps> = Yup.object({
children: Yup.mixed().optional(),
className: Yup.mixed().optional(),
componentPlugins: Yup.object({
@@ -31,8 +34,14 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionProps> = Yup.object({
})
.optional()
.noUnknown(),
- questionId: Yup.mixed().required(),
+ questionId: Yup.mixed().when(["token", "query"], {
+ is: (token: unknown, query: unknown) =>
+ token !== undefined || query !== undefined,
+ then: (schema) => schema.optional(),
+ otherwise: (schema) => schema.required(),
+ }),
token: Yup.mixed().optional(),
+ query: Yup.mixed().optional(),
style: Yup.mixed().optional(),
targetCollection: Yup.mixed().optional(),
targetDashboardId: Yup.mixed().optional(),
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
index c43ca9ae8c1..ae1c198bd43 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
@@ -1,3 +1,6 @@
+import type { FC } from "react";
+import { useMemo } from "react";
+
import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
import { SdkInternalNavigationBackButton } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton";
import {
@@ -28,20 +31,39 @@ import {
SdkQuestion,
type SdkQuestionProps,
} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";
+import type {
+ SdkQuestionEntityInternalProps,
+ SdkQuestionEntityPublicProps,
+} from "embedding-sdk-bundle/types/question";
+import { deserializeCardFromQuery } from "metabase/common/utils/card";
import { QuestionAlertsButton } from "../notifications/QuestionAlertsButton";
import { interactiveQuestionSchema } from "./InteractiveQuestion.schema";
+export type InteractiveQuestionBaseProps = Omit<
+ SdkQuestionProps,
+ | "token"
+ | "questionId"
+ | "getClickActionMode"
+ | "navigateToNewCard"
+ | "backToDashboard"
+>;
+
/**
* @interface
* @expand
* @category InteractiveQuestion
*/
-export type InteractiveQuestionProps = Omit<
- SdkQuestionProps,
- "token" | "getClickActionMode" | "navigateToNewCard" | "backToDashboard"
->;
+export type InteractiveQuestionProps = InteractiveQuestionBaseProps &
+ SdkQuestionEntityPublicProps;
+
+/**
+ * Internal type that includes the `query` prop used by the `useMetabot` hook.
+ * Not re-exported from the public SDK package entry point.
+ */
+export type InteractiveQuestionInternalProps = InteractiveQuestionBaseProps &
+ SdkQuestionEntityInternalProps;
/**
* @interface
@@ -79,9 +101,19 @@ export type InteractiveQuestionComponents = {
SqlParametersList: typeof SqlParametersList;
};
-export const _InteractiveQuestion = (props: InteractiveQuestionProps) => (
- <SdkQuestion {...props} />
-);
+function InteractiveQuestionInner({
+ query,
+ ...rest
+}: InteractiveQuestionInternalProps) {
+ const deserializedCard = useMemo(
+ () => (query ? deserializeCardFromQuery(query) : undefined),
+ [query],
+ );
+
+ return <SdkQuestion {...rest} deserializedCard={deserializedCard} />;
+}
+
+export const _InteractiveQuestion = InteractiveQuestionInner;
const subComponents: InteractiveQuestionComponents = {
BackButton: BackButton,
@@ -112,10 +144,23 @@ const subComponents: InteractiveQuestionComponents = {
SqlParametersList: SqlParametersList,
};
+const _InteractiveQuestionWrapped = withPublicComponentWrapper(
+ _InteractiveQuestion,
+ { supportsGuestEmbed: false },
+);
+
export const InteractiveQuestion = Object.assign(
- withPublicComponentWrapper(_InteractiveQuestion, {
- supportsGuestEmbed: false,
- }),
+ _InteractiveQuestionWrapped as FC<InteractiveQuestionProps>,
+ subComponents,
+ { schema: interactiveQuestionSchema },
+);
+
+/**
+ * Same runtime component as {@link InteractiveQuestion}, typed to accept the
+ * internal `query` prop. This component is intended for internal use only.
+ */
+export const InteractiveQuestionInternal = Object.assign(
+ _InteractiveQuestionWrapped as FC<InteractiveQuestionInternalProps>,
subComponents,
{ schema: interactiveQuestionSchema },
);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
index 572b4087fc5..20498346d95 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
@@ -5,7 +5,6 @@ import {
setupEnterprisePlugins,
} from "__support__/enterprise";
import {
- findRequests,
setupAlertsEndpoints,
setupCardEndpoints,
setupCardQueryEndpoints,
@@ -31,68 +30,38 @@ import {
waitForLoaderToBeRemoved,
within,
} from "__support__/ui";
+import { addAlertModalTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec";
+import { addAlertsButtonTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec";
+import type { SetupOpts } from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
+import {
+ TEST_COLUMN,
+ TEST_DATASET,
+ TEST_DB,
+ TEST_TABLE,
+} from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
+import { addQueryPropTests } from "embedding-sdk-bundle/components/public/question/shared-tests/query-prop.spec";
import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";
import { createMockModelResult } from "metabase/browse/models/test-utils";
-import { reinitialize } from "metabase/plugins";
import type { EmbeddingDataPicker } from "metabase/redux/store/embedding-data-picker";
-import type { CardId, CollectionType, TokenFeatures } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
createMockCollection,
- createMockColumn,
- createMockDatabase,
- createMockDataset,
- createMockDatasetData,
- createMockTable,
createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
-import { createMockNotification } from "metabase-types/api/mocks/notification";
-
-import { InteractiveQuestion } from "./InteractiveQuestion";
-
-const TEST_DB_ID = 1;
-const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
-
-const TEST_TABLE_ID = 1;
-const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });
-
-const TEST_COLUMN = createMockColumn({
- display_name: "Test Column",
- name: "Test Column",
-});
-
-const TEST_DATASET = createMockDataset({
- data: createMockDatasetData({
- cols: [TEST_COLUMN],
- rows: [["Test Row"]],
- }),
-});
-const TEST_CARD_ID: CardId = 1 as const;
+import {
+ InteractiveQuestion,
+ InteractiveQuestionInternal,
+} from "./InteractiveQuestion";
+const TEST_CARD_ID = 1;
const USER_ID = 999;
-interface SetupOpts {
- title?: string | boolean;
- withChartTypeSelector?: boolean;
- withDownloads?: boolean;
- withAlerts?: boolean;
- isEmailSetup?: boolean;
- canManageSubscriptions?: boolean;
- isSuperuser?: boolean;
- isModel?: boolean;
- notifications?: ReturnType<typeof createMockNotification>[];
- collectionType?: CollectionType;
- tokenFeatures?: Partial<TokenFeatures>;
- enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
- children?: React.ReactNode;
-}
-
const setup = async ({
title,
withChartTypeSelector,
@@ -110,7 +79,7 @@ const setup = async ({
}: SetupOpts = {}) => {
setupNotificationChannelsEndpoints({
email: { configured: isEmailSetup },
- } as any);
+ });
const user = createMockUser({
id: USER_ID,
@@ -208,7 +177,14 @@ const setup = async ({
await waitForLoaderToBeRemoved();
};
+addQueryPropTests({ Component: InteractiveQuestionInternal });
+
describe("InteractiveQuestion", () => {
+ addAlertsButtonTests(setup, {
+ customComponent: InteractiveQuestion.AlertsButton,
+ });
+ addAlertModalTests(setup, { userId: USER_ID });
+
beforeAll(() => {
mockGetBoundingClientRect();
});
@@ -267,180 +243,6 @@ describe("InteractiveQuestion", () => {
});
});
- describe("alerts button with different Metabase version configurations", () => {
- beforeEach(() => {
- reinitialize();
- });
-
- // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
- describe.skip("OSS (Open Source Software)", () => {
- it("should not show the alert button in OSS regardless of settings", async () => {
- // Don't setup enterprise plugin for OSS
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- tokenFeatures: {}, // No embedding_sdk feature
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
-
- // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
- describe.skip("EE (Enterprise Edition) without embedding_sdk token feature", () => {
- it("should not show the alert button when plugin is enabled but token feature is missing", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- tokenFeatures: {}, // No embedding_sdk feature
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
-
- describe("EE with embedding_sdk token feature", () => {
- it("should show the alert button when plugin and token feature are both enabled", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
- });
-
- it("should show the alert button for custom layouts when withAlerts is true", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- children: (
- <div>
- <span>Custom Layout</span>
- <InteractiveQuestion.AlertsButton />
- </div>
- ),
- });
-
- expect(screen.getByText("Custom Layout")).toBeVisible();
- expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
- });
-
- it("should not show the alert button for custom layouts when withAlerts is false", async () => {
- await setup({
- withAlerts: false,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- children: (
- <div>
- <span>Custom Layout</span>
- <InteractiveQuestion.AlertsButton />
- </div>
- ),
- });
-
- expect(screen.getByText("Custom Layout")).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when withAlerts is false", async () => {
- await setup({
- withAlerts: false,
- isEmailSetup: true,
- canManageSubscriptions: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when email is not configured", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: false,
- canManageSubscriptions: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when user cannot manage subscriptions and is not admin", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- isSuperuser: false,
- canManageSubscriptions: false,
- enterprisePlugins: ["sdk_notifications", "application_permissions"],
- tokenFeatures: { embedding_sdk: true, advanced_permissions: true },
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button for models", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button for analytics collection", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- collectionType: "instance-analytics",
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
- });
-
it("should not show alerts and downloads buttons when editing the question", async () => {
await setup({
withDownloads: true,
@@ -473,108 +275,15 @@ describe("InteractiveQuestion", () => {
screen.queryByRole("button", { name: "Download results" }),
).not.toBeInTheDocument();
});
-
- describe("alert modal", () => {
- it("should show alert list modal when there are existing alerts", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- notifications: [createMockNotification()],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
-
- await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
-
- // Verify the alert list modal appears, not the create modal
- const withinModal = within(await findModal());
-
- // Show the alert list modal title
- expect(
- await withinModal.findByRole("heading", { name: "Edit alerts" }),
- ).toBeVisible();
-
- // Should show the button to create a new alert in the list modal
- expect(withinModal.getByText("New alert")).toBeVisible();
-
- // Should NOT show the create alert form fields
- expect(
- withinModal.queryByText("What do you want to be alerted about?"),
- ).not.toBeInTheDocument();
- });
-
- it("should not show email selector on the SDK and use current logged in user as the recipient", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
-
- const withinModal = within(await findModal());
- expect(
- withinModal.getByRole("heading", { name: "New alert" }),
- ).toBeVisible();
- expect(
- withinModal.getByText("What do you want to be alerted about?"),
- ).toBeVisible();
- expect(
- withinModal.getByText("When do you want to check this?"),
- ).toBeVisible();
- // Email selector is within this section, checking only the header is fine
- expect(
- withinModal.queryByText("Where do you want to send the results?"),
- ).not.toBeInTheDocument();
- expect(withinModal.getByText("More options")).toBeVisible();
- await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
-
- const createNotificationRequest = (await findRequests("POST")).find(
- (postRequest) =>
- postRequest.url === "http://localhost/api/notification",
- );
- // Checks that we're using the current logged in user as the sole recipient
- expect(createNotificationRequest?.body).toMatchObject({
- handlers: [
- {
- channel_type: "channel/email",
- recipients: [
- {
- details: null,
- type: "notification-recipient/user",
- user_id: USER_ID,
- },
- ],
- },
- ],
- });
- // So that when we assert this value, we know we won't accidentally match the default mock ID
- expect(USER_ID).not.toBe(1);
- });
- });
});
-async function findModal() {
- return await screen.findByRole("dialog");
-}
-
describe('questionId: "new"', () => {
interface SetupOpts {
- questionId?: SdkQuestionId;
+ questionId: SdkQuestionId;
dataPicker?: EmbeddingDataPicker;
}
- async function setup({ questionId, dataPicker }: SetupOpts = {}) {
+ async function setup({ questionId, dataPicker }: SetupOpts) {
setupDatabasesEndpoints([TEST_DB]);
setupCollectionByIdEndpoint({
collections: [createMockCollection({ id: 1 })],
diff --git a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx
index d7211b8ab9c..ea4c5f0a34f 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
+import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";
import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
import type { MetabotQuestionProps } from "./types";
@@ -11,11 +12,13 @@ type MetabotQuestionComponent = ((props: MetabotQuestionProps) => ReactNode) & {
export const METABOT_SDK_EE_PLUGIN: {
MetabotQuestion: MetabotQuestionComponent;
MetabotProvider: ({ children }: { children: ReactNode }) => ReactNode;
+ useMetabot: () => UseMetabotResult | null;
} = {
// Placeholder implementation – replaced by EE plugin at runtime
MetabotQuestion: ((_props: MetabotQuestionProps) =>
null) as MetabotQuestionComponent,
MetabotProvider: ({ children }: { children: ReactNode }) => children,
+ useMetabot: () => null,
};
export const MetabotQuestion = (props: MetabotQuestionProps) => {
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
index a0e69cd22ed..696daa2a47c 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
@@ -2,20 +2,25 @@ import * as Yup from "yup";
import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
-import type { StaticQuestionProps } from "./StaticQuestion";
+import type { StaticQuestionInternalProps } from "./StaticQuestion";
-const propsSchema: Yup.SchemaOf<StaticQuestionProps> = Yup.object({
+// Typed against the internal shape so runtime validation still accepts the
+// `query` prop used by the `useMetabot` hook. The public API (see
+// `StaticQuestionProps`) intentionally doesn't expose `query` to users.
+const propsSchema: Yup.SchemaOf<StaticQuestionInternalProps> = Yup.object({
children: Yup.mixed().optional(),
className: Yup.mixed().optional(),
height: Yup.mixed().optional(),
initialSqlParameters: Yup.mixed().optional(),
hiddenParameters: Yup.mixed().optional(),
- questionId: Yup.mixed().when("token", {
- is: (token: unknown) => token !== undefined,
+ questionId: Yup.mixed().when(["token", "query"], {
+ is: (token: unknown, query: unknown) =>
+ token !== undefined || query !== undefined,
then: (schema) => schema.optional(),
otherwise: (schema) => schema.required(),
}),
token: Yup.mixed().optional(),
+ query: Yup.mixed().optional(),
style: Yup.mixed().optional(),
title: Yup.mixed().optional(),
width: Yup.mixed().optional(),
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
index 619bc1ad56e..dd62941a66a 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
@@ -1,4 +1,4 @@
-import type { PropsWithChildren } from "react";
+import { type FC, type PropsWithChildren, useMemo } from "react";
import { FlexibleSizeComponent } from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";
import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
@@ -33,7 +33,11 @@ import { useMobileLayout } from "embedding-sdk-bundle/hooks/private/use-mobile-l
import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";
-import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";
+import type {
+ SdkQuestionEntityInternalProps,
+ SdkQuestionEntityPublicProps,
+} from "embedding-sdk-bundle/types/question";
+import { deserializeCardFromQuery } from "metabase/common/utils/card";
import { Box, Group, Stack } from "metabase/ui";
import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";
import { EmbeddingSdkStaticMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode";
@@ -42,12 +46,7 @@ import type Question from "metabase-lib/v1/Question";
import { staticQuestionSchema } from "./StaticQuestion.schema";
-/**
- * @interface
- * @expand
- * @category StaticQuestion
- */
-export type StaticQuestionProps = PropsWithChildren<
+type StaticQuestionBaseProps = PropsWithChildren<
Pick<
SdkQuestionProps,
| "withChartTypeSelector"
@@ -61,9 +60,23 @@ export type StaticQuestionProps = PropsWithChildren<
| "withAlerts"
| "title"
>
-> &
+>;
+
+/**
+ * @interface
+ * @expand
+ * @category StaticQuestion
+ */
+export type StaticQuestionProps = StaticQuestionBaseProps &
SdkQuestionEntityPublicProps;
+/**
+ * Internal type that includes the `query` prop used by the `useMetabot` hook.
+ * Not re-exported from the public SDK package entry point.
+ */
+export type StaticQuestionInternalProps = StaticQuestionBaseProps &
+ SdkQuestionEntityInternalProps;
+
/**
* @interface
*/
@@ -88,11 +101,15 @@ export type StaticQuestionComponents = {
};
const StaticQuestionInner = (
- props: StaticQuestionProps,
+ props: StaticQuestionInternalProps,
): JSX.Element | null => {
+ const query = props.query;
+
// Normalize props for Guest Embed usage (e.g. enforce withDownloads in OSS).
const normalizedProps =
- useNormalizeGuestEmbedQuestionOrDashboardComponentProps(props);
+ useNormalizeGuestEmbedQuestionOrDashboardComponentProps(
+ props as StaticQuestionProps,
+ );
const {
questionId,
@@ -110,6 +127,11 @@ const StaticQuestionInner = (
children,
} = normalizedProps;
+ const deserializedCard = useMemo(
+ () => (query ? deserializeCardFromQuery(query) : undefined),
+ [query],
+ );
+
const isGuestEmbed = useSdkSelector(getIsGuestEmbed);
const { ref: containerRef, isMobile } = useMobileLayout();
@@ -130,8 +152,9 @@ const StaticQuestionInner = (
return (
<SdkQuestion
- questionId={questionId ?? null}
+ questionId={questionId}
token={token}
+ deserializedCard={deserializedCard}
getClickActionMode={getClickActionMode}
navigateToNewCard={null}
initialSqlParameters={initialSqlParameters}
@@ -215,10 +238,22 @@ const subComponents: StaticQuestionComponents = {
SqlParametersList: SqlParametersList,
};
+const _StaticQuestionWrapped = withPublicComponentWrapper(StaticQuestionInner, {
+ supportsGuestEmbed: true,
+});
+
export const StaticQuestion = Object.assign(
- withPublicComponentWrapper(StaticQuestionInner, {
- supportsGuestEmbed: true,
- }),
+ _StaticQuestionWrapped as FC<StaticQuestionProps>,
+ subComponents,
+ { schema: staticQuestionSchema },
+);
+
+/**
+ * Same runtime component as {@link StaticQuestion}, typed to accept the
+ * internal `query` prop. This component is intended for internal use only.
+ */
+export const StaticQuestionInternal = Object.assign(
+ _StaticQuestionWrapped as FC<StaticQuestionInternalProps>,
subComponents,
{ schema: staticQuestionSchema },
);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
index 91fc75ece88..51b3324381d 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
@@ -1,8 +1,5 @@
-import userEvent from "@testing-library/user-event";
-
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
- findRequests,
setupAlertsEndpoints,
setupCardEndpoints,
setupCardQueryEndpoints,
@@ -24,65 +21,32 @@ import {
waitForLoaderToBeRemoved,
within,
} from "__support__/ui";
+import { addAlertModalTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec";
+import { addAlertsButtonTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec";
+import type { SetupOpts } from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
+import {
+ TEST_COLUMN,
+ TEST_DATASET,
+ TEST_DB,
+ TEST_TABLE,
+} from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
+import { addQueryPropTests } from "embedding-sdk-bundle/components/public/question/shared-tests/query-prop.spec";
import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
-import { reinitialize } from "metabase/plugins";
-import type { CardId, CollectionType, TokenFeatures } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
createMockCollection,
- createMockColumn,
- createMockDatabase,
- createMockDataset,
- createMockDatasetData,
- createMockTable,
createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
-import { createMockNotification } from "metabase-types/api/mocks/notification";
-
-import { StaticQuestion } from "./StaticQuestion";
-
-const TEST_DB_ID = 1;
-const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
-const TEST_TABLE_ID = 1;
-const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });
-
-const TEST_COLUMN = createMockColumn({
- display_name: "Test Column",
- name: "Test Column",
-});
-
-const TEST_DATASET = createMockDataset({
- data: createMockDatasetData({
- cols: [TEST_COLUMN],
- rows: [["Test Row"]],
- }),
-});
-
-const TEST_CARD_ID: CardId = 1 as const;
+import { StaticQuestion, StaticQuestionInternal } from "./StaticQuestion";
+const TEST_CARD_ID = 1;
const USER_ID = 999;
-interface SetupOpts {
- title?: string | boolean;
- withChartTypeSelector?: boolean;
- withDownloads?: boolean;
- withAlerts?: boolean;
- isEmailSetup?: boolean;
- canManageSubscriptions?: boolean;
- isSuperuser?: boolean;
- isModel?: boolean;
- notifications?: ReturnType<typeof createMockNotification>[];
- collectionType?: CollectionType;
- tokenFeatures?: Partial<TokenFeatures>;
- enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
- children?: React.ReactNode;
-}
-
const setup = async ({
title,
withChartTypeSelector,
@@ -100,7 +64,7 @@ const setup = async ({
}: SetupOpts = {}) => {
setupNotificationChannelsEndpoints({
email: { configured: isEmailSetup },
- } as any);
+ });
const user = createMockUser({
id: USER_ID,
@@ -189,7 +153,12 @@ const setup = async ({
await waitForLoaderToBeRemoved();
};
+addQueryPropTests({ Component: StaticQuestionInternal });
+
describe("StaticQuestion", () => {
+ addAlertsButtonTests(setup, { customComponent: StaticQuestion.AlertsButton });
+ addAlertModalTests(setup, { userId: USER_ID });
+
beforeAll(() => {
mockGetBoundingClientRect();
});
@@ -269,182 +238,6 @@ describe("StaticQuestion", () => {
).toBeVisible();
});
- describe("alerts button with different Metabase version configurations", () => {
- beforeEach(() => {
- reinitialize();
- });
-
- // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
- describe.skip("OSS (Open Source Software)", () => {
- it("should not show the alert button in OSS regardless of settings", async () => {
- // Don't setup enterprise plugin for OSS
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- tokenFeatures: {}, // No embedding_sdk feature
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
-
- // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
- describe.skip("EE (Enterprise Edition) without embedding_sdk token feature", () => {
- it("should not show the alert button when plugin is enabled but token feature is missing", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- tokenFeatures: {}, // No embedding_sdk feature
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
-
- describe("EE with embedding_sdk token feature", () => {
- it("should show the alert button when plugin and token feature are both enabled", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- expect(
- await screen.findByRole("button", { name: "Alerts" }),
- ).toBeVisible();
- });
-
- it("should show the alert button for custom layouts when withAlerts is true", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- children: (
- <div>
- <span>Custom Layout</span>
- <StaticQuestion.AlertsButton />
- </div>
- ),
- });
-
- expect(screen.getByText("Custom Layout")).toBeVisible();
- expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
- });
-
- it("should not show the alert button for custom layouts when withAlerts is false", async () => {
- await setup({
- withAlerts: false,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- children: (
- <div>
- <span>Custom Layout</span>
- <StaticQuestion.AlertsButton />
- </div>
- ),
- });
-
- expect(screen.getByText("Custom Layout")).toBeVisible();
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when withAlerts is false", async () => {
- await setup({
- withAlerts: false,
- isEmailSetup: true,
- canManageSubscriptions: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when email is not configured", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: false,
- canManageSubscriptions: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button when user cannot manage subscriptions and is not admin", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- isSuperuser: false,
- canManageSubscriptions: false,
- enterprisePlugins: ["sdk_notifications", "application_permissions"],
- tokenFeatures: { embedding_sdk: true, advanced_permissions: true },
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button for models", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: true,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
-
- it("should not show the alert button for analytics collection", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- collectionType: "instance-analytics",
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- screen.queryByRole("button", { name: "Alerts" }),
- ).not.toBeInTheDocument();
- });
- });
- });
-
it("should show the TopBar when multiple UI elements are provided", async () => {
await setup({
title: "My Title",
@@ -461,101 +254,4 @@ describe("StaticQuestion", () => {
expect(screen.getByTestId("chart-type-selector-button")).toBeVisible();
});
});
-
- describe("alert modal", () => {
- it("should show alert list modal when there are existing alerts", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- notifications: [createMockNotification()],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
-
- await userEvent.click(
- await screen.findByRole("button", { name: "Alerts" }),
- );
-
- // Verify the alert list modal appears, not the create modal
- const withinModal = within(await findModal());
-
- // Show the alert list modal title
- expect(
- await withinModal.findByRole("heading", { name: "Edit alerts" }),
- ).toBeVisible();
-
- // Should show the button to create a new alert in the list modal
- expect(withinModal.getByText("New alert")).toBeVisible();
-
- // Should NOT show the create alert form fields
- expect(
- withinModal.queryByText("What do you want to be alerted about?"),
- ).not.toBeInTheDocument();
- });
-
- it("should not show email selector on the SDK and use current logged in user as the recipient", async () => {
- await setup({
- withAlerts: true,
- isEmailSetup: true,
- canManageSubscriptions: true,
- isModel: false,
- enterprisePlugins: ["sdk_notifications"],
- });
-
- expect(
- within(screen.getByRole("gridcell")).getByText("Test Row"),
- ).toBeVisible();
- await userEvent.click(
- await screen.findByRole("button", { name: "Alerts" }),
- );
-
- const withinModal = within(await findModal());
- expect(
- withinModal.getByRole("heading", { name: "New alert" }),
- ).toBeVisible();
- expect(
- withinModal.getByText("What do you want to be alerted about?"),
- ).toBeVisible();
- expect(
- withinModal.getByText("When do you want to check this?"),
- ).toBeVisible();
- // Email selector is within this section, checking only the header is fine
- expect(
- withinModal.queryByText("Where do you want to send the results?"),
- ).not.toBeInTheDocument();
- expect(withinModal.getByText("More options")).toBeVisible();
- await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
-
- const createNotificationRequest = (await findRequests("POST")).find(
- (postRequest) =>
- postRequest.url === "http://localhost/api/notification",
- );
- // Checks that we're using the current logged in user as the sole recipient
- expect(createNotificationRequest?.body).toMatchObject({
- handlers: [
- {
- channel_type: "channel/email",
- recipients: [
- {
- details: null,
- type: "notification-recipient/user",
- user_id: USER_ID,
- },
- ],
- },
- ],
- });
- // So that when we assert this value, we know we won't accidentally match the default mock ID
- expect(USER_ID).not.toBe(1);
- });
- });
});
-
-async function findModal() {
- return await screen.findByRole("dialog");
-}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts
new file mode 100644
index 00000000000..ce1065b7cbd
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts
@@ -0,0 +1,111 @@
+import userEvent from "@testing-library/user-event";
+
+import { findRequests } from "__support__/server-mocks";
+import { screen, within } from "__support__/ui";
+import { createMockNotification } from "metabase-types/api/mocks/notification";
+
+import type { SetupOpts } from "./constants.spec";
+
+type Setup = (opts?: SetupOpts) => Promise<void>;
+
+async function findModal() {
+ return await screen.findByRole("dialog");
+}
+
+export function addAlertModalTests(
+ setup: Setup,
+ { userId }: { userId: number },
+) {
+ describe("alert modal", () => {
+ it("should show alert list modal when there are existing alerts", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ notifications: [createMockNotification()],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Alerts" }),
+ );
+
+ // Verify the alert list modal appears, not the create modal
+ const withinModal = within(await findModal());
+
+ // Show the alert list modal title
+ expect(
+ await withinModal.findByRole("heading", { name: "Edit alerts" }),
+ ).toBeVisible();
+
+ // Should show the button to create a new alert in the list modal
+ expect(withinModal.getByText("New alert")).toBeVisible();
+
+ // Should NOT show the create alert form fields
+ expect(
+ withinModal.queryByText("What do you want to be alerted about?"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show email selector on the SDK and use current logged in user as the recipient", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Alerts" }),
+ );
+
+ const withinModal = within(await findModal());
+ expect(
+ withinModal.getByRole("heading", { name: "New alert" }),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("What do you want to be alerted about?"),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("When do you want to check this?"),
+ ).toBeVisible();
+ // Email selector is within this section, checking only the header is fine
+ expect(
+ withinModal.queryByText("Where do you want to send the results?"),
+ ).not.toBeInTheDocument();
+ expect(withinModal.getByText("More options")).toBeVisible();
+ await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
+
+ const createNotificationRequest = (await findRequests("POST")).find(
+ (postRequest) =>
+ postRequest.url === "http://localhost/api/notification",
+ );
+ // Checks that we're using the current logged in user as the sole recipient
+ expect(createNotificationRequest?.body).toMatchObject({
+ handlers: [
+ {
+ channel_type: "channel/email",
+ recipients: [
+ {
+ details: null,
+ type: "notification-recipient/user",
+ user_id: userId,
+ },
+ ],
+ },
+ ],
+ });
+ // So that when we assert this value, we know we won't accidentally match the default mock ID
+ expect(userId).not.toBe(1);
+ });
+ });
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec.tsx
new file mode 100644
index 00000000000..adda8a6e4d7
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec.tsx
@@ -0,0 +1,190 @@
+import type { ComponentType } from "react";
+
+import { screen, within } from "__support__/ui";
+import { reinitialize } from "metabase/plugins";
+
+import type { SetupOpts } from "./constants.spec";
+
+type Setup = (opts?: SetupOpts) => Promise<void>;
+
+export function addAlertsButtonTests(
+ setup: Setup,
+ { customComponent: AlertsButton }: { customComponent: ComponentType },
+) {
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- test description
+ describe("alerts button with different Metabase version configurations", () => {
+ beforeEach(() => {
+ reinitialize();
+ });
+
+ // Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("OSS (Open Source Software)", () => {
+ it("should not show the alert button in OSS regardless of settings", async () => {
+ // Don't setup enterprise plugin for OSS
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ // Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("EE (Enterprise Edition) without embedding_sdk token feature", () => {
+ it("should not show the alert button when plugin is enabled but token feature is missing", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("EE with embedding_sdk token feature", () => {
+ it("should show the alert button when plugin and token feature are both enabled", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ await screen.findByRole("button", { name: "Alerts" }),
+ ).toBeVisible();
+ });
+
+ it("should show the alert button for custom layouts when withAlerts is true", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
+ });
+
+ it("should not show the alert button for custom layouts when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when email is not configured", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: false,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when user cannot manage subscriptions and is not admin", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ isSuperuser: false,
+ canManageSubscriptions: false,
+ enterprisePlugins: ["sdk_notifications", "application_permissions"],
+ tokenFeatures: { embedding_sdk: true, advanced_permissions: true },
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for models", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for analytics collection", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ collectionType: "instance-analytics",
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+ });
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/constants.spec.ts b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/constants.spec.ts
new file mode 100644
index 00000000000..e57abc95d48
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/constants.spec.ts
@@ -0,0 +1,46 @@
+import type { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import type { CollectionType, TokenFeatures } from "metabase-types/api";
+import {
+ createMockColumn,
+ createMockDatabase,
+ createMockDataset,
+ createMockDatasetData,
+ createMockTable,
+} from "metabase-types/api/mocks";
+import type { createMockNotification } from "metabase-types/api/mocks/notification";
+
+const TEST_DB_ID = 1;
+export const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
+
+export const TEST_TABLE = createMockTable({
+ id: 1,
+ db_id: TEST_DB_ID,
+});
+
+export const TEST_COLUMN = createMockColumn({
+ display_name: "Test Column",
+ name: "Test Column",
+});
+
+export const TEST_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"]],
+ }),
+});
+
+export interface SetupOpts {
+ title?: string | boolean;
+ withChartTypeSelector?: boolean;
+ withDownloads?: boolean;
+ withAlerts?: boolean;
+ isEmailSetup?: boolean;
+ canManageSubscriptions?: boolean;
+ isSuperuser?: boolean;
+ isModel?: boolean;
+ notifications?: ReturnType<typeof createMockNotification>[];
+ collectionType?: CollectionType;
+ tokenFeatures?: Partial<TokenFeatures>;
+ enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
+ children?: React.ReactNode;
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/query-prop.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/query-prop.spec.tsx
new file mode 100644
index 00000000000..14396068ac4
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/query-prop.spec.tsx
@@ -0,0 +1,88 @@
+import {
+ setupAdhocQueryMetadataEndpoint,
+ setupCardDataset,
+ setupCollectionByIdEndpoint,
+ setupNotificationChannelsEndpoints,
+} from "__support__/server-mocks";
+import {
+ mockGetBoundingClientRect,
+ screen,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import { utf8_to_b64url } from "metabase/utils/encoding";
+import {
+ createMockCardQueryMetadata,
+ createMockCollection,
+ createMockDataset,
+ createMockDatasetData,
+} from "metabase-types/api/mocks";
+
+import { TEST_COLUMN, TEST_DB, TEST_TABLE } from "./constants.spec";
+
+export function addQueryPropTests({
+ Component,
+}: {
+ Component: (props: { query: string }) => React.ReactNode;
+}) {
+ describe("query prop", () => {
+ const QUERY_PROP = utf8_to_b64url(
+ JSON.stringify({
+ dataset_query: {
+ database: TEST_DB.id,
+ type: "query",
+ query: { "source-table": TEST_TABLE.id },
+ },
+ }),
+ );
+
+ async function setup() {
+ const { state } = setupSdkState();
+
+ setupNotificationChannelsEndpoints({ email: { configured: false } });
+ setupAdhocQueryMetadataEndpoint(
+ createMockCardQueryMetadata({ databases: [TEST_DB] }),
+ );
+ // Needs >1 row so Question.maybeResetDisplay doesn't force scalar.
+ setupCardDataset({
+ dataset: createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"], ["Test Row 2"]],
+ }),
+ }),
+ });
+ setupCollectionByIdEndpoint({
+ collections: [createMockCollection({ id: 1 })],
+ });
+
+ renderWithSDKProviders(<Component query={QUERY_PROP} />, {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: state,
+ });
+
+ await waitForLoaderToBeRemoved();
+ }
+
+ beforeAll(() => {
+ mockGetBoundingClientRect();
+ });
+
+ it("should render a visualization when given a valid query base64 string", async () => {
+ await setup();
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ expect(
+ within(screen.getAllByRole("gridcell")[0]).getByText("Test Row"),
+ ).toBeVisible();
+ });
+ });
+}
diff --git a/frontend/src/embedding-sdk-bundle/hooks/public/use-metabot.tsx b/frontend/src/embedding-sdk-bundle/hooks/public/use-metabot.tsx
new file mode 100644
index 00000000000..a85ad507efe
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/hooks/public/use-metabot.tsx
@@ -0,0 +1,5 @@
+import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";
+import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";
+
+export const useMetabot = (): UseMetabotResult | null =>
+ METABOT_SDK_EE_PLUGIN.useMetabot();
diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.ts
index 673982c7781..01336c04104 100644
--- a/frontend/src/embedding-sdk-bundle/index.ts
+++ b/frontend/src/embedding-sdk-bundle/index.ts
@@ -19,6 +19,7 @@ import "sdk-specific-imports";
import type { MetabaseEmbeddingSdkBundleExports } from "./types/sdk-bundle";
+import { MetabotSubscriber } from "./components/private/MetabotSubscriber/MetabotSubscriber";
import { CollectionBrowser } from "./components/public/CollectionBrowser";
import { CreateDashboardModal } from "./components/public/CreateDashboardModal";
import { CreateQuestion } from "./components/public/CreateQuestion";
@@ -73,6 +74,7 @@ const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {
useInitData,
useLogVersionInfo,
validateFunctionSchema,
+ MetabotSubscriber,
};
// Define a global export METABASE_EMBEDDING_SDK_BUNDLE for SDK package
diff --git a/frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx b/frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx
index 0700f47626e..b9486e82a58 100644
--- a/frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx
+++ b/frontend/src/embedding-sdk-bundle/test/CommonSdkStoryWrapper.tsx
@@ -7,6 +7,7 @@ import "embedding-sdk-bundle";
import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
import { USERS } from "../../../../e2e/support/cypress_data";
@@ -48,7 +49,27 @@ export const storybookSdkAuthDefaultConfig =
export const CommonSdkStoryWrapper = (Story: StoryFn, context: any) => {
const sdkTheme = context.globals.sdkTheme;
- const theme = sdkTheme ? storybookThemes[sdkTheme] : undefined;
+ const globalTheme: MetabaseTheme | undefined = sdkTheme
+ ? storybookThemes[sdkTheme]
+ : undefined;
+
+ // Per-story theme overrides passed via `parameters.sdkThemeOverride`.
+ // Useful for stories that render their chat UI inside a fixed overlay and
+ // need SDK popovers to stack above the host app's modal backdrop.
+ const themeOverride: MetabaseTheme | undefined =
+ context.parameters?.sdkThemeOverride;
+
+ const theme: MetabaseTheme | undefined = themeOverride
+ ? {
+ ...globalTheme,
+ ...themeOverride,
+ components: {
+ ...globalTheme?.components,
+ ...themeOverride?.components,
+ },
+ }
+ : globalTheme;
+
const locale = context.globals.locale;
const user = context.globals.user;
diff --git a/frontend/src/embedding-sdk-bundle/types/index.ts b/frontend/src/embedding-sdk-bundle/types/index.ts
index dffc29ba2a3..e12eb46a71e 100644
--- a/frontend/src/embedding-sdk-bundle/types/index.ts
+++ b/frontend/src/embedding-sdk-bundle/types/index.ts
@@ -3,6 +3,7 @@ export type * from "./collection";
export type * from "./dashboard";
export type * from "./entity";
export type * from "./events";
+export type * from "./metabot";
export type * from "./plugins";
export type * from "./question";
export type * from "./theme";
diff --git a/frontend/src/embedding-sdk-bundle/types/metabot.ts b/frontend/src/embedding-sdk-bundle/types/metabot.ts
new file mode 100644
index 00000000000..2f2ad8df465
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/types/metabot.ts
@@ -0,0 +1,91 @@
+import type React from "react";
+
+import type { InteractiveQuestionProps } from "embedding-sdk-bundle/components/public/InteractiveQuestion";
+import type { StaticQuestionProps } from "embedding-sdk-bundle/components/public/StaticQuestion";
+
+// User messages
+
+export type MetabotUserTextMessage = {
+ id: string;
+ role: "user";
+ type: "text";
+ message: string;
+};
+
+// Agent messages
+
+export type MetabotAgentTextMessage = {
+ id: string;
+ role: "agent";
+ type: "text";
+ message: string;
+};
+
+export type MetabotAgentChartMessage = {
+ id: string;
+ role: "agent";
+ type: "chart";
+ /** URL path to the question, e.g. `/question#<base64>` */
+ questionPath: string;
+ /** A pre-wired React component that renders the chart. */
+ Chart: React.ComponentType<MetabotChartProps>;
+};
+
+// Internal variants intentionally omitted. `use-metabot.tsx` filters these out before mapping:
+// - `tool_call`: debug-only, gated on metabot's `debugMode`.
+// - `edit_suggestion`: targets the in-app Transform editor, which the SDK does not render.
+// - `action`: unused in shipped code.
+// - `todo_list`: only reachable via the `codegen/transforms` profile, not the SDK.
+export type MetabotAgentMessage =
+ | MetabotAgentTextMessage
+ | MetabotAgentChartMessage;
+
+export type MetabotMessage = MetabotUserTextMessage | MetabotAgentMessage;
+
+export type MetabotChartProps =
+ | (Omit<StaticQuestionProps, "questionId" | "token" | "query"> & {
+ drills?: false;
+ })
+ | (Omit<InteractiveQuestionProps, "questionId" | "token" | "query"> & {
+ drills: true;
+ });
+
+export type MetabotErrorMessage = {
+ /** `"alert"` renders with a warning icon and error color; `"message"` renders as plain text. */
+ type: "message" | "alert" | "locked";
+ message: string;
+};
+
+export type UseMetabotResult = {
+ /** Submit a new message to the conversation. */
+ submitMessage: (message: string) => Promise<void>;
+ /**
+ * Rewinds the conversation to the user message preceding `messageId` and re-submits
+ * that prompt. The agent message at `messageId` and anything after it is dropped.
+ */
+ retryMessage: (messageId: string) => Promise<void>;
+ /** Cancel the current in-flight request. */
+ cancelRequest: () => void;
+ /** Clear all messages and start fresh. */
+ resetConversation: () => void;
+
+ /** All messages in the conversation. Chart messages include a `Chart` property. */
+ messages: MetabotMessage[];
+ /** Errors are conversation-level, not attached to individual messages. */
+ errorMessages: MetabotErrorMessage[];
+ /**
+ * `true` from the moment a message is submitted until the response
+ * completes — including success, error, or cancellation.
+ */
+ isProcessing: boolean;
+
+ /**
+ * A pre-wired component bound to the latest `navigate_to` path.
+ * `null` until the agent sends a chart — lets consumers detect presence
+ * and render a placeholder or swap panel content only when set.
+ *
+ * @example
+ * {CurrentChart ? <CurrentChart /> : <Placeholder />}
+ */
+ CurrentChart: React.ComponentType<MetabotChartProps> | null;
+};
diff --git a/frontend/src/embedding-sdk-bundle/types/question.ts b/frontend/src/embedding-sdk-bundle/types/question.ts
index 827a32f86fd..09af3d0a162 100644
--- a/frontend/src/embedding-sdk-bundle/types/question.ts
+++ b/frontend/src/embedding-sdk-bundle/types/question.ts
@@ -52,6 +52,7 @@ export type SdkQuestionEntityPublicProps =
*/
questionId: SdkQuestionId | null;
token?: never;
+ query?: never;
}
| {
questionId?: never;
@@ -59,6 +60,19 @@ export type SdkQuestionEntityPublicProps =
* A valid JWT token for the guest embed.
*/
token: SdkEntityToken | null;
+ query?: never;
+ };
+
+/**
+ * Internal type that adds the `query` prop used by the `useMetabot` hook. Not
+ * re-exported from the public SDK package entry point.
+ */
+export type SdkQuestionEntityInternalProps =
+ | SdkQuestionEntityPublicProps
+ | {
+ questionId?: never;
+ token?: never;
+ query: string;
};
export interface SdkQuestionState {
diff --git a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
index a4dc5ef0a56..1b776ab9c86 100644
--- a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
+++ b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
@@ -1,5 +1,6 @@
import type { JSXElementConstructor } from "react";
+import type { MetabotSubscriber } from "embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber";
import type { CollectionBrowser } from "embedding-sdk-bundle/components/public/CollectionBrowser";
import type { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
import type { CreateDashboardModal } from "embedding-sdk-bundle/components/public/CreateDashboardModal";
@@ -39,9 +40,10 @@ export type MetabaseEmbeddingSdkBundleExports = PublicExports &
ReduxStoreUtilityFunctionExports &
ReduxStoreSelectorsExports &
InternalHooksExports &
- SchemaValidationUtils;
+ SchemaValidationUtils &
+ InternalComponentExports;
-export type PublicExports = {
+type PublicExports = {
CollectionBrowser: InternalComponent<typeof CollectionBrowser>;
CreateDashboardModal: InternalComponent<typeof CreateDashboardModal>;
CreateQuestion: InternalComponent<typeof CreateQuestion>;
@@ -55,30 +57,34 @@ export type PublicExports = {
StaticQuestion: InternalComponent<typeof StaticQuestion>;
};
-export type ReduxStoreExports = {
+type ReduxStoreExports = {
getSdkStore: ReduxStoreFactory;
};
-export type ReduxStoreUtilityFunctionExports = {
+type ReduxStoreUtilityFunctionExports = {
createDashboard: ReduxStoreUtilityFunction<
(params: CreateDashboardValues) => Promise<MetabaseDashboard>
>;
};
-export type ReduxStoreSelectorsExports = {
+type ReduxStoreSelectorsExports = {
getApplicationName: ReduxStoreSelector<string>;
getAvailableFonts: ReduxStoreSelector<string[]>;
getLoginStatus: ReduxStoreSelector<LoginStatus>;
getUser: ReduxStoreSelector<User | null>;
};
-export type InternalHooksExports = {
+type InternalHooksExports = {
useInitData: InternalHook;
useLogVersionInfo: InternalHook;
};
-export type SchemaValidationUtils = {
+type SchemaValidationUtils = {
validateFunctionSchema: (
schema: any,
) => FunctionSchemaValidationResult<unknown[], unknown>;
};
+
+type InternalComponentExports = {
+ MetabotSubscriber: typeof MetabotSubscriber;
+};
diff --git a/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.ts b/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.ts
index e62d249449c..a739d464fe0 100644
--- a/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.ts
+++ b/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.ts
@@ -1,22 +1,28 @@
-import { useRef, useSyncExternalStore } from "react";
+import { useCallback, useSyncExternalStore } from "react";
import { ensureMetabaseProviderPropsStore } from "../lib/ensure-metabase-provider-props-store";
export function useMetabaseProviderPropsStore() {
- const storeRef = useRef<ReturnType<typeof ensureMetabaseProviderPropsStore>>(
- ensureMetabaseProviderPropsStore(),
+ // Re-resolve the store from `window` on every subscribe/snapshot call.
+ // `cleanup()` deletes the window key, and the next `ensureMetabaseProviderPropsStore()`
+ // creates a fresh store. Holding a `useRef`'d store across React StrictMode's
+ // simulated unmount/remount cycle would leave the component reading from a
+ // stale store object while writes (via direct `ensureMetabaseProviderPropsStore()`
+ // calls in effects) target the current one.
+ const subscribe = useCallback(
+ (listener: () => void) =>
+ ensureMetabaseProviderPropsStore().subscribe(listener),
+ [],
);
-
- const state = useSyncExternalStore(
- storeRef.current.subscribe,
- storeRef.current.getState,
- storeRef.current.getState,
+ const getSnapshot = useCallback(
+ () => ensureMetabaseProviderPropsStore().getState(),
+ [],
);
- const store = storeRef.current;
+ const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return {
state,
- store,
+ store: ensureMetabaseProviderPropsStore(),
};
}
diff --git a/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.unit.spec.tsx b/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.unit.spec.tsx
new file mode 100644
index 00000000000..63a55f1db41
--- /dev/null
+++ b/frontend/src/embedding-sdk-shared/hooks/use-metabase-provider-props-store.unit.spec.tsx
@@ -0,0 +1,63 @@
+import { act, render, screen } from "@testing-library/react";
+import { StrictMode, useEffect } from "react";
+
+import { ensureMetabaseProviderPropsStore } from "../lib/ensure-metabase-provider-props-store";
+
+import { useMetabaseProviderPropsStore } from "./use-metabase-provider-props-store";
+
+const PROPS_STORE_KEY = "METABASE_PROVIDER_PROPS_STORE" as const;
+
+const resetWindow = () => {
+ delete (window as any)[PROPS_STORE_KEY];
+};
+
+// Mirrors `MetabaseProviderInner`'s cleanup effect: deletes the store
+// from `window` on unmount. Under StrictMode this fires during the
+// simulated unmount/remount cycle.
+const ParentWithCleanup = ({ children }: { children: React.ReactNode }) => {
+ useEffect(
+ () => () => {
+ ensureMetabaseProviderPropsStore().cleanup();
+ },
+ [],
+ );
+ return <>{children}</>;
+};
+
+const Consumer = () => {
+ const { state } = useMetabaseProviderPropsStore();
+ return (
+ <div data-testid="instance-url">
+ {state.props?.authConfig?.metabaseInstanceUrl ?? "none"}
+ </div>
+ );
+};
+
+describe("useMetabaseProviderPropsStore under StrictMode", () => {
+ beforeEach(resetWindow);
+ afterEach(resetWindow);
+
+ it("re-subscribes to the new store after the StrictMode cleanup cycle wipes the previous one", () => {
+ render(
+ <StrictMode>
+ <ParentWithCleanup>
+ <Consumer />
+ </ParentWithCleanup>
+ </StrictMode>,
+ );
+
+ // Strict mode just ran setup → cleanup (which deleted win[KEY]) → setup.
+ // The hook should now be subscribed to the freshly-created window store.
+ expect(screen.getByTestId("instance-url")).toHaveTextContent("none");
+
+ act(() => {
+ ensureMetabaseProviderPropsStore().setProps({
+ authConfig: { metabaseInstanceUrl: "https://example.com" } as any,
+ });
+ });
+
+ expect(screen.getByTestId("instance-url")).toHaveTextContent(
+ "https://example.com",
+ );
+ });
+});
diff --git a/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts b/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
index 1d2cdd859e2..958d0eb2851 100644
--- a/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
+++ b/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
@@ -30,7 +30,6 @@ export type MetabaseProviderPropsStoreInternalProps = {
export type MetabaseProviderPropsStore = {
getState(): MetabaseProviderPropsStoreState;
subscribe(listener: () => void): () => void;
- initialize(initialProps: MetabaseProviderPropsStoreExternalProps): void;
updateInternalProps(
internalProps: Partial<MetabaseProviderPropsStoreInternalProps>,
): void;
@@ -77,15 +76,6 @@ export function ensureMetabaseProviderPropsStore(): MetabaseProviderPropsStore {
return () => listeners.delete(listener);
},
- initialize(initialProps) {
- state = {
- ...state,
- props: {
- ...getDefaultProps(),
- ...initialProps,
- },
- } as MetabaseProviderPropsStoreState;
- },
updateInternalProps(internalProps) {
state = {
...state,
diff --git a/frontend/src/embedding-sdk-shared/lib/metabot-state-channel.ts b/frontend/src/embedding-sdk-shared/lib/metabot-state-channel.ts
new file mode 100644
index 00000000000..66d8fa657f9
--- /dev/null
+++ b/frontend/src/embedding-sdk-shared/lib/metabot-state-channel.ts
@@ -0,0 +1,49 @@
+import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";
+
+import { getWindow } from "./get-window";
+
+type MetabotStateChannel = {
+ value: UseMetabotResult | null;
+ listeners: Set<() => void>;
+};
+
+// Collision note: like METABASE_EMBEDDING_SDK_BUNDLE, this global is
+// single-version-per-page. Loading two SDK bundles on the same page
+// clobbers the state. Not a supported scenario.
+const METABOT_STATE_KEY = "METABASE_EMBEDDING_SDK_METABOT_STATE";
+
+const EMPTY_CHANNEL: MetabotStateChannel = {
+ value: null,
+ listeners: new Set(),
+};
+
+function getChannel(): MetabotStateChannel {
+ const windowObject = getWindow();
+ if (!windowObject) {
+ return EMPTY_CHANNEL;
+ }
+ if (!windowObject[METABOT_STATE_KEY]) {
+ windowObject[METABOT_STATE_KEY] = { value: null, listeners: new Set() };
+ }
+ return windowObject[METABOT_STATE_KEY];
+}
+
+export function publishMetabotState(value: UseMetabotResult | null): void {
+ const channel = getChannel();
+ channel.value = value;
+ channel.listeners.forEach((listener) => listener());
+}
+
+export function subscribeMetabotState(listener: () => void): () => void {
+ const channel = getChannel();
+ channel.listeners.add(listener);
+ return () => {
+ channel.listeners.delete(listener);
+ };
+}
+
+export function getMetabotStateSnapshot(): UseMetabotResult | null {
+ return getChannel().value;
+}
+
+export type { MetabotStateChannel };
diff --git a/frontend/src/embedding-sdk-shared/types/globals.d.ts b/frontend/src/embedding-sdk-shared/types/globals.d.ts
index 3db73699efb..07816a445eb 100644
--- a/frontend/src/embedding-sdk-shared/types/globals.d.ts
+++ b/frontend/src/embedding-sdk-shared/types/globals.d.ts
@@ -13,4 +13,5 @@ interface Window {
METABASE_EMBEDDING_SDK_IS_HOST_APP_IN_DEV_MODE?: boolean; // Added in v59
METABASE_EMBEDDING_SDK_AUTH_STATE?: import("embedding-sdk-shared/types/auth-state").SdkAuthState;
FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS?: boolean;
+ METABASE_EMBEDDING_SDK_METABOT_STATE?: import("embedding-sdk-shared/lib/metabot-state-channel").MetabotStateChannel;
}
diff --git a/frontend/src/metabase/common/utils/card.ts b/frontend/src/metabase/common/utils/card.ts
index fb9b0dcdc8f..e049abde3da 100644
--- a/frontend/src/metabase/common/utils/card.ts
+++ b/frontend/src/metabase/common/utils/card.ts
@@ -3,7 +3,11 @@ import querystring from "querystring";
import _ from "underscore";
import { clone } from "metabase/utils/clone";
-import { b64hash_to_utf8, utf8_to_b64url } from "metabase/utils/encoding";
+import {
+ b64hash_to_utf8,
+ b64url_to_utf8,
+ utf8_to_b64url,
+} from "metabase/utils/encoding";
import { stableStringify } from "metabase/utils/objects";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
@@ -102,6 +106,18 @@ export function deserializeCardFromUrl(serialized: string): Card {
return JSON.parse(b64hash_to_utf8(serialized));
}
+/**
+ * Converts a Metabot `navigate_to` path like `/question#<base64>` into a
+ * Card suitable for `deserializedCard`.
+ *
+ * Sole producer is Metabot's `navigate_to` stream part, which always emits
+ * `/question#<base64>`. Intentionally not guarded against other shapes.
+ */
+export function deserializeCardFromQuery(query: string): Card {
+ const base64 = query.replace(/^\/question#/, "");
+ return JSON.parse(b64url_to_utf8(base64));
+}
+
export function deserializeCard(serializedCard: string) {
const card = deserializeCardFromUrl(serializedCard);
if (card.dataset_query.database != null) {
diff --git a/frontend/src/metabase/common/utils/card.unit.spec.ts b/frontend/src/metabase/common/utils/card.unit.spec.ts
new file mode 100644
index 00000000000..144b17fb61a
--- /dev/null
+++ b/frontend/src/metabase/common/utils/card.unit.spec.ts
@@ -0,0 +1,22 @@
+import { deserializeCardFromQuery } from "metabase/common/utils/card";
+import { utf8_to_b64url } from "metabase/utils/encoding";
+
+describe("deserializeCardFromQuery", () => {
+ const MBQL_QUERY = {
+ database: 1,
+ type: "query",
+ query: { "source-table": 2 },
+ };
+ const CARD_PAYLOAD = {
+ dataset_query: MBQL_QUERY,
+ display: "bar",
+ visualization_settings: {},
+ };
+ const WRAPPED_B64 = utf8_to_b64url(JSON.stringify(CARD_PAYLOAD));
+
+ it("should strip /question# prefix and decode the payload", () => {
+ expect(deserializeCardFromQuery(`/question#${WRAPPED_B64}`)).toEqual(
+ CARD_PAYLOAD,
+ );
+ });
+});
diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.ts
index 60ac2c248be..bd69aadb1b3 100644
--- a/frontend/src/metabase/metabot/state/actions.ts
+++ b/frontend/src/metabase/metabot/state/actions.ts
@@ -38,6 +38,7 @@ import {
getUserPromptForMessageId,
} from "./selectors";
import type {
+ MetabotAgentChartMessage,
MetabotAgentEditSuggestionChatMessage,
MetabotAgentId,
MetabotAgentTodoListChatMessage,
@@ -355,6 +356,18 @@ export const sendAgentRequest = createAsyncThunk<
try {
let state = {};
let error: unknown = undefined;
+ /**
+ * Hold the chart message until the stream finishes so it renders after
+ * the agent's final text. `navigate_to` arrives mid-stream, before the
+ * last message, so inserting it eagerly would show the chart above later
+ * text.
+ *
+ * Last navigate_to wins, matching setNavigateToPath/CurrentChart semantics.
+ * In practice we don't expect more than one navigate_to in a single stream.
+ */
+ let pendingChartMessage:
+ | { type: "chart"; navigateTo: string }
+ | undefined = undefined;
const response = await aiStreamingQuery(
{
@@ -391,6 +404,19 @@ export const sendAgentRequest = createAsyncThunk<
.with({ type: "navigate_to" }, (part) => {
dispatch(setNavigateToPath(part.value));
+ if (isEmbeddingSdk()) {
+ if (pendingChartMessage) {
+ console.warn("Overwriting pending navigate_to: ", {
+ previous: pendingChartMessage.navigateTo,
+ next: part.value,
+ });
+ }
+ pendingChartMessage = {
+ type: "chart",
+ navigateTo: part.value,
+ };
+ }
+
if (!isEmbeddingSdk()) {
dispatch(push(part.value) as UnknownAction);
}
@@ -439,6 +465,15 @@ export const sendAgentRequest = createAsyncThunk<
},
);
+ // Preserve any chart the agent already committed via `navigate_to`,
+ // even if the stream errored or was cancelled before the closing text
+ // arrived.
+ if (pendingChartMessage != null) {
+ const chartMessage: Omit<MetabotAgentChartMessage, "id" | "role"> =
+ pendingChartMessage;
+ dispatch(addAgentMessage({ ...chartMessage, agentId }));
+ }
+
if (error) {
throw error;
}
diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.ts
index 0e711abe897..5679692d9e7 100644
--- a/frontend/src/metabase/metabot/state/types.ts
+++ b/frontend/src/metabase/metabot/state/types.ts
@@ -57,11 +57,19 @@ export type MetabotDebugToolCallMessage = {
is_error?: boolean;
};
+export type MetabotAgentChartMessage = {
+ id: string;
+ role: "agent";
+ type: "chart";
+ navigateTo: string;
+};
+
export type MetabotAgentChatMessage =
| MetabotAgentTextChatMessage
| MetabotAgentTodoListChatMessage
| MetabotAgentEditSuggestionChatMessage
- | MetabotDebugToolCallMessage;
+ | MetabotDebugToolCallMessage
+ | MetabotAgentChartMessage;
export type MetabotUserChatMessage =
| MetabotUserTextChatMessage
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
index 751dbbcc5ad..316c4fa90cd 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -186,7 +186,6 @@ describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
expect(scheduleTypeSelect).toHaveValue("weekly");
expect(screen.getByTestId("select-weekday")).toHaveValue("Monday");
- // screen.debug(undefined, Infinity);
// Verify time is 2:00pm
const timeSelector = screen.getByTestId("select-time");
expect(timeSelector).toHaveValue("2:00");