The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(sdk): Fix and improve Metabot for SDK (#62822)
Timofey Kachalov101fb38bfcd1
diff --git a/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsxnew file mode 100644index 00000000000..82ea3d44488--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx@@ -0,0 +1,148 @@+const { H } = cy;++import { MetabotQuestion } from "@metabase/embedding-sdk-react";++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 } = SAMPLE_DATABASE;++const metabot_id = "c61bf5f5-1025-47b6-9298-bf1827105bb6";+const query = {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+};+const adHocQuestionPath = `/question#${btoa(+ JSON.stringify({+ dataset_query: { database: 1, type: "query", query },+ display: "table",+ displayIsLocked: true,+ visualization_settings: {},+ }),+)}`;++const metabotResponse = `0:"Here is the [question link](${adHocQuestionPath})"`;+const metabotResponseWithNavigateTo = `${metabotResponse}+2:{"type":"navigate_to","version":1,"value":"${adHocQuestionPath}"}`;++const metabotRetryResponse = `0:"Retry: Here is the [question link](${adHocQuestionPath})"`;++describe("scenarios > embedding-sdk > metabot-question", () => {+ const setup = (response: string) => {+ signInAsAdminAndEnableEmbeddingSdk();++ H.mockMetabotResponse({+ statusCode: 200,+ body: response,+ });++ H.createQuestion({+ name: "1",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ cy.wrap(question.entity_id).as("questionEntityId");+ });++ cy.signOut();+ mockAuthProviderAndJwtSignIn();+ };++ it("should automatically show the ad-hoc question for the last agent message containing ad-hoc question link", () => {+ setup(metabotResponseWithNavigateTo);++ mountSdkContent(<MetabotQuestion />);++ getSdkRoot().within(() => {+ cy.findByTestId("metabot-chat-input").type("Show orders {enter}");++ cy.findByTestId("visualization-root").should("exist");+ });+ });++ it("should show the ad-hoc question when clicking its link", () => {+ setup(metabotResponse);++ mountSdkContent(<MetabotQuestion />);++ getSdkRoot().within(() => {+ cy.findByTestId("metabot-chat-input").type("Show orders {enter}");++ cy.findAllByTestId("metabot-chat-message")+ .should("have.length", 2)+ .last()+ .findByText("question link")+ .click();++ cy.findByTestId("visualization-root").should("exist");+ });+ });++ it("should retry a message when clicking the retry button", () => {+ setup(metabotResponse);++ mountSdkContent(<MetabotQuestion />);++ getSdkRoot().within(() => {+ cy.findByTestId("metabot-chat-input").type("Show orders {enter}");++ H.mockMetabotResponse({+ statusCode: 200,+ body: metabotRetryResponse,+ });++ cy.findAllByTestId("metabot-chat-message")+ .should("have.length", 2)+ .last()+ .findByTestId("metabot-chat-message-retry")+ .click();++ cy.findAllByTestId("metabot-chat-message")+ .should("have.length", 2)+ .last()+ .findByText(/Retry: Here is the/)+ .should("exist");+ });+ });++ it("should set correct metabot_id both for the a new message and when retrying", () => {+ setup(metabotResponse);++ mountSdkContent(<MetabotQuestion />);++ getSdkRoot().within(() => {+ cy.findByTestId("metabot-chat-input").type("Show orders {enter}");++ cy.wait("@metabotAgent").then((interception) => {+ const requestBody = interception.request.body;+ expect(requestBody).to.have.property("metabot_id", metabot_id);+ });++ H.mockMetabotResponse({+ statusCode: 200,+ body: metabotRetryResponse,+ });++ cy.findAllByTestId("metabot-chat-message")+ .should("have.length", 2)+ .last()+ .findByTestId("metabot-chat-message-retry")+ .click();++ cy.wait("@metabotAgent").then((interception) => {+ const requestBody = interception.request.body;+ expect(requestBody).to.have.property("metabot_id", metabot_id);+ });+ });+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotChatEmbedding.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotChatEmbedding.tsxindex e37b778c52d..b58ea1d0f8a 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotChatEmbedding.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotChatEmbedding.tsx@@ -1,5 +1,5 @@import cx from "classnames";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { t } from "ttag";import { useSdkDispatch } from "embedding-sdk-bundle/store";@@ -13,8 +13,10 @@ import {UnstyledButton,} from "metabase/ui";import { MetabotIcon } from "metabase-enterprise/metabot/components/MetabotIcon";-import { METABOT_RESULTS_MESSAGE } from "metabase-enterprise/metabot/constants";-import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";+import {+ useMetabotAgent,+ useMetabotChatHandlers,+} from "metabase-enterprise/metabot/hooks";import {cancelInflightAgentRequests,resetConversationId,@@ -24,56 +26,19 @@ import Styles from "./MetabotChatEmbedding.module.css";const MIN_INPUT_HEIGHT = 42;-interface MetabotChatEmbeddingProps {- onRedirectUrl: (result: string) => void;- onMessages: (messages: string[]) => void;-}--const EMBEDDING_METABOT_ID = "c61bf5f5-1025-47b6-9298-bf1827105bb6";--export const MetabotChatEmbedding = ({- onRedirectUrl,- onMessages,-}: MetabotChatEmbeddingProps) => {- const textareaRef = useRef<HTMLTextAreaElement>(null);-- const [input, setMessage] = useState("");-+export const MetabotChatEmbedding = () => {const metabot = useMetabotAgent();+ const { handleSubmitInput, handleResetInput } = useMetabotChatHandlers();const resetInput = useCallback(() => {- setMessage("");+ handleResetInput();setInputExpanded(false);- }, []);-- const handleSend = () => {- const trimmedInput = input.trim();- if (!trimmedInput.length || metabot.isDoingScience) {- return;- }- setMessage("");- const metabotRequestPromise = metabot.submitInput(- trimmedInput,- EMBEDDING_METABOT_ID,- );-- metabotRequestPromise- .then((result) => {- const redirectUrl = (result.payload as any)?.data?.reactions?.find(- (reaction: { type: string; url: string }) =>- reaction.type === "metabot.reaction/redirect",- )?.url;- if (redirectUrl) {- onRedirectUrl(redirectUrl);- }- })- .catch((err) => console.error(err))- .finally(() => textareaRef.current?.focus());- };+ }, [handleResetInput]);const [inputExpanded, setInputExpanded] = useState(false);const handleMaybeExpandInput = () => {- const textarea = textareaRef.current;+ const textarea = metabot.promptInputRef?.current;+if (!textarea) {return;}@@ -86,10 +51,6 @@ export const MetabotChatEmbedding = ({textarea.scrollTop = Math.max(MIN_INPUT_HEIGHT, textarea.scrollHeight);};- const handleInputChange = (value: string) => {- setMessage(value);- };-const inputPlaceholder = t`Tell me to do something, or ask a question`;const placeholder = metabot.isDoingScience? t`Doing science...`@@ -100,17 +61,11 @@ export const MetabotChatEmbedding = ({}const dispatch = useSdkDispatch();+useEffect(() => {dispatch(resetConversationId());}, [dispatch]);- useEffect(() => {- const normalizedMessages = metabot.lastAgentMessages.filter(- (message) => message !== METABOT_RESULTS_MESSAGE,- );- onMessages(normalizedMessages);- }, [metabot.lastAgentMessages, onMessages]);-return (<Box className={Styles.container} data-testid="metabot-chat"><Flex@@ -142,9 +97,9 @@ export const MetabotChatEmbedding = ({autosizeminRows={1}maxRows={4}- ref={textareaRef}+ ref={metabot.promptInputRef}autoFocus- value={input}+ value={metabot.prompt}disabled={metabot.isDoingScience}className={cx(Styles.textarea,@@ -152,18 +107,19 @@ export const MetabotChatEmbedding = ({metabot.isDoingScience && Styles.textareaLoading,)}placeholder={placeholder}- onChange={(e) => handleInputChange(e.target.value)}+ onChange={(e) => metabot.setPrompt(e.target.value)}// @ts-expect-error - undocumented API for mantine Textarea - leverages the prop from react-textarea-autosize's TextareaAutosize componentonHeightChange={handleMaybeExpandInput}onKeyDown={(e) => {if (e.nativeEvent.isComposing) {return;}+if (e.key === "Enter") {// prevent event from inserting new line + interacting with other contente.preventDefault();e.stopPropagation();- handleSend();+ handleSubmitInput(metabot.prompt);}}}/>@@ -183,7 +139,7 @@ export const MetabotChatEmbedding = ({onClick={resetInput}data-testid="metabot-close-chat"style={{- visibility: input.length > 0 ? "visible" : "hidden",+ visibility: metabot.prompt.length > 0 ? "visible" : "hidden",}}><Icon name="close" c="var(--mb-color-text-primary)" size="1rem" />diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.stories.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.stories.tsxindex 1cce62bd637..d4739b92ded 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.stories.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.stories.tsx@@ -3,6 +3,10 @@ import { HttpResponse, http } from "msw";import type { ComponentProps } from "react";import { CommonSdkStoryWrapper } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";+import {+ MOCK_AD_HOC_QUESTION_ID,+ mockStreamResponse,+} from "embedding-sdk-shared/test/mocks/mock-metabot-response";import { Box } from "metabase/ui";import { MetabotQuestion } from "./MetabotQuestion";@@ -40,267 +44,11 @@ export const RedirectReaction = {parameters: {msw: {handlers: [- http.post("*/api/ee/metabot-v3/v2/agent", () => {- return HttpResponse.json({- reactions: [- {- type: "metabot.reaction/message",- "repl/message_color": "green",- "repl/message_emoji": "π€",- message: "Here are the results",- },- {- type: "metabot.reaction/redirect",- url: "/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJ0eXBlIjoicXVlcnkiLCJxdWVyeSI6eyJzb3VyY2UtdGFibGUiOjJ9fSwiZGlzcGxheSI6InRhYmxlIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e30sInR5cGUiOiJxdWVzdGlvbiJ9",- },- ],- history: [- {- role: "user",- content: "best selling products in 2024",- },- {- role: "assistant",- "tool-calls": [- {- id: "call_5PU7OwgEiDnYKr9A2FTiNAfp",- name: "query",- arguments:- '{"query_plan":{"user_message_analysis":"The user is asking for the best selling products in 2024, which implies a need for sales data filtered by year.","candidate_metrics":[],"candidate_tables":["card__139","card__140"],"conclusion":"I will use the Orders table to analyze the total quantity sold for each product in 2024."},"query":"Show the total quantity sold for each product in 2024, grouped by Product ID.","source":{"table_id":"card__139"}}',- },- ],- },- {- content: "Success!",- role: "tool",- "tool-call-id": "call_5PU7OwgEiDnYKr9A2FTiNAfp",- },- {- content: "Here are the results",- role: "assistant",- "navigate-to":- "/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJ0eXBlIjoicXVlcnkiLCJxdWVyeSI6eyJzb3VyY2UtdGFibGUiOjJ9fSwiZGlzcGxheSI6InRhYmxlIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e30sInR5cGUiOiJxdWVzdGlvbiJ9",- },- ],- state: {- queries: {- "5kt_rzk_792erogqj_oh_ku_5m": {- database: 2,- type: "query",- query: {- aggregation: [- [- "sum",- [- "field",- "quantity",- {- base_type: "type/Decimal",- },- ],- ],- ],- breakout: [- [- "field",- "product_id",- {- base_type: "type/BigInteger",- },- ],- ],- source_table: "card__139",- aggregation_idents: {- "0": "_c5p_PVpsm6A7dOqupLHE",- },- breakout_idents: {- "0": "9URvg0Oy6owTr7qt2UdsZ",- },- filter: [- "=",- [- "get-year",- [- "field",- "created_at",- {- base_type: "type/DateTimeWithLocalTZ",- },- ],- ],- 2024,- ],- },- },- "8zzlkFleApnbGONeqT4sN": {- database: 2,- type: "query",- query: {- aggregation: [- [- "sum",- [- "field",- "quantity",- {- "base-type": "type/Decimal",- },- ],- ],- ],- breakout: [- [- "field",- "product_id",- {- "base-type": "type/BigInteger",- },- ],- ],- "source-table": "card__139",- filter: [- "=",- [- "get-year",- [- "field",- "created_at",- {- "base-type": "type/DateTimeWithLocalTZ",- },- ],- ],- 2024,- ],- },- },- },- },- conversation_id: "d90328fc-5ed5-1119-03f7-86866d71c488",- });- }),- ],- },- },-};--export const MessageReaction = {- render: Template,- parameters: {- msw: {- handlers: [- http.post("*/api/ee/metabot-v3/v2/agent", () => {- return HttpResponse.json({- reactions: [- {- type: "metabot.reaction/message",- "repl/message_color": "green",- "repl/message_emoji": "π€",- message:- "Do you want to see the products earning the most money or the ones selling most units?",- },- ],- history: [- {- role: "user",- content: "This is what user has typed",- },- {- content:- "Do you want to see the products earning the most money or the ones selling most units?",- role: "assistant",- },- ],- state: {- queries: {},- },- conversation_id: "c7635bd0-84f3-f06d-1db8-571db7ff0cf6",- });- }),- ],- },- },-};--export const LongMessageReaction = {- render: Template,- parameters: {- msw: {- handlers: [- http.post("*/api/ee/metabot-v3/v2/agent", () => {- return HttpResponse.json({- reactions: [- {- type: "metabot.reaction/message",- "repl/message_color": "green",- "repl/message_emoji": "π€",- message:- "lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",- },- ],- history: [- {- role: "user",- content: "This is what user has typed",- },- {- content:- "lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",- role: "assistant",- },- ],- state: {- queries: {},- },- conversation_id: "c7635bd0-84f3-f06d-1db8-571db7ff0cf6",- });- }),- ],- },- },-};--export const MultipleMessagesReaction = {- render: Template,- parameters: {- msw: {- handlers: [- http.post("*/api/ee/metabot-v3/v2/agent", () => {- return HttpResponse.json({- reactions: [- {- type: "metabot.reaction/message",- "repl/message_color": "green",- "repl/message_emoji": "π€",- message: "This is the first message",- },- {- type: "metabot.reaction/message",- "repl/message_color": "green",- "repl/message_emoji": "π€",- message: "This is the second message",- },- ],- history: [- {- role: "user",- content: "This is what user has typed",- },- {- content: "This is the first message",- role: "assistant",- },- {- content: "This is the second message",- role: "assistant",- },- ],- state: {- queries: {},- },- conversation_id: "c7635bd0-84f3-f06d-1db8-571db7ff0cf6",- });- }),+ mockStreamResponse([+ `0:"Here is the [question link](${MOCK_AD_HOC_QUESTION_ID})"`,+ `2:{"type":"navigate_to","version":1,"value":"${MOCK_AD_HOC_QUESTION_ID}"}+`,+ ]),],},},@@ -311,7 +59,7 @@ export const MetabotError = {parameters: {msw: {handlers: [- http.post("*/api/ee/metabot-v3/v2/agent", () => {+ http.post("*/api/ee/metabot-v3/v2/agent-streaming", () => {return new HttpResponse(null, {status: 500,});@@ -320,3 +68,12 @@ export const MetabotError = {},},};++export const MultipleInstances = {+ render: () => (+ <>+ <Template />+ <Template />+ </>+ ),+};diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsxindex 584177f7d12..b3766c18214 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useId } from "react";import { t } from "ttag";import {@@ -7,9 +7,16 @@ import {} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkAdHocQuestion } from "embedding-sdk-bundle/components/private/SdkAdHocQuestion";import { SdkQuestionDefaultView } from "embedding-sdk-bundle/components/private/SdkQuestionDefaultView";+import { EnsureSingleInstance } from "embedding-sdk-shared/components/EnsureSingleInstance/EnsureSingleInstance";import { useLocale } from "metabase/common/hooks/use-locale";-import { Flex, Icon, Paper, Stack, Text } from "metabase/ui";-import { METABOT_ERR_MSG } from "metabase-enterprise/metabot/constants";+import { Flex, Paper, Stack, Text } from "metabase/ui";+import { Messages } from "metabase-enterprise/metabot/components/MetabotChat/MetabotChatMessage";+import { MetabotResetLongChatButton } from "metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton";+import {+ useMetabotAgent,+ useMetabotChatHandlers,+} from "metabase-enterprise/metabot/hooks";+import { useMetabotReactions } from "metabase-enterprise/metabot/hooks/use-metabot-reactions";import { MetabotChatEmbedding } from "./MetabotChatEmbedding";import { QuestionDetails } from "./QuestionDetails";@@ -17,8 +24,7 @@ import { QuestionTitle } from "./QuestionTitle";const MetabotQuestionInner = () => {const { isLocaleLoading } = useLocale();- const [redirectUrl, setRedirectUrl] = useState<string>("");- const [messages, setMessages] = useState<string[]>([]);+ const { navigateToPath } = useMetabotReactions();if (isLocaleLoading) {return <SdkLoader />;@@ -26,16 +32,13 @@ const MetabotQuestionInner = () => {return (<Flex direction="column" align="center" gap="md">- <MetabotChatEmbedding- onRedirectUrl={setRedirectUrl}- onMessages={setMessages}- />- {messages.map((message, index) => (- <Message key={index} message={message} />- ))}- {redirectUrl && (+ <MetabotMessages />++ <MetabotChatEmbedding />++ {!!navigateToPath && (<SdkAdHocQuestion- questionPath={redirectUrl}+ questionPath={navigateToPath}title={false}isSaveEnabled={false}>@@ -50,28 +53,36 @@ const MetabotQuestionInner = () => {/></SdkAdHocQuestion>)}+<Disclaimer /></Flex>);};-interface MessageProps {- message: string;-}-function Message({ message }: MessageProps) {- const isErrorMessage = message === METABOT_ERR_MSG.agentOffline;- if (isErrorMessage) {- return (- <Paper shadow="sm" p="lg" w="100%" maw="41.5rem" radius="lg" ta="center">- <Icon name="info_filled" c="var(--mb-color-text-tertiary)" size={32} />- <Text mt="sm">{message}</Text>- </Paper>- );+function MetabotMessages() {+ const metabot = useMetabotAgent();+ const { messages, errorMessages } = metabot;+ const { handleRetryMessage } = useMetabotChatHandlers();+ const { setNavigateToPath } = useMetabotReactions();++ if (!messages.length && !errorMessages.length) {+ return null;}return (<Paper shadow="sm" p="lg" w="100%" maw="41.5rem" radius="lg">- <Text>{message}</Text>+ <Flex direction="column">+ <Messages+ messages={messages}+ errorMessages={errorMessages}+ onRetryMessage={handleRetryMessage}+ isDoingScience={metabot.isDoingScience}+ showFeedbackButtons={false}+ onInternalLinkClick={setNavigateToPath}+ />+ </Flex>++ {metabot.isLongConversation && <MetabotResetLongChatButton />}</Paper>);}@@ -82,4 +93,22 @@ function Disclaimer() {);}-export const MetabotQuestion = withPublicComponentWrapper(MetabotQuestionInner);+const MetabotQuestionWrapped = () => {+ const ensureSingleInstanceId = useId();++ return (+ <EnsureSingleInstance+ groupId="metabot-question"+ instanceId={ensureSingleInstanceId}+ multipleRegisteredInstancesWarningMessage={+ "Multiple instances of MetabotQuestion detected. Ensure only one instance of MetabotQuestion is rendered at a time."+ }+ >+ <MetabotQuestionInner />+ </EnsureSingleInstance>+ );+};++export const MetabotQuestion = withPublicComponentWrapper(+ MetabotQuestionWrapped,+);diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsxindex de132a47df4..1a842865936 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx@@ -1,5 +1,9 @@import { getStorybookSdkAuthConfigForUser } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";import { getHostedBundleStoryDecorator } from "embedding-sdk-package/test/getHostedBundleStoryDecorator";+import {+ MOCK_AD_HOC_QUESTION_ID,+ mockStreamResponse,+} from "embedding-sdk-shared/test/mocks/mock-metabot-response";import { MetabaseProvider } from "../MetabaseProvider";@@ -11,6 +15,15 @@ export default {title: "EmbeddingSDK/MetabotQuestion/public",parameters: {layout: "fullscreen",+ msw: {+ handlers: [+ mockStreamResponse([+ `0:"Here is the [question link](${MOCK_AD_HOC_QUESTION_ID})"`,+ `2:{"type":"navigate_to","version":1,"value":"${MOCK_AD_HOC_QUESTION_ID}"}+`,+ ]),+ ],+ },},decorators: [getHostedBundleStoryDecorator()],};diff --git a/enterprise/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.ts b/enterprise/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.tsnew file mode 100644index 00000000000..d77a78e7d5b--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.ts@@ -0,0 +1,38 @@+import { http } from "msw";++export const MOCK_AD_HOC_QUESTION_ID =+ "/question#eyJkYXRhc2V0X3F1ZXJ5IjogeyJkYXRhYmFzZSI6IDEsICJ0eXBlIjogInF1ZXJ5IiwgInF1ZXJ5IjogeyJzb3VyY2UtdGFibGUiOiAiY2FyZF9fMSJ9fSwgImRpc3BsYXkiOiAidGFibGUiLCAiZGlzcGxheUlzTG9ja2VkIjogdHJ1ZSwgInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOiB7fX0=";++export const mockStreamResponse = (chunks: string[]) => {+ return http.post("*/api/ee/metabot-v3/v2/agent-streaming", () => {+ const encoder = new TextEncoder();++ const stream = new ReadableStream({+ start(controller) {+ let i = 0;++ const pushNext = () => {+ if (i < chunks.length) {+ controller.enqueue(encoder.encode(`${chunks[i]}\n`));+ i++;+ setTimeout(pushNext, 100);+ } else {+ controller.close();+ }+ };++ pushNext();+ },+ });++ return new Response(stream, {+ status: 200,+ headers: {+ "Content-Type": "text/event-stream; charset=utf-8",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ "Transfer-Encoding": "chunked",+ },+ });+ });+};diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.tsindex b75b0cce0fc..8f194971858 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts@@ -43,7 +43,8 @@ export async function aiStreamingQuery(}inflightAiStreamingRequests.set(reqId, { abortController });- const response = await fetch(req.url, {+ // The basename is needed to work within the Embedding SDK+ const response = await fetch(`${api.basename}${req.url}`, {method: "POST",headers: {...api.getClientHeaders(),diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.unit.spec.tsindex 3f4eb3894a7..10fc1b0aec8 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.unit.spec.ts@@ -1,22 +1,51 @@import fetchMock from "fetch-mock";+import api from "metabase/lib/api";+import { aiStreamingQuery, getInflightRequestsForUrl } from "./requests";import { mockStreamedEndpoint } from "./test-utils";-const ENDPOINT = "/some-streamed-endpoint";+const endpoint = "/some-streamed-endpoint";+const fakeBasename = "http://example.com";+const originalBasename = api.basename;describe("ai requests", () => {+ beforeAll(() => {+ api.basename = fakeBasename;+ });++ afterAll(() => {+ api.basename = originalBasename;+ });+describe("aiStreamingQuery", () => {+ it("should call a request with a baseurl", async () => {+ const fetchSpy = jest.spyOn(global, "fetch");++ mockStreamedEndpoint(endpoint, {+ textChunks: whoIsYourFavoriteResponse,+ });++ await aiStreamingQuery({ url: endpoint, body: {} });++ expect(fetchSpy).toHaveBeenCalledWith(+ "http://example.com/some-streamed-endpoint",+ expect.anything(),+ );++ fetchSpy.mockRestore();+ });+it("should return full result of a successful request", async () => {- mockStreamedEndpoint(ENDPOINT, {+ mockStreamedEndpoint(endpoint, {textChunks: whoIsYourFavoriteResponse,});- const result = await aiStreamingQuery({ url: ENDPOINT, body: {} });+ const result = await aiStreamingQuery({ url: endpoint, body: {} });expect(result).toMatchSnapshot();});it("should call callbacks for relevant chunk types", async () => {- mockStreamedEndpoint(ENDPOINT, {+ mockStreamedEndpoint(endpoint, {textChunks: [`0:"Testing"`,`2:{"type":"state","version":1,"value":{}}`,@@ -34,14 +63,14 @@ describe("ai requests", () => {onError: jest.fn(),};- await aiStreamingQuery({ url: ENDPOINT, body: {} }, successCbs);+ await aiStreamingQuery({ url: endpoint, body: {} }, successCbs);expect(successCbs.onTextPart).toHaveBeenCalled();expect(successCbs.onDataPart).toHaveBeenCalled();expect(successCbs.onToolCallPart).toHaveBeenCalled();expect(successCbs.onToolResultPart).toHaveBeenCalled();expect(successCbs.onError).not.toHaveBeenCalled();- mockStreamedEndpoint(ENDPOINT, {+ mockStreamedEndpoint(endpoint, {textChunks: [`3:{}`, // error after finish to trigger all callbacks],@@ -51,33 +80,33 @@ describe("ai requests", () => {onError: jest.fn(),};try {- await aiStreamingQuery({ url: ENDPOINT, body: {} }, failureCbs);+ await aiStreamingQuery({ url: endpoint, body: {} }, failureCbs);} catch (_) {}expect(failureCbs.onError).toHaveBeenCalled();});it("throw error if bad http status code", async () => {- fetchMock.post(`path:${ENDPOINT}`, 500);+ fetchMock.post(`path:${endpoint}`, 500);await expect(- aiStreamingQuery({ url: ENDPOINT, body: {} }),+ aiStreamingQuery({ url: endpoint, body: {} }),).rejects.toThrow(/Response status: 500/);});it("throw error if no response", async () => {- mockStreamedEndpoint(ENDPOINT, {+ mockStreamedEndpoint(endpoint, {textChunks: undefined,});await expect(- aiStreamingQuery({ url: ENDPOINT, body: {} }),+ aiStreamingQuery({ url: endpoint, body: {} }),).rejects.toThrow(/No response/);});it("should be able abort request via a passed in signal", async () => {const controller = new AbortController();- fetchMock.post(`path:${ENDPOINT}`, { delay: 100, status: 200 });+ fetchMock.post(`path:${endpoint}`, { delay: 100, status: 200 });const promise = aiStreamingQuery({- url: ENDPOINT,+ url: endpoint,body: {},signal: controller.signal,});@@ -87,29 +116,29 @@ describe("ai requests", () => {describe("in-flight request tracking", () => {it("should register/unregister with inflight requests on a successful request", async () => {- mockStreamedEndpoint(ENDPOINT, {+ mockStreamedEndpoint(endpoint, {textChunks: whoIsYourFavoriteResponse,});- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(0);- const promise = aiStreamingQuery({ url: ENDPOINT, body: {} });- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(1);+ expect(getInflightRequestsForUrl(endpoint).length).toBe(0);+ const promise = aiStreamingQuery({ url: endpoint, body: {} });+ expect(getInflightRequestsForUrl(endpoint).length).toBe(1);await promise;- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(0);+ expect(getInflightRequestsForUrl(endpoint).length).toBe(0);});it("should properly unregister with inflight requests on abort", async () => {const controller = new AbortController();- fetchMock.post(`path:${ENDPOINT}`, { delay: 100, status: 200 });- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(0);+ fetchMock.post(`path:${endpoint}`, { delay: 100, status: 200 });+ expect(getInflightRequestsForUrl(endpoint).length).toBe(0);const promise = aiStreamingQuery({- url: ENDPOINT,+ url: endpoint,body: {},signal: controller.signal,});- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(1);+ expect(getInflightRequestsForUrl(endpoint).length).toBe(1);controller.abort();- expect(getInflightRequestsForUrl(ENDPOINT).length).toBe(0);+ expect(getInflightRequestsForUrl(endpoint).length).toBe(0);try {await promise;} catch (err) {}diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/AIMarkdown/AIMarkdown.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/AIMarkdown/AIMarkdown.tsxindex 11f7761b9a2..15685dd8af5 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/AIMarkdown/AIMarkdown.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/AIMarkdown/AIMarkdown.tsx@@ -1,7 +1,7 @@// TODO: consolidate this component w/ AIAnalysisContentimport cx from "classnames";-import { memo } from "react";+import { memo, useMemo } from "react";import Link from "metabase/common/components/Link/Link";import Markdown, {@@ -10,7 +10,13 @@ import Markdown, {import S from "./AIMarkdown.module.css";-const components = {+type AIMarkdownProps = MarkdownProps & {+ onInternalLinkClick?: (link: string) => void;+};++const getComponents = ({+ onInternalLinkClick,+}: Pick<AIMarkdownProps, "onInternalLinkClick">) => ({a: ({href,children,@@ -23,6 +29,15 @@ const components = {[key: string]: any;}) => {if (href && href.startsWith("/")) {+ // A custom handler for internal links (use by Embedding SDK)+ if (onInternalLinkClick) {+ return (+ <a {...rest} onClick={() => onInternalLinkClick(href)}>+ {children}+ </a>+ );+ }+return (<Link to={href} variant="brand">{children}@@ -37,13 +52,23 @@ const components = {</a>);},-};+});++export const AIMarkdown = memo(+ ({ className, onInternalLinkClick, ...props }: AIMarkdownProps) => {+ const components = useMemo(+ () => getComponents({ onInternalLinkClick }),+ [onInternalLinkClick],+ );++ return (+ <Markdown+ className={cx(S.aiMarkdown, className)}+ components={components}+ {...props}+ />+ );+ },+);-export const AIMarkdown = memo(({ className, ...props }: MarkdownProps) => (- <Markdown- className={cx(S.aiMarkdown, className)}- components={components}- {...props}- />-));AIMarkdown.displayName = "AIMarkdown";diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsxindex 69fbc0ee84f..b022a7224e7 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx@@ -1,6 +1,6 @@import cx from "classnames";import { useMemo } from "react";-import { c, jt, t } from "ttag";+import { t } from "ttag";import _ from "underscore";import EmptyDashboardBot from "assets/img/dashboard-empty.svg?component";@@ -15,11 +15,11 @@ import {Stack,Text,Textarea,- UnstyledButton,} from "metabase/ui";import { useGetSuggestedMetabotPromptsQuery } from "metabase-enterprise/api";+import { MetabotResetLongChatButton } from "metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton";-import { useMetabotAgent } from "../../hooks";+import { useMetabotAgent, useMetabotChatHandlers } from "../../hooks";import Styles from "./MetabotChat.module.css";import { Messages } from "./MetabotChatMessage";@@ -28,6 +28,8 @@ import { useScrollManager } from "./hooks";export const MetabotChat = () => {const metabot = useMetabotAgent();+ const { handleSubmitInput, handleRetryMessage, handleResetInput } =+ useMetabotChatHandlers();const hasMessages =metabot.messages.length > 0 || metabot.errorMessages.length > 0;@@ -44,32 +46,8 @@ export const MetabotChat = () => {return suggestedPromptsReq.currentData?.prompts ?? [];}, [suggestedPromptsReq.currentData?.prompts]);- const handleSubmitInput = (input: string) => {- if (metabot.isDoingScience) {- return;- }-- const trimmedInput = input.trim();- if (!trimmedInput.length || metabot.isDoingScience) {- return;- }- metabot.setPrompt("");- metabot.promptInputRef?.current?.focus();- metabot.submitInput(trimmedInput).catch((err) => console.error(err));- };-- const handleRetryMessage = (messageId: string) => {- if (metabot.isDoingScience) {- return;- }-- metabot.setPrompt("");- metabot.promptInputRef?.current?.focus();- metabot.retryMessage(messageId).catch((err) => console.error(err));- };-const handleClose = () => {- metabot.setPrompt("");+ handleResetInput();metabot.setVisible(false);};@@ -161,6 +139,7 @@ export const MetabotChat = () => {errorMessages={metabot.errorMessages}onRetryMessage={handleRetryMessage}isDoingScience={metabot.isDoingScience}+ showFeedbackButtons/>{/* loading */}@@ -177,21 +156,7 @@ export const MetabotChat = () => {<div ref={fillerRef} data-testid="metabot-message-filler" />{/* long convo warning */}- {metabot.isLongConversation && (- <Text lh={1} c="text-light" m={0} ta="center">- {jt`This chat is getting long. You can ${(- <UnstyledButton- key="reset"- data-testid="metabot-reset-long-chat"- display="inline"- c="brand"- td="underline"- onClick={() => metabot.resetConversation()}- >{c("'it' refers to a chat with an AI agent")- .t`clear it`}</UnstyledButton>- )}.`}- </Text>- )}+ {metabot.isLongConversation && <MetabotResetLongChatButton />}</Box>)}</Box>diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatMessage.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatMessage.tsxindex 6d5dacc0db0..08e9cbe309d 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatMessage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatMessage.tsx@@ -107,8 +107,10 @@ const FeedbackButton = ({interface AgentMessageProps extends BaseMessageProps {onRetry: (messageId: string) => void;onCopy: (messageId: string) => void;+ showFeedbackButtons: boolean;setFeedbackMessage?: (data: { messageId: string; positive: boolean }) => void;submittedFeedback: "positive" | "negative" | undefined;+ onInternalLinkClick?: (link: string) => void;}export const AgentMessage = ({@@ -116,13 +118,21 @@ export const AgentMessage = ({className,onCopy,onRetry,+ showFeedbackButtons,setFeedbackMessage,submittedFeedback,+ onInternalLinkClick,hideActions,...props}: AgentMessageProps) => (<MessageContainer chatRole={message.role} {...props}>- <AIMarkdown className={Styles.message}>{message.message}</AIMarkdown>+ <AIMarkdown+ className={Styles.message}+ onInternalLinkClick={onInternalLinkClick}+ >+ {message.message}+ </AIMarkdown>+<Flex className={Styles.messageActions}>{!hideActions && (<>@@ -133,7 +143,7 @@ export const AgentMessage = ({><Icon name="copy" size="1rem" /></ActionIcon>- {setFeedbackMessage && (+ {showFeedbackButtons && setFeedbackMessage && (<><FeedbackButtondata-testid="metabot-chat-message-thumbs-up"@@ -161,6 +171,7 @@ export const AgentMessage = ({/></>)}+<ActionIcononClick={() => onRetry(message.id)}h="sm"@@ -228,11 +239,15 @@ export const Messages = ({errorMessages,onRetryMessage,isDoingScience,+ showFeedbackButtons,+ onInternalLinkClick,}: {messages: MetabotChatMessage[];errorMessages: MetabotErrorMessage[];onRetryMessage: (messageId: string) => void;isDoingScience: boolean;+ showFeedbackButtons: boolean;+ onInternalLinkClick?: (navigateToPath: string) => void;}) => {const clipboard = useClipboard();const [sendToast] = useToast();@@ -270,9 +285,13 @@ export const Messages = ({const setFeedbackModal = useCallback((data: { messageId: string; positive: boolean } | undefined) => {+ if (!showFeedbackButtons) {+ return;+ }+setFeedbackState((prev) => ({ ...prev, modal: data }));},- [],+ [showFeedbackButtons],);return (@@ -285,9 +304,11 @@ export const Messages = ({message={message}onRetry={onRetryMessage}onCopy={onAgentMessageCopy}+ showFeedbackButtons={showFeedbackButtons}setFeedbackMessage={setFeedbackModal}submittedFeedback={feedbackState.submitted[message.id]}hideActions={messages[index + 1]?.role === "agent"}+ onInternalLinkClick={onInternalLinkClick}/>) : (<UserMessagediff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsxnew file mode 100644index 00000000000..641740a9cff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx@@ -0,0 +1,24 @@+import { c, jt } from "ttag";++import { Text, UnstyledButton } from "metabase/ui";+import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";++export const MetabotResetLongChatButton = () => {+ const metabot = useMetabotAgent();++ return (+ <Text lh={1} c="text-light" m={0} ta="center">+ {jt`This chat is getting long. You can ${(+ <UnstyledButton+ key="reset"+ data-testid="metabot-reset-long-chat"+ display="inline"+ c="brand"+ td="underline"+ onClick={() => metabot.resetConversation()}+ >{c("'it' refers to a chat with an AI agent")+ .t`clear it`}</UnstyledButton>+ )}.`}+ </Text>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts b/enterprise/frontend/src/metabase-enterprise/metabot/constants.tsindex 27a11ad8897..d75babfcef8 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts@@ -8,6 +8,10 @@ export const FIXED_METABOT_IDS = {EMBEDDED: 2 as const,};+export const METABOT_REQUEST_IDS = {+ EMBEDDED: "c61bf5f5-1025-47b6-9298-bf1827105bb6",+};+export const METABOT_ERR_MSG = {get default() {return t`Sorry, I ran into an error. Could you please try that again?`;@@ -17,9 +21,6 @@ export const METABOT_ERR_MSG = {},};-// We don't need to translate this yet, as it's from ai-service which isn't translated-export const METABOT_RESULTS_MESSAGE = "Here are the results";-export const TOOL_CALL_MESSAGES: Record<string, string | undefined> = {get construct_notebook_query() {return t`Creating a query`;diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.tsnew file mode 100644index 00000000000..24c2b58a2ac--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts@@ -0,0 +1,2 @@+export { useMetabotAgent } from "./use-metabot-agent";+export { useMetabotChatHandlers } from "./use-metabot-chat-handlers";diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.tssimilarity index 67%rename from enterprise/frontend/src/metabase-enterprise/metabot/hooks.tsrename to enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.tsindex 2ace9155156..2ce84bf95b0 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.ts@@ -12,34 +12,55 @@ import {getLastAgentMessagesByType,getMessages,getMetabotId,+ getMetabotRequestId,getMetabotVisible,getToolCalls,resetConversation as resetConversationAction,retryPrompt,setVisible as setVisibleAction,submitInput as submitInputAction,-} from "./state";+} from "../state";export const useMetabotAgent = () => {const dispatch = useDispatch();const { prompt, setPrompt, promptInputRef, getChatContext } =useMetabotContext();+ const isDoingScience = useSelector(getIsProcessing as any) as ReturnType<+ typeof getIsProcessing+ >;+// TODO: create an enterprise useSelectorconst messages = useSelector(getMessages as any) as ReturnType<typeof getMessages>;+ const lastAgentMessages = useSelector(+ getLastAgentMessagesByType as any,+ ) as ReturnType<typeof getLastAgentMessagesByType>;+const errorMessages = useSelector(getAgentErrorMessages as any) as ReturnType<typeof getAgentErrorMessages>;- const isProcessing = useSelector(getIsProcessing as any) as ReturnType<- typeof getIsProcessing- >;++ const isLongConversation = useSelector(+ getIsLongMetabotConversation as any,+ ) as ReturnType<typeof getIsLongMetabotConversation>;const visible = useSelector(getMetabotVisible as any) as ReturnType<typeof getMetabotVisible>;+ const metabotId = useSelector(getMetabotId as any) as ReturnType<+ typeof getMetabotId+ >;+ const metabotRequestId = useSelector(+ getMetabotRequestId as any,+ ) as ReturnType<typeof getMetabotRequestId>;++ const toolCalls = useSelector(getToolCalls as any) as ReturnType<+ typeof getToolCalls+ >;+const setVisible = useCallback((isVisible: boolean) => dispatch(setVisibleAction(isVisible)),[dispatch],@@ -61,7 +82,7 @@ export const useMetabotAgent = () => {);const submitInput = useCallback(- async (prompt: string, metabotId?: string) => {+ async (prompt: string) => {if (!visible) {setVisible(true);}@@ -71,7 +92,7 @@ export const useMetabotAgent = () => {submitInputAction({message: prompt,context,- metabot_id: metabotId,+ metabot_id: metabotRequestId,}),);@@ -81,62 +102,61 @@ export const useMetabotAgent = () => {return action;},- [dispatch, getChatContext, prepareRetryIfUnsuccesful, setVisible, visible],+ [+ dispatch,+ getChatContext,+ metabotRequestId,+ prepareRetryIfUnsuccesful,+ setVisible,+ visible,+ ],);const retryMessage = useCallback(- async (messageId: string, metabotId?: string) => {+ async (messageId: string) => {const context = await getChatContext();const action = await dispatch(retryPrompt({messageId,context,- metabot_id: metabotId,+ metabot_id: metabotRequestId,}),);if (isFulfilled(action)) {prepareRetryIfUnsuccesful(action.payload);}},- [dispatch, getChatContext, prepareRetryIfUnsuccesful],+ [dispatch, getChatContext, metabotRequestId, prepareRetryIfUnsuccesful],);const startNewConversation = useCallback(- async (message: string, metabotId?: string) => {+ async (message: string) => {await resetConversation();setVisible(true);if (message) {- submitInput(message, metabotId);+ submitInput(message);}promptInputRef?.current?.focus();},- [submitInput, resetConversation, setVisible, promptInputRef],+ [resetConversation, setVisible, promptInputRef, submitInput],);return {+ isDoingScience,prompt,setPrompt,promptInputRef,- metabotId: useSelector(getMetabotId as any) as ReturnType<- typeof getMetabotId- >,+ metabotId,visible,messages,+ lastAgentMessages,errorMessages,- lastAgentMessages: useSelector(- getLastAgentMessagesByType as any,- ) as ReturnType<typeof getLastAgentMessagesByType>,- isLongConversation: useSelector(- getIsLongMetabotConversation as any,- ) as ReturnType<typeof getIsLongMetabotConversation>,+ isLongConversation,resetConversation,setVisible,startNewConversation,submitInput,- isDoingScience: isProcessing,- toolCalls: useSelector(getToolCalls as any) as ReturnType<- typeof getToolCalls- >,retryMessage,+ toolCalls,};};diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-chat-handlers.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-chat-handlers.tsnew file mode 100644index 00000000000..4c3164b31b4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-chat-handlers.ts@@ -0,0 +1,53 @@+import { useCallback } from "react";++import { useMetabotAgent } from "./use-metabot-agent";++export const useMetabotChatHandlers = () => {+ const {+ isDoingScience,+ setPrompt,+ promptInputRef,+ submitInput,+ retryMessage,+ } = useMetabotAgent();++ const handleSubmitInput = useCallback(+ (input: string) => {+ if (isDoingScience) {+ return;+ }++ const trimmedInput = input.trim();+ if (!trimmedInput.length || isDoingScience) {+ return;+ }+ setPrompt("");+ promptInputRef?.current?.focus();+ submitInput(trimmedInput).catch((err) => console.error(err));+ },+ [isDoingScience, promptInputRef, setPrompt, submitInput],+ );++ const handleRetryMessage = useCallback(+ (messageId: string) => {+ if (isDoingScience) {+ return;+ }++ setPrompt("");+ promptInputRef?.current?.focus();+ retryMessage(messageId).catch((err) => console.error(err));+ },+ [isDoingScience, promptInputRef, retryMessage, setPrompt],+ );++ const handleResetInput = useCallback(() => {+ setPrompt("");+ }, [setPrompt]);++ return {+ handleSubmitInput,+ handleRetryMessage,+ handleResetInput,+ };+};diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-reactions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-reactions.tsnew file mode 100644index 00000000000..36210197bec--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-reactions.ts@@ -0,0 +1,27 @@+import { useCallback } from "react";++import { useDispatch, useSelector } from "metabase/lib/redux";+import {+ getMetabotReactionsState,+ setNavigateToPath as setNavigateToPathAction,+} from "metabase-enterprise/metabot/state";++export const useMetabotReactions = () => {+ const dispatch = useDispatch();++ const { navigateToPath } = useSelector(+ getMetabotReactionsState as any,+ ) as ReturnType<typeof getMetabotReactionsState>;++ const setNavigateToPath = useCallback(+ async (navigateToPath: string) => {+ dispatch(setNavigateToPathAction(navigateToPath));+ },+ [dispatch],+ );++ return {+ navigateToPath,+ setNavigateToPath,+ };+};diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.tsindex c6b01bd278c..878fba6ac43 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts@@ -3,6 +3,7 @@ import { push } from "react-router-redux";import { P, match } from "ts-pattern";import { createAsyncThunk } from "metabase/lib/redux";+import { getIsEmbedding } from "metabase/selectors/embed";import { getUser } from "metabase/selectors/user";import { EnterpriseApi } from "metabase-enterprise/api";import {@@ -40,6 +41,7 @@ export const {addUserMessage,resetConversationId,setIsProcessing,+ setNavigateToPath,toolCallStart,toolCallEnd,} = metabot.actions;@@ -164,6 +166,8 @@ export const sendAgentRequest = createAsyncThunk<req,{ dispatch, getState, signal, rejectWithValue, fulfillWithValue },) => {+ const isEmbedding = getIsEmbedding(getState() as any);+// TODO: make enterprise storelet sessionId = getMetabotConversationId(getState() as any);@@ -195,7 +199,11 @@ export const sendAgentRequest = createAsyncThunk<// only update the convo state if the request is successful.with({ type: "state" }, (part) => (state = part.value)).with({ type: "navigate_to" }, (part) => {- dispatch(push(part.value) as UnknownAction);+ dispatch(setNavigateToPath(part.value));++ if (!isEmbedding) {+ dispatch(push(part.value) as UnknownAction);+ }}).exhaustive();},diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.tsindex e3e6dd7ad0d..3db5c98e769 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts@@ -28,6 +28,10 @@ export type MetabotToolCall = {status: "started" | "ended";};+export type MetabotReactionsState = {+ navigateToPath: string | null;+};+export interface MetabotState {isProcessing: boolean;conversationId: string;@@ -36,6 +40,7 @@ export interface MetabotState {visible: boolean;history: MetabotHistory;state: any;+ reactions: MetabotReactionsState;toolCalls: MetabotToolCall[];}@@ -47,6 +52,9 @@ export const getMetabotInitialState = (): MetabotState => ({visible: false,history: [],state: {},+ reactions: {+ navigateToPath: null,+ },toolCalls: [],});@@ -147,6 +155,9 @@ export const metabot = createSlice({setIsProcessing: (state, action: PayloadAction<boolean>) => {state.isProcessing = action.payload;},+ setNavigateToPath: (state, action: PayloadAction<string>) => {+ state.reactions.navigateToPath = action.payload;+ },setVisible: (state, action: PayloadAction<boolean>) => {state.visible = action.payload;},diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.tsindex 71d2ebf43b0..e0a5ea89fc6 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts@@ -6,12 +6,14 @@ import { getIsEmbedding } from "metabase/selectors/embed";import {FIXED_METABOT_IDS,LONG_CONVO_MSG_LENGTH_THRESHOLD,+ METABOT_REQUEST_IDS,} from "../constants";import type { MetabotStoreState } from "./types";-export const getMetabot = (state: MetabotStoreState) =>- state.plugins.metabotPlugin;+export const getMetabot = (state: MetabotStoreState) => {+ return state.plugins.metabotPlugin;+};export const getMetabotVisible = createSelector(getMetabot,@@ -89,6 +91,11 @@ export const getMetabotState = createSelector((metabot) => metabot.state,);+export const getMetabotReactionsState = createSelector(+ getMetabot,+ (metabot) => metabot.reactions,+);+export const getIsLongMetabotConversation = createSelector(getMessages,(messages) => {@@ -103,6 +110,11 @@ export const getMetabotId = createSelector(getIsEmbedding, (isEmbedding) =>isEmbedding ? FIXED_METABOT_IDS.EMBEDDED : FIXED_METABOT_IDS.DEFAULT,);+export const getMetabotRequestId = createSelector(+ getIsEmbedding,+ (isEmbedding) => (isEmbedding ? METABOT_REQUEST_IDS.EMBEDDED : undefined),+);+export const getAgentRequestMetadata = createSelector(getHistory,getMetabotState,@@ -114,3 +126,8 @@ export const getAgentRequestMetadata = createSelector(),}),);++export const getNavigateToPath = createSelector(+ getMetabotReactionsState,+ (reactionsState) => reactionsState.navigateToPath,+);