Skip to content

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

22.7 KB
Raw Blame
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 type { GeneratedCard } from "metabase/api/ai-streaming/schemas";
import type {
  FinishReason,
  SSEEvent,
} from "metabase/api/ai-streaming/sse-types";
import { getMetabotState, metabotActions } from "metabase/metabot/state";
import {
  createTestMetabotState,
  lastReqBody,
  mockAgentEndpoint,
  setup,
  startRequestlessAgentTurn,
  testConversationId,
  whoIsYourFavoriteResponse,
} from "metabase/metabot/tests/utils";
import * as Urls from "metabase/urls";

import { useMetabot } from "./use-metabot";

const makeCard = (id: string, sourceTable = 1): GeneratedCard => ({
  type: "card",
  id,
  title: "Chart",
  query: {
    id: `q-${id}`,
    query: {
      database: 1,
      type: "query",
      query: { "source-table": sourceTable },
    },
  },
  display: "table",
});

const conversationId = testConversationId("omnibot");

const addAgentMessage = (
  store: { dispatch: (action: unknown) => unknown },
  ...parts: unknown[]
) => {
  startRequestlessAgentTurn(store, conversationId);
  parts.forEach((part) =>
    // `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
    // here.
    store.dispatch(metabotActions.addAgentMessage(part as any)),
  );
};

const cardMessage = (id: string, sourceTable = 1) =>
  // `addAgentMessage` types its payload with a non-distributive `Omit` that
  // collapses the message union to common keys, so the branch-specific `part`
  // field fails excess-property checks (see the fuller note on `addAgentMessage`
  // above).
  ({
    conversationId,
    type: "data_part",
    part: {
      type: "data-generated_entity",
      data: makeCard(id, sourceTable),
    },
  }) as any;

const cardPath = (id: string, sourceTable = 1) =>
  Urls.generatedCard(makeCard(id, sourceTable));

/**
 * Covers `useMetabot()` non-passthrough wiring: `CurrentChart`,
 * `messages[n].Chart`, `submitMessage`, `messages` mapping, `incompleteResponse`.
 * 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 a chart path is set", () => {
      setup({ ui: <TestCurrentChart /> });

      expect(
        screen.queryByTestId("mock-static-question"),
      ).not.toBeInTheDocument();
    });

    it("renders a chart after a chart path is set", 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 chart path is set", 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({
            conversationId,
            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(() => {
        addAgentMessage(store, { conversationId, type: "text", message: "ok" });
      });

      const [message] = await readMessages();
      expect(message).toEqual({
        id: expect.any(String),
        role: "agent",
        type: "text",
        message: "ok",
      });
    });

    it("projects a generated_entity card data_part into a chart message with questionPath", async () => {
      const { store } = setup({ ui: <TestMessages /> });

      act(() => {
        addAgentMessage(store, cardMessage("card-1"));
      });

      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: cardPath("card-1"),
      });
    });

    it("filters out internal-only variants (tool_call, edit_suggestion, todo_list)", async () => {
      const { store } = setup({ ui: <TestMessages /> });

      act(() => {
        store.dispatch(metabotActions.setDebugMode(true));
        addAgentMessage(
          store,
          { conversationId, type: "tool_call", name: "fn", status: "started" },
          {
            conversationId,
            type: "edit_suggestion",
            model: "transform",
            payload: {
              editorTransform: undefined,
              suggestedTransform: {
                name: "Transform A",
                description: "Does X",
                source: "SRC",
                target: "TGT",
                active: true,
                suggestionId: "s1",
              },
            },
          },
          {
            conversationId,
            type: "todo_list",
            payload: [
              {
                id: "t1",
                content: "work",
                status: "pending",
                priority: "high",
              },
            ],
          },
          { conversationId, type: "text", message: "ok" },
        );
      });

      const messages = await readMessages();
      expect(messages).toHaveLength(1);
      expect(messages[0]).toEqual({
        id: expect.any(String),
        role: "agent",
        type: "text",
        message: "ok",
      });
    });

    it("keeps only the last chart per turn, across multiple turns", async () => {
      const { store } = setup({ ui: <TestMessages /> });

      act(() => {
        store.dispatch(
          metabotActions.addUserMessage({
            conversationId,
            id: "u1",
            type: "text",
            message: "first",
          }),
        );
        addAgentMessage(
          store,
          cardMessage("card-1A", 1),
          cardMessage("card-1B", 2),
        );
        store.dispatch(
          metabotActions.addUserMessage({
            conversationId,
            id: "u2",
            type: "text",
            message: "second",
          }),
        );
        addAgentMessage(store, cardMessage("card-2", 3));
      });

      const messages = await readMessages();
      const charts = messages.filter((m) => m.type === "chart");
      expect(charts).toHaveLength(2);
      expect(charts[0].questionPath).toBe(cardPath("card-1B", 2));
      expect(charts[1].questionPath).toBe(cardPath("card-2", 3));
    });
  });

  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({
        events: 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({ events: 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: createTestMetabotState(),
      });

      expect(
        getMetabotState(store.getState()).conversations[conversationId]
          ?.messages.length,
      ).toBe(0);
      expect(getMetabotState(store.getState()).agents.omnibot?.visible).toBe(
        false,
      );

      await userEvent.click(screen.getByTestId("submit-btn"));

      await waitFor(() => {
        expect(
          getMetabotState(store.getState()).conversations[conversationId]
            ?.messages.length,
        ).toBeGreaterThan(0);
      });

      expect(getMetabotState(store.getState()).agents.omnibot?.visible).toBe(
        false,
      );
    });

    it("resolves to undefined even though agent.submitInput returns an action", async () => {
      mockAgentEndpoint({ events: 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("incompleteResponse", () => {
    const CONTEXT_WINDOW = 1000;
    const fullContextWindow = {
      contextTokens: CONTEXT_WINDOW,
      contextWindowTokens: CONTEXT_WINDOW,
    };

    let turnCount = 0;
    const turnEndingWith = (
      finishReason: FinishReason,
      messageMetadata?: typeof fullContextWindow,
    ): SSEEvent[] => [
      { type: "start", messageId: `msg_turn_${++turnCount}` },
      { type: "text-start", id: "t1" },
      { type: "text-delta", id: "t1", delta: "Here is the start" },
      { type: "text-end", id: "t1" },
      {
        type: "finish",
        finishReason,
        ...(messageMetadata && { messageMetadata }),
      },
    ];

    const TestIncomplete = ({
      onContinued,
    }: {
      onContinued?: (value: unknown) => void;
    }) => {
      const { submitMessage, incompleteResponse } = useMetabot();
      const continueResponse = incompleteResponse?.continueResponse;
      const handleContinue = async () => {
        const result = await continueResponse?.();
        onContinued?.(result);
      };
      return (
        <div>
          <button data-testid="submit-btn" onClick={() => submitMessage("hi")}>
            submit
          </button>
          {incompleteResponse && (
            <div data-testid="incomplete-response">
              <span data-testid="reason">{incompleteResponse.reason}</span>
              <span data-testid="message">{incompleteResponse.message}</span>
              {continueResponse && (
                <button data-testid="continue-btn" onClick={handleContinue}>
                  continue
                </button>
              )}
            </div>
          )}
        </div>
      );
    };

    const submit = () => userEvent.click(screen.getByTestId("submit-btn"));
    const continueBtn = () => screen.findByTestId("continue-btn");
    const waitForMessageCount = (
      store: ReturnType<typeof setup>["store"],
      count: number,
    ) =>
      waitFor(() =>
        expect(
          getMetabotState(store.getState()).conversations[conversationId]
            ?.messages,
        ).toHaveLength(count),
      );

    it("exposes nothing after a response that finishes with stop", async () => {
      mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
      const { store } = setup({ ui: <TestIncomplete /> });

      await submit();
      await waitForMessageCount(store, 2);

      expect(
        screen.queryByTestId("incomplete-response"),
      ).not.toBeInTheDocument();
    });

    it.each<{
      finishReason: FinishReason;
      messageMetadata?: typeof fullContextWindow;
      reason: string;
      continuable: boolean;
    }>([
      {
        finishReason: "tool-calls",
        reason: "step-limit",
        continuable: true,
      },
      {
        finishReason: "length",
        reason: "max-length",
        continuable: true,
      },
      {
        finishReason: "tool-calls",
        messageMetadata: fullContextWindow,
        reason: "step-limit",
        continuable: false,
      },
      {
        finishReason: "length",
        messageMetadata: fullContextWindow,
        reason: "context-window-full",
        continuable: false,
      },
      {
        finishReason: "content-filter",
        reason: "content-filter",
        continuable: false,
      },
      {
        finishReason: "other",
        reason: "other",
        continuable: false,
      },
    ])(
      "exposes $reason for a $finishReason finish (continuable: $continuable)",
      async ({ finishReason, messageMetadata, reason, continuable }) => {
        mockAgentEndpoint({
          events: turnEndingWith(finishReason, messageMetadata),
        });
        setup({ ui: <TestIncomplete /> });

        await submit();

        expect(await screen.findByTestId("reason")).toHaveTextContent(reason);
        expect(screen.getByTestId("message")).not.toBeEmptyDOMElement();
        expect(screen.queryByTestId("continue-btn") !== null).toBe(continuable);
      },
    );

    it("continueResponse submits the resume prompt as a new user turn", async () => {
      mockAgentEndpoint({ events: turnEndingWith("tool-calls") });
      setup({ ui: <TestIncomplete /> });
      await submit();

      const continuationSpy = mockAgentEndpoint({
        events: whoIsYourFavoriteResponse,
      });
      await userEvent.click(await continueBtn());

      expect((await lastReqBody(continuationSpy))?.message).toBe(
        "Continue working on my last request.",
      );
    });

    it("continueResponse does not expose the agent's internal result to the caller", async () => {
      mockAgentEndpoint({ events: turnEndingWith("tool-calls") });
      const onContinued = jest.fn();
      setup({ ui: <TestIncomplete onContinued={onContinued} /> });
      await submit();

      mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
      await userEvent.click(await continueBtn());

      await waitFor(() => expect(onContinued).toHaveBeenCalledWith(undefined));
    });

    it("clears once the continued turn finishes", async () => {
      mockAgentEndpoint({ events: turnEndingWith("tool-calls") });
      const { store } = setup({ ui: <TestIncomplete /> });
      await submit();

      mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
      await userEvent.click(await continueBtn());
      await waitForMessageCount(store, 4);

      expect(
        screen.queryByTestId("incomplete-response"),
      ).not.toBeInTheDocument();
    });

    it("re-exposes when the continued response is cut off again", async () => {
      mockAgentEndpoint({ events: turnEndingWith("tool-calls") });
      setup({ ui: <TestIncomplete /> });
      await submit();

      mockAgentEndpoint({ events: turnEndingWith("length") });
      await userEvent.click(await continueBtn());

      await waitFor(() =>
        expect(screen.getByTestId("reason")).toHaveTextContent("max-length"),
      );
      expect(await continueBtn()).toBeInTheDocument();
    });
  });

  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(() => {
        addAgentMessage(store, cardMessage("card-1"));
      });

      expect(await screen.findByTestId("mock-static-question")).toBeVisible();
    });

    it("renders InteractiveQuestion when drills is true", async () => {
      const { store } = setup({ ui: <TestChart drills /> });

      act(() => {
        addAgentMessage(store, cardMessage("card-1"));
      });

      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.addUserMessage({
            conversationId,
            id: "u1",
            type: "text",
            message: "first",
          }),
        );
        addAgentMessage(store, cardMessage("card-abc", 1));
      });

      await waitFor(() => {
        expect(screen.getByTestId("chart-count")).toHaveTextContent("1");
      });
      const capturedChart = firstChart;
      expect(capturedChart).not.toBeNull();

      // Open a second turn so both charts survive the per-turn filter.
      act(() => {
        store.dispatch(
          metabotActions.addUserMessage({
            conversationId,
            id: "u2",
            type: "text",
            message: "second",
          }),
        );
        addAgentMessage(store, cardMessage("card-xyz", 2));
      });

      await waitFor(() => {
        expect(screen.getByTestId("chart-count")).toHaveTextContent("2");
      });

      expect(firstChart).toBe(capturedChart);
    });
  });
});