Skip to content

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

[Metabot] Multi-convo support (#66864)

Sloan Sparger7615ef0b9b27
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
index 85b0a1c3eba..d54a3fad6d8 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
@@ -3,10 +3,7 @@ import { useEffect, useRef } from "react";
import { Stack } 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 { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
import { useMetabotReactions } from "metabase-enterprise/metabot/hooks/use-metabot-reactions";
import S from "./MetabotQuestion.module.css";
@@ -14,7 +11,6 @@ import S from "./MetabotQuestion.module.css";
export function MetabotChatHistory() {
const metabot = useMetabotAgent();
const { messages, errorMessages } = metabot;
- const { handleRetryMessage } = useMetabotChatHandlers();
const { setNavigateToPath } = useMetabotReactions();
const scrollContainerRef = useRef<HTMLDivElement>(null);
@@ -41,13 +37,17 @@ export function MetabotChatHistory() {
<Messages
messages={messages}
errorMessages={errorMessages}
- onRetryMessage={handleRetryMessage}
+ onRetryMessage={metabot.retryMessage}
isDoingScience={metabot.isDoingScience}
showFeedbackButtons={false}
onInternalLinkClick={setNavigateToPath}
/>
) : null}
- {metabot.isLongConversation && <MetabotResetLongChatButton />}
+ {metabot.isLongConversation && (
+ <MetabotResetLongChatButton
+ onResetConversation={metabot.resetConversation}
+ />
+ )}
</Stack>
);
}
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatInput.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatInput.tsx
index 51faa4ecdc9..91ef8031f39 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatInput.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatInput.tsx
@@ -2,7 +2,6 @@ import cx from "classnames";
import type { LegacyRef } from "react";
import { t } from "ttag";
-import { useSdkDispatch } from "embedding-sdk-bundle/store";
import {
Flex,
Icon,
@@ -12,35 +11,17 @@ import {
Tooltip,
UnstyledButton,
} from "metabase/ui";
-import {
- useMetabotAgent,
- useMetabotChatHandlers,
-} from "metabase-enterprise/metabot/hooks";
-import { cancelInflightAgentRequests } from "metabase-enterprise/metabot/state";
+import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
import S from "./MetabotQuestion.module.css";
export function MetabotChatInput() {
const metabot = useMetabotAgent();
- const { handleSubmitInput, handleResetInput } = useMetabotChatHandlers();
- const dispatch = useSdkDispatch();
const placeholder = metabot.isDoingScience
? t`Doing science...`
: t`Ask AI a question...`;
- const cancelRequest = () => {
- dispatch(cancelInflightAgentRequests());
- };
-
- const resetInput = () => {
- handleResetInput();
- };
-
- const startNewConversation = () => {
- metabot.resetConversation();
- };
-
return (
<Flex
gap="xs"
@@ -85,7 +66,7 @@ export function MetabotChatInput() {
if (e.key === "Enter" && !isModifiedKeyPress) {
e.preventDefault();
e.stopPropagation();
- handleSubmitInput(metabot.prompt);
+ metabot.submitInput(metabot.prompt, { focusInput: true });
}
}}
/>
@@ -93,7 +74,7 @@ export function MetabotChatInput() {
<Flex align="center" justify="center" gap="xs">
{metabot.isDoingScience && (
<UnstyledButton
- onClick={cancelRequest}
+ onClick={metabot.cancelRequest}
className={cx(S.chatButton, S.stopGenerationButton)}
>
<Tooltip label={t`Stop generation`}>
@@ -104,7 +85,7 @@ export function MetabotChatInput() {
{!metabot.isDoingScience && metabot.prompt.length > 0 && (
<UnstyledButton
- onClick={resetInput}
+ onClick={() => metabot.setPrompt("")}
data-testid="metabot-close-chat"
className={S.chatButton}
>
@@ -126,7 +107,7 @@ export function MetabotChatInput() {
<Menu.Dropdown>
<Menu.Item
leftSection={<Icon name="edit_document_outlined" size="1rem" />}
- onClick={startNewConversation}
+ onClick={metabot.resetConversation}
>
{t`Start new chat`}
</Menu.Item>
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatSuggestions.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatSuggestions.tsx
index 8309d26b0b8..e60cf936306 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatSuggestions.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatSuggestions.tsx
@@ -1,15 +1,11 @@
import { Button, Stack } from "metabase/ui";
import { useGetSuggestedMetabotPromptsQuery } from "metabase-enterprise/api";
-import {
- useMetabotAgent,
- useMetabotChatHandlers,
-} from "metabase-enterprise/metabot/hooks";
+import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
import S from "./MetabotQuestion.module.css";
export const MetabotChatSuggestions = () => {
const metabot = useMetabotAgent();
- const { handleSubmitInput } = useMetabotChatHandlers();
// Keep in sync with [MetabotChat.tsx]
const suggestedPromptsQuery = useGetSuggestedMetabotPromptsQuery({
@@ -38,7 +34,7 @@ export const MetabotChatSuggestions = () => {
size="xs"
variant="outline"
fw={400}
- onClick={() => handleSubmitInput(prompt)}
+ onClick={() => metabot.submitInput(prompt, { focusInput: true })}
className={S.promptSuggestionButton}
data-testid="metabot-suggestion-button"
>
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/SidebarHeader.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/SidebarHeader.tsx
index fd211c42d6e..d198a737725 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/SidebarHeader.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/SidebarHeader.tsx
@@ -8,10 +8,6 @@ import S from "./MetabotQuestion.module.css";
export function SidebarHeader() {
const metabot = useMetabotAgent();
- const startNewConversation = () => {
- metabot.resetConversation();
- };
-
return (
<Flex
px="md"
@@ -26,7 +22,7 @@ export function SidebarHeader() {
<Tooltip label={t`Start new chat`}>
<UnstyledButton
- onClick={startNewConversation}
+ onClick={() => metabot.resetConversation()}
data-testid="metabot-new-conversation"
>
<Icon
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/components/AIQuestionAnalysisButton.tsx b/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/components/AIQuestionAnalysisButton.tsx
index 463b80e25ea..fd8f5e72a4e 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/components/AIQuestionAnalysisButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/components/AIQuestionAnalysisButton.tsx
@@ -6,7 +6,7 @@ import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
import { trackExplainChartClicked } from "../analytics";
export const AIQuestionAnalysisButton = () => {
- const { submitInput } = useMetabotAgent();
+ const { submitInput } = useMetabotAgent("omnibot");
const handleClick = () => {
trackExplainChartClicked();
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/components/FixSqlQueryButton/FixSqlQueryButton.tsx b/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/components/FixSqlQueryButton/FixSqlQueryButton.tsx
index 049c2a48664..8abb47d04ac 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/components/FixSqlQueryButton/FixSqlQueryButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/components/FixSqlQueryButton/FixSqlQueryButton.tsx
@@ -6,7 +6,7 @@ import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
import { trackQueryFixClicked } from "../../analytics";
export function FixSqlQueryButton() {
- const { submitInput } = useMetabotAgent();
+ const { submitInput } = useMetabotAgent("omnibot");
const handleClick = () => {
trackQueryFixClicked();
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
index 2db7628520c..77a05580ee0 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
@@ -1,2 +1,5 @@
-export { aiStreamingQuery, getInflightRequestsForUrl } from "./requests";
+export {
+ aiStreamingQuery,
+ findMatchingInflightAiStreamingRequests,
+} from "./requests";
export type { JSONValue } from "./types";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
index 8f194971858..c8777bfbfd2 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
@@ -9,12 +9,21 @@ import type { JSONValue } from "./types";
// places in the app w/o passing references to the abort controller directly
export const inflightAiStreamingRequests = new Map<
string,
- { abortController: AbortController }
+ {
+ sourceId?: string;
+ abortController: AbortController;
+ }
>();
-export const getInflightRequestsForUrl = (url: string) => {
+export const findMatchingInflightAiStreamingRequests = (
+ url: string,
+ sourceId?: string,
+) => {
return [...inflightAiStreamingRequests.entries()]
- .filter(([reqId]) => reqId.startsWith(`${url}-`))
+ .filter(
+ ([reqId, req]) =>
+ reqId.startsWith(`${url}-`) && (!sourceId || sourceId === req.sourceId),
+ )
.map(([_reqId, reqInfo]) => reqInfo);
};
@@ -27,6 +36,7 @@ export async function aiStreamingQuery(
url: string;
signal?: AbortSignal | null | undefined;
body: JSONValue;
+ sourceId?: string;
},
config: AIStreamingConfig = {},
) {
@@ -41,7 +51,10 @@ export async function aiStreamingQuery(
inflightAiStreamingRequests.delete(reqId);
});
}
- inflightAiStreamingRequests.set(reqId, { abortController });
+ inflightAiStreamingRequests.set(reqId, {
+ sourceId: req.sourceId,
+ abortController,
+ });
// The basename is needed to work within the Embedding SDK
const response = await fetch(`${api.basename}${req.url}`, {
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.ts
index 10fc1b0aec8..5cd434117a6 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
@@ -2,7 +2,10 @@ import fetchMock from "fetch-mock";
import api from "metabase/lib/api";
-import { aiStreamingQuery, getInflightRequestsForUrl } from "./requests";
+import {
+ aiStreamingQuery,
+ findMatchingInflightAiStreamingRequests,
+} from "./requests";
import { mockStreamedEndpoint } from "./test-utils";
const endpoint = "/some-streamed-endpoint";
@@ -119,26 +122,38 @@ describe("ai requests", () => {
mockStreamedEndpoint(endpoint, {
textChunks: whoIsYourFavoriteResponse,
});
- expect(getInflightRequestsForUrl(endpoint).length).toBe(0);
+ expect(findMatchingInflightAiStreamingRequests(endpoint).length).toBe(
+ 0,
+ );
const promise = aiStreamingQuery({ url: endpoint, body: {} });
- expect(getInflightRequestsForUrl(endpoint).length).toBe(1);
+ expect(findMatchingInflightAiStreamingRequests(endpoint).length).toBe(
+ 1,
+ );
await promise;
- expect(getInflightRequestsForUrl(endpoint).length).toBe(0);
+ expect(findMatchingInflightAiStreamingRequests(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);
+ expect(findMatchingInflightAiStreamingRequests(endpoint).length).toBe(
+ 0,
+ );
const promise = aiStreamingQuery({
url: endpoint,
body: {},
signal: controller.signal,
});
- expect(getInflightRequestsForUrl(endpoint).length).toBe(1);
+ expect(findMatchingInflightAiStreamingRequests(endpoint).length).toBe(
+ 1,
+ );
controller.abort();
- expect(getInflightRequestsForUrl(endpoint).length).toBe(0);
+ expect(findMatchingInflightAiStreamingRequests(endpoint).length).toBe(
+ 0,
+ );
try {
await promise;
} catch (err) {}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
index cfe6431c948..2a8070d6c50 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
@@ -8,11 +8,13 @@ import { getUser } from "metabase/selectors/user";
import { trackMetabotChatOpened } from "../analytics";
import { useMetabotAgent } from "../hooks";
+import type { MetabotAgentId } from "../state";
import { MetabotChat } from "./MetabotChat";
// TODO: add test coverage for these
export interface MetabotConfig {
+ agentId?: MetabotAgentId;
emptyText?: string;
hideSuggestedPrompts?: boolean;
preventClose?: boolean;
@@ -26,7 +28,7 @@ export interface MetabotProps {
}
export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {
- const { visible, setVisible } = useMetabotAgent();
+ const { visible, setVisible } = useMetabotAgent(config?.agentId ?? "omnibot");
useEffect(() => {
return tinykeys(window, {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx
index d4a629c4763..11ebba80d8e 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx
@@ -14,7 +14,7 @@ export function MetabotAppBarButton({
className,
...rest
}: MetabotAppBarButtonProps) {
- const metabot = useMetabotAgent();
+ const metabot = useMetabotAgent("omnibot");
const handleClick = () => {
if (!metabot.visible) {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.unit.spec.tsx
index dc77e596564..ea15f614ca9 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.unit.spec.tsx
@@ -18,7 +18,7 @@ import { createMockState } from "metabase-types/store/mocks";
import type {
MetabotAgentEditSuggestionChatMessage,
MetabotSuggestedTransform,
-} from "../../state/reducer";
+} from "../../state/types";
import { AgentSuggestionMessage } from "./MetabotAgentSuggestionMessage";
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 a83ee4b4958..50fae83370a 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
@@ -1,5 +1,5 @@
import cx from "classnames";
-import { useCallback, useMemo } from "react";
+import { useMemo } from "react";
import { t } from "ttag";
import EmptyDashboardBot from "assets/img/dashboard-empty.svg?component";
@@ -18,7 +18,7 @@ import {
import { useGetSuggestedMetabotPromptsQuery } from "metabase-enterprise/api";
import { MetabotResetLongChatButton } from "metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton";
-import { useMetabotAgent, useMetabotChatHandlers } from "../../hooks";
+import { useMetabotAgent } from "../../hooks";
import type { MetabotConfig } from "../Metabot";
import Styles from "./MetabotChat.module.css";
@@ -28,6 +28,7 @@ import { MetabotThinking } from "./MetabotThinking";
import { useScrollManager } from "./hooks";
const defaultConfig: MetabotConfig = {
+ agentId: "omnibot",
suggestionModels: [
"dataset",
"metric",
@@ -43,9 +44,7 @@ export const MetabotChat = ({
}: {
config?: MetabotConfig;
}) => {
- const metabot = useMetabotAgent();
- const { handleSubmitInput, handleRetryMessage, handleResetInput } =
- useMetabotChatHandlers(config);
+ const metabot = useMetabotAgent(config.agentId);
const hasMessages =
metabot.messages.length > 0 || metabot.errorMessages.length > 0;
@@ -62,19 +61,17 @@ export const MetabotChat = ({
return suggestedPromptsReq.currentData?.prompts ?? [];
}, [suggestedPromptsReq.currentData?.prompts]);
+ const handleResetChat = () => {
+ metabot.resetConversation();
+ suggestedPromptsReq.refetch();
+ };
+
const handleClose = () => {
- handleResetInput();
+ metabot.setPrompt("");
metabot.setVisible(false);
};
- const handleEditorChange = useCallback(
- (value: string) => metabot.setPrompt(value),
- [metabot],
- );
-
- const handleEditorSubmit = useCallback(() => {
- handleSubmitInput(metabot.prompt);
- }, [handleSubmitInput, metabot.prompt]);
+ const handleEditorSubmit = () => metabot.submitInput(metabot.prompt);
return (
<Sidebar
@@ -97,7 +94,7 @@ export const MetabotChat = ({
<Flex gap="sm">
<Tooltip label={t`Clear conversation`} position="bottom">
<ActionIcon
- onClick={() => metabot.resetConversation()}
+ onClick={handleResetChat}
data-testid="metabot-reset-chat"
>
<Icon c="text-primary" name="revert" />
@@ -149,7 +146,7 @@ export const MetabotChat = ({
<Button
fz="sm"
size="xs"
- onClick={() => handleSubmitInput(prompt)}
+ onClick={() => metabot.submitInput(prompt)}
className={Styles.promptSuggestionButton}
>
{prompt}
@@ -171,7 +168,9 @@ export const MetabotChat = ({
<Messages
messages={metabot.messages}
errorMessages={metabot.errorMessages}
- onRetryMessage={handleRetryMessage}
+ onRetryMessage={
+ config.preventRetryMessage ? undefined : metabot.retryMessage
+ }
isDoingScience={metabot.isDoingScience}
showFeedbackButtons
/>
@@ -182,7 +181,11 @@ export const MetabotChat = ({
{/* filler - height gets set via ref mutation */}
<div ref={fillerRef} data-testid="metabot-message-filler" />
{/* long convo warning */}
- {metabot.isLongConversation && <MetabotResetLongChatButton />}
+ {metabot.isLongConversation && (
+ <MetabotResetLongChatButton
+ onResetConversation={metabot.resetConversation}
+ />
+ )}
</Box>
)}
</Box>
@@ -200,7 +203,7 @@ export const MetabotChat = ({
autoFocus
isResponding={metabot.isDoingScience}
placeholder={t`Tell me to do something, or ask a question`}
- onChange={handleEditorChange}
+ onChange={metabot.setPrompt}
onSubmit={handleEditorSubmit}
onStop={metabot.cancelRequest}
suggestionModels={config.suggestionModels}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotFeedbackModal.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
index 7268808034a..613a9aee7e3 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
@@ -8,7 +8,11 @@ import { useSelector } from "metabase/lib/redux";
import { getUserIsAdmin } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Button, Group, Modal, Stack, Text } from "metabase/ui";
-import { getMetabot, getMetabotId } from "metabase-enterprise/metabot/state";
+import { useMetabotSelector } from "metabase-enterprise/metabot/hooks/use-metabot-store";
+import {
+ getMetabotId,
+ getMetabotState,
+} from "metabase-enterprise/metabot/state";
import type { MetabotFeedback } from "metabase-types/api";
interface MetabotFeedbackModalProps {
@@ -28,12 +32,8 @@ export const MetabotFeedbackModal = ({
const isAdmin = useSelector(getUserIsAdmin);
const version = useSetting("version");
- const metabotId = useSelector(getMetabotId as any) as ReturnType<
- typeof getMetabotId
- >;
- const metabotState = useSelector(getMetabot as any) as ReturnType<
- typeof getMetabot
- >;
+ const metabotId = useMetabotSelector(getMetabotId);
+ const metabotState = useMetabotSelector(getMetabotState);
const handleSubmit = (
values: Pick<
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx
index 641740a9cff..782bea6db6a 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotResetLongChatButton.tsx
@@ -1,24 +1,25 @@
import { c, jt } from "ttag";
import { Text, UnstyledButton } from "metabase/ui";
-import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
-export const MetabotResetLongChatButton = () => {
- const metabot = useMetabotAgent();
+interface MetabotResetLongChatButtonProps {
+ onResetConversation: () => void;
+}
- 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>
- );
-};
+export const MetabotResetLongChatButton = ({
+ onResetConversation,
+}: MetabotResetLongChatButtonProps) => (
+ <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={onResetConversation}
+ >{c("'it' refers to a chat with an AI agent")
+ .t`clear it`}</UnstyledButton>
+ )}.`}
+ </Text>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotDataStudioButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotDataStudioButton.tsx
index 842008c224a..48180065214 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotDataStudioButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotDataStudioButton.tsx
@@ -10,7 +10,7 @@ import { trackMetabotChatOpened } from "../analytics";
import { useMetabotAgent } from "../hooks";
export const MetabotDataStudioButton = () => {
- const metabot = useMetabotAgent();
+ const metabot = useMetabotAgent("omnibot");
const location = useSelector(getLocation);
const disabled = !location.pathname?.startsWith(Urls.transformList());
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotQuickLinks.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotQuickLinks.tsx
index b0ec41d5973..7545e32906d 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotQuickLinks.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotQuickLinks.tsx
@@ -11,7 +11,7 @@ export const getMetabotQuickLinks = () => {
key="metabot"
path="metabot/new"
component={(props) => {
- const { startNewConversation } = useMetabotAgent();
+ const { submitInput } = useMetabotAgent("omnibot");
const prompt = String(props.location.query?.q ?? "");
const dispatch = useDispatch();
@@ -19,7 +19,7 @@ export const getMetabotQuickLinks = () => {
dispatch(replace("/"));
if (prompt) {
- startNewConversation(prompt);
+ submitInput(prompt, { focusInput: true });
}
});
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx
index 3005d4f1d72..cc5258c9603 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx
@@ -10,7 +10,7 @@ interface MetabotToggleButtonProps {
}
export function MetabotToggleButton({ className }: MetabotToggleButtonProps) {
- const metabot = useMetabotAgent();
+ const metabot = useMetabotAgent("omnibot");
const handleClick = () => {
if (!metabot.visible) {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts
index 24c2b58a2ac..237f62445d1 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/index.ts
@@ -1,2 +1,2 @@
export { useMetabotAgent } from "./use-metabot-agent";
-export { useMetabotChatHandlers } from "./use-metabot-chat-handlers";
+export { useMetabotAgentsManager } from "./use-metabot-agents-manager";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.ts
index b5ec08560ea..0b28670daaf 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agent.ts
@@ -1,11 +1,11 @@
import { isFulfilled } from "@reduxjs/toolkit";
import { useCallback } from "react";
-import { useDispatch, useSelector } from "metabase/lib/redux";
import { useMetabotContext } from "metabase/metabot";
import { trackMetabotRequestSent } from "../analytics";
import {
+ type MetabotAgentId,
type MetabotPromptSubmissionResult,
type MetabotUserChatMessage,
cancelInflightAgentRequests,
@@ -26,63 +26,23 @@ import {
submitInput as submitInputAction,
} from "../state";
-export const useMetabotAgent = () => {
- const dispatch = useDispatch();
+import { useMetabotDispatch, useMetabotSelector } from "./use-metabot-store";
+
+export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
+ const dispatch = useMetabotDispatch();
const { prompt, setPrompt, promptInputRef, getChatContext } =
useMetabotContext();
- const isDoingScience = useSelector(getIsProcessing as any) as ReturnType<
- typeof getIsProcessing
- >;
-
- // TODO: create an enterprise useSelector
- const messages = useSelector(getMessages as any) as ReturnType<
- typeof getMessages
- >;
-
- const errorMessages = useSelector(getAgentErrorMessages as any) as ReturnType<
- typeof getAgentErrorMessages
- >;
-
- 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 activeToolCalls = useSelector(getActiveToolCalls as any) as ReturnType<
- typeof getActiveToolCalls
- >;
-
- const debugMode = useSelector(getDebugMode as any) as ReturnType<
- typeof getDebugMode
- >;
-
- const setVisible = useCallback(
- (isVisible: boolean) => dispatch(setVisibleAction(isVisible)),
- [dispatch],
+ const metabotRequestId = useMetabotSelector((state) =>
+ getMetabotRequestId(state, agentId),
+ );
+ const visible = useMetabotSelector((state) =>
+ getMetabotVisible(state, agentId),
);
- const profileOverride = useSelector(getProfileOverride as any) as ReturnType<
- typeof getProfileOverride
- >;
-
- const reactions = useSelector(getMetabotReactionsState as any) as ReturnType<
- typeof getMetabotReactionsState
- >;
-
- const resetConversation = useCallback(
- () => dispatch(resetConversationAction()),
- [dispatch],
+ const setVisible = useCallback(
+ (visible: boolean) => dispatch(setVisibleAction({ agentId, visible })),
+ [dispatch, agentId],
);
const prepareRetryIfUnsuccesful = useCallback(
@@ -96,27 +56,33 @@ export const useMetabotAgent = () => {
);
const submitInput = useCallback(
- async (prompt: string | Omit<MetabotUserChatMessage, "id" | "role">) => {
- if (!visible) {
+ async (
+ prompt: string | Omit<MetabotUserChatMessage, "id" | "role">,
+ options?: {
+ profile?: string | undefined;
+ preventOpenSidebar?: boolean;
+ focusInput?: boolean;
+ },
+ ) => {
+ setPrompt("");
+
+ if (!visible && !options?.preventOpenSidebar) {
setVisible(true);
}
- const context = await getChatContext();
+ if (options?.focusInput) {
+ promptInputRef?.current?.focus();
+ }
+
const action = await dispatch(
- submitInputAction(
- typeof prompt === "string"
- ? {
- type: "text",
- message: prompt,
- context,
- metabot_id: metabotRequestId,
- }
- : {
- ...prompt,
- context,
- metabot_id: metabotRequestId,
- },
- ),
+ submitInputAction({
+ ...(typeof prompt === "string"
+ ? { type: "text", message: prompt }
+ : prompt),
+ context: await getChatContext(),
+ agentId,
+ metabot_id: metabotRequestId,
+ }),
);
trackMetabotRequestSent();
@@ -134,6 +100,9 @@ export const useMetabotAgent = () => {
prepareRetryIfUnsuccesful,
setVisible,
visible,
+ agentId,
+ promptInputRef,
+ setPrompt,
],
);
@@ -145,50 +114,58 @@ export const useMetabotAgent = () => {
messageId,
context,
metabot_id: metabotRequestId,
+ agentId,
}),
);
if (isFulfilled(action)) {
prepareRetryIfUnsuccesful(action.payload);
}
},
- [dispatch, getChatContext, metabotRequestId, prepareRetryIfUnsuccesful],
+ [
+ dispatch,
+ getChatContext,
+ metabotRequestId,
+ prepareRetryIfUnsuccesful,
+ agentId,
+ ],
);
const cancelRequest = useCallback(() => {
- dispatch(cancelInflightAgentRequests());
- }, [dispatch]);
-
- const startNewConversation = useCallback(
- async (message: string) => {
- await resetConversation();
- setVisible(true);
- if (message) {
- submitInput(message);
- }
- promptInputRef?.current?.focus();
- },
- [resetConversation, setVisible, promptInputRef, submitInput],
- );
+ dispatch(cancelInflightAgentRequests(agentId));
+ }, [dispatch, agentId]);
+
+ const resetConversation = useCallback(() => {
+ dispatch(resetConversationAction({ agentId }));
+ }, [agentId, dispatch]);
return {
- isDoingScience,
prompt,
setPrompt,
promptInputRef,
- metabotId,
visible,
- messages,
- errorMessages,
- isLongConversation,
- resetConversation,
setVisible,
- startNewConversation,
+ resetConversation,
submitInput,
retryMessage,
cancelRequest,
- activeToolCalls,
- debugMode,
- profileOverride,
- reactions,
+ metabotId: useMetabotSelector(getMetabotId),
+ messages: useMetabotSelector((state) => getMessages(state, agentId)),
+ errorMessages: useMetabotSelector((state) =>
+ getAgentErrorMessages(state, agentId),
+ ),
+ isDoingScience: useMetabotSelector((state) =>
+ getIsProcessing(state, agentId),
+ ),
+ isLongConversation: useMetabotSelector((state) =>
+ getIsLongMetabotConversation(state, agentId),
+ ),
+ activeToolCalls: useMetabotSelector((state) =>
+ getActiveToolCalls(state, agentId),
+ ),
+ debugMode: useMetabotSelector(getDebugMode),
+ profileOverride: useMetabotSelector((state) =>
+ getProfileOverride(state, agentId),
+ ),
+ reactions: useMetabotSelector(getMetabotReactionsState),
};
};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agents-manager.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agents-manager.ts
new file mode 100644
index 00000000000..72ee6de6667
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-agents-manager.ts
@@ -0,0 +1,47 @@
+import { useCallback } from "react";
+import { useMount } from "react-use";
+import _ from "underscore";
+
+import {
+ type MetabotAgentId,
+ createAgent as createAgentAction,
+ destroyAgent,
+ getActiveMetabotAgentIds,
+ resetConversation,
+} from "../state";
+
+import { useMetabotDispatch, useMetabotSelector } from "./use-metabot-store";
+
+type CreatePayload = Parameters<typeof createAgentAction>[0];
+type DestroyPayload = Parameters<typeof destroyAgent>[0];
+type ResetPayload = Parameters<typeof resetConversation>[0];
+
+export const useMetabotAgentsManager = (
+ autoStartAgentIds: MetabotAgentId[],
+) => {
+ const dispatch = useMetabotDispatch();
+ const activeAgentIds = useMetabotSelector(getActiveMetabotAgentIds);
+
+ useMount(() => {
+ const agentIdsToStart = _.difference(autoStartAgentIds, activeAgentIds);
+ agentIdsToStart.forEach((agentId) =>
+ dispatch(createAgentAction({ agentId, visible: false })),
+ );
+ });
+
+ return {
+ activeAgentIds,
+ createAgent: useCallback(
+ (p: CreatePayload) => dispatch(createAgentAction(p)),
+ [dispatch],
+ ),
+ resetConversation: useCallback(
+ (p: ResetPayload) => dispatch(resetConversation(p)),
+ [dispatch],
+ ),
+ destroyAgent: useCallback(
+ (p: DestroyPayload) => dispatch(destroyAgent(p)),
+ [dispatch],
+ ),
+ };
+};
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.ts
deleted file mode 100644
index 8c9d07a0e61..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-chat-handlers.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useCallback, useMemo } from "react";
-
-import type { MetabotConfig } from "../components/Metabot";
-
-import { useMetabotAgent } from "./use-metabot-agent";
-
-export const useMetabotChatHandlers = (
- config?: Partial<Pick<MetabotConfig, "preventRetryMessage">>,
-) => {
- 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 = useMemo(() => {
- if (config?.preventRetryMessage) {
- return undefined;
- }
-
- return (messageId: string) => {
- if (isDoingScience) {
- return;
- }
-
- setPrompt("");
- promptInputRef?.current?.focus();
- retryMessage(messageId).catch((err) => console.error(err));
- };
- }, [
- config?.preventRetryMessage,
- 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.ts
index 36210197bec..7479385fe96 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-reactions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-reactions.ts
@@ -1,17 +1,17 @@
import { useCallback } from "react";
-import { useDispatch, useSelector } from "metabase/lib/redux";
+import { useDispatch } from "metabase/lib/redux";
import {
- getMetabotReactionsState,
+ getNavigateToPath,
setNavigateToPath as setNavigateToPathAction,
} from "metabase-enterprise/metabot/state";
+import { useMetabotSelector } from "./use-metabot-store";
+
export const useMetabotReactions = () => {
const dispatch = useDispatch();
- const { navigateToPath } = useSelector(
- getMetabotReactionsState as any,
- ) as ReturnType<typeof getMetabotReactionsState>;
+ const navigateToPath = useMetabotSelector(getNavigateToPath);
const setNavigateToPath = useCallback(
async (navigateToPath: string) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-store.ts b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-store.ts
new file mode 100644
index 00000000000..88b044eabfa
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/hooks/use-metabot-store.ts
@@ -0,0 +1,16 @@
+import type { AnyAction, ThunkDispatch } from "@reduxjs/toolkit";
+import type { TypedUseSelectorHook } from "react-redux";
+import { createDispatchHook, createSelectorHook } from "react-redux";
+
+import { MetabaseReduxContext } from "metabase/lib/redux";
+
+import type { MetabotStoreState } from "../state/types";
+
+export const useMetabotSelector: TypedUseSelectorHook<MetabotStoreState> =
+ createSelectorHook(MetabaseReduxContext);
+
+export const useMetabotDispatch: () => ThunkDispatch<
+ MetabotStoreState,
+ void,
+ AnyAction
+> = createDispatchHook(MetabaseReduxContext);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index 00298752fa5..f2f20f156ac 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -60,7 +60,6 @@ export function initializePlugin() {
</Route>
);
- // TODO: make enterprise store + fix type
PLUGIN_METABOT.getMetabotVisible =
getMetabotVisible as unknown as typeof PLUGIN_METABOT.getMetabotVisible;
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 db205b45b96..5bbd5fd4f0b 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
@@ -2,6 +2,7 @@
import { combineReducers } from "@reduxjs/toolkit";
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
+import { assocIn } from "icepick";
import { P, isMatching } from "ts-pattern";
import _ from "underscore";
@@ -10,7 +11,6 @@ import { setupDatabaseListEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import {
act,
- fireEvent,
renderWithProviders,
screen,
waitFor,
@@ -20,15 +20,14 @@ import { logout } from "metabase/auth/actions";
import * as domModule from "metabase/lib/dom";
import { useRegisterMetabotContextProvider } from "metabase/metabot";
import {
- type MockStreamedEndpointParams,
createMockReadableStream,
createPauses,
- mockStreamedEndpoint,
} from "metabase-enterprise/api/ai-streaming/test-utils";
import type { User } from "metabase-types/api";
import {
createMockDatabase,
createMockTokenFeatures,
+ createMockTransform,
createMockUser,
createMockUserPermissions,
} from "metabase-types/api/mocks";
@@ -44,18 +43,35 @@ import { MetabotProvider } from "./context";
import { useMetabotAgent } from "./hooks";
import {
type MetabotState,
+ type MetabotStoreState,
+ addSuggestedTransform,
addUserMessage,
getHistory,
- getMetabot,
- getMetabotConversationId,
- getMetabotInitialState,
- getMetabotState,
+ getMetabotConversation,
+ getMetabotReactionsState,
+ getMetabotRequestState,
metabotReducer,
- setVisible,
+ setNavigateToPath,
} from "./state";
-
-const mockAgentEndpoint = (params: MockStreamedEndpointParams) =>
- mockStreamedEndpoint("/api/ee/metabot-v3/agent-streaming", params);
+import { getMetabotInitialState } from "./state/reducer-utils";
+import {
+ assertConversation,
+ assertNotVisible,
+ assertVisible,
+ chat,
+ closeChatButton,
+ enterChatMessage,
+ hideMetabot,
+ input,
+ lastChatMessage,
+ lastReqBody,
+ mockAgentEndpoint,
+ resetChatButton,
+ responseLoader,
+ sendMessageButton,
+ showMetabot,
+ stopResponseButton,
+} from "./tests/utils";
function setup(
options: {
@@ -73,14 +89,17 @@ function setup(
setupEnterprisePlugins();
+ const _metabotState = getMetabotInitialState();
+ const metabotState = assocIn(
+ _metabotState,
+ ["conversations", "omnibot", "visible"],
+ true,
+ );
+
const {
ui = <Metabot />,
currentUser = createMockUser(),
- metabotPluginInitialState = {
- ...getMetabotInitialState(),
- visible: true,
- useStreaming: true,
- },
+ metabotPluginInitialState = metabotState,
promptSuggestions = [],
} = options || {};
@@ -90,86 +109,34 @@ function setup(
);
setupDatabaseListEndpoint([]);
- return renderWithProviders(<MetabotProvider>{ui}</MetabotProvider>, {
- storeInitialState: createMockState({
- settings,
- currentUser: currentUser ? currentUser : undefined,
- plugins: {
- metabotPlugin: metabotPluginInitialState,
+ const { store, rerender } = renderWithProviders(
+ <MetabotProvider>{ui}</MetabotProvider>,
+ {
+ storeInitialState: createMockState({
+ settings,
+ currentUser: currentUser ? currentUser : undefined,
+ plugins: {
+ metabotPlugin: metabotPluginInitialState,
+ },
+ } as any),
+ customReducers: {
+ plugins: combineReducers({
+ metabotPlugin: metabotReducer,
+ }),
},
- } as any),
- customReducers: {
- plugins: combineReducers({
- metabotPlugin: metabotReducer,
- }),
},
- });
-}
-
-const chat = () => screen.findByTestId("metabot-chat");
-const chatMessages = () => screen.findAllByTestId("metabot-chat-message");
-const lastChatMessage = async () => (await chatMessages()).at(-1);
-const input = async () => {
- const chatInput = await screen.findByTestId("metabot-chat-input");
- // get tiptap content editable node
- // eslint-disable-next-line testing-library/no-node-access
- return chatInput.querySelector('[contenteditable="true"]')!;
-};
-const enterChatMessage = async (message: string, send = true) => {
- // using userEvent.type works locally but in CI characters are sometimes dropped
- // so "Who is your favorite?" becomes something like "Woi or fvrite?"
- const editor = await input();
- editor.textContent = message;
- fireEvent.input(editor, {
- target: { textContent: message },
- });
- if (send) {
- await userEvent.type(await input(), "{Enter}");
- }
-};
-const sendMessageButton = () => screen.findByTestId("metabot-send-message");
-const stopResponseButton = () => screen.findByTestId("metabot-stop-response");
-const closeChatButton = () => screen.findByTestId("metabot-close-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();
-const assertNotVisible = async () =>
- await waitFor(() => {
- expect(screen.queryByTestId("metabot-chat")).not.toBeInTheDocument();
- });
-
-// NOTE: for some reason the keyboard shortcuts won't work with tinykeys while testing, using redux for now...
-const hideMetabot = (dispatch: any) => act(() => dispatch(setVisible(false)));
-const showMetabot = (dispatch: any) => act(() => dispatch(setVisible(true)));
-
-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(realMessages.length).toBe(expectedMessages.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);
-};
+ return {
+ rerender,
+ conversationIds: Object.keys(metabotState.conversations),
+ store: store as Omit<typeof store, "getState"> & {
+ getState: () => MetabotStoreState;
+ },
+ };
+}
-describe("metabot-streaming", () => {
+describe("metabot", () => {
describe("ui", () => {
it("should be able to render metabot", async () => {
setup();
@@ -386,7 +353,7 @@ describe("metabot-streaming", () => {
it("should be able to set the prompt input's value from anywhere in the app", async () => {
const AnotherComponent = () => {
- const { setPrompt } = useMetabotAgent();
+ const { setPrompt } = useMetabotAgent("omnibot");
return (
<button onClick={() => setPrompt("TEST VAL")}>CLICK HERE</button>
@@ -493,12 +460,6 @@ describe("metabot-streaming", () => {
});
describe("message", () => {
- it("should have a conversation id before sending any messages", async () => {
- const { store } = setup();
- const state = store.getState() as any;
- expect(getMetabotConversationId(state)).not.toBeUndefined();
- });
-
it("should properly send chat messages", async () => {
setup();
@@ -923,29 +884,29 @@ describe("metabot-streaming", () => {
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);
+ const getConvoReqState = () =>
+ getMetabotRequestState(store.getState(), "omnibot");
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({});
+ expect(getConvoReqState()).toEqual({});
yield `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`;
})(),
),
});
- expect(getState()).toEqual({});
+ expect(getConvoReqState()).toEqual({});
await enterChatMessage("Request");
- expect(getState()).toEqual({ queries: {} });
+ expect(getConvoReqState()).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);
+ const getConvoReqState = () =>
+ getMetabotRequestState(store.getState(), "omnibot");
mockAgentEndpoint({
textChunks: [
@@ -954,14 +915,15 @@ describe("metabot-streaming", () => {
],
});
- expect(getState()).toEqual({});
+ expect(getConvoReqState()).toEqual({});
await enterChatMessage("Request");
- expect(getState()).toEqual({});
+ expect(getConvoReqState()).toEqual({});
});
it("should preserve conversation state if aborted response didn't contain a state data object", async () => {
const { store } = setup();
- const getState = () => getMetabotState(store.getState() as any);
+ const getConvoReqState = () =>
+ getMetabotRequestState(store.getState(), "omnibot");
// insert some state via previous convo
mockAgentEndpoint({
@@ -976,7 +938,7 @@ describe("metabot-streaming", () => {
["user", "gimme state plz"],
["agent", "here ya go"],
]);
- expect(getState()).toEqual({ testing: 123 });
+ expect(getConvoReqState()).toEqual({ testing: 123 });
const [pause1] = createPauses(1);
mockAgentEndpoint({
@@ -999,12 +961,11 @@ describe("metabot-streaming", () => {
await userEvent.click(await stopResponseButton());
pause1.resolve();
- expect(getState()).toEqual({ testing: 123 });
+ expect(getConvoReqState()).toEqual({ testing: 123 });
});
it("should use new state object if aborted response contained one", async () => {
const { store } = setup();
- const getState = () => getMetabotState(store.getState() as any);
// insert some state via previous convo
const [pause1] = createPauses(1);
@@ -1018,7 +979,8 @@ describe("metabot-streaming", () => {
});
await enterChatMessage("hi");
await userEvent.click(await stopResponseButton());
- expect(getState()).toEqual({ testing: 123 });
+ const reqState = getMetabotRequestState(store.getState(), "omnibot");
+ expect(reqState).toEqual({ testing: 123 });
});
});
@@ -1078,12 +1040,12 @@ describe("metabot-streaming", () => {
],
});
- const initialHistory = getHistory(store.getState() as any);
+ const initialHistory = getHistory(store.getState(), "omnibot");
expect(initialHistory).toEqual([]);
await enterChatMessage("Who is your favorite?");
- const finalHistory = getHistory(store.getState() as any);
+ const finalHistory = getHistory(store.getState(), "omnibot");
expect(finalHistory).toHaveLength(2);
expect(finalHistory[0].role).toBe("user");
expect(finalHistory[0].content).toBe("Who is your favorite?");
@@ -1093,7 +1055,8 @@ describe("metabot-streaming", () => {
it("should clear history when the user hits the reset button", async () => {
const { store } = setup();
- const getState = () => getMetabot(store.getState() as any);
+ const getState = () =>
+ getMetabotConversation(store.getState(), "omnibot");
mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });
// send a message to get some history back
@@ -1104,13 +1067,12 @@ describe("metabot-streaming", () => {
]);
const beforeResetState = getState();
- expect(beforeResetState.conversationId).not.toBe(null);
- expect(_.omit(beforeResetState.messages[0], "id")).toStrictEqual({
+ expect(_.omit(beforeResetState.messages[0], ["id"])).toStrictEqual({
role: "user",
type: "text",
message: "Who is your favorite?",
});
- expect(_.omit(beforeResetState.messages[1], "id")).toStrictEqual({
+ expect(_.omit(beforeResetState.messages[1], ["id"])).toStrictEqual({
role: "agent",
type: "text",
message: "You, but don't tell anyone.",
@@ -1132,7 +1094,12 @@ describe("metabot-streaming", () => {
// adding messages this long via the ui's input makes the test hang
act(() => {
store.dispatch(
- addUserMessage({ id: "1", type: "text", message: longMsg }),
+ addUserMessage({
+ id: "1",
+ type: "text",
+ message: longMsg,
+ agentId: "omnibot",
+ }),
);
});
expect(await screen.findByText(/xxxxxxx/)).toBeInTheDocument();
@@ -1142,7 +1109,12 @@ describe("metabot-streaming", () => {
act(() => {
store.dispatch(
- addUserMessage({ id: "2", type: "text", message: longMsg }),
+ addUserMessage({
+ id: "2",
+ type: "text",
+ message: longMsg,
+ agentId: "omnibot",
+ }),
);
});
expect(
@@ -1176,7 +1148,7 @@ describe("metabot-streaming", () => {
await enterChatMessage("hi");
await userEvent.click(await stopResponseButton());
pause1.resolve();
- expect(getHistory(store.getState() as any)).toMatchObject([
+ expect(getHistory(store.getState(), "omnibot")).toMatchObject([
{ content: "hi", role: "user" },
{
role: "assistant",
@@ -1191,6 +1163,32 @@ describe("metabot-streaming", () => {
});
});
+ describe("reaction state", () => {
+ it("should clear navigateToPath and suggestedTransforms when resetting omnibot conversation", async () => {
+ const { store } = setup();
+ const getReactions = () => getMetabotReactionsState(store.getState());
+
+ act(() => {
+ store.dispatch(setNavigateToPath("/some/path"));
+ store.dispatch(
+ addSuggestedTransform({
+ ...createMockTransform(),
+ active: true,
+ suggestionId: "test-suggestion",
+ }),
+ );
+ });
+
+ expect(getReactions().navigateToPath).toBe("/some/path");
+ expect(getReactions().suggestedTransforms).toHaveLength(1);
+
+ await userEvent.click(await resetChatButton());
+
+ expect(getReactions().navigateToPath).toBeNull();
+ expect(getReactions().suggestedTransforms).toEqual([]);
+ });
+ });
+
describe("experimental", () => {
describe("debug mode", () => {
const mockResponse = () => {
@@ -1218,18 +1216,10 @@ describe("metabot-streaming", () => {
});
it("should show tool_call messages in chat if debug mode is enabled", async () => {
- setup({
- metabotPluginInitialState: {
- ...getMetabotInitialState(),
- visible: true,
- experimental: {
- ...getMetabotInitialState().experimental,
- debugMode: true,
- },
- },
- });
+ setup();
mockResponse();
+ await enterChatMessage("/debug");
await enterChatMessage("Don't show me tool call messages");
await assertConversation([
["user", "Don't show me tool call messages"],
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
index 5bb339a7cd4..c785c083dfc 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
@@ -1,17 +1,20 @@
-import { type UnknownAction, isRejected, nanoid } from "@reduxjs/toolkit";
+import {
+ type UnknownAction,
+ createAsyncThunk as createAsyncThunkOriginal,
+ isRejected,
+ nanoid,
+} from "@reduxjs/toolkit";
import { push } from "react-router-redux";
import { P, match } from "ts-pattern";
import _ from "underscore";
-import { createAsyncThunk } from "metabase/lib/redux";
import { addUndo } from "metabase/redux/undo";
import { getIsEmbedding } from "metabase/selectors/embed";
import { getUser } from "metabase/selectors/user";
-import { EnterpriseApi } from "metabase-enterprise/api";
import {
type JSONValue,
aiStreamingQuery,
- getInflightRequestsForUrl,
+ findMatchingInflightAiStreamingRequests,
} from "metabase-enterprise/api/ai-streaming";
import type {
MetabotAgentRequest,
@@ -23,13 +26,7 @@ import type { Dispatch } from "metabase-types/store";
import { METABOT_ERR_MSG } from "../constants";
-import {
- type MetabotAgentEditSuggestionChatMessage,
- type MetabotAgentTodoListChatMessage,
- type MetabotErrorMessage,
- type MetabotUserChatMessage,
- metabot,
-} from "./reducer";
+import { metabot } from "./reducer";
import {
getAgentErrorMessages,
getAgentRequestMetadata,
@@ -37,18 +34,32 @@ import {
getHistory,
getIsProcessing,
getLastMessage,
- getMetabotConversationId,
+ getMetabotConversation,
getUserPromptForMessageId,
} from "./selectors";
-import type { MetabotStoreState, SlashCommand } from "./types";
+import type {
+ MetabotAgentEditSuggestionChatMessage,
+ MetabotAgentId,
+ MetabotAgentTodoListChatMessage,
+ MetabotErrorMessage,
+ MetabotStoreState,
+ MetabotUserChatMessage,
+ SlashCommand,
+} from "./types";
import { createMessageId, parseSlashCommand } from "./utils";
+interface MetabotThunkConfig {
+ state: MetabotStoreState;
+}
+
+const createAsyncThunk =
+ createAsyncThunkOriginal.withTypes<MetabotThunkConfig>();
+
export const {
addAgentTextDelta,
addAgentMessage,
addAgentErrorMessage,
addUserMessage,
- resetConversationId,
setIsProcessing,
setNavigateToPath,
toolCallStart,
@@ -59,6 +70,8 @@ export const {
addSuggestedTransform,
activateSuggestedTransform,
deactivateSuggestedTransform,
+ createAgent,
+ destroyAgent,
} = metabot.actions;
type PromptErrorOutcome = {
@@ -93,7 +106,8 @@ const handleResponseError = (error: unknown): PromptErrorOutcome => {
};
export const setVisible =
- (isVisible: boolean) => (dispatch: Dispatch, getState: any) => {
+ (payload: { agentId: MetabotAgentId; visible: boolean }) =>
+ (dispatch: Dispatch, getState: () => MetabotStoreState) => {
const currentUser = getUser(getState());
if (!currentUser) {
console.error(
@@ -102,29 +116,32 @@ export const setVisible =
return;
}
- dispatch(metabot.actions.setVisible(isVisible));
+ dispatch(metabot.actions.setVisible(payload));
};
-export const executeSlashCommand = createAsyncThunk<void, SlashCommand>(
+export const executeSlashCommand = createAsyncThunk<
+ void,
+ { command: SlashCommand; agentId: MetabotAgentId }
+>(
"metabase-enterprise/metabot/executeSlashCommand",
- async (slashCommand, { dispatch, getState }) => {
- match(slashCommand)
+ async ({ command, agentId }, { dispatch, getState }) => {
+ match(command)
.with({ cmd: "profile" }, ({ args }) => {
if (args.length <= 1) {
- dispatch(setProfileOverride(args[0]));
+ dispatch(setProfileOverride({ agentId, profile: args[0] }));
} else {
dispatch(addUndo({ message: "/profile <name>" }));
}
})
.with({ cmd: "metabot" }, ({ args }) => {
if (args.length <= 1) {
- dispatch(setMetabotReqIdOverride(args[0]));
+ dispatch(setMetabotReqIdOverride({ id: args[0], agentId }));
} else {
dispatch(addUndo({ message: "/metabot <name>" }));
}
})
.with({ cmd: "debug" }, () => {
- const currentDebugMode = getDebugMode(getState() as MetabotStoreState);
+ const currentDebugMode = getDebugMode(getState());
const newDebugMode = !currentDebugMode;
dispatch(setDebugMode(newDebugMode));
dispatch(
@@ -150,46 +167,71 @@ export const submitInput = createAsyncThunk<
MetabotPromptSubmissionResult,
Omit<MetabotUserChatMessage, "id" | "role"> & {
context: MetabotChatContext;
+ agentId: MetabotAgentId;
metabot_id?: string;
}
>(
"metabase-enterprise/metabot/submitInput",
- async (data, { dispatch, getState, signal }) => {
+ async (payload, { dispatch, getState, signal }) => {
+ const state = getState();
+ const { agentId, message: rawPrompt, ...data } = payload;
+ const convo = getMetabotConversation(state, agentId);
+
+ const prompt = rawPrompt.trim();
+ if (prompt === "") {
+ console.warn("An empty prompt was submitted to conversation: ", agentId);
+ return { prompt, success: true };
+ }
+
try {
- const state = getState() as any;
- const isProcessing = getIsProcessing(state);
+ const isProcessing = getIsProcessing(state, agentId);
if (isProcessing) {
console.error("Metabot is actively serving a request");
- return { prompt: data.message, success: false, shouldRetry: false };
+ return { prompt, success: false, shouldRetry: false };
}
// if there were from the last prompt, remove the last prompt from the history
- const errors = getAgentErrorMessages(state);
- const lastMessageId = getLastMessage(state)?.id;
+ const errors = getAgentErrorMessages(state, agentId);
+ const lastMessageId = getLastMessage(state, agentId)?.id;
if (errors.length > 0 && lastMessageId) {
- dispatch(rewindConversation(lastMessageId));
+ dispatch(
+ rewindConversation({
+ agentId,
+ messageId: lastMessageId,
+ }),
+ );
}
- const slashCommand = parseSlashCommand(data.message);
- if (slashCommand) {
- await dispatch(executeSlashCommand(slashCommand));
- return { prompt: data.message, success: true };
+ const command = parseSlashCommand(prompt);
+ if (command) {
+ await dispatch(
+ executeSlashCommand({
+ command,
+ agentId,
+ }),
+ );
+ return { prompt, success: true };
}
// it's important that we get the current metadata containing the history before
// altering it by adding the current message the user is wanting to send
- const agentMetadata = getAgentRequestMetadata(getState() as any);
+ const agentMetadata = getAgentRequestMetadata(getState(), agentId);
const messageId = createMessageId();
dispatch(
addUserMessage({
id: messageId,
..._.omit(data, ["context", "metabot_id"]),
+ message: prompt,
+ agentId,
}),
);
const sendMessageRequestPromise = dispatch(
sendAgentRequest({
...data,
+ message: prompt,
+ agentId,
+ conversation_id: convo.conversationId,
...agentMetadata,
}),
);
@@ -200,20 +242,25 @@ export const submitInput = createAsyncThunk<
const result = await sendMessageRequestPromise;
if (isRejected(result) && result.payload?.type === "error") {
- dispatch(stopProcessingAndNotify(result.payload?.errorMessage));
+ dispatch(
+ stopProcessingAndNotify({
+ agentId,
+ message: result.payload?.errorMessage,
+ }),
+ );
return {
- prompt: data.message,
+ prompt,
success: false,
shouldRetry: result.payload?.shouldRetry ?? false,
};
}
- return { prompt: data.message, success: true, data: result.payload };
+ return { prompt, success: true, data: result.payload };
} catch (error) {
// NOTE: all errors should be caught above, this is is a catch-all
// to make sure that this async action always resolves to a value
console.error(error);
- return { prompt: data.message, success: false, shouldRetry: true };
+ return { prompt, success: false, shouldRetry: true };
}
},
);
@@ -227,30 +274,18 @@ type SendAgentRequestError =
export const sendAgentRequest = createAsyncThunk<
MetabotAgentResponse,
- Omit<MetabotAgentRequest, "conversation_id">,
+ MetabotAgentRequest & { agentId: MetabotAgentId },
{ rejectValue: SendAgentRequestError }
>(
"metabase-enterprise/metabot/sendAgentRequest",
async (
- req,
+ payload,
{ dispatch, getState, signal, rejectWithValue, fulfillWithValue },
) => {
- const isEmbedding = getIsEmbedding(getState() as any);
-
- // 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 isEmbedding = getIsEmbedding(getState());
+ const { agentId, ...request } = payload;
try {
- const body = { ...req, conversation_id: sessionId };
let state = {};
let error: unknown = undefined;
@@ -259,8 +294,9 @@ export const sendAgentRequest = createAsyncThunk<
url: "/api/ee/metabot-v3/agent-streaming",
// NOTE: StructuredDatasetQuery as part of the EntityInfo in MetabotChatContext
// is upsetting the types, casting for now
- body: body as JSONValue,
+ body: request as JSONValue,
signal,
+ sourceId: agentId,
},
{
onDataPart: function handleDataPart(part) {
@@ -276,7 +312,7 @@ export const sendAgentRequest = createAsyncThunk<
payload: part.value,
};
- dispatch(addAgentMessage(message));
+ dispatch(addAgentMessage({ ...message, agentId }));
})
.with({ type: "navigate_to" }, (part) => {
dispatch(setNavigateToPath(part.value));
@@ -294,7 +330,7 @@ export const sendAgentRequest = createAsyncThunk<
};
dispatch(addSuggestedTransform(suggestedTransform));
- const transform = req.context.user_is_viewing
+ const transform = request.context.user_is_viewing
.filter(
(t): t is MetabotTransformInfo => t.type === "transform",
)
@@ -310,18 +346,18 @@ export const sendAgentRequest = createAsyncThunk<
suggestedTransform,
},
};
- dispatch(addAgentMessage(message));
+ dispatch(addAgentMessage({ ...message, agentId }));
})
.exhaustive();
},
onTextPart: function handleTextPart(part) {
- dispatch(addAgentTextDelta(String(part)));
+ dispatch(addAgentTextDelta({ agentId, text: String(part) }));
},
onToolCallPart: function handleToolCallPart(part) {
- dispatch(toolCallStart(part));
+ dispatch(toolCallStart({ ...part, agentId }));
},
onToolResultPart: function handleToolResultPart(part) {
- dispatch(toolCallEnd(part));
+ dispatch(toolCallEnd({ ...part, agentId }));
},
onError: function handleError(part) {
error = part;
@@ -336,20 +372,20 @@ export const sendAgentRequest = createAsyncThunk<
if (response.aborted) {
return rejectWithValue({
type: "abort",
- conversation_id: body.conversation_id,
+ conversation_id: request.conversation_id,
unresolved_tool_calls: response.toolCalls.filter(
(tc) => tc.state === "call",
),
- history: [...getHistory(getState() as any), ...response.history],
+ history: [...getHistory(getState(), agentId), ...response.history],
// state object comes at the end, so we may not have recieved it
// so fallback to the state used when the request was issued
- state: Object.keys(state).length === 0 ? body.state : state,
+ state: Object.keys(state).length === 0 ? request.state : state,
});
}
return fulfillWithValue({
- conversation_id: body.conversation_id,
- history: [...getHistory(getState() as any), ...response.history],
+ conversation_id: request.conversation_id,
+ history: [...getHistory(getState(), agentId), ...response.history],
state,
});
} catch (error) {
@@ -361,23 +397,44 @@ export const sendAgentRequest = createAsyncThunk<
export const cancelInflightAgentRequests = createAsyncThunk(
"metabase-enterprise/metabot/cancelInflightAgentRequests",
- (_args) => {
- getInflightRequestsForUrl("/api/ee/metabot-v3/agent-streaming").forEach(
- (req) => req.abortController.abort(),
- );
+ (agentId: MetabotAgentId) => {
+ findMatchingInflightAiStreamingRequests(
+ "/api/ee/metabot-v3/agent-streaming",
+ agentId,
+ ).forEach((req) => req.abortController.abort());
},
);
const rewindConversation = createAsyncThunk(
"metabase-enterprise/metabot/rewindConversation",
- (messageId: string, { dispatch, getState }) => {
- dispatch(cancelInflightAgentRequests());
-
- const promptMessage = getUserPromptForMessageId(getState(), messageId);
+ (
+ {
+ agentId,
+ messageId,
+ }: {
+ agentId: MetabotAgentId;
+ messageId: string;
+ },
+ { dispatch, getState },
+ ) => {
+ const promptMessage = getUserPromptForMessageId(
+ getState(),
+ agentId,
+ messageId,
+ );
if (!promptMessage) {
- throw new Error("Unable to rewind conversation to prompt for pro");
+ throw new Error(
+ `Unable to find the prompt for message ${messageId} in conversation with agent ${agentId}`,
+ );
}
- dispatch(metabot.actions.rewindStateToMessageId(promptMessage.id));
+
+ dispatch(cancelInflightAgentRequests(agentId));
+ dispatch(
+ metabot.actions.rewindStateToMessageId({
+ agentId,
+ messageId: promptMessage.id,
+ }),
+ );
},
);
@@ -387,21 +444,34 @@ export const retryPrompt = createAsyncThunk<
messageId: string;
context: MetabotChatContext;
metabot_id?: string;
+ agentId: MetabotAgentId;
}
>(
"metabase-enterprise/metabot/retryPrompt",
- async ({ messageId, context, metabot_id }, { getState, dispatch }) => {
- const prompt = getUserPromptForMessageId(getState() as any, messageId);
+ async (
+ { messageId, context, metabot_id, agentId },
+ { getState, dispatch },
+ ) => {
+ const state = getState();
+
+ const prompt = getUserPromptForMessageId(state, agentId, messageId);
if (!prompt) {
throw new Error("Agent message was not proceeded by a user message");
}
- dispatch(rewindConversation(prompt.id));
- dispatch(cancelInflightAgentRequests());
- dispatch(metabot.actions.rewindStateToMessageId(messageId));
+ const isProcessing = getIsProcessing(state, agentId);
+ if (isProcessing) {
+ console.error("Metabot is actively serving a request");
+ return { prompt: prompt.message, success: false, shouldRetry: false };
+ }
+
+ dispatch(rewindConversation({ agentId, messageId: prompt.id }));
+ dispatch(cancelInflightAgentRequests(agentId));
+ dispatch(metabot.actions.rewindStateToMessageId({ agentId, messageId }));
return await dispatch(
submitInput({
+ agentId,
type: "text",
message: prompt.message,
context,
@@ -413,32 +483,29 @@ export const retryPrompt = createAsyncThunk<
export const resetConversation = createAsyncThunk(
"metabase-enterprise/metabot/resetConversation",
- (_args, { dispatch }) => {
- dispatch(cancelInflightAgentRequests());
-
- // clear out suggested prompts so the user is shown something fresh
- dispatch(EnterpriseApi.util.invalidateTags(["metabot-prompt-suggestions"]));
-
- dispatch(metabot.actions.resetConversation());
+ (payload: { agentId: MetabotAgentId }, { dispatch }) => {
+ dispatch(cancelInflightAgentRequests(payload.agentId));
+ dispatch(metabot.actions.resetConversation(payload));
},
);
-export const stopProcessing = () => (dispatch: Dispatch) => {
- dispatch(setIsProcessing(false));
-};
-
export const stopProcessingAndNotify =
- (message?: MetabotErrorMessage | false | undefined) =>
+ (payload: {
+ agentId: MetabotAgentId;
+ message?: MetabotErrorMessage | false | undefined;
+ }) =>
(dispatch: Dispatch) => {
- dispatch(stopProcessing());
- if (message !== false) {
+ dispatch(setIsProcessing({ agentId: payload.agentId, processing: false }));
+ if (payload.message !== false) {
+ const message = payload.message ?? {
+ type: "message",
+ message: METABOT_ERR_MSG.default,
+ };
dispatch(
- addAgentErrorMessage(
- message ?? {
- type: "message",
- message: METABOT_ERR_MSG.default,
- },
- ),
+ addAgentErrorMessage({
+ agentId: payload.agentId,
+ ...message,
+ }),
);
}
};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts
new file mode 100644
index 00000000000..ded5b9c3e5d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts
@@ -0,0 +1,134 @@
+import type { PayloadAction } from "@reduxjs/toolkit";
+import { merge } from "icepick";
+import type { WritableDraft } from "immer";
+import { match } from "ts-pattern";
+
+import { uuid } from "metabase/lib/uuid";
+
+import type {
+ MetabotAgentId,
+ MetabotConverstationState,
+ MetabotState,
+} from "./types";
+
+export type ConvoPayloadAction<
+ Value extends Record<string, any> = Record<string, any>,
+> = PayloadAction<{ agentId: MetabotAgentId } & Value>;
+
+export const getRequestConversation = (
+ state: WritableDraft<MetabotState>,
+ action: {
+ meta: { arg: { agentId: MetabotAgentId; conversation_id: string } };
+ },
+) => {
+ const { agentId, conversation_id } = action.meta.arg;
+ const convo = state.conversations[agentId];
+
+ if (!convo) {
+ console.warn(`Unable to find metabot conversation for ${agentId}`);
+ return undefined;
+ }
+
+ if (conversation_id !== convo.conversationId) {
+ console.warn(
+ `Metabot conversation ${agentId} has ${convo.conversationId} but request was for ${conversation_id}`,
+ );
+ return undefined;
+ }
+
+ return convo;
+};
+
+const agentOverridesByAgentId: Partial<
+ Record<MetabotAgentId, Partial<MetabotConverstationState>>
+> = {
+ inline_sql: {
+ profileOverride: "inline_sql",
+ },
+};
+
+export const createConversation = (
+ agentId: MetabotAgentId,
+ conversationOverrides?: Partial<MetabotConverstationState>,
+): MetabotConverstationState => {
+ const agentOverrides = agentOverridesByAgentId[agentId] ?? {};
+ const overrides = merge(agentOverrides, conversationOverrides);
+
+ return {
+ isProcessing: false,
+ messages: [],
+ errorMessages: [],
+ visible: false,
+ history: [],
+ state: {},
+ activeToolCalls: [],
+ profileOverride: undefined,
+ ...overrides,
+ conversationId: overrides?.conversationId ?? uuid(),
+ experimental: {
+ developerMessage: "",
+ metabotReqIdOverride: undefined,
+ ...overrides?.experimental,
+ },
+ };
+};
+
+export const resetReactionState = (
+ state: WritableDraft<MetabotState>,
+ agentId: MetabotAgentId,
+) => {
+ match(agentId)
+ .with("omnibot", () => {
+ state.reactions.navigateToPath = null;
+ state.reactions.suggestedTransforms = [];
+ })
+ .otherwise(() => {});
+};
+
+export const getConversationOrThrow = (
+ state: WritableDraft<MetabotState>,
+ agentId: MetabotAgentId,
+): WritableDraft<MetabotConverstationState> => {
+ const convo = state.conversations[agentId];
+ if (!convo) {
+ throw new Error(
+ `Could not find metabot conversation with convo id: ${agentId}`,
+ );
+ }
+ return convo;
+};
+
+export const convoReducer =
+ <
+ Action extends {
+ payload: { agentId: MetabotAgentId };
+ },
+ >(
+ convoReducerFn: (
+ convo: WritableDraft<MetabotConverstationState>,
+ action: Action,
+ state: WritableDraft<MetabotState>,
+ ) => void,
+ ) =>
+ (state: WritableDraft<MetabotState>, action: Action) => {
+ convoReducerFn(
+ getConversationOrThrow(state, action.payload.agentId),
+ action,
+ state,
+ );
+ };
+
+export const getMetabotInitialState = (): MetabotState => {
+ return {
+ conversations: {
+ omnibot: createConversation("omnibot"),
+ inline_sql: createConversation("inline_sql"),
+ },
+ reactions: {
+ navigateToPath: null,
+ // NOTE: suggestedTransforms should be folded into suggestedCodeEdits eventually
+ suggestedTransforms: [],
+ },
+ debugMode: false,
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
index ab9f282b8ac..b1cb316a1ce 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
@@ -1,296 +1,206 @@
import { type PayloadAction, createSlice } from "@reduxjs/toolkit";
+import { castDraft } from "immer";
import _ from "underscore";
import { logout } from "metabase/auth/actions";
-import { uuid } from "metabase/lib/uuid";
-import type {
- MetabotHistory,
- MetabotTodoItem,
- MetabotTransformInfo,
- SuggestedTransform,
-} from "metabase-types/api";
+import type { SuggestedTransform } from "metabase-types/api";
import { TOOL_CALL_MESSAGES } from "../constants";
import { sendAgentRequest } from "./actions";
+import {
+ type ConvoPayloadAction,
+ convoReducer,
+ createConversation,
+ getMetabotInitialState,
+ getRequestConversation,
+ resetReactionState,
+} from "./reducer-utils";
+import type {
+ MetabotAgentChatMessage,
+ MetabotErrorMessage,
+ MetabotSuggestedTransform,
+ MetabotUserChatMessage,
+} from "./types";
import { createMessageId } from "./utils";
-export type MetabotUserTextChatMessage = {
- id: string;
- role: "user";
- type: "text";
- message: string;
-};
-
-export type MetabotUserActionChatMessage = {
- id: string;
- role: "user";
- type: "action";
- message: string;
- userMessage: string;
-};
-
-export type MetabotAgentTextChatMessage = {
- id: string;
- role: "agent";
- type: "text";
- message: string;
-};
-
-export type MetabotAgentTodoListChatMessage = {
- id: string;
- role: "agent";
- type: "todo_list";
- payload: MetabotTodoItem[];
-};
-
-export type MetabotAgentEditSuggestionChatMessage = {
- id: string;
- role: "agent";
- type: "edit_suggestion";
- model: "transform";
- payload: {
- editorTransform: MetabotTransformInfo | undefined;
- suggestedTransform: MetabotSuggestedTransform;
- };
-};
-
-export type MetabotDebugToolCallMessage = {
- id: string;
- role: "agent";
- type: "tool_call";
- name: string;
- args?: string;
- status: "started" | "ended";
- result?: string;
- is_error?: boolean;
-};
-
-export type MetabotAgentChatMessage =
- | MetabotAgentTextChatMessage
- | MetabotAgentTodoListChatMessage
- | MetabotAgentEditSuggestionChatMessage
- | MetabotDebugToolCallMessage;
-
-export type MetabotUserChatMessage =
- | MetabotUserTextChatMessage
- | MetabotUserActionChatMessage;
-
-export type MetabotDebugChatMessage = MetabotDebugToolCallMessage;
-
-export type MetabotChatMessage =
- | MetabotUserChatMessage
- | MetabotAgentChatMessage
- | MetabotDebugChatMessage;
-
-export type MetabotErrorMessage = {
- type: "message" | "alert";
- message: string;
-};
-
-export type MetabotToolCall = {
- id: string;
- name: string;
- message: string | undefined;
- status: "started" | "ended";
-};
-
-export type MetabotSuggestedTransform = SuggestedTransform & {
- active: boolean;
- suggestionId: string; // internal unique identifier for marking active/inactive
-};
-
-export type MetabotReactionsState = {
- navigateToPath: string | null;
- suggestedTransforms: MetabotSuggestedTransform[];
-};
-
-export interface MetabotState {
- isProcessing: boolean;
- conversationId: string;
- messages: MetabotChatMessage[];
- errorMessages: MetabotErrorMessage[];
- visible: boolean;
- history: MetabotHistory;
- state: any;
- reactions: MetabotReactionsState;
- activeToolCalls: MetabotToolCall[];
- experimental: {
- debugMode: boolean;
- metabotReqIdOverride: string | undefined;
- profileOverride: string | undefined;
- };
-}
-
-export const getMetabotInitialState = (): MetabotState => ({
- isProcessing: false,
- conversationId: uuid(),
- messages: [],
- errorMessages: [],
- visible: false,
- history: [],
- state: {},
- reactions: {
- navigateToPath: null,
- suggestedTransforms: [],
- },
- activeToolCalls: [],
- experimental: {
- debugMode: false,
- metabotReqIdOverride: undefined,
- profileOverride: undefined,
- },
-});
-
export const metabot = createSlice({
name: "metabase-enterprise/metabot",
initialState: getMetabotInitialState(),
reducers: {
- addUserMessage: (
- state,
- action: PayloadAction<Omit<MetabotUserChatMessage, "role">>,
- ) => {
- const { id, message, ...rest } = action.payload;
-
- state.errorMessages = [];
- state.messages.push({ id, role: "user", message, ...rest } as any);
- state.history.push({ id, role: "user", content: message });
+ // TOP-LEVEL STATE REDUCERS
+ createAgent: (state, action: ConvoPayloadAction<{ visible?: boolean }>) => {
+ const { agentId, ...options } = action.payload;
+ if (!state.conversations[agentId]) {
+ const newConvo = createConversation(agentId, options);
+ state.conversations[agentId] = castDraft(newConvo);
+ } else {
+ console.warn("Conversation already exists for agentId: ", agentId);
+ }
},
- addAgentMessage: (
- state,
- action: PayloadAction<Omit<MetabotAgentChatMessage, "id" | "role">>,
- ) => {
- state.activeToolCalls = [];
- state.messages.push({
- id: createMessageId(),
- role: "agent",
- ...action.payload,
- // transforms in message is making this flakily produce possibly infinite
- // typescript errors. since unused ts-expect-error directives produces
- // errors, casting this as any to avoid having to add / remove constantly.
- } as any);
+ destroyAgent: (state, action: ConvoPayloadAction) => {
+ const { agentId } = action.payload;
+ delete state.conversations[agentId];
+ resetReactionState(state, agentId);
},
- addAgentErrorMessage: (
- state,
- action: PayloadAction<MetabotErrorMessage>,
- ) => {
- state.errorMessages.push(action.payload);
+ resetConversation: (state, action: ConvoPayloadAction) => {
+ const { agentId } = action.payload;
+ const visible = state.conversations[agentId]?.visible ?? false;
+ const newConvo = createConversation(agentId, { visible });
+ state.conversations[agentId] = castDraft(newConvo);
+ resetReactionState(state, agentId);
},
- addAgentTextDelta: (state, action: PayloadAction<string>) => {
- const hasToolCalls = state.activeToolCalls.length > 0;
- const lastMessage = _.last(state.messages);
- const canAppend =
- !hasToolCalls &&
- lastMessage?.role === "agent" &&
- lastMessage.type === "text";
-
- if (canAppend) {
- lastMessage.message = lastMessage.message + action.payload;
- } else {
- state.messages.push({
+ setDebugMode: (state, action: PayloadAction<boolean>) => {
+ state.debugMode = action.payload;
+ },
+ addUserMessage: convoReducer(
+ (
+ convo,
+ action: ConvoPayloadAction<Omit<MetabotUserChatMessage, "role">>,
+ ) => {
+ const { id, message, agentId, ...rest } = action.payload;
+ convo.errorMessages = [];
+ convo.messages.push({ id, role: "user", ...rest, message } as any);
+ convo.history.push({ id, role: "user", content: message });
+ },
+ ),
+ addAgentMessage: convoReducer(
+ (
+ convo,
+ action: ConvoPayloadAction<
+ Omit<MetabotAgentChatMessage, "id" | "role">
+ >,
+ ) => {
+ convo.activeToolCalls = [];
+ convo.messages.push({
id: createMessageId(),
role: "agent",
- type: "text",
- message: action.payload,
- });
- }
+ ...action.payload,
+ // transforms in message is making this flakily produce possibly infinite
+ // typescript errors. since unused ts-expect-error directives produces
+ // errors, casting this as any to avoid having to add / remove constantly.
+ } as any);
+ },
+ ),
+ addAgentErrorMessage: convoReducer(
+ (convo, action: ConvoPayloadAction<MetabotErrorMessage>) => {
+ convo.errorMessages.push(action.payload);
+ },
+ ),
+ addAgentTextDelta: convoReducer(
+ (convo, action: ConvoPayloadAction<{ text: string }>) => {
+ const hasToolCalls = convo.activeToolCalls.length > 0;
+ const lastMessage = _.last(convo.messages);
+ const canAppend =
+ !hasToolCalls &&
+ lastMessage?.role === "agent" &&
+ lastMessage.type === "text";
- state.activeToolCalls = hasToolCalls ? [] : state.activeToolCalls;
- },
- toolCallStart: (
- state,
- action: PayloadAction<{
- toolCallId: string;
- toolName: string;
- args?: string;
- }>,
- ) => {
- const { toolCallId, toolName, args } = action.payload;
- state.messages.push({
- id: toolCallId,
- role: "agent",
- type: "tool_call",
- name: toolName,
- args,
- status: "started",
- });
- state.activeToolCalls.push({
- id: toolCallId,
- name: toolName,
- message: TOOL_CALL_MESSAGES[toolName],
- status: "started",
- });
- },
- toolCallEnd: (
- state,
- action: PayloadAction<{ toolCallId: string; result?: any }>,
- ) => {
- state.activeToolCalls = state.activeToolCalls.map((tc) =>
- tc.id === action.payload.toolCallId ? { ...tc, status: "ended" } : tc,
- );
+ if (canAppend) {
+ lastMessage.message = lastMessage.message + action.payload.text;
+ } else {
+ convo.messages.push({
+ id: createMessageId(),
+ role: "agent",
+ type: "text",
+ message: action.payload.text,
+ });
+ }
- // Update the message in messages array with result for debug history
- const message = state.messages.findLast(
- (msg) =>
- msg.type === "tool_call" && msg.id === action.payload.toolCallId,
- );
- if (message?.type === "tool_call") {
- message.status = "ended";
- message.result = action.payload.result;
- }
- },
+ convo.activeToolCalls = hasToolCalls ? [] : convo.activeToolCalls;
+ },
+ ),
+ toolCallStart: convoReducer(
+ (
+ convo,
+ action: ConvoPayloadAction<{
+ toolCallId: string;
+ toolName: string;
+ args?: string;
+ }>,
+ ) => {
+ const { toolCallId, toolName, args } = action.payload;
+ convo.messages.push({
+ id: toolCallId,
+ role: "agent",
+ type: "tool_call",
+ name: toolName,
+ args,
+ status: "started",
+ });
+ convo.activeToolCalls.push({
+ id: toolCallId,
+ name: toolName,
+ message: TOOL_CALL_MESSAGES[toolName],
+ status: "started",
+ });
+ },
+ ),
+ toolCallEnd: convoReducer(
+ (
+ convo,
+ action: ConvoPayloadAction<{ toolCallId: string; result?: any }>,
+ ) => {
+ convo.activeToolCalls = convo.activeToolCalls.map((tc) =>
+ tc.id === action.payload.toolCallId ? { ...tc, status: "ended" } : tc,
+ );
+
+ // Update the message in messages array with result for debug history
+ const message = convo.messages.findLast(
+ (msg) =>
+ msg.type === "tool_call" && msg.id === action.payload.toolCallId,
+ );
+ if (message?.type === "tool_call") {
+ message.status = "ended";
+ message.result = action.payload.result;
+ }
+ },
+ ),
// NOTE: this reducer fn should be made smarter if/when we want to have
// metabot's `state` object be able to remove / forget values. currently
// we do not rewind the state to the point in time of the original prompt
// so if / when this becomes expected, we'll need to do some extra work here
// NOTE: this doesn't work in non-streaming contexts right now
- rewindStateToMessageId: (state, { payload: id }: PayloadAction<string>) => {
- state.isProcessing = false;
- const messageIndex = state.messages.findLastIndex((m) => id === m.id);
- if (messageIndex > -1) {
- state.messages = state.messages.slice(0, messageIndex);
- }
+ rewindStateToMessageId: convoReducer(
+ (convo, action: ConvoPayloadAction<{ messageId: string }>) => {
+ convo.isProcessing = false;
- const historyIndex = state.history.findLastIndex((h) => id === h.id);
- if (historyIndex > -1) {
- state.history = state.history.slice(0, historyIndex);
- }
- },
- resetConversation: (state) => {
- state.messages = [];
- state.errorMessages = [];
- state.history = [];
- state.state = {};
- state.isProcessing = false;
- state.activeToolCalls = [];
- state.conversationId = uuid();
- state.reactions.suggestedTransforms = [];
- state.experimental.metabotReqIdOverride = undefined;
- },
- resetConversationId: (state) => {
- state.conversationId = uuid();
- },
- setIsProcessing: (state, action: PayloadAction<boolean>) => {
- state.isProcessing = action.payload;
- },
+ const id = action.payload.messageId;
+ const messageIndex = convo.messages.findLastIndex((m) => id === m.id);
+ if (messageIndex > -1) {
+ convo.messages = convo.messages.slice(0, messageIndex);
+ }
+
+ const historyIndex = convo.history.findLastIndex((h) => id === h.id);
+ if (historyIndex > -1) {
+ convo.history = convo.history.slice(0, historyIndex);
+ }
+ },
+ ),
+ setIsProcessing: convoReducer(
+ (state, action: ConvoPayloadAction<{ processing: boolean }>) => {
+ state.isProcessing = action.payload.processing;
+ },
+ ),
+ setVisible: convoReducer(
+ (state, action: ConvoPayloadAction<{ visible: boolean }>) => {
+ state.visible = action.payload.visible;
+ },
+ ),
+ setMetabotReqIdOverride: convoReducer(
+ (state, action: ConvoPayloadAction<{ id: string | undefined }>) => {
+ state.experimental.metabotReqIdOverride = action.payload.id;
+ },
+ ),
+ setProfileOverride: convoReducer(
+ (state, action: ConvoPayloadAction<{ profile: string | undefined }>) => {
+ state.profileOverride = action.payload.profile;
+ },
+ ),
+ // REACTIONS REDUCERS
setNavigateToPath: (state, action: PayloadAction<string>) => {
state.reactions.navigateToPath = action.payload;
},
- setVisible: (state, action: PayloadAction<boolean>) => {
- state.visible = action.payload;
- },
- setMetabotReqIdOverride: (
- state,
- action: PayloadAction<string | undefined>,
- ) => {
- state.experimental.metabotReqIdOverride = action.payload;
- },
- setProfileOverride: (state, action: PayloadAction<string | undefined>) => {
- state.experimental.profileOverride = action.payload;
- },
- setDebugMode: (state, action: PayloadAction<boolean>) => {
- state.experimental.debugMode = action.payload;
- },
addSuggestedTransform: (
state,
{ payload: transform }: PayloadAction<MetabotSuggestedTransform>,
@@ -334,46 +244,56 @@ export const metabot = createSlice({
extraReducers: (builder) => {
builder
.addCase(logout.pending, getMetabotInitialState)
- // streamed response handlers
- .addCase(sendAgentRequest.pending, (state) => {
- state.isProcessing = true;
- state.errorMessages = [];
+ // CONVERSATION REQUEST REDUCERS
+ .addCase(sendAgentRequest.pending, (state, action) => {
+ const convo = getRequestConversation(state, action);
+ if (convo) {
+ convo.isProcessing = true;
+ convo.errorMessages = [];
+ }
})
.addCase(sendAgentRequest.fulfilled, (state, action) => {
- state.state = { ...(action.payload?.state ?? {}) };
- state.history = action.payload?.history?.slice() ?? [];
- state.activeToolCalls = [];
- state.isProcessing = false;
+ const convo = getRequestConversation(state, action);
+ if (convo) {
+ convo.state = { ...(action.payload?.state ?? {}) };
+ convo.history = action.payload?.history?.slice() ?? [];
+ convo.activeToolCalls = [];
+ convo.isProcessing = false;
+ convo.experimental.developerMessage = "";
+ }
})
.addCase(sendAgentRequest.rejected, (state, action) => {
- // aborted requests needs special state adjustments
- if (action.payload?.type === "abort") {
- state.state = { ...(action.payload?.state ?? {}) };
- state.history = action.payload?.history?.slice() ?? [];
- if (action.payload.unresolved_tool_calls.length > 0) {
- // update history w/ synthetic tool_result entries for each unresolved tool call
- // as having a tool_call without a matching tool_result is invalid
- const syntheticToolResults =
- action.payload.unresolved_tool_calls.map((tc) => ({
- role: "tool" as const,
- content: "Tool execution interrupted by user",
- tool_call_id: tc.toolCallId,
- }));
- state.history.push(...syntheticToolResults);
+ const convo = getRequestConversation(state, action);
+ if (convo) {
+ // aborted requests needs special state adjustments
+ if (action.payload?.type === "abort") {
+ convo.state = { ...(action.payload?.state ?? {}) };
+ convo.history = action.payload?.history?.slice() ?? [];
+ if (action.payload.unresolved_tool_calls.length > 0) {
+ // update history w/ synthetic tool_result entries for each unresolved tool call
+ // as having a tool_call without a matching tool_result is invalid
+ const syntheticToolResults =
+ action.payload.unresolved_tool_calls.map((tc) => ({
+ role: "tool" as const,
+ content: "Tool execution interrupted by user",
+ tool_call_id: tc.toolCallId,
+ }));
+ convo.history.push(...syntheticToolResults);
- // update message state so that unresolved tools are marked as ended
- state.messages.forEach((msg) => {
- if (msg.type === "tool_call" && msg.status === "started") {
- msg.status = "ended";
- msg.result = "Tool execution interrupted by user";
- msg.is_error = true;
- }
- });
+ // update message state so that unresolved tools are marked as ended
+ convo.messages.forEach((msg) => {
+ if (msg.type === "tool_call" && msg.status === "started") {
+ msg.status = "ended";
+ msg.result = "Tool execution interrupted by user";
+ msg.is_error = true;
+ }
+ });
+ }
}
- }
- state.activeToolCalls = [];
- state.isProcessing = false;
+ convo.activeToolCalls = [];
+ convo.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 ebb9270e94a..835da8d1bf7 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
@@ -12,26 +12,105 @@ import {
METABOT_REQUEST_IDS,
} from "../constants";
-import type { MetabotUserChatMessage } from "./reducer";
-import type { MetabotStoreState } from "./types";
+import type {
+ MetabotAgentId,
+ MetabotStoreState,
+ MetabotUserChatMessage,
+} from "./types";
-export const getMetabot = (state: MetabotStoreState) => {
+/*
+ * Top Level Selectors
+ */
+
+export const getMetabotState = (state: MetabotStoreState) => {
return state.plugins.metabotPlugin;
};
-export const getMetabotVisible = createSelector(
- [getMetabot],
- (metabot) => metabot.visible,
+export const getActiveMetabotAgentIds = createSelector(
+ getMetabotState,
+ (state) => Object.keys(state.conversations) as MetabotAgentId[],
+);
+
+export const getMetabotId = createSelector(getIsEmbedding, (isEmbedding) =>
+ isEmbedding ? FIXED_METABOT_IDS.EMBEDDED : FIXED_METABOT_IDS.DEFAULT,
+);
+
+export const getUseCase = createSelector(
+ getLocation,
+ (location): "transforms" | "omnibot" => {
+ return location.pathname.startsWith(Urls.transformList())
+ ? "transforms"
+ : "omnibot";
+ },
);
export const getDebugMode = createSelector(
- getMetabot,
- (metabot) => metabot.experimental.debugMode,
+ getMetabotState,
+ (state) => state.debugMode,
+);
+
+export const getMetabotReactionsState = createSelector(
+ getMetabotState,
+ (state) => state.reactions,
+);
+
+export const getNavigateToPath = createSelector(
+ getMetabotReactionsState,
+ (reactionsState) => reactionsState.navigateToPath,
+);
+
+export const getMetabotSuggestedTransforms = createSelector(
+ getMetabotReactionsState,
+ (reactionsState) => reactionsState.suggestedTransforms,
+);
+
+export const getMetabotSuggestedTransform = createSelector(
+ [
+ getMetabotSuggestedTransforms,
+ (_, transformId?: TransformId) => transformId,
+ ],
+ (suggestedTransforms, transformId) => {
+ return suggestedTransforms.findLast(
+ (t) => t.id === transformId && t.active,
+ );
+ },
+);
+
+export const getIsSuggestedTransformActive = createSelector(
+ [getMetabotSuggestedTransforms, (_, suggestionId: string) => suggestionId],
+ (suggestedTransforms, suggestionId) => {
+ const suggestion = suggestedTransforms.find(
+ (t) => t.suggestionId === suggestionId,
+ );
+ return suggestion?.active ?? false;
+ },
+);
+
+/*
+ * Conversation Selectors
+ */
+
+const getAgentId = (_: MetabotStoreState, agentId: MetabotAgentId) => agentId;
+
+export const getMetabotConversation = createSelector(
+ [getMetabotState, getAgentId],
+ (state, agentId) => {
+ const convo = state.conversations[agentId];
+ if (!convo) {
+ throw new Error(`No conversation exists for agent: ${agentId}`);
+ }
+ return convo;
+ },
+);
+
+export const getMetabotVisible = createSelector(
+ getMetabotConversation,
+ (convo) => convo.visible,
);
const getInternalMessages = createSelector(
- getMetabot,
- (metabot) => metabot.messages,
+ getMetabotConversation,
+ (convo) => convo.messages,
);
export const getMessages = createSelector(
@@ -44,8 +123,8 @@ export const getMessages = createSelector(
);
export const getActiveToolCalls = createSelector(
- getMetabot,
- (metabot) => metabot.activeToolCalls,
+ getMetabotConversation,
+ (convo) => convo.activeToolCalls,
);
export const getLastMessage = createSelector(getMessages, (messages) =>
@@ -53,15 +132,15 @@ export const getLastMessage = createSelector(getMessages, (messages) =>
);
export const getAgentErrorMessages = createSelector(
- getMetabot,
- (metabot) => metabot.errorMessages,
+ getMetabotConversation,
+ (convo) => convo.errorMessages,
);
// if the message id provided is an agent id the first user message
// that precedes it will be returned. if a user message id is provided
// that exact message will be returned.
export const getUserPromptForMessageId = createSelector(
- [getMessages, (_, messageId: string) => messageId],
+ [getMessages, (_, __, messageId: string) => messageId],
(messages, messageId): MetabotUserChatMessage | undefined => {
const messageIndex = messages.findLastIndex((m) => m.id === messageId);
const message = messages[messageIndex];
@@ -80,28 +159,18 @@ export const getUserPromptForMessageId = createSelector(
);
export const getIsProcessing = createSelector(
- getMetabot,
- (metabot) => metabot.isProcessing,
+ getMetabotConversation,
+ (convo) => convo.isProcessing,
);
export const getHistory = createSelector(
- getMetabot,
- (metabot) => metabot.history,
-);
-
-export const getMetabotConversationId = createSelector(
- getMetabot,
- (metabot) => metabot.conversationId,
+ getMetabotConversation,
+ (convo) => convo.history,
);
-export const getMetabotState = createSelector(
- getMetabot,
- (metabot) => metabot.state,
-);
-
-export const getMetabotReactionsState = createSelector(
- getMetabot,
- (metabot) => metabot.reactions,
+export const getMetabotRequestState = createSelector(
+ getMetabotConversation,
+ (convo) => convo.state,
);
export const getIsLongMetabotConversation = createSelector(
@@ -114,13 +183,9 @@ export const getIsLongMetabotConversation = createSelector(
},
);
-export const getMetabotId = createSelector(getIsEmbedding, (isEmbedding) =>
- isEmbedding ? FIXED_METABOT_IDS.EMBEDDED : FIXED_METABOT_IDS.DEFAULT,
-);
-
export const getMetabotReqIdOverride = createSelector(
- getMetabot,
- (metabot) => metabot.experimental.metabotReqIdOverride,
+ getMetabotConversation,
+ (convo) => convo.experimental.metabotReqIdOverride,
);
export const getMetabotRequestId = createSelector(
@@ -132,22 +197,13 @@ export const getMetabotRequestId = createSelector(
);
export const getProfileOverride = createSelector(
- getMetabot,
- (metabot) => metabot.experimental.profileOverride,
-);
-
-export const getUseCase = createSelector(
- getLocation,
- (location): "transforms" | "omnibot" => {
- return location.pathname.startsWith(Urls.transformList())
- ? "transforms"
- : "omnibot";
- },
+ getMetabotConversation,
+ (convo) => convo.profileOverride,
);
export const getAgentRequestMetadata = createSelector(
getHistory,
- getMetabotState,
+ getMetabotRequestState,
getUseCase,
getProfileOverride,
(history, state, useCase, profileOverride) => ({
@@ -160,35 +216,3 @@ export const getAgentRequestMetadata = createSelector(
...(profileOverride ? { profile_id: profileOverride } : {}),
}),
);
-
-export const getNavigateToPath = createSelector(
- getMetabotReactionsState,
- (reactionsState) => reactionsState.navigateToPath,
-);
-
-export const getMetabotSuggestedTransforms = createSelector(
- getMetabotReactionsState,
- (reactionsState) => reactionsState.suggestedTransforms,
-);
-
-export const getMetabotSuggestedTransform = createSelector(
- [
- getMetabotSuggestedTransforms,
- (_, transformId?: TransformId) => transformId,
- ],
- (suggestedTransforms, transformId) => {
- return suggestedTransforms.findLast(
- (t) => t.id === transformId && t.active,
- );
- },
-);
-
-export const getIsSuggestedTransformActive = createSelector(
- [getMetabotSuggestedTransforms, (_, suggestionId: string) => suggestionId],
- (suggestedTransforms, suggestionId) => {
- const suggestion = suggestedTransforms.find(
- (t) => t.suggestionId === suggestionId,
- );
- return suggestion?.active ?? false;
- },
-);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.unit.spec.ts
index a5e9fa38073..c86d14c76f8 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.unit.spec.ts
@@ -1,36 +1,43 @@
+import { assocIn } from "icepick";
+
import { setupEnterprisePlugins } from "__support__/enterprise";
import { createMockState } from "metabase-types/store/mocks";
-import {
- type MetabotState,
- getMetabotInitialState,
- getUserPromptForMessageId,
-} from "./index";
+import { getMetabotInitialState } from "./reducer-utils";
+import type { MetabotStoreState } from "./types";
+
+import { type MetabotChatMessage, getUserPromptForMessageId } from "./index";
-function setup(metabotState: Partial<MetabotState>) {
+function setup(messages: MetabotChatMessage[]): MetabotStoreState {
setupEnterprisePlugins();
+ const state = getMetabotInitialState();
+ const visibleState = assocIn(
+ state,
+ ["conversations", "omnibot", "visible"],
+ true,
+ );
+ const withMessages = assocIn(
+ visibleState,
+ ["conversations", "omnibot", "messages"],
+ messages,
+ );
+
return createMockState({
plugins: {
- metabotPlugin: {
- ...getMetabotInitialState(),
- visible: true,
- ...metabotState,
- },
+ metabotPlugin: withMessages,
},
- } as any);
+ } as any) as unknown as MetabotStoreState;
}
describe("metabot selectors", () => {
describe("getUserPromptForMessageId", () => {
it("should return the message with the matching id if id is for a user message", () => {
- const state = setup({
- messages: [
- { id: "1", role: "user", type: "text", message: "bleh" },
- { id: "2", role: "agent", type: "text", message: "blah" },
- ],
- });
- const message = getUserPromptForMessageId(state as any, "1");
+ const state = setup([
+ { id: "1", role: "user", type: "text", message: "bleh" },
+ { id: "2", role: "agent", type: "text", message: "blah" },
+ ]);
+ const message = getUserPromptForMessageId(state, "omnibot", "1");
expect(message).toEqual({
id: "1",
role: "user",
@@ -40,22 +47,20 @@ describe("metabot selectors", () => {
});
it("should return the message with the matching id if id is for an agent message", () => {
- const state = setup({
- messages: [
- { id: "1", type: "text", role: "user", message: "bleh" },
- { id: "2", type: "text", role: "agent", message: "blah" },
- { id: "3", type: "text", role: "user", message: "bleh bleh" },
- { id: "4", type: "text", role: "agent", message: "blah blah" },
- ],
- });
- const message1 = getUserPromptForMessageId(state as any, "2");
+ const state = setup([
+ { id: "1", type: "text", role: "user", message: "bleh" },
+ { id: "2", type: "text", role: "agent", message: "blah" },
+ { id: "3", type: "text", role: "user", message: "bleh bleh" },
+ { id: "4", type: "text", role: "agent", message: "blah blah" },
+ ]);
+ const message1 = getUserPromptForMessageId(state, "omnibot", "2");
expect(message1).toEqual({
id: "1",
role: "user",
type: "text",
message: "bleh",
});
- const message2 = getUserPromptForMessageId(state as any, "4");
+ const message2 = getUserPromptForMessageId(state, "omnibot", "4");
expect(message2).toEqual({
id: "3",
role: "user",
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
index 1621a5fdc55..7fcb10f3697 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
@@ -1,7 +1,128 @@
import type { EnterpriseSharedState } from "metabase-enterprise/shared/reducer";
import type { EnterpriseState } from "metabase-enterprise/shared/types";
+import type {
+ MetabotHistory,
+ MetabotTodoItem,
+ MetabotTransformInfo,
+ SuggestedTransform,
+} from "metabase-types/api";
-import type { MetabotState } from "./reducer";
+export type MetabotUserTextChatMessage = {
+ id: string;
+ role: "user";
+ type: "text";
+ message: string;
+};
+
+export type MetabotUserActionChatMessage = {
+ id: string;
+ role: "user";
+ type: "action";
+ message: string;
+ userMessage: string;
+};
+
+export type MetabotAgentTextChatMessage = {
+ id: string;
+ role: "agent";
+ type: "text";
+ message: string;
+};
+
+export type MetabotAgentTodoListChatMessage = {
+ id: string;
+ role: "agent";
+ type: "todo_list";
+ payload: MetabotTodoItem[];
+};
+
+export type MetabotAgentEditSuggestionChatMessage = {
+ id: string;
+ role: "agent";
+ type: "edit_suggestion";
+ model: "transform";
+ payload: {
+ editorTransform: MetabotTransformInfo | undefined;
+ suggestedTransform: MetabotSuggestedTransform;
+ };
+};
+
+export type MetabotDebugToolCallMessage = {
+ id: string;
+ role: "agent";
+ type: "tool_call";
+ name: string;
+ args?: string;
+ status: "started" | "ended";
+ result?: string;
+ is_error?: boolean;
+};
+
+export type MetabotAgentChatMessage =
+ | MetabotAgentTextChatMessage
+ | MetabotAgentTodoListChatMessage
+ | MetabotAgentEditSuggestionChatMessage
+ | MetabotDebugToolCallMessage;
+
+export type MetabotUserChatMessage =
+ | MetabotUserTextChatMessage
+ | MetabotUserActionChatMessage;
+
+export type MetabotDebugChatMessage = MetabotDebugToolCallMessage;
+
+export type MetabotChatMessage =
+ | MetabotUserChatMessage
+ | MetabotAgentChatMessage
+ | MetabotDebugChatMessage;
+
+export type MetabotErrorMessage = {
+ type: "message" | "alert";
+ message: string;
+};
+
+export type MetabotToolCall = {
+ id: string;
+ name: string;
+ message: string | undefined;
+ status: "started" | "ended";
+};
+
+export type MetabotSuggestedTransform = SuggestedTransform & {
+ active: boolean;
+ suggestionId: string; // internal unique identifier for marking active/inactive
+};
+
+export type MetabotReactionsState = {
+ navigateToPath: string | null;
+ suggestedTransforms: MetabotSuggestedTransform[];
+};
+
+export interface MetabotConverstationState {
+ conversationId: string;
+ isProcessing: boolean;
+ messages: MetabotChatMessage[];
+ errorMessages: MetabotErrorMessage[];
+ visible: boolean;
+ history: MetabotHistory;
+ state: any;
+ activeToolCalls: MetabotToolCall[];
+ profileOverride: string | undefined;
+ experimental: {
+ developerMessage: string;
+ metabotReqIdOverride: string | undefined;
+ };
+}
+
+export const fixedMetabotAgentIds = ["omnibot", "inline_sql"] as const;
+type FixedMetabotAgentId = (typeof fixedMetabotAgentIds)[number];
+
+export type MetabotAgentId = FixedMetabotAgentId | `test_${number}`;
+
+export interface MetabotState {
+ conversations: Record<MetabotAgentId, MetabotConverstationState | undefined>;
+ reactions: MetabotReactionsState;
+ debugMode: boolean;
+}
export interface MetabotStoreState extends EnterpriseState {
plugins: {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx
new file mode 100644
index 00000000000..d58898406b6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx
@@ -0,0 +1,147 @@
+import type { AnyAction, ThunkDispatch } from "@reduxjs/toolkit";
+import { combineReducers } from "@reduxjs/toolkit";
+
+import { mockSettings } from "__support__/settings";
+import { act, renderHookWithProviders } from "__support__/ui";
+import { createMockTokenFeatures } from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { useMetabotAgentsManager } from "../hooks";
+import {
+ type MetabotAgentId,
+ type MetabotStoreState,
+ getMessages,
+ metabotReducer,
+ submitInput,
+} from "../state";
+import { getMetabotInitialState } from "../state/reducer-utils";
+
+import { mockAgentEndpoint } from "./utils";
+
+function setup(
+ options: {
+ ui?: React.ReactElement;
+ agentIds: MetabotAgentId[];
+ } | void,
+) {
+ const { agentIds = ["omnibot", "inline_sql"] } = options || {};
+
+ const settings = mockSettings({
+ "token-features": createMockTokenFeatures({
+ metabot_v3: true,
+ }),
+ });
+
+ const { store: _store, result: hook } = renderHookWithProviders(
+ () => useMetabotAgentsManager(agentIds),
+ {
+ storeInitialState: createMockState({
+ settings,
+ plugins: {
+ metabotPlugin: getMetabotInitialState(),
+ },
+ } as any),
+ customReducers: {
+ plugins: combineReducers({
+ metabotPlugin: metabotReducer,
+ }),
+ },
+ },
+ );
+
+ const store = _store as Omit<typeof _store, "getState" | "dispatch"> & {
+ getState: () => MetabotStoreState;
+ dispatch: ThunkDispatch<MetabotStoreState, void, AnyAction>;
+ };
+
+ return {
+ agentIds,
+ store,
+ hook,
+ };
+}
+
+type BaseInput = Parameters<typeof submitInput>[0];
+type Input = Omit<BaseInput, "message" | "agentId">;
+const input: Input = {
+ type: "text",
+ context: {
+ user_is_viewing: [],
+ current_time_with_timezone: "",
+ },
+};
+
+describe("multi-convo support", () => {
+ it("should support being able to hold two conversations at once", async () => {
+ // ARRANGE
+ const { store } = setup({ agentIds: ["test_1", "test_2"] });
+
+ // ACT
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"Test 1 response"`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+ ],
+ });
+ const msg1 = { ...input, message: "test1", agentId: "test_1" } as const;
+ await store.dispatch(submitInput(msg1));
+
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"Test 2 response"`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
+ ],
+ });
+ const msg2 = { ...input, message: "test2", agentId: "test_2" } as const;
+ await act(async () => {
+ await store.dispatch(submitInput(msg2));
+ });
+
+ // ASSERT
+ const state = store.getState();
+ expect(getMessages(state, "test_1")).toMatchObject([
+ { message: "test1", role: "user", type: "text" },
+ { message: "Test 1 response", role: "agent", type: "text" },
+ ]);
+ expect(getMessages(state, "test_2")).toMatchObject([
+ { message: "test2", role: "user", type: "text" },
+ { message: "Test 2 response", role: "agent", type: "text" },
+ ]);
+ });
+
+ it("should be able to start a conversation", async () => {
+ const { hook } = setup({ agentIds: [] });
+
+ const agentId = "test_1" as const;
+ expect(hook.current.activeAgentIds).not.toContain(agentId);
+ await act(() => hook.current.createAgent({ agentId, visible: false }));
+ expect(hook.current.activeAgentIds).toContain(agentId);
+ });
+
+ it("should be able to reset a conversation", async () => {
+ const { hook, store } = setup({ agentIds: ["test_1"] });
+ mockAgentEndpoint({
+ textChunks: [
+ `0:"response"`,
+ `d:{"finishReason":"stop","usage":{"promptTokens":1,"completionTokens":1}}`,
+ ],
+ });
+ await store.dispatch(
+ submitInput({ ...input, message: "test", agentId: "test_1" }),
+ );
+ expect(getMessages(store.getState(), "test_1")).toHaveLength(2);
+
+ await act(() => hook.current.resetConversation({ agentId: "test_1" }));
+
+ expect(hook.current.activeAgentIds).toContain("test_1");
+ expect(getMessages(store.getState(), "test_1")).toHaveLength(0);
+ });
+
+ it("should be able to remove a conversation", async () => {
+ const { hook } = setup({ agentIds: ["test_1"] });
+
+ expect(hook.current.activeAgentIds).toContain("test_1");
+ await act(() => hook.current.destroyAgent({ agentId: "test_1" }));
+ expect(hook.current.activeAgentIds).not.toContain("test_1");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
similarity index 81%
rename from enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.unit.spec.ts
rename to enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
index 4ac3dad3ae5..7c054430cb3 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
@@ -1,4 +1,5 @@
import { configureStore } from "@reduxjs/toolkit";
+import { createDraft } from "immer";
import {
type MetabotState,
@@ -6,11 +7,16 @@ import {
activateSuggestedTransform,
addSuggestedTransform,
deactivateSuggestedTransform,
- getMetabotInitialState,
metabotReducer,
} from "metabase-enterprise/metabot/state";
import { createMockTransform } from "metabase-types/api/mocks/transform";
+import {
+ createConversation,
+ getMetabotInitialState,
+ getRequestConversation,
+} from "../state/reducer-utils";
+
const createMockSuggestedTransform = (
overrides: Partial<MetabotSuggestedTransform>,
): MetabotSuggestedTransform => ({
@@ -223,4 +229,46 @@ describe("metabot reducer", () => {
});
});
});
+
+ describe("getRequestConversation", () => {
+ it("should return undefined if no matching convo", () => {
+ const state = createDraft(getMetabotInitialState());
+ const action = {
+ meta: {
+ arg: { agentId: "test_1" as const, conversation_id: "some-id" },
+ },
+ };
+
+ expect(getRequestConversation(state, action)).toBeUndefined();
+ });
+
+ it("should return undefined if the conversation's conversation_id doesn't match the value in the store", () => {
+ const state = createDraft(getMetabotInitialState());
+ state.conversations.test_1 = createDraft(
+ createConversation("test_1", { conversationId: "stored-id" }),
+ );
+ const action = {
+ meta: {
+ arg: { agentId: "test_1" as const, conversation_id: "different-id" },
+ },
+ };
+
+ expect(getRequestConversation(state, action)).toBeUndefined();
+ });
+
+ it("should return conversation if agentId and request conversation_id match", () => {
+ const state = createDraft(getMetabotInitialState());
+ const convo = createDraft(
+ createConversation("test_1", { conversationId: "matching-id" }),
+ );
+ state.conversations.test_1 = convo;
+ const action = {
+ meta: {
+ arg: { agentId: "test_1" as const, conversation_id: "matching-id" },
+ },
+ };
+
+ expect(getRequestConversation(state, action)).toBe(convo);
+ });
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/tests/utils.ts b/enterprise/frontend/src/metabase-enterprise/metabot/tests/utils.ts
new file mode 100644
index 00000000000..b4261ad28ad
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/tests/utils.ts
@@ -0,0 +1,85 @@
+import userEvent from "@testing-library/user-event";
+
+import { act, fireEvent, screen, waitFor } from "__support__/ui";
+import {
+ type MockStreamedEndpointParams,
+ mockStreamedEndpoint,
+} from "metabase-enterprise/api/ai-streaming/test-utils";
+
+import { type MetabotAgentId, setVisible } from "../state";
+
+export const mockAgentEndpoint = (params: MockStreamedEndpointParams) =>
+ mockStreamedEndpoint("/api/ee/metabot-v3/agent-streaming", params);
+
+export const chat = () => screen.findByTestId("metabot-chat");
+export const chatMessages = () =>
+ screen.findAllByTestId("metabot-chat-message");
+export const lastChatMessage = async () => (await chatMessages()).at(-1);
+export const input = async () => {
+ const chatInput = await screen.findByTestId("metabot-chat-input");
+ return chatInput.querySelector('[contenteditable="true"]')!;
+};
+export const enterChatMessage = async (message: string, send = true) => {
+ // using userEvent.type works locally but in CI characters are sometimes dropped
+ // so "Who is your favorite?" becomes something like "Woi or fvrite?"
+ const editor = await input();
+ editor.textContent = message;
+ fireEvent.input(editor, {
+ target: { textContent: message },
+ });
+ if (send) {
+ await userEvent.type(await input(), "{Enter}");
+ }
+};
+export const sendMessageButton = () =>
+ screen.findByTestId("metabot-send-message");
+export const stopResponseButton = () =>
+ screen.findByTestId("metabot-stop-response");
+export const closeChatButton = () => screen.findByTestId("metabot-close-chat");
+export const responseLoader = () =>
+ screen.findByTestId("metabot-response-loader");
+export const resetChatButton = () => screen.findByTestId("metabot-reset-chat");
+
+export const assertVisible = async () =>
+ expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();
+export const assertNotVisible = async () =>
+ await waitFor(() => {
+ expect(screen.queryByTestId("metabot-chat")).not.toBeInTheDocument();
+ });
+
+// NOTE: for some reason the keyboard shortcuts won't work with tinykeys while testing, using redux for now...
+export const hideMetabot = (
+ dispatch: any,
+ agentId: MetabotAgentId = "omnibot",
+) => act(() => dispatch(setVisible({ agentId, visible: false })));
+export const showMetabot = (
+ dispatch: any,
+ agentId: MetabotAgentId = "omnibot",
+) => act(() => dispatch(setVisible({ agentId, visible: true })));
+
+export 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(realMessages.length).toBe(expectedMessages.length);
+ expectedMessages.forEach(([expectedRole, expectedMessage], index) => {
+ const realMessage = realMessages[index];
+ expect(realMessage).toHaveAttribute("data-message-role", expectedRole);
+ expect(realMessage).toHaveTextContent(expectedMessage);
+ });
+ }
+};
+
+export const lastReqBody = async (
+ agentSpy: ReturnType<typeof mockAgentEndpoint>,
+) => {
+ await waitFor(() => expect(agentSpy).toHaveBeenCalled());
+ return JSON.parse(agentSpy.mock.lastCall?.[1]?.body as string);
+};
diff --git a/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx b/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx
index d3aa95a9681..82c8b918154 100644
--- a/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx
+++ b/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx
@@ -32,7 +32,7 @@ const mapStateToProps = (state: State, props: RouterProps) => ({
collectionId: Collections.selectors.getInitialCollectionId(state, props),
isNavBarOpen: getIsNavbarOpen(state),
isNavBarEnabled: getIsNavBarEnabled(state, props),
- isMetabotVisible: PLUGIN_METABOT.getMetabotVisible(state),
+ isMetabotVisible: PLUGIN_METABOT.getMetabotVisible(state, "omnibot"),
isDocumentSidebarOpen: getSidebarOpen(state),
isCommentSidebarOpen: getCommentSidebarOpen(state),
isLogoVisible: getIsLogoVisible(state),
diff --git a/frontend/src/metabase/plugins/oss/ai.ts b/frontend/src/metabase/plugins/oss/ai.ts
index b41b8c62db4..ffa8f57535d 100644
--- a/frontend/src/metabase/plugins/oss/ai.ts
+++ b/frontend/src/metabase/plugins/oss/ai.ts
@@ -65,7 +65,7 @@ type PluginMetabotType = {
getAdminRoutes: () => React.ReactElement;
getMetabotRoutes: () => React.ReactElement | null;
MetabotAdminPage: ComponentType;
- getMetabotVisible: (state: State) => boolean;
+ getMetabotVisible: (state: State, conversation_id: string) => boolean;
MetabotToggleButton: ComponentType<{ className?: string }>;
MetabotAppBarButton: ComponentType;
MetabotAdminAppBarButton: ComponentType;
diff --git a/frontend/src/metabase/selectors/routing.ts b/frontend/src/metabase/selectors/routing.ts
index 14085e93138..81e43d64a76 100644
--- a/frontend/src/metabase/selectors/routing.ts
+++ b/frontend/src/metabase/selectors/routing.ts
@@ -1,4 +1,6 @@
import type { State } from "metabase-types/store";
+const DEFAULT_LOCATION = { pathname: "" };
+
export const getLocation = (state: State) =>
- state.routing?.locationBeforeTransitions ?? { pathname: "" };
+ state.routing?.locationBeforeTransitions ?? DEFAULT_LOCATION;