Skip to content

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

[Metabot] Remove non-streaming metabot code (#61988)

Sloan Spargera076cca120d2
diff --git a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
index ea5497468ab..f40b36258f6 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
@@ -1,7 +1,5 @@
import type {
DeleteSuggestedMetabotPromptRequest,
- MetabotAgentRequest,
- MetabotAgentResponse,
MetabotApiEntity,
MetabotEntity,
MetabotId,
@@ -17,13 +15,6 @@ import { idTag } from "./tags";
export const metabotApi = EnterpriseApi.injectEndpoints({
endpoints: (builder) => ({
- metabotAgent: builder.mutation<MetabotAgentResponse, MetabotAgentRequest>({
- query: (body) => ({
- method: "POST",
- url: "/api/ee/metabot-v3/v2/agent",
- body,
- }),
- }),
listMetabots: builder.query<{ items: MetabotInfo[] }, void>({
query: () => ({
method: "GET",
@@ -123,9 +114,7 @@ export const metabotApi = EnterpriseApi.injectEndpoints({
}),
});
-export const { metabotAgent } = metabotApi.endpoints;
export const {
- useMetabotAgentMutation,
useListMetabotsQuery,
useListMetabotsEntitiesQuery,
useUpdateMetabotEntitiesMutation,
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
index a8065942285..1529609b361 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
@@ -158,7 +158,6 @@ export const MetabotChat = () => {
{/* conversation messages */}
{metabot.messages.map((message, index) => {
const canRetry =
- metabot.useStreaming &&
message.role === "agent" &&
metabot.messages[index + 1]?.role !== "agent";
@@ -189,7 +188,7 @@ export const MetabotChat = () => {
{/* loading */}
{metabot.isDoingScience && (
<MetabotThinking
- toolCalls={metabot.useStreaming ? metabot.toolCalls : []}
+ toolCalls={metabot.toolCalls}
hasStartedResponse={
_.last(metabot.messages)?.role === "agent"
}
@@ -231,11 +230,8 @@ export const MetabotChat = () => {
data-testid="metabot-chat-input"
w="100%"
leftSection={
- <Box h="100%" pt="11px" onDoubleClick={metabot.toggleStreaming}>
- <Icon
- name="metabot"
- c={metabot.useStreaming ? "brand" : "warning"}
- />
+ <Box h="100%" pt="11px">
+ <Icon name="metabot" c="brand" />
</Box>
}
autosize
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts
index ef63d7a2e83..2ace9155156 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts
@@ -14,12 +14,10 @@ import {
getMetabotId,
getMetabotVisible,
getToolCalls,
- getUseStreaming,
resetConversation as resetConversationAction,
retryPrompt,
setVisible as setVisibleAction,
submitInput as submitInputAction,
- toggleStreaming,
} from "./state";
export const useMetabotAgent = () => {
@@ -139,10 +137,6 @@ export const useMetabotAgent = () => {
toolCalls: useSelector(getToolCalls as any) as ReturnType<
typeof getToolCalls
>,
- useStreaming: useSelector(getUseStreaming as any) as ReturnType<
- typeof getUseStreaming
- >,
- toggleStreaming: () => dispatch(toggleStreaming()),
retryMessage,
};
};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/metabot-streaming.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/metabot-streaming.unit.spec.tsx
deleted file mode 100644
index 7e9b7f70e64..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/metabot-streaming.unit.spec.tsx
+++ /dev/null
@@ -1,609 +0,0 @@
-// NOTE: these tests can replace their counterparts in the metabot.unit.spec.tsx once streaming becomes the default
-
-import { combineReducers } from "@reduxjs/toolkit";
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-import { P, isMatching } from "ts-pattern";
-
-import { setupEnterprisePlugins } from "__support__/enterprise";
-import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
-import {
- type MockStreamedEndpointParams,
- createMockReadableStream,
- createPauses,
- mockStreamedEndpoint,
-} from "metabase-enterprise/api/ai-streaming/test-utils";
-import type { User } from "metabase-types/api";
-import {
- createMockTokenFeatures,
- createMockUser,
-} from "metabase-types/api/mocks";
-import { createMockState } from "metabase-types/store/mocks";
-
-import { Metabot } from "./components/Metabot";
-import { FIXED_METABOT_IDS, METABOT_ERR_MSG } from "./constants";
-import { MetabotProvider } from "./context";
-import {
- type MetabotState,
- getHistory,
- getMetabotInitialState,
- getMetabotState,
- metabotReducer,
-} from "./state";
-
-const mockAgentEndpoint = (params: MockStreamedEndpointParams) =>
- mockStreamedEndpoint("/api/ee/metabot-v3/v2/agent-streaming", params);
-
-function setup(
- options: {
- ui?: React.ReactElement;
- metabotPluginInitialState?: MetabotState;
- currentUser?: User | null | undefined;
- promptSuggestions?: { prompt: string }[];
- } | void,
-) {
- const settings = mockSettings({
- "token-features": createMockTokenFeatures({
- metabot_v3: true,
- }),
- });
-
- setupEnterprisePlugins();
-
- const {
- ui = <Metabot />,
- currentUser = createMockUser(),
- metabotPluginInitialState = {
- ...getMetabotInitialState(),
- visible: true,
- useStreaming: true,
- },
- promptSuggestions = [],
- } = options || {};
-
- fetchMock.get(
- `path:/api/ee/metabot-v3/metabot/${FIXED_METABOT_IDS.DEFAULT}/prompt-suggestions`,
- { prompts: promptSuggestions, offset: 0, limit: 3, total: 3 },
- );
-
- return renderWithProviders(<MetabotProvider>{ui}</MetabotProvider>, {
- storeInitialState: createMockState({
- settings,
- currentUser: currentUser ? currentUser : undefined,
- plugins: {
- metabotPlugin: metabotPluginInitialState,
- },
- } as any),
- customReducers: {
- plugins: combineReducers({
- metabotPlugin: metabotReducer,
- }),
- },
- });
-}
-
-const chatMessages = () => screen.findAllByTestId("metabot-chat-message");
-const lastChatMessage = async () => (await chatMessages()).at(-1);
-const input = () => screen.findByTestId("metabot-chat-input");
-const enterChatMessage = async (message: string, send = true) =>
- userEvent.type(await input(), `${message}${send ? "{Enter}" : ""}`);
-const responseLoader = () => screen.findByTestId("metabot-response-loader");
-const resetChatButton = () => screen.findByTestId("metabot-reset-chat");
-
-const assertVisible = async () =>
- expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();
-
-const assertConversation = async (
- expectedMessages: ["user" | "agent", string][],
-) => {
- if (!expectedMessages.length) {
- await waitFor(() => {
- expect(
- screen.queryByTestId("metabot-chat-message"),
- ).not.toBeInTheDocument();
- });
- } else {
- const realMessages = await chatMessages();
- expect(expectedMessages.length).toBe(realMessages.length);
- expectedMessages.forEach(([expectedRole, expectedMessage], index) => {
- const realMessage = realMessages[index];
- expect(realMessage).toHaveAttribute("data-message-role", expectedRole);
- expect(realMessage).toHaveTextContent(expectedMessage);
- });
- }
-};
-
-const lastReqBody = async (agentSpy: ReturnType<typeof mockAgentEndpoint>) => {
- await waitFor(() => expect(agentSpy).toHaveBeenCalled());
- return JSON.parse(agentSpy.mock.lastCall?.[1]?.body as string);
-};
-
-describe("metabot-streaming", () => {
- describe("ui", () => {
- it("should be able to render metabot", async () => {
- setup();
- await assertVisible();
- });
-
- it("should show empty state ui if conversation is empty", async () => {
- setup();
- mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
-
- expect(
- await screen.findByTestId("metabot-empty-chat-info"),
- ).toBeInTheDocument();
-
- await enterChatMessage("Who is your favorite?");
- expect(
- await screen.findByText("Who is your favorite?"),
- ).toBeInTheDocument();
-
- expect(
- screen.queryByTestId("metabot-empty-chat-info"),
- ).not.toBeInTheDocument();
- });
-
- it("should render markdown for metabot's replies", async () => {
- setup();
- mockAgentEndpoint({
- textChunks: [
- `0:"# You, but don't tell anyone."`,
- `2:{"type":"state","version":1,"value":{"queries":{}}}`,
- `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
- ],
- });
- await enterChatMessage("Who is your favorite?");
-
- const heading = await screen.findByRole("heading", { level: 1 });
- expect(heading).toBeInTheDocument();
- expect(heading).toHaveTextContent(`You, but don't tell anyone.`);
- });
-
- it("should present the user an option to retry a response", async () => {
- setup();
- mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
-
- await enterChatMessage("Who is your favorite?");
- const lastMessage = await lastChatMessage();
- expect(lastMessage).toHaveTextContent(/You, but don't tell anyone./);
- expect(
- await within(lastMessage!).findByTestId("metabot-chat-message-retry"),
- ).toBeInTheDocument();
- });
-
- it("should successfully rewind a response", async () => {
- setup();
- mockAgentEndpoint({
- // add two messages to ensure we rollback both
- textChunks: [`0:"Let me think..."`, ...whoIsYourFavoriteResponse],
- });
- await enterChatMessage("Who is your favorite?");
-
- const beforeMessages = await screen.findByTestId("metabot-chat-messages");
- expect(beforeMessages).toHaveTextContent(/Let me think.../);
- expect(beforeMessages).toHaveTextContent(/You, but don't tell anyone./);
-
- mockAgentEndpoint({
- textChunks: [
- `0:"The answer is always you."`,
- `2:{"type":"state","version":1,"value":{"queries":{}}}`,
- `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
- ],
- });
- await userEvent.click(
- await screen.findByTestId("metabot-chat-message-retry"),
- );
-
- const afterMessages = await screen.findByTestId("metabot-chat-messages");
-
- // rolled back both messages
- expect(afterMessages).not.toHaveTextContent(/Let me think.../);
- expect(afterMessages).not.toHaveTextContent(
- /You, but don't tell anyone./,
- );
-
- // shows the new one
- expect(afterMessages).toHaveTextContent(/The answer is always you./);
- });
-
- it("should not show retry option for error messages", async () => {
- setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
-
- await enterChatMessage("Who is your favorite?");
-
- const lastMessage = await lastChatMessage();
- expect(lastMessage).toHaveTextContent(METABOT_ERR_MSG.agentOffline);
- expect(
- within(lastMessage!).queryByTestId("metabot-chat-message-retry"),
- ).not.toBeInTheDocument();
- });
- });
-
- describe("message", () => {
- it("should properly send chat messages", async () => {
- setup();
-
- mockAgentEndpoint(
- { textChunks: whoIsYourFavoriteResponse, initialDelay: 50 }, // small delay to cause loading state
- );
-
- await enterChatMessage("Who is your favorite?", false);
- expect(await input()).toHaveValue("Who is your favorite?");
-
- await enterChatMessage("Who is your favorite?");
- expect(await responseLoader()).toBeInTheDocument();
- expect(
- await screen.findByText("You, but don't tell anyone."),
- ).toBeInTheDocument();
-
- // should auto-clear input + refocus
- expect(await input()).toHaveValue("");
- expect(await input()).toHaveFocus();
- });
-
- it("should properly handle partial messages", async () => {
- setup();
-
- const [pause1] = createPauses(2);
- mockAgentEndpoint({
- stream: createMockReadableStream(
- (async function* () {
- yield `0:"You, but "\n`;
- await pause1.promise;
- yield `0:"don't tell anyone."\n`;
- yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
- })(),
- ),
- });
-
- await enterChatMessage("Who is your favorite?");
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", "You, but"],
- ]);
-
- pause1.resolve();
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", "You, but don't tell anyone."],
- ]);
- });
- });
-
- describe("tool calls", () => {
- it("should show list each tool being called as it comes in and cleared when finished", async () => {
- setup();
-
- const [pause1, pause2] = createPauses(2);
- mockAgentEndpoint({
- stream: createMockReadableStream(
- (async function* () {
- yield `9:{"toolCallId":"x","toolName":"analyze_data","args":""}\n`;
- yield `a:{"toolCallId":"x","result":""}\n`;
- await pause1.promise;
- yield `9:{"toolCallId":"y","toolName":"analyze_chart","args":""}\n`;
- yield `a:{"toolCallId":"y","result":""}\n`;
- await pause2.promise;
- yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
- })(),
- ),
- });
-
- await enterChatMessage("Analyze this query");
-
- // should show first tool call
- expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
- expect(
- screen.queryByText("Inspecting the visualization"),
- ).not.toBeInTheDocument();
-
- pause1.resolve();
-
- // should show both tool calls
- expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
- expect(
- await screen.findByText("Inspecting the visualization"),
- ).toBeInTheDocument();
-
- pause2.resolve();
-
- // should clear tool call notifications at end of request
- await waitFor(() => {
- expect(
- screen.queryByText("Analyzing the data"),
- ).not.toBeInTheDocument();
- });
- await waitFor(() => {
- expect(
- screen.queryByText("Inspecting the visualization"),
- ).not.toBeInTheDocument();
- });
- });
-
- it("should clear out list of tool calls when new text comes in", async () => {
- setup();
-
- const [pause1, pause2, pause3] = createPauses(3);
- mockAgentEndpoint({
- stream: createMockReadableStream(
- (async function* () {
- yield `9:{"toolCallId":"x","toolName":"analyze_data","args":""}\n`;
- yield `a:{"toolCallId":"x","result":""}\n`;
- await pause1.promise;
- yield `0:"Hey."`;
- await pause2.promise;
- yield `9:{"toolCallId":"y","toolName":"analyze_chart","args":""}\n`;
- yield `a:{"toolCallId":"y","result":""}\n`;
- await pause3.promise;
- yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
- })(),
- ),
- });
-
- await enterChatMessage("Analyze this query");
-
- // should show first tool call
- expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
- expect(
- screen.queryByText("Inspecting the visualization"),
- ).not.toBeInTheDocument();
-
- pause1.resolve();
-
- // should not show any tool calls, only the new text
- await waitFor(() => {
- expect(
- screen.queryByText("Analyzing the data"),
- ).not.toBeInTheDocument();
- });
- expect(screen.getByText("Hey.")).toBeInTheDocument();
- await waitFor(() => {
- expect(
- screen.queryByText("Inspecting the visualization"),
- ).not.toBeInTheDocument();
- });
-
- pause2.resolve();
-
- // expect text and new tool call to be in the document
- expect(await screen.findByText("Hey.")).toBeInTheDocument();
- expect(
- await screen.findByText("Inspecting the visualization"),
- ).toBeInTheDocument();
- expect(screen.queryByText("Analyzing the data")).not.toBeInTheDocument();
-
- pause3.resolve();
-
- await waitFor(async () => {
- await assertConversation([
- ["user", "Analyze this query"],
- ["agent", "Hey."],
- ]);
- });
- });
-
- it("should start a new message if there's tool calls between streamed text parts", async () => {
- setup();
- mockAgentEndpoint(
- {
- textChunks: [
- `0:"Response 1"`,
- `9:{"toolCallId":"x","toolName":"x","args":""}`,
- `a:{"toolCallId":"x","result":""}`,
- `0:"Response 2"`,
- `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
- ],
- }, // small delay to cause loading state
- );
- await enterChatMessage("Request");
-
- await assertConversation([
- ["user", "Request"],
- ["agent", "Response 1"],
- ["agent", "Response 2"],
- ]);
- });
- });
-
- describe("errors", () => {
- it("should handle service error response", async () => {
- setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
-
- await enterChatMessage("Who is your favorite?");
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", METABOT_ERR_MSG.agentOffline],
- ]);
- expect(await input()).toHaveValue("Who is your favorite?");
- });
-
- it("should handle non-successful responses", async () => {
- setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 400);
-
- await enterChatMessage("Who is your favorite?");
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", METABOT_ERR_MSG.default],
- ]);
- expect(await input()).toHaveValue("Who is your favorite?");
- });
-
- it("should handle show error if data error part is in response", async () => {
- setup();
- mockAgentEndpoint({ textChunks: erroredResponse });
-
- await enterChatMessage("Who is your favorite?");
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", METABOT_ERR_MSG.default],
- ]);
- expect(await input()).toHaveValue("Who is your favorite?");
- });
-
- it("should not show a user error when an AbortError is triggered", async () => {
- setup();
- mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
-
- await enterChatMessage("Who is your favorite?");
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", "You, but don't tell anyone."],
- ]);
-
- await userEvent.click(await resetChatButton());
-
- await assertConversation([]);
- expect(await input()).toHaveValue("");
- });
-
- it("should remove previous error messages and prompt when submiting next prompt", async () => {
- setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
-
- await enterChatMessage("Who is your favorite?");
-
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", METABOT_ERR_MSG.agentOffline],
- ]);
- expect(await input()).toHaveValue("Who is your favorite?");
-
- mockAgentEndpoint({
- textChunks: whoIsYourFavoriteResponse,
- });
- await enterChatMessage("Who is your favorite?");
- await assertConversation([
- ["user", "Who is your favorite?"],
- ["agent", "You, but don't tell anyone."],
- ]);
- });
- });
-
- describe("context", () => {
- it("should send along default context", async () => {
- setup();
- const agentSpy = mockAgentEndpoint({
- textChunks: whoIsYourFavoriteResponse,
- });
-
- await enterChatMessage("Who is your favorite?");
-
- expect(
- isMatching(
- { current_time_with_timezone: P.string },
- (await lastReqBody(agentSpy))?.context,
- ),
- ).toEqual(true);
- });
- });
-
- describe("convo state", () => {
- it("should update the convo state on a successful request", async () => {
- const { store } = setup();
- // TODO: make enterprise store
- const getState = () => getMetabotState(store.getState() as any);
-
- mockAgentEndpoint({
- stream: createMockReadableStream(
- (async function* () {
- yield `2:{"type":"state","version":1,"value":{"queries":{}}}\n`;
- // assert that state hasn't been updated mid-response
- expect(getState()).toEqual({});
- yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
- })(),
- ),
- });
-
- expect(getState()).toEqual({});
- await enterChatMessage("Request");
- expect(getState()).toEqual({ queries: {} });
- });
-
- it("should not update the convo state on a failed request", async () => {
- const { store } = setup();
- // TODO: make enterprise store
- const getState = () => getMetabotState(store.getState() as any);
-
- mockAgentEndpoint({
- textChunks: [
- `2:{"type":"state","version":1,"value":{"queries":{}}}`,
- ...erroredResponse,
- ],
- });
-
- expect(getState()).toEqual({});
- await enterChatMessage("Request");
- expect(getState()).toEqual({});
- });
- });
-
- describe("history", () => {
- it("should send conversation history along with future messages", async () => {
- setup();
-
- // create some chat history + wait for a response
- mockAgentEndpoint({
- textChunks: whoIsYourFavoriteResponse,
- initialDelay: 50,
- });
- await enterChatMessage("Who is your favorite?");
- expect(
- await screen.findByText("You, but don't tell anyone."),
- ).toBeInTheDocument();
-
- // send another message and check that the proper history is being sent along
- const agentSpy2 = mockAgentEndpoint({
- textChunks: [], // next response doesn't matter
- });
- await enterChatMessage("Hi!");
- const reqBody = await lastReqBody(agentSpy2);
- expect(reqBody?.history).toEqual([
- { content: "Who is your favorite?", role: "user" },
- { content: "You, but don't tell anyone.", role: "assistant" },
- ]);
- });
-
- it("should merge text chunks in the history", async () => {
- const { store } = setup();
- mockAgentEndpoint({
- textChunks: [
- `0:"You, but "`,
- `0:"don't tell anyone."`,
- `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
- ],
- });
-
- const initialHistory = getHistory(store.getState() as any);
- expect(initialHistory).toEqual([]);
-
- await enterChatMessage("Who is your favorite?");
-
- const finalHistory = getHistory(store.getState() as any);
- expect(finalHistory).toHaveLength(2);
- expect(finalHistory[0].role).toBe("user");
- expect(finalHistory[0].content).toBe("Who is your favorite?");
- expect(finalHistory[1].role).toBe("assistant");
- expect(finalHistory[1].content).toBe("You, but don't tell anyone.");
- });
- });
-});
-
-const whoIsYourFavoriteResponse = [
- `0:"You, but don't tell anyone."`,
- `2:{"type":"state","version":1,"value":{"queries":{}}}`,
- `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
-];
-
-const erroredResponse = [
- `3:{"type": "error", "value": "Couldn't do the thing"}`,
- `d:{"finishReason":"error","usage":{"promptTokens":4916,"completionTokens":8}}`,
-];
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
index b89149d8ede..431d988b399 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
@@ -16,7 +16,13 @@ import {
import { logout } from "metabase/auth/actions";
import * as domModule from "metabase/lib/dom";
import { useRegisterMetabotContextProvider } from "metabase/metabot";
-import type { SuggestedMetabotPrompt, User } from "metabase-types/api";
+import {
+ type MockStreamedEndpointParams,
+ createMockReadableStream,
+ createPauses,
+ mockStreamedEndpoint,
+} from "metabase-enterprise/api/ai-streaming/test-utils";
+import type { User } from "metabase-types/api";
import {
createMockTokenFeatures,
createMockUser,
@@ -34,18 +40,24 @@ import { useMetabotAgent } from "./hooks";
import {
type MetabotState,
addUserMessage,
+ getHistory,
+ getMetabot,
getMetabotConversationId,
getMetabotInitialState,
+ getMetabotState,
metabotReducer,
setVisible,
} from "./state";
+const mockAgentEndpoint = (params: MockStreamedEndpointParams) =>
+ mockStreamedEndpoint("/api/ee/metabot-v3/v2/agent-streaming", params);
+
function setup(
options: {
ui?: React.ReactElement;
metabotPluginInitialState?: MetabotState;
currentUser?: User | null | undefined;
- promptSuggestions?: SuggestedMetabotPrompt[];
+ promptSuggestions?: { prompt: string }[];
} | void,
) {
const settings = mockSettings({
@@ -62,7 +74,7 @@ function setup(
metabotPluginInitialState = {
...getMetabotInitialState(),
visible: true,
- useStreaming: false,
+ useStreaming: true,
},
promptSuggestions = [],
} = options || {};
@@ -95,8 +107,8 @@ const input = () => screen.findByTestId("metabot-chat-input");
const enterChatMessage = async (message: string, send = true) =>
userEvent.type(await input(), `${message}${send ? "{Enter}" : ""}`);
const closeChatButton = () => screen.findByTestId("metabot-close-chat");
-const resetChatButton = () => screen.findByTestId("metabot-reset-chat");
const responseLoader = () => screen.findByTestId("metabot-response-loader");
+const resetChatButton = () => screen.findByTestId("metabot-reset-chat");
const assertVisible = async () =>
expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();
@@ -109,16 +121,32 @@ const assertNotVisible = async () =>
const hideMetabot = (dispatch: any) => act(() => dispatch(setVisible(false)));
const showMetabot = (dispatch: any) => act(() => dispatch(setVisible(true)));
-const getMetabotState = (store: any) => store.getState().plugins.metabotPlugin;
+const assertConversation = async (
+ expectedMessages: ["user" | "agent", string][],
+) => {
+ if (!expectedMessages.length) {
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("metabot-chat-message"),
+ ).not.toBeInTheDocument();
+ });
+ } else {
+ const realMessages = await chatMessages();
+ expect(expectedMessages.length).toBe(realMessages.length);
+ expectedMessages.forEach(([expectedRole, expectedMessage], index) => {
+ const realMessage = realMessages[index];
+ expect(realMessage).toHaveAttribute("data-message-role", expectedRole);
+ expect(realMessage).toHaveTextContent(expectedMessage);
+ });
+ }
+};
-const lastReqBody = async () => {
- const calls = fetchMock.callHistory.calls();
- const lastCall = calls[calls.length - 1];
- const bodyStr = String(await lastCall?.options?.body) || "";
- return JSON.parse(bodyStr);
+const lastReqBody = async (agentSpy: ReturnType<typeof mockAgentEndpoint>) => {
+ await waitFor(() => expect(agentSpy).toHaveBeenCalled());
+ return JSON.parse(agentSpy.mock.lastCall?.[1]?.body as string);
};
-describe("metabot", () => {
+describe("metabot-streaming", () => {
describe("ui", () => {
it("should be able to render metabot", async () => {
setup();
@@ -134,10 +162,7 @@ describe("metabot", () => {
it("should show empty state ui if conversation is empty", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
expect(
await screen.findByTestId("metabot-empty-chat-info"),
@@ -220,122 +245,92 @@ describe("metabot", () => {
}
});
+ it("should not render markdown for user messages", async () => {
+ setup();
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
+
+ const msg = "# Who is your favorite?";
+ await enterChatMessage(msg);
+ expect(await screen.findByText(msg)).toBeInTheDocument();
+ expect(
+ screen.queryByRole("heading", { level: 1 }),
+ ).not.toBeInTheDocument();
+ });
+
it("should render markdown for metabot's replies", async () => {
setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent`, {
- ...whoIsYourFavoriteResponse,
- reactions: [
- {
- type: "metabot.reaction/message",
- message: "# You are... but don't tell anyone!",
- },
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"# You, but don't tell anyone."`,
+ `2:{"type":"state","version":1,"value":{"queries":{}}}`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
],
});
await enterChatMessage("Who is your favorite?");
const heading = await screen.findByRole("heading", { level: 1 });
expect(heading).toBeInTheDocument();
- expect(heading).toHaveTextContent(`You are... but don't tell anyone!`);
+ expect(heading).toHaveTextContent(`You, but don't tell anyone.`);
});
- it("should not render markdown for user messages", async () => {
+ it("should present the user an option to retry a response", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
- const msg = "# Who is your favorite?";
- await enterChatMessage(msg);
- expect(await screen.findByText(msg)).toBeInTheDocument();
+ await enterChatMessage("Who is your favorite?");
+ const lastMessage = await lastChatMessage();
+ expect(lastMessage).toHaveTextContent(/You, but don't tell anyone./);
expect(
- screen.queryByRole("heading", { level: 1 }),
- ).not.toBeInTheDocument();
+ await within(lastMessage!).findByTestId("metabot-chat-message-retry"),
+ ).toBeInTheDocument();
});
- it("should provide prompt suggestions if available", async () => {
- const prompts = [
- {
- id: 1,
- metabot_id: 1,
- prompt: "What is the total revenue for this quarter?",
- model: "metric" as const,
- model_id: 1,
- model_name: "Quarterly Revenue Calculator",
- created_at: "2025-05-15T10:30:00Z",
- updated_at: "2025-05-15T10:30:00Z",
- },
- {
- id: 2,
- metabot_id: 1,
- prompt:
- "Show me the customer acquisition trends over the last 6 months",
- model: "model" as const,
- model_id: 2,
- model_name: "Customer Acquisition Trend Analyzer",
- created_at: "2025-05-15T11:15:00Z",
- updated_at: "2025-05-15T11:15:00Z",
- },
- {
- id: 3,
- metabot_id: 1,
- prompt: "What are our top performing products by sales volume?",
- model: "metric" as const,
- model_id: 3,
- model_name: "Product Performance Ranking",
- created_at: "2025-05-15T14:22:00Z",
- updated_at: "2025-05-16T09:45:00Z",
- },
- ];
- setup({ promptSuggestions: prompts });
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ it("should successfully rewind a response", async () => {
+ setup();
+ mockAgentEndpoint({
+ // add two messages to ensure we rollback both
+ textChunks: [`0:"Let me think..."`, ...whoIsYourFavoriteResponse],
+ });
+ await enterChatMessage("Who is your favorite?");
- // should render prompts
- expect(
- await screen.findByTestId("metabot-prompt-suggestions"),
- ).toBeInTheDocument();
- expect(await screen.findByText(prompts[0].prompt)).toBeInTheDocument();
- const prompt1 = await screen.findByText(prompts[1].prompt);
- expect(prompt1).toBeInTheDocument();
+ const beforeMessages = await screen.findByTestId("metabot-chat-messages");
+ expect(beforeMessages).toHaveTextContent(/Let me think.../);
+ expect(beforeMessages).toHaveTextContent(/You, but don't tell anyone./);
- // user should be able to click prompts to start a new convo
- await userEvent.click(prompt1);
- await waitFor(async () => {
- expect(
- fetchMock.callHistory.calls(`path:/api/ee/metabot-v3/v2/agent`),
- ).toHaveLength(1);
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"The answer is always you."`,
+ `2:{"type":"state","version":1,"value":{"queries":{}}}`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+ ],
});
+ await userEvent.click(
+ await screen.findByTestId("metabot-chat-message-retry"),
+ );
- // unclicked prompts should be gone, but clicked prompt should be in convo
- expect(await screen.findByText(prompts[1].prompt)).toBeInTheDocument();
- expect(screen.queryByText(prompts[0].prompt)).not.toBeInTheDocument();
- expect(
- screen.queryByTestId("metabot-prompt-suggestions"),
- ).not.toBeInTheDocument();
+ const afterMessages = await screen.findByTestId("metabot-chat-messages");
+
+ // rolled back both messages
+ expect(afterMessages).not.toHaveTextContent(/Let me think.../);
+ expect(afterMessages).not.toHaveTextContent(
+ /You, but don't tell anyone./,
+ );
+
+ // shows the new one
+ expect(afterMessages).toHaveTextContent(/The answer is always you./);
});
- it("should make a request for new suggested prompts when the conversation is reset", async () => {
- setup({ promptSuggestions: [] });
- await waitFor(async () => {
- expect(
- fetchMock.callHistory.calls(
- `path:/api/ee/metabot-v3/metabot/1/prompt-suggestions`,
- ),
- ).toHaveLength(1);
- });
+ it("should not show retry option for error messages", async () => {
+ setup();
+ fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
- await userEvent.click(await resetChatButton());
+ await enterChatMessage("Who is your favorite?");
- await waitFor(async () => {
- expect(
- fetchMock.callHistory.calls(
- `path:/api/ee/metabot-v3/metabot/1/prompt-suggestions`,
- ),
- ).toHaveLength(2);
- });
+ const lastMessage = await lastChatMessage();
+ expect(lastMessage).toHaveTextContent(METABOT_ERR_MSG.agentOffline);
+ expect(
+ within(lastMessage!).queryByTestId("metabot-chat-message-retry"),
+ ).not.toBeInTheDocument();
});
it("should be able to set the prompt input's value from anywhere in the app", async () => {
@@ -361,21 +356,88 @@ describe("metabot", () => {
expect(await input()).toHaveValue("TEST VAL");
});
- it("should not present the user an option to retry a prompt (not yet supported)", async () => {
- setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ describe("prompt-suggestions", () => {
+ it("should provide prompt suggestions if available", async () => {
+ const prompts = [
+ {
+ id: 1,
+ metabot_id: 1,
+ prompt: "What is the total revenue for this quarter?",
+ model: "metric" as const,
+ model_id: 1,
+ model_name: "Quarterly Revenue Calculator",
+ created_at: "2025-05-15T10:30:00Z",
+ updated_at: "2025-05-15T10:30:00Z",
+ },
+ {
+ id: 2,
+ metabot_id: 1,
+ prompt:
+ "Show me the customer acquisition trends over the last 6 months",
+ model: "model" as const,
+ model_id: 2,
+ model_name: "Customer Acquisition Trend Analyzer",
+ created_at: "2025-05-15T11:15:00Z",
+ updated_at: "2025-05-15T11:15:00Z",
+ },
+ {
+ id: 3,
+ metabot_id: 1,
+ prompt: "What are our top performing products by sales volume?",
+ model: "metric" as const,
+ model_id: 3,
+ model_name: "Product Performance Ranking",
+ created_at: "2025-05-15T14:22:00Z",
+ updated_at: "2025-05-16T09:45:00Z",
+ },
+ ];
+ setup({ promptSuggestions: prompts });
+ const agentSpy = mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
- await enterChatMessage("Who is your favorite?");
- const lastMessage = await lastChatMessage();
- expect(lastMessage).toHaveTextContent(
- /You are... but don't tell anyone!/,
- );
- expect(
- within(lastMessage!).queryByTestId("metabot-chat-message-retry"),
- ).not.toBeInTheDocument();
+ // should render prompts
+ expect(
+ await screen.findByTestId("metabot-prompt-suggestions"),
+ ).toBeInTheDocument();
+ expect(await screen.findByText(prompts[0].prompt)).toBeInTheDocument();
+ const prompt1 = await screen.findByText(prompts[1].prompt);
+ expect(prompt1).toBeInTheDocument();
+
+ // user should be able to click prompts to start a new convo
+ await userEvent.click(prompt1);
+ await waitFor(async () => {
+ expect(agentSpy).toHaveBeenCalledTimes(1);
+ });
+
+ // unclicked prompts should be gone, but clicked prompt should be in convo
+ expect(await screen.findByText(prompts[1].prompt)).toBeInTheDocument();
+ expect(screen.queryByText(prompts[0].prompt)).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("metabot-prompt-suggestions"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should make a request for new suggested prompts when the conversation is reset", async () => {
+ setup({ promptSuggestions: [] });
+ await waitFor(async () => {
+ expect(
+ fetchMock.callHistory.calls(
+ `path:/api/ee/metabot-v3/metabot/1/prompt-suggestions`,
+ ),
+ ).toHaveLength(1);
+ });
+
+ await userEvent.click(await resetChatButton());
+
+ await waitFor(async () => {
+ expect(
+ fetchMock.callHistory.calls(
+ `path:/api/ee/metabot-v3/metabot/1/prompt-suggestions`,
+ ),
+ ).toHaveLength(2);
+ });
+ });
});
});
@@ -388,10 +450,9 @@ describe("metabot", () => {
it("should properly send chat messages", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- { delay: 50 }, // small delay to cause loading state
+
+ mockAgentEndpoint(
+ { textChunks: whoIsYourFavoriteResponse, initialDelay: 50 }, // small delay to cause loading state
);
await enterChatMessage("Who is your favorite?", false);
@@ -400,84 +461,280 @@ describe("metabot", () => {
await enterChatMessage("Who is your favorite?");
expect(await responseLoader()).toBeInTheDocument();
expect(
- await screen.findByText("You are... but don't tell anyone!"),
+ await screen.findByText("You, but don't tell anyone."),
).toBeInTheDocument();
// should auto-clear input + refocus
expect(await input()).toHaveValue("");
expect(await input()).toHaveFocus();
});
+
+ it("should properly handle partial messages", async () => {
+ setup();
+
+ const [pause1] = createPauses(2);
+ mockAgentEndpoint({
+ stream: createMockReadableStream(
+ (async function* () {
+ yield `0:"You, but "\n`;
+ await pause1.promise;
+ yield `0:"don't tell anyone."\n`;
+ yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
+ })(),
+ ),
+ });
+
+ await enterChatMessage("Who is your favorite?");
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", "You, but"],
+ ]);
+
+ pause1.resolve();
+
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", "You, but don't tell anyone."],
+ ]);
+ });
+ });
+
+ describe("tool calls", () => {
+ it("should show list each tool being called as it comes in and cleared when finished", async () => {
+ setup();
+
+ const [pause1, pause2] = createPauses(2);
+ mockAgentEndpoint({
+ stream: createMockReadableStream(
+ (async function* () {
+ yield `9:{"toolCallId":"x","toolName":"analyze_data","args":""}\n`;
+ yield `a:{"toolCallId":"x","result":""}\n`;
+ await pause1.promise;
+ yield `9:{"toolCallId":"y","toolName":"analyze_chart","args":""}\n`;
+ yield `a:{"toolCallId":"y","result":""}\n`;
+ await pause2.promise;
+ yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
+ })(),
+ ),
+ });
+
+ await enterChatMessage("Analyze this query");
+
+ // should show first tool call
+ expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Inspecting the visualization"),
+ ).not.toBeInTheDocument();
+
+ pause1.resolve();
+
+ // should show both tool calls
+ expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
+ expect(
+ await screen.findByText("Inspecting the visualization"),
+ ).toBeInTheDocument();
+
+ pause2.resolve();
+
+ // should clear tool call notifications at end of request
+ await waitFor(() => {
+ expect(
+ screen.queryByText("Analyzing the data"),
+ ).not.toBeInTheDocument();
+ });
+ await waitFor(() => {
+ expect(
+ screen.queryByText("Inspecting the visualization"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("should clear out list of tool calls when new text comes in", async () => {
+ setup();
+
+ const [pause1, pause2, pause3] = createPauses(3);
+ mockAgentEndpoint({
+ stream: createMockReadableStream(
+ (async function* () {
+ yield `9:{"toolCallId":"x","toolName":"analyze_data","args":""}\n`;
+ yield `a:{"toolCallId":"x","result":""}\n`;
+ await pause1.promise;
+ yield `0:"Hey."`;
+ await pause2.promise;
+ yield `9:{"toolCallId":"y","toolName":"analyze_chart","args":""}\n`;
+ yield `a:{"toolCallId":"y","result":""}\n`;
+ await pause3.promise;
+ yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
+ })(),
+ ),
+ });
+
+ await enterChatMessage("Analyze this query");
+
+ // should show first tool call
+ expect(await screen.findByText("Analyzing the data")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Inspecting the visualization"),
+ ).not.toBeInTheDocument();
+
+ pause1.resolve();
+
+ // should not show any tool calls, only the new text
+ await waitFor(() => {
+ expect(
+ screen.queryByText("Analyzing the data"),
+ ).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("Hey.")).toBeInTheDocument();
+ await waitFor(() => {
+ expect(
+ screen.queryByText("Inspecting the visualization"),
+ ).not.toBeInTheDocument();
+ });
+
+ pause2.resolve();
+
+ // expect text and new tool call to be in the document
+ expect(await screen.findByText("Hey.")).toBeInTheDocument();
+ expect(
+ await screen.findByText("Inspecting the visualization"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Analyzing the data")).not.toBeInTheDocument();
+
+ pause3.resolve();
+
+ await waitFor(async () => {
+ await assertConversation([
+ ["user", "Analyze this query"],
+ ["agent", "Hey."],
+ ]);
+ });
+ });
+
+ it("should start a new message if there's tool calls between streamed text parts", async () => {
+ setup();
+ mockAgentEndpoint(
+ {
+ textChunks: [
+ `0:"Response 1"`,
+ `9:{"toolCallId":"x","toolName":"x","args":""}`,
+ `a:{"toolCallId":"x","result":""}`,
+ `0:"Response 2"`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+ ],
+ }, // small delay to cause loading state
+ );
+ await enterChatMessage("Request");
+
+ await assertConversation([
+ ["user", "Request"],
+ ["agent", "Response 1"],
+ ["agent", "Response 2"],
+ ]);
+ });
});
describe("errors", () => {
it("should handle service error response", async () => {
setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent`, 500);
+ fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
await enterChatMessage("Who is your favorite?");
- expect(await lastChatMessage()).toHaveTextContent(
- METABOT_ERR_MSG.agentOffline,
- );
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", METABOT_ERR_MSG.agentOffline],
+ ]);
expect(await input()).toHaveValue("Who is your favorite?");
});
it("should handle non-successful responses", async () => {
setup();
- fetchMock.post(`path:/api/ee/metabot-v3/v2/agent`, 400);
+ fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 400);
await enterChatMessage("Who is your favorite?");
- expect(await lastChatMessage()).toHaveTextContent(
- METABOT_ERR_MSG.default,
- );
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", METABOT_ERR_MSG.default],
+ ]);
+ expect(await input()).toHaveValue("Who is your favorite?");
+ });
+
+ it("should handle show error if data error part is in response", async () => {
+ setup();
+ mockAgentEndpoint({ textChunks: erroredResponse });
+
+ await enterChatMessage("Who is your favorite?");
+
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", METABOT_ERR_MSG.default],
+ ]);
expect(await input()).toHaveValue("Who is your favorite?");
});
it("should not show a user error when an AbortError is triggered", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- { delay: 50 }, // small delay to cause loading state
- );
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
await enterChatMessage("Who is your favorite?");
- expect(await chatMessages()).toHaveLength(1);
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", "You, but don't tell anyone."],
+ ]);
+
await userEvent.click(await resetChatButton());
- await waitFor(() => {
- expect(
- screen.queryByTestId("metabot-chat-message"),
- ).not.toBeInTheDocument();
- });
+
+ await assertConversation([]);
expect(await input()).toHaveValue("");
});
+
+ it("should remove previous error messages and prompt when submiting next prompt", async () => {
+ setup();
+ fetchMock.post(`path:/api/ee/metabot-v3/v2/agent-streaming`, 500);
+
+ await enterChatMessage("Who is your favorite?");
+
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", METABOT_ERR_MSG.agentOffline],
+ ]);
+ expect(await input()).toHaveValue("Who is your favorite?");
+
+ mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
+ await enterChatMessage("Who is your favorite?");
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", "You, but don't tell anyone."],
+ ]);
+ });
});
describe("context", () => {
it("should send along default context", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ const agentSpy = mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
await enterChatMessage("Who is your favorite?");
expect(
isMatching(
{ current_time_with_timezone: P.string },
- (await lastReqBody())?.context,
+ (await lastReqBody(agentSpy))?.context,
),
).toEqual(true);
});
it("should allow components to register additional context", async () => {
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ const agentSpy = mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
const TestComponent = () => {
useRegisterMetabotContextProvider(
@@ -507,91 +764,147 @@ describe("metabot", () => {
current_time_with_timezone: P.string,
user_is_viewing: [{ type: "dashboard", id: 1 }],
},
- (await lastReqBody())?.context,
+ (await lastReqBody(agentSpy))?.context,
),
).toBe(true);
});
});
+ describe("convo state", () => {
+ it("should update the convo state on a successful request", async () => {
+ const { store } = setup();
+ // TODO: make enterprise store
+ const getState = () => getMetabotState(store.getState() as any);
+
+ mockAgentEndpoint({
+ stream: createMockReadableStream(
+ (async function* () {
+ yield `2:{"type":"state","version":1,"value":{"queries":{}}}\n`;
+ // assert that state hasn't been updated mid-response
+ expect(getState()).toEqual({});
+ yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
+ })(),
+ ),
+ });
+
+ expect(getState()).toEqual({});
+ await enterChatMessage("Request");
+ expect(getState()).toEqual({ queries: {} });
+ });
+
+ it("should not update the convo state on a failed request", async () => {
+ const { store } = setup();
+ // TODO: make enterprise store
+ const getState = () => getMetabotState(store.getState() as any);
+
+ mockAgentEndpoint({
+ textChunks: [
+ `2:{"type":"state","version":1,"value":{"queries":{}}}`,
+ ...erroredResponse,
+ ],
+ });
+
+ expect(getState()).toEqual({});
+ await enterChatMessage("Request");
+ expect(getState()).toEqual({});
+ });
+ });
+
describe("history", () => {
- it("should send history from last response along with next message", async () => {
+ it("should send conversation history along with future messages", async () => {
setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
- // send a message to get some history back
+ // create some chat history + wait for a response
+ mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ initialDelay: 50,
+ });
await enterChatMessage("Who is your favorite?");
- await waitFor(() =>
- expect(
- fetchMock.callHistory.calls(`path:/api/ee/metabot-v3/v2/agent`),
- ).toHaveLength(1),
- );
+ expect(
+ await screen.findByText("You, but don't tell anyone."),
+ ).toBeInTheDocument();
- // send another message and check that there is proper history
+ // send another message and check that the proper history is being sent along
+ const agentSpy = mockAgentEndpoint({
+ textChunks: [], // next response doesn't matter
+ });
await enterChatMessage("Hi!");
- const lastCall = fetchMock.callHistory.lastCall();
- const bodyStr = String(lastCall?.response?.body) || "";
- const sentHistory = JSON.parse(bodyStr)?.history;
- expect(sentHistory).toEqual(whoIsYourFavoriteResponse.history);
+ const reqBody = await lastReqBody(agentSpy);
+ expect(reqBody?.history).toEqual([
+ { content: "Who is your favorite?", role: "user" },
+ { content: "You, but don't tell anyone.", role: "assistant" },
+ ]);
});
it("should not clear history when metabot is hidden or opened", async () => {
const { store } = setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ const agentSpy = mockAgentEndpoint({
+ textChunks: whoIsYourFavoriteResponse,
+ });
// send a message to get some history back
await enterChatMessage("Who is your favorite?");
- await waitFor(() =>
- expect(
- fetchMock.callHistory.calls(`path:/api/ee/metabot-v3/v2/agent`),
- ).toHaveLength(1),
- );
+ await waitFor(() => expect(agentSpy).toHaveBeenCalledTimes(1));
// close, open, and then send another message and check that there is no history
hideMetabot(store.dispatch);
showMetabot(store.dispatch);
await enterChatMessage("Hi!");
- const lastCall = fetchMock.callHistory.lastCall();
- const bodyStr = String(lastCall?.response?.body) || "";
- const sentHistory = JSON.parse(bodyStr)?.history;
- expect(sentHistory).toEqual(whoIsYourFavoriteResponse.history);
+ const lastCall = agentSpy.mock.lastCall;
+ const reqBody = JSON.parse(String(lastCall?.[1]?.body));
+ const sentHistory = reqBody.history;
+ expect(sentHistory).not.toEqual([]);
+ });
+
+ it("should merge text chunks in the history", async () => {
+ const { store } = setup();
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"You, but "`,
+ `0:"don't tell anyone."`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+ ],
+ });
+
+ const initialHistory = getHistory(store.getState() as any);
+ expect(initialHistory).toEqual([]);
+
+ await enterChatMessage("Who is your favorite?");
+
+ const finalHistory = getHistory(store.getState() as any);
+ expect(finalHistory).toHaveLength(2);
+ expect(finalHistory[0].role).toBe("user");
+ expect(finalHistory[0].content).toBe("Who is your favorite?");
+ expect(finalHistory[1].role).toBe("assistant");
+ expect(finalHistory[1].content).toBe("You, but don't tell anyone.");
});
it("should clear history when the user hits the reset button", async () => {
const { store } = setup();
- fetchMock.post(
- `path:/api/ee/metabot-v3/v2/agent`,
- whoIsYourFavoriteResponse,
- );
+ const getState = () => getMetabot(store.getState() as any);
+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
// send a message to get some history back
await enterChatMessage("Who is your favorite?");
- await waitFor(() =>
- expect(
- fetchMock.callHistory.calls(`path:/api/ee/metabot-v3/v2/agent`),
- ).toHaveLength(1),
- );
+ await assertConversation([
+ ["user", "Who is your favorite?"],
+ ["agent", "You, but don't tell anyone."],
+ ]);
- const beforeResetState = getMetabotState(store);
+ const beforeResetState = getState();
expect(beforeResetState.conversationId).not.toBe(null);
- expect(beforeResetState.messages).toHaveLength(2);
expect(_.omit(beforeResetState.messages[0], "id")).toStrictEqual({
role: "user",
message: "Who is your favorite?",
});
expect(_.omit(beforeResetState.messages[1], "id")).toStrictEqual({
role: "agent",
- message: "You are... but don't tell anyone!",
+ message: "You, but don't tell anyone.",
});
await userEvent.click(await resetChatButton());
- const afterResetState = getMetabotState(store);
+ const afterResetState = getState();
expect(afterResetState.conversationId).not.toBe(
beforeResetState.conversationId,
);
@@ -631,38 +944,13 @@ describe("metabot", () => {
});
});
-const whoIsYourFavoriteResponse = {
- reactions: [
- {
- type: "metabot.reaction/message",
- message: "You are... but don't tell anyone!",
- },
- ],
- history: [
- {
- role: "user",
- content: "Who is your favorite?",
- },
- {
- content: "",
- role: "assistant",
- "tool-calls": [
- {
- id: "call_PVmnR8mcnYFF2AmqupSKzJDh",
- name: "who-is-your-favorite",
- arguments: {},
- },
- ],
- },
- {
- role: "tool",
- "tool-call-id": "call_PVmnR8mcnYFF2AmqupSKzJDh",
- content: "You are... but don't tell anyone!",
- },
- {
- content: "You are... but don't tell anyone!",
- role: "assistant",
- },
- ],
- state: {},
-};
+const whoIsYourFavoriteResponse = [
+ `0:"You, but don't tell anyone."`,
+ `2:{"type":"state","version":1,"value":{"queries":{}}}`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+];
+
+const erroredResponse = [
+ `3:{"type": "error", "value": "Couldn't do the thing"}`,
+ `d:{"finishReason":"error","usage":{"promptTokens":4916,"completionTokens":8}}`,
+];
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
index cb565e8361b..c6b01bd278c 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
@@ -4,11 +4,7 @@ import { P, match } from "ts-pattern";
import { createAsyncThunk } from "metabase/lib/redux";
import { getUser } from "metabase/selectors/user";
-import {
- EnterpriseApi,
- metabotAgent,
- metabotApi,
-} from "metabase-enterprise/api";
+import { EnterpriseApi } from "metabase-enterprise/api";
import {
type JSONValue,
aiStreamingQuery,
@@ -33,7 +29,6 @@ import {
getIsProcessing,
getLastMessage,
getMetabotConversationId,
- getUseStreaming,
getUserPromptForMessageId,
} from "./selectors";
import { createMessageId } from "./utils";
@@ -80,11 +75,6 @@ const handleResponseError = (error: unknown): PromptErrorOutcome => {
}));
};
-export const toggleStreaming = () => (dispatch: Dispatch) => {
- dispatch(resetConversation());
- dispatch(metabot.actions.toggleStreaming());
-};
-
export const setVisible =
(isVisible: boolean) => (dispatch: Dispatch, getState: any) => {
const currentUser = getUser(getState());
@@ -133,12 +123,8 @@ export const submitInput = createAsyncThunk<
const agentMetadata = getAgentRequestMetadata(getState() as any);
const messageId = createMessageId();
dispatch(addUserMessage({ id: messageId, message: data.message }));
- const useStreaming = getUseStreaming(getState() as any);
- const sendRequestAction = useStreaming
- ? sendStreamedAgentRequest
- : sendAgentRequest;
const sendMessageRequestPromise = dispatch(
- sendRequestAction({
+ sendAgentRequest({
...data,
...agentMetadata,
}),
@@ -169,46 +155,6 @@ export const submitInput = createAsyncThunk<
);
export const sendAgentRequest = createAsyncThunk<
- MetabotAgentResponse,
- Omit<MetabotAgentRequest, "conversation_id">,
- { rejectValue: PromptErrorOutcome }
->(
- "metabase-enterprise/metabot/sendAgentRequest",
- async (
- data: Omit<MetabotAgentRequest, "conversation_id">,
- { dispatch, getState, rejectWithValue, fulfillWithValue },
- ) => {
- try {
- // TODO: make enterprise store
- let sessionId = getMetabotConversationId(getState() as any);
- // should not be needed, but just in case the value got unset
- if (!sessionId) {
- console.warn(
- "Metabot has no session id while open, this should never happen",
- );
- dispatch(resetConversationId());
- sessionId = getMetabotConversationId(getState() as any) as string;
- }
-
- const metabotRequestPromise = dispatch(
- metabotAgent.initiate({ ...data, conversation_id: sessionId }),
- );
- const result = await metabotRequestPromise;
-
- if (result.data) {
- await dispatch(processMetabotReactions(result.data?.reactions || []));
- return fulfillWithValue(result.data);
- } else {
- throw result.error;
- }
- } catch (error) {
- console.error(error);
- return rejectWithValue(handleResponseError(error));
- }
- },
-);
-
-export const sendStreamedAgentRequest = createAsyncThunk<
Omit<MetabotAgentResponse, "reactions">,
Omit<MetabotAgentRequest, "conversation_id">,
{ rejectValue: PromptErrorOutcome }
@@ -280,15 +226,7 @@ export const sendStreamedAgentRequest = createAsyncThunk<
export const cancelInflightAgentRequests = createAsyncThunk(
"metabase-enterprise/metabot/cancelInflightAgentRequests",
- (_args, { dispatch }) => {
- // cancel rtkquery managed requests
- const requests = dispatch(EnterpriseApi.util.getRunningMutationsThunk());
- const agentRequests = requests.filter(
- (req) => req.arg.endpointName === metabotApi.endpoints.metabotAgent.name,
- );
- agentRequests.forEach((req) => req.abort());
-
- // cancel streamed requests
+ (_args) => {
getInflightRequestsForUrl("/api/ee/metabot-v3/v2/agent-streaming").forEach(
(req) => req.abortController.abort(),
);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/getPrevAgentResponse.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/getPrevAgentResponse.ts
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
index e4199534de2..e3e6dd7ad0d 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
@@ -7,7 +7,7 @@ import type { MetabotHistory } from "metabase-types/api";
import { TOOL_CALL_MESSAGES } from "../constants";
-import { sendAgentRequest, sendStreamedAgentRequest } from "./actions";
+import { sendAgentRequest } from "./actions";
import { createMessageId } from "./utils";
export type MetabotChatMessage = {
@@ -29,7 +29,6 @@ export type MetabotToolCall = {
};
export interface MetabotState {
- useStreaming: boolean;
isProcessing: boolean;
conversationId: string;
messages: MetabotChatMessage[];
@@ -41,7 +40,6 @@ export interface MetabotState {
}
export const getMetabotInitialState = (): MetabotState => ({
- useStreaming: true,
isProcessing: false,
conversationId: uuid(),
messages: [],
@@ -56,9 +54,6 @@ export const metabot = createSlice({
name: "metabase-enterprise/metabot",
initialState: getMetabotInitialState(),
reducers: {
- toggleStreaming: (state) => {
- state.useStreaming = !state.useStreaming;
- },
addUserMessage: (
state,
action: PayloadAction<Omit<MetabotChatMessage, "role">>,
@@ -67,10 +62,7 @@ export const metabot = createSlice({
state.errorMessages = [];
state.messages.push({ id, role: "user", message });
-
- if (state.useStreaming) {
- state.history.push({ id, role: "user", content: message });
- }
+ state.history.push({ id, role: "user", content: message });
},
addAgentMessage: (
state,
@@ -136,7 +128,7 @@ export const metabot = createSlice({
}
const historyIndex = state.history.findLastIndex((h) => id === h.id);
- if (state.useStreaming && historyIndex > -1) {
+ if (historyIndex > -1) {
state.history = state.history.slice(0, historyIndex);
}
},
@@ -163,21 +155,6 @@ export const metabot = createSlice({
builder
.addCase(logout.pending, getMetabotInitialState)
// streamed response handlers
- .addCase(sendStreamedAgentRequest.pending, (state) => {
- state.isProcessing = true;
- state.errorMessages = [];
- })
- .addCase(sendStreamedAgentRequest.fulfilled, (state, action) => {
- state.history = action.payload?.history?.slice() ?? [];
- state.state = { ...(action.payload?.state ?? {}) };
- state.toolCalls = [];
- state.isProcessing = false;
- })
- .addCase(sendStreamedAgentRequest.rejected, (state) => {
- state.toolCalls = [];
- state.isProcessing = false;
- })
- // non-streamed response handlers
.addCase(sendAgentRequest.pending, (state) => {
state.isProcessing = true;
state.errorMessages = [];
@@ -185,9 +162,11 @@ export const metabot = createSlice({
.addCase(sendAgentRequest.fulfilled, (state, action) => {
state.history = action.payload?.history?.slice() ?? [];
state.state = { ...(action.payload?.state ?? {}) };
+ state.toolCalls = [];
state.isProcessing = false;
})
.addCase(sendAgentRequest.rejected, (state) => {
+ state.toolCalls = [];
state.isProcessing = false;
});
},
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
index a7e4c7894cf..21a0e522df9 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
@@ -13,11 +13,6 @@ import type { MetabotStoreState } from "./types";
export const getMetabot = (state: MetabotStoreState) =>
state.plugins.metabotPlugin;
-export const getUseStreaming = createSelector(
- getMetabot,
- (metabot) => metabot.useStreaming,
-);
-
export const getMetabotVisible = createSelector(
getMetabot,
(metabot) => metabot.visible,