The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
[Metabot] Key conversation state by conversation id (#78759)
Sloan Sparger4dbf593d2367
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsxindex a93eea7b6a8..8cf6033f28e 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx@@ -1,20 +1,19 @@import { assocIn } from "icepick";import { screen } from "__support__/ui";-import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import type { MetabotChatMessage } from "metabase/metabot/state/types";-import { setup } from "metabase/metabot/tests/utils";+import {+ createTestMetabotState,+ setup,+ testConversationId,+} from "metabase/metabot/tests/utils";import { MetabotChatHistory } from "./MetabotChatHistory";const makeVisibleState = (messages: MetabotChatMessage[]) =>assocIn(- assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "visible"],- true,- ),- ["conversations", "omnibot", "messages"],+ assocIn(createTestMetabotState(), ["agents", "omnibot", "visible"], true),+ ["conversations", testConversationId("omnibot"), "messages"],messages,);diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsxindex ff69898a2a1..4873cbdd2ae 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx@@ -16,7 +16,10 @@ import type {} from "embedding-sdk-bundle/types/metabot";import { useMetabotAgent } from "metabase/metabot/hooks";import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";-import { getFinalChartMessageIdsPerTurn } from "metabase/metabot/state";+import {+ getFinalChartMessageIdsPerTurn,+ getMetabotConversationId,+} from "metabase/metabot/state";import type { MetabotChatMessage } from "metabase/metabot/state/types";import { useSelector } from "metabase/redux";import * as Urls from "metabase/urls";@@ -83,7 +86,10 @@ export const useMetabot = (): UseMetabotResult => {// keep only the last chart per turn — agent may emit several mid-streamconst finalChartIds = useSelector((state) =>- getFinalChartMessageIdsPerTurn(state, "omnibot"),+ getFinalChartMessageIdsPerTurn(+ state,+ getMetabotConversationId(state, "omnibot"),+ ),);const messages = useMemo<MetabotMessage[]>(() =>diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsxindex 4382c874f19..ee518f36dec 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx@@ -6,11 +6,12 @@ import { act, screen, waitFor } from "__support__/ui";import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";import { metabotActions } from "metabase/metabot/state";-import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import {+ createTestMetabotState,lastReqBody,mockAgentEndpoint,setup,+ testConversationId,whoIsYourFavoriteResponse,} from "metabase/metabot/tests/utils";import * as Urls from "metabase/urls";@@ -32,13 +33,15 @@ const makeCard = (id: string, sourceTable = 1): GeneratedCard => ({display: "table",});+const conversationId = testConversationId("omnibot");+const cardMessage = (id: string, sourceTable = 1) =>// `addAgentMessage` types its payload with a non-distributive `Omit` that// collapses the message union to common keys, so the branch-specific `part`// field fails excess-property checks (see the fuller note in the// "maps agent.text passthrough" test below).({- agentId: "omnibot",+ conversationId,type: "data_part",part: {type: "data-generated_entity",@@ -232,7 +235,7 @@ describe("useMetabot", () => {act(() => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId,id: "u1",type: "text",message: "hi",@@ -260,7 +263,7 @@ describe("useMetabot", () => {// reducer.ts). Keeping `as any` for now — applies to every dispatch// below.metabotActions.addAgentMessage({- agentId: "omnibot",+ conversationId,type: "text",message: "ok",} as any),@@ -304,7 +307,7 @@ describe("useMetabot", () => {store.dispatch(// Unjustified type cast. FIXMEmetabotActions.addAgentMessage({- agentId: "omnibot",+ conversationId,type: "tool_call",name: "fn",status: "started",@@ -313,7 +316,7 @@ describe("useMetabot", () => {store.dispatch(// Unjustified type cast. FIXMEmetabotActions.addAgentMessage({- agentId: "omnibot",+ conversationId,type: "edit_suggestion",model: "transform",payload: {@@ -332,7 +335,7 @@ describe("useMetabot", () => {store.dispatch(// Unjustified type cast. FIXMEmetabotActions.addAgentMessage({- agentId: "omnibot",+ conversationId,type: "todo_list",payload: [{@@ -347,7 +350,7 @@ describe("useMetabot", () => {store.dispatch(// Unjustified type cast. FIXMEmetabotActions.addAgentMessage({- agentId: "omnibot",+ conversationId,type: "text",message: "ok",} as any),@@ -370,7 +373,7 @@ describe("useMetabot", () => {act(() => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId,id: "u1",type: "text",message: "first",@@ -384,7 +387,7 @@ describe("useMetabot", () => {);store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId,id: "u2",type: "text",message: "second",@@ -439,27 +442,25 @@ describe("useMetabot", () => {// observe whether submitMessage would flip it back on.const { store } = setup({ui: <TestSubmit />,- metabotInitialState: getMetabotInitialState(),+ metabotInitialState: createTestMetabotState(),});expect(- store.getState().metabot?.conversations?.omnibot?.messages.length,+ store.getState().metabot?.conversations?.[conversationId]?.messages+ .length,).toBe(0);- expect(store.getState().metabot?.conversations?.omnibot?.visible).toBe(- false,- );+ expect(store.getState().metabot?.agents?.omnibot?.visible).toBe(false);await userEvent.click(screen.getByTestId("submit-btn"));await waitFor(() => {expect(- store.getState().metabot?.conversations?.omnibot?.messages.length,+ store.getState().metabot?.conversations?.[conversationId]?.messages+ .length,).toBeGreaterThan(0);});- expect(store.getState().metabot?.conversations?.omnibot?.visible).toBe(- false,- );+ expect(store.getState().metabot?.agents?.omnibot?.visible).toBe(false);});it("resolves to undefined even though agent.submitInput returns an action", async () => {@@ -526,7 +527,7 @@ describe("useMetabot", () => {act(() => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId,id: "u1",type: "text",message: "first",@@ -547,7 +548,7 @@ describe("useMetabot", () => {act(() => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId,id: "u2",type: "text",message: "second",diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/slash-commands.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/slash-commands.tsindex 7dd4a799923..7eb52ac9479 100644--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/slash-commands.ts+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/slash-commands.ts@@ -1,5 +1,5 @@import { getUserIsAdmin } from "metabase/current-user";-import { getMetabotConversation } from "metabase/metabot/state";+import { getIsConversationEmpty } from "metabase/metabot/state";import type { MetabotSlashCommandHandler } from "metabase/plugins/oss/audit";import { addUndo } from "metabase/redux/undo";import { navigate } from "metabase/router";@@ -7,7 +7,7 @@ import * as Urls from "metabase/urls";export const handleMetabotSlashCommand: MetabotSlashCommandHandler = ({command,- agentId,+ conversationId,dispatch,getState,}) => {@@ -18,11 +18,7 @@ export const handleMetabotSlashCommand: MetabotSlashCommandHandler = ({dispatch(addUndo({ message: "Unknown command" }));return true;}- const { conversationId, messages } = getMetabotConversation(- getState(),- agentId,- );- if (messages.length === 0) {+ if (getIsConversationEmpty(getState(), conversationId)) {dispatch(addUndo({ message: "No message history to inspect" }));return true;}diff --git a/frontend/src/metabase/explorations/pages/NewExplorationDraftProvider.unit.spec.tsx b/frontend/src/metabase/explorations/pages/NewExplorationDraftProvider.unit.spec.tsxindex bf47f6d40e7..2e31a69b2b6 100644--- a/frontend/src/metabase/explorations/pages/NewExplorationDraftProvider.unit.spec.tsx+++ b/frontend/src/metabase/explorations/pages/NewExplorationDraftProvider.unit.spec.tsx@@ -3,7 +3,11 @@ import { useState } from "react";import { act, renderWithProviders, screen } from "__support__/ui";import type { ExplorationSelection } from "metabase/explorations/hooks";import { makeMockSelection } from "metabase/explorations/test-utils";-import { getMessages, metabotActions } from "metabase/metabot/state";+import {+ getMessages,+ getMetabotConversationId,+ metabotActions,+} from "metabase/metabot/state";import { Route } from "metabase/router";import { NewExplorationDraftProvider } from "./NewExplorationDraftProvider";@@ -62,12 +66,15 @@ function setup() {},);+ const draftConversationId = () =>+ getMetabotConversationId(store.getState(), "explorations");+// stand-in for the request "Create plan" fires just before navigatingconst submitDraftMessage = () =>act(() => {store.dispatch(metabotActions.addUserMessage({- agentId: "explorations",+ conversationId: draftConversationId(),id: "draft-1",type: "text",message: "Why are signups down?",@@ -75,7 +82,8 @@ function setup() {);});- const getDraftMessages = () => getMessages(store.getState(), "explorations");+ const getDraftMessages = () =>+ getMessages(store.getState(), draftConversationId());return {router,diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsxindex e60aaf0444d..34eeed86499 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx@@ -92,14 +92,16 @@ describe("AIMarkdown", () => {);expect(await screen.findByText("Orders by month")).toBeInTheDocument();- expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Orders by month/ }),+ ).toHaveAttribute("href", expect.stringContaining("/question#"));});it("should still render the chart mention chip when the chart is not in conversation state", async () => {setup({ children: "[Orders by month](metabase://chart/chart-1)" });expect(await screen.findByText("Orders by month")).toBeInTheDocument();- expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();});it("should render GFM tables", async () => {diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsxindex e537006581c..7c39ba1f2f9 100644--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx@@ -1,5 +1,4 @@import userEvent from "@testing-library/user-event";-import { assocIn } from "icepick";import { setupEnterprisePlugins } from "__support__/enterprise";import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";@@ -7,8 +6,10 @@ import { mockSettings } from "__support__/settings";import { renderWithProviders, screen } from "__support__/ui";import { mockStreamedEndpoint } from "metabase/api/ai-streaming/test-utils";import { MetabotProvider } from "metabase/metabot/context";-import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";-import { lastReqBody } from "metabase/metabot/tests/utils";+import {+ createTestMetabotState,+ lastReqBody,+} from "metabase/metabot/tests/utils";import { createMockState } from "metabase/redux/store/mocks";import { AIQuestionAnalysisButton } from "./AIQuestionAnalysisButton";@@ -38,11 +39,9 @@ function setup({setupUserMetabotPermissionsEndpoint();setupEnterprisePlugins();- const metabotState = assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "title"],- "Chart analysis",- );+ const metabotState = createTestMetabotState({+ conversationTitle: "Chart analysis",+ });renderWithProviders(<MetabotProvider>diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsxindex 14e8e7bee51..df36e424f77 100644--- a/frontend/src/metabase/metabot/components/Metabot.tsx+++ b/frontend/src/metabase/metabot/components/Metabot.tsx@@ -107,14 +107,17 @@ const MetabotSidebarActions = ({ agentId }: { agentId: MetabotAgentId }) => {};// TODO: add test coverage for these-export interface MetabotConfig {- agentId: MetabotAgentId;+export interface MetabotChatConfig {emptyText?: string;hideSuggestedPrompts?: boolean;preventRetryMessage?: boolean;suggestionModels: SuggestionModel[];}+export interface MetabotConfig extends MetabotChatConfig {+ agentId: MetabotAgentId;+}+export interface MetabotProps {hide?: boolean;config?: MetabotConfig;@@ -122,7 +125,8 @@ export interface MetabotProps {export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {const agentId = config?.agentId ?? "omnibot";- const { visible, setVisible } = useMetabotAgent(agentId);+ const { visible, setVisible, conversationId, createNewConversation } =+ useMetabotAgent(agentId);const [errorBoundaryKey, setErrorBoundaryKey] = useState(0);const [MetabotChat, setMetabotChat] = useState(createLazyMetabotChat);const isFullPageMetabot = useIsFullPageMetabot();@@ -184,6 +188,9 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {aria-hidden={!visible}><MetabotChat+ conversationId={conversationId}+ agentId={agentId}+ onNewConversation={createNewConversation}config={config}headerActions={<MetabotSidebarActions agentId={agentId} />}/>diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsxindex 03cc7d87635..89b4fe60705 100644--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx@@ -114,7 +114,7 @@ describe("MetabotAppBarButton", () => {// Unjustified type cast. FIXMEconst initialState = store.getState() as any;- expect(initialState.metabot.conversations.omnibot.visible).toBe(false);+ expect(initialState.metabot.agents.omnibot.visible).toBe(false);await userEvent.click(await screen.findByRole("button", { name: /Chat with Metabot/ }),@@ -122,6 +122,6 @@ describe("MetabotAppBarButton", () => {// Unjustified type cast. FIXMEconst newState = store.getState() as any;- expect(newState.metabot.conversations.omnibot.visible).toBe(true);+ expect(newState.metabot.agents.omnibot.visible).toBe(true);});});diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsxindex e81e1ee4f89..48419965e8b 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx@@ -1,6 +1,5 @@import { useEffect } from "react";-import type { MetabotConfig } from "metabase/metabot/components/Metabot";import { MetabotChat } from "metabase/metabot/components/MetabotChat";import { MetabotConversationHistory } from "metabase/metabot/components/MetabotChat/MetabotConversationHistory";import { isHistoryEnabledProfile } from "metabase/metabot/constants";@@ -26,16 +25,11 @@ const SUGGESTION_MODELS: SuggestionModel[] = ["dashboard",];-const askConfig: MetabotConfig = {- agentId: "ask",- suggestionModels: SUGGESTION_MODELS,-};-export const MetabotAsk = () => {const navigate = useNavigate();const { setVisible: setSidebarVisible } = useMetabotAgent("omnibot");- const askAgent = useMetabotAgent("ask");- const { messages, isDoingScience, conversationId } = askAgent;+ const { conversationId, messages, isDoingScience, profile } =+ useMetabotAgent("ask");const { isConfigured } = useUserMetabotPermissions();const isAskPage = useIsAskPage();@@ -57,10 +51,10 @@ export const MetabotAsk = () => {const showGreeting = messages.length === 0 && !isDoingScience;- const showHistory = isConfigured && isHistoryEnabledProfile(askAgent.profile);+ const showHistory = isConfigured && isHistoryEnabledProfile(profile);const historyAction = showHistory ? (<MetabotConversationHistory- profileId={askAgent.profile}+ profileId={profile}activeConversationId={conversationId}onConversationSelect={(id) => navigate(Urls.metabotConversation(id))}/>@@ -75,13 +69,21 @@ export const MetabotAsk = () => {{historyAction}</Flex>)}- <MetabotGreeting agentId="ask" suggestionModels={SUGGESTION_MODELS} />+ <MetabotGreeting+ conversationId={conversationId}+ suggestionModels={SUGGESTION_MODELS}+ /></>) : (<Box pos="relative" h="100%" w="100%"><Box className={S.topFade} /><MetabotChat- config={askConfig}+ conversationId={conversationId}+ agentId="ask"+ onNewConversation={() =>+ navigate(Urls.newQuestion({ mode: "ask" }))+ }+ config={{ suggestionModels: SUGGESTION_MODELS }}className={S.chat}headerActions={historyAction}/>diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsxindex 61d5511dceb..2c5bb9e347e 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx@@ -2,20 +2,19 @@ import userEvent from "@testing-library/user-event";import { assocIn } from "icepick";import { screen, waitFor } from "__support__/ui";-import {- getMetabotConversationId,- getMetabotVisible,-} from "metabase/metabot/state";-import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";+import { getMetabotVisible } from "metabase/metabot/state";import {createMockMetabotConversation,createMockUser,} from "metabase-types/api/mocks";import {+ conversationIdForAgent,+ createTestMetabotState,enterChatMessage,mockAgentEndpoint,setup,+ testConversationId,whoIsYourFavoriteResponse,} from "../../tests/utils";@@ -26,36 +25,21 @@ const greetingTitle =type SetupOpts = Exclude<Parameters<typeof setup>[0], void>;+const ASK_CONVERSATION_ID = testConversationId("ask");+const setupMetabotAsk = (options?: Omit<SetupOpts, "ui">) =>setup({ ...options, ui: <MetabotAsk /> });-// The history control lives in the chat header, which only renders once the ask-// conversation has messages (i.e. past the greeting).-const askStateWithMessage = () => {- const state = getMetabotInitialState();- const ask = state.conversations.ask;- if (!ask) {- throw new Error("Expected ask conversation");- }- ask.messages.push({- id: "seed-message",- role: "user",- type: "text",- message: "Earlier question",- });- return state;-};+const askConversation = (field: string, value: unknown) =>+ assocIn(+ createTestMetabotState(),+ ["conversations", ASK_CONVERSATION_ID, field],+ value,+ );describe("MetabotAsk", () => {it("shows the greeting and closes the global Metabot sidebar", async () => {- const metabotInitialState = assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "visible"],- true,- );-const { store } = setupMetabotAsk({- metabotInitialState,promptSuggestions: [{ prompt: "Show me all orders" }],});@@ -124,7 +108,16 @@ describe("MetabotAsk", () => {});it("shows the conversation history control in the chat header", async () => {- setupMetabotAsk({ metabotInitialState: askStateWithMessage() });+ setupMetabotAsk({+ metabotInitialState: askConversation("messages", [+ {+ id: "seed-message",+ role: "user",+ type: "text",+ message: "Earlier question",+ },+ ]),+ });expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();expect(@@ -142,14 +135,9 @@ describe("MetabotAsk", () => {});it("does not show the conversation history control for a non-internal/nlq profile", async () => {- const state = getMetabotInitialState();- const ask = state.conversations.ask;- if (!ask) {- throw new Error("Expected ask conversation");- }- ask.profileOverride = "sql";-- setupMetabotAsk({ metabotInitialState: state });+ setupMetabotAsk({+ metabotInitialState: askConversation("profileOverride", "sql"),+ });expect(await screen.findByText(greetingTitle)).toBeInTheDocument();expect(@@ -158,18 +146,18 @@ describe("MetabotAsk", () => {});it("navigates to the conversation route after the first message", async () => {- const { store, router } = setupMetabotAsk({+ const { router, store } = setupMetabotAsk({withRouter: true,initialRoute: "/question/ask",});mockAgentEndpoint({ events: whoIsYourFavoriteResponse });- const askId = getMetabotConversationId(store.getState(), "ask");-await enterChatMessage("Who is your favorite?");await waitFor(() => {- expect(router?.location.pathname).toBe(`/metabot/conversation/${askId}`);+ expect(router?.location.pathname).toBe(+ `/metabot/conversation/${conversationIdForAgent(store, "ask")}`,+ );});});diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsxindex 745e0513058..2a3af8fc1f1 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx@@ -8,10 +8,9 @@ import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProvimport { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";import {- useMetabotAgent,+ useMetabotConversation,useUserMetabotPermissions,} from "metabase/metabot/hooks";-import type { MetabotAgentId } from "metabase/metabot/state";import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";import {ActionIcon,@@ -41,12 +40,12 @@ const getTitleText = () => {};interface MetabotGreetingProps {- agentId: MetabotAgentId;+ conversationId: string;suggestionModels: SuggestionModel[];}export const MetabotGreeting = ({- agentId,+ conversationId,suggestionModels,}: MetabotGreetingProps) => {const [title] = useState(getTitleText);@@ -57,7 +56,7 @@ export const MetabotGreeting = ({open: openAiProviderConfigurationModal,},] = useDisclosure(false);- const metabot = useMetabotAgent(agentId);+ const metabot = useMetabotConversation(conversationId);const { canUseNlq, hasNlqAccess } = useUserMetabotPermissions();const suggestedPromptsReq = useGetSuggestedMetabotPromptsQuery(diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsxindex b1b9711853f..efe508426ba 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx@@ -11,16 +11,16 @@ import { useSetting } from "metabase/settings";import { Box, Button, Flex, Paper, Stack, Text } from "metabase/ui";import { useGetSuggestedMetabotPromptsQuery } from "../../api";-import { useMetabotAgent, useUserMetabotPermissions } from "../../hooks";-import type { MetabotConfig } from "../Metabot";+import { useMetabotConversation, useUserMetabotPermissions } from "../../hooks";+import type { MetabotAgentId } from "../../state";+import type { MetabotChatConfig } from "../Metabot";import Styles from "./MetabotChat.module.css";import { MetabotChatEditor } from "./MetabotChatEditor";import { Messages } from "./MetabotChatMessage";import { useScrollManager } from "./hooks";-const defaultConfig: MetabotConfig = {- agentId: "omnibot",+const defaultConfig: MetabotChatConfig = {suggestionModels: ["dataset","metric",@@ -32,11 +32,17 @@ const defaultConfig: MetabotConfig = {};export const MetabotChat = ({+ conversationId,+ agentId,+ onNewConversation,config = defaultConfig,className,headerActions,}: {- config?: MetabotConfig;+ conversationId: string;+ agentId?: MetabotAgentId;+ onNewConversation?: () => void;+ config?: MetabotChatConfig;className?: string;headerActions?: ReactNode;}) => {@@ -47,7 +53,7 @@ export const MetabotChat = ({open: openAiProviderConfigurationModal,},] = useDisclosure(false);- const metabot = useMetabotAgent(config.agentId);+ const metabot = useMetabotConversation(conversationId);const metabotName = useSetting("metabot-name");const { isConfigured } = useUserMetabotPermissions();const showIllustrations = useSetting("metabot-show-illustrations");@@ -178,20 +184,20 @@ export const MetabotChat = ({onContinueMessage={metabot.submitInput}onRefreshConversation={() => {metabot.setPrompt("");- metabot.loadConversation(metabot.conversationId);+ metabot.reloadConversation();}}isDoingScience={metabot.isDoingScience}supportsReasoning={supportsReasoning}debug={metabot.debugMode}- agentId={config.agentId}+ agentId={agentId}conversationId={metabot.conversationId}/>{/* filler - height gets set via ref mutation */}<div ref={fillerRef} data-testid="metabot-message-filler" />{/* long convo warning */}- {metabot.isLongConversation && (+ {metabot.isLongConversation && onNewConversation && (<MetabotResetLongChatButton- onResetConversation={metabot.createNewConversation}+ onResetConversation={onNewConversation}/>)}</Box>diff --git a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsxindex 53f5f98566f..174b0d89ad7 100644--- a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx+++ b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx@@ -9,6 +9,7 @@ import {useUserMetabotPermissions,} from "metabase/metabot/hooks";import {+ getIsConversationEmpty,getIsConversationInProgress,setConversationSnapshot,} from "metabase/metabot/state";@@ -29,15 +30,18 @@ export const MetabotConversationPage = () => {const { canUseNlq, isLoading } = useUserMetabotPermissions();const { conversationId } = useMetabotAgent("ask");+ const isAttached = urlConvoId != null && conversationId === urlConvoId;+const isSettingsLoading = useSelector(getSettingsLoading);const isInProgress = useSelector((state) =>- getIsConversationInProgress(state, "ask"),+ isAttached ? getIsConversationInProgress(state, urlConvoId) : false,+ );+ const isEmpty = useSelector((state) =>+ isAttached ? getIsConversationEmpty(state, urlConvoId) : true,);-- const isConvoLoaded = conversationId === urlConvoId;const { currentData: conversation, isError } = useGetMetabotConversationQuery(- !urlConvoId || !canUseNlq || (isConvoLoaded && !isInProgress)+ !urlConvoId || !canUseNlq || (!isEmpty && !isInProgress)? skipToken: urlConvoId,{@@ -53,7 +57,6 @@ export const MetabotConversationPage = () => {dispatch(setConversationSnapshot({- agentId: "ask",conversationId: conversation.conversation_id,title: conversation.title ?? undefined,forkedFromConversationId:@@ -71,7 +74,7 @@ export const MetabotConversationPage = () => {return <ConversationLoader />;}- if (!canUseNlq) {+ if (!canUseNlq || !urlConvoId) {return <Navigate to={Urls.newQuestion({ mode: "ask" })} replace />;}@@ -79,7 +82,7 @@ export const MetabotConversationPage = () => {return <ConversationLoadError />;}- if (!isConvoLoaded) {+ if (!isAttached || isEmpty) {return <ConversationLoader />;}diff --git a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsxindex 52eb057b807..6c80ae0ab67 100644--- a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx@@ -1,4 +1,5 @@import fetchMock, { type RouteResponse } from "fetch-mock";+import { assocIn } from "icepick";import { setupEnterprisePlugins } from "__support__/enterprise";import {@@ -17,8 +18,11 @@ import { createMockUser } from "metabase-types/api/mocks";import { FIXED_METABOT_IDS } from "../../constants";import { MetabotProvider } from "../../context";-import { getMetabotConversationId, metabotReducer } from "../../state";-import { getMetabotInitialState } from "../../state/reducer-utils";+import { metabotReducer } from "../../state";+import {+ createConversation,+ getMetabotInitialState,+} from "../../state/reducer-utils";import {IN_PROGRESS_POLL_MS,@@ -43,29 +47,23 @@ const mockConversationDetail = (response: RouteResponse, delay?: number) => {});};-const createAskState = ({+const stateWithConversation = ({conversationId = OTHER_CONVERSATION_ID,message,}: {conversationId?: string;message?: string;-} = {}) => {- const state = getMetabotInitialState();- const ask = state.conversations.ask;- if (!ask) {- throw new Error("Expected ask conversation");- }- ask.conversationId = conversationId;- if (message) {- ask.messages.push({- id: "seed-message",- role: "user",- type: "text",- message,- });- }- return state;-};+} = {}) =>+ assocIn(+ getMetabotInitialState(),+ ["conversations", conversationId],+ createConversation({+ conversationId,+ messages: message+ ? [{ id: "seed-message", role: "user", type: "text", message }]+ : [],+ }),+ );const TestConversationPage = () => (<MetabotProvider>@@ -148,7 +146,7 @@ describe("MetabotConversationPage", () => {);const { store } = setup({- metabotInitialState: createAskState(),+ metabotInitialState: stateWithConversation(),});expect(@@ -161,13 +159,13 @@ describe("MetabotConversationPage", () => {screen.queryByTestId("metabot-conversation-loading"),).not.toBeInTheDocument();await waitFor(() => {- expect(getMetabotConversationId(store.getState(), "ask")).toBe(- CONVERSATION_ID,- );+ expect(+ store.getState().metabot.conversations[CONVERSATION_ID],+ ).toBeDefined();});});- it("does not load when the ask agent already holds the URL conversation", async () => {+ it("does not load when the store already holds the URL conversation", async () => {setupGetMetabotConversationEndpoint(createMockMetabotConversationDetail({conversation_id: CONVERSATION_ID,@@ -175,7 +173,7 @@ describe("MetabotConversationPage", () => {);setup({- metabotInitialState: createAskState({+ metabotInitialState: stateWithConversation({conversationId: CONVERSATION_ID,message: "Existing question",}),@@ -194,7 +192,7 @@ describe("MetabotConversationPage", () => {mockConversationDetail(404);const { router } = setup({- metabotInitialState: createAskState(),+ metabotInitialState: stateWithConversation(),});expect(@@ -211,7 +209,7 @@ describe("MetabotConversationPage", () => {mockConversationDetail(inProgressDetail());setup({- metabotInitialState: createAskState(),+ metabotInitialState: stateWithConversation(),});expect(await screen.findByText("Loaded question")).toBeInTheDocument();@@ -232,7 +230,7 @@ describe("MetabotConversationPage", () => {});setup({- metabotInitialState: createAskState(),+ metabotInitialState: stateWithConversation(),});expect(await screen.findByText("Thinking")).toBeInTheDocument();diff --git a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsxindex 98b445e8a00..bafcec1a81c 100644--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx@@ -1,8 +1,6 @@import { t } from "ttag";import { ForwardRefLink } from "metabase/common/components/Link";-import { resetConversation } from "metabase/metabot/state";-import { useDispatch } from "metabase/redux";import { Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";import type { CollectionId } from "metabase-types/api";@@ -16,8 +14,6 @@ export function NewMenuItemAIExploration({collectionId,hasNlqAccess,}: NewMenuItemAIExplorationProps) {- const dispatch = useDispatch();-const url = hasNlqAccess? Urls.newQuestion({mode: "ask",@@ -31,11 +27,6 @@ export function NewMenuItemAIExploration({component={ForwardRefLink}to={url}leftSection={<Icon name="comment" />}- onClick={() => {- if (hasNlqAccess) {- dispatch(resetConversation({ agentId: "ask" }));- }- }}>{t`AI exploration`}</Menu.Item>diff --git a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsxindex f260b0ad384..6ad9dbe6f87 100644--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx@@ -1,8 +1,5 @@-import userEvent from "@testing-library/user-event";-import { assocIn } from "icepick";-import { renderWithProviders, screen } from "__support__/ui";-import { getMessages, metabotReducer } from "metabase/metabot/state";+import { metabotReducer } from "metabase/metabot/state";import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import { createMockState } from "metabase/redux/store/mocks";import { Route } from "metabase/router";@@ -15,12 +12,6 @@ function setup(hasNlqAccess: true,},) {- const metabotInitialState = assocIn(- getMetabotInitialState(),- ["conversations", "ask", "messages"],- [{ id: "1", role: "user", type: "text", message: "hi" }],- );-const TestComponent = () => (<Menu opened><Menu.Dropdown>@@ -33,7 +24,7 @@ function setup(<Route path="*" element={<TestComponent />} />,{withRouter: true,- storeInitialState: createMockState({ metabot: metabotInitialState }),+ storeInitialState: createMockState({ metabot: getMetabotInitialState() }),customReducers: { metabot: metabotReducer },},);@@ -50,18 +41,6 @@ describe("NewMenuItemAIExploration", () => {).toHaveAttribute("href", "/question/ask");});- it("resets the ask conversation when clicked", async () => {- const { store } = setup();-- expect(getMessages(store.getState(), "ask")).toHaveLength(1);-- await userEvent.click(- screen.getByRole("menuitem", { name: /AI exploration/ }),- );-- expect(getMessages(store.getState(), "ask")).toHaveLength(0);- });-it("should link to the research mode page when hasNlqAccess is false", () => {setup({hasNlqAccess: false,diff --git a/frontend/src/metabase/metabot/hooks/index.ts b/frontend/src/metabase/metabot/hooks/index.tsindex e6113e3e07b..58cd431c9e7 100644--- a/frontend/src/metabase/metabot/hooks/index.ts+++ b/frontend/src/metabase/metabot/hooks/index.ts@@ -4,6 +4,7 @@ export { useLlmConnectionModels } from "./use-llm-connection-models";export { useMetabotEnabledEmbeddingAware } from "./use-metabot-embedding-aware-enabled";export { useBranchableMessages } from "./use-branchable-messages";export { useMetabotAgent } from "./use-metabot-agent";+export { useMetabotConversation } from "./use-metabot-conversation";export { useMetabotAgentsManager } from "./use-metabot-agents-manager";export { useDashCardAnalysis } from "./useDashCardAnalysis";export { useUserMetabotPermissions } from "./use-user-metabot-permissions";diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts b/frontend/src/metabase/metabot/hooks/use-metabot-agent.tsindex d0402db8c5d..72655c029c8 100644--- a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts+++ b/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts@@ -1,54 +1,27 @@-import { isFulfilled } from "@reduxjs/toolkit";import { useCallback } from "react";-import { useMetabotContext } from "metabase/metabot";import { useDispatch, useSelector } from "metabase/redux";-import { useMaybeLocation } from "metabase/router";-import * as Urls from "metabase/urls";-import { trackMetabotRequestSent } from "../analytics";-import type { MetabotProfileId } from "../constants";import {type MetabotAgentId,- type MetabotPromptSubmissionResult,- type MetabotUserChatMessage,- cancelInflightAgentRequests,- getActiveToolCalls,- getDebugMode,- getIsLongMetabotConversation,- getIsProcessing,- getMessages,- getMetabotConversationForkedFrom,getMetabotConversationId,- getMetabotConversationTitle,- getMetabotId,- getMetabotReactionsState,- getMetabotRequestId,getMetabotVisible,- getProfile,loadConversation as loadConversationAction,- resetConversation as resetConversationAction,- retryPrompt,- setProfileOverride as setProfileOverrideAction,setVisible as setVisibleAction,- submitInput as submitInputAction,+ startNewConversation as startNewConversationAction,} from "../state";+import {+ type SubmitInputOptions,+ useMetabotConversation,+} from "./use-metabot-conversation";+export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {const dispatch = useDispatch();- const { prompt, setPrompt, promptInputRef, getChatContext } =- useMetabotContext();-- // `null` when rendered outside the app router (e.g. the SDK), where there is- // no transforms page. Drives the transforms-codegen profile auto-selection- // that used to read the retired routing slice.- const location = useMaybeLocation();- const isTransformsPage =- location?.pathname.startsWith(Urls.transformList()) ?? false;-- const metabotRequestId = useSelector((state) =>- getMetabotRequestId(state, agentId),+ const conversationId = useSelector((state) =>+ getMetabotConversationId(state, agentId),);+ const conversation = useMetabotConversation(conversationId);const visible = useSelector((state) => getMetabotVisible(state, agentId));const setVisible = useCallback(@@ -56,148 +29,35 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {[dispatch, agentId],);- const prepareRetryIfUnsuccesful = useCallback(- (result: MetabotPromptSubmissionResult) => {- if (!result.success && result.shouldRetry) {- promptInputRef?.current?.focus();- setPrompt(result.prompt);- }- },- [promptInputRef, setPrompt],- );-- const setProfileOverride = useCallback(- (profile: MetabotProfileId | undefined) => {- dispatch(setProfileOverrideAction({ agentId, profile }));- },- [dispatch, agentId],- );-const submitInput = useCallback(- async (- prompt: string | Omit<MetabotUserChatMessage, "id" | "role">,- options?: {- profile?: MetabotProfileId | undefined;- preventOpenSidebar?: boolean;- focusInput?: boolean;- },- ) => {- setPrompt("");-- if (!visible && !options?.preventOpenSidebar) {- setVisible(true);- }-- if (options?.focusInput) {- promptInputRef?.current?.focus();- }-- const action = await dispatch(- submitInputAction({- ...(typeof prompt === "string"- ? { type: "text", message: prompt }- : prompt),- context: await getChatContext(),- agentId,- metabot_id: metabotRequestId,- profile: options?.profile,- isTransformsPage,- }),- );-- trackMetabotRequestSent();-- if (isFulfilled(action)) {- prepareRetryIfUnsuccesful(action.payload);- }-- return action;- },- [- dispatch,- getChatContext,- metabotRequestId,- prepareRetryIfUnsuccesful,- setVisible,- visible,- agentId,- promptInputRef,- setPrompt,- isTransformsPage,- ],- );-- const retryMessage = useCallback(- async (messageId: string, options?: { profile?: MetabotProfileId }) => {- const context = await getChatContext();- const action = await dispatch(- retryPrompt({- messageId,- context,- metabot_id: metabotRequestId,- agentId,- profile: options?.profile,- isTransformsPage,- }),- );- if (isFulfilled(action)) {- prepareRetryIfUnsuccesful(action.payload);- }- },- [- dispatch,- getChatContext,- metabotRequestId,- prepareRetryIfUnsuccesful,- agentId,- isTransformsPage,- ],- );-- const cancelRequest = useCallback(() => {- dispatch(cancelInflightAgentRequests(agentId));- }, [dispatch, agentId]);-- const createNewConversation = useCallback(() => {- dispatch(resetConversationAction({ agentId }));- }, [agentId, dispatch]);-- const loadConversation = useCallback(- (conversationId: string) =>- dispatch(loadConversationAction({ agentId, conversationId })),- [agentId, dispatch],+ (+ prompt: Parameters<typeof conversation.submitInput>[0],+ options?: SubmitInputOptions & { preventOpenSidebar?: boolean },+ ) =>+ conversation.submitInput(prompt, {+ ...options,+ onBeforeSubmit: () => {+ if (!visible && !options?.preventOpenSidebar) {+ setVisible(true);+ }+ },+ }),+ [conversation, setVisible, visible],);return {- prompt,- setPrompt,- promptInputRef,+ ...conversation,+ submitInput,visible,setVisible,- setProfileOverride,- createNewConversation,- loadConversation,- submitInput,- retryMessage,- cancelRequest,- metabotId: useSelector(getMetabotId),- profile: useSelector((state) =>- getProfile(state, agentId, isTransformsPage),- ),- conversationId: useSelector((state) =>- getMetabotConversationId(state, agentId),- ),- title: useSelector((state) => getMetabotConversationTitle(state, agentId)),- forkedFromConversationId: useSelector((state) =>- getMetabotConversationForkedFrom(state, agentId),+ createNewConversation: useCallback(+ () => dispatch(startNewConversationAction({ agentId })),+ [agentId, dispatch],),- messages: useSelector((state) => getMessages(state, agentId)),- isDoingScience: useSelector((state) => getIsProcessing(state, agentId)),- isLongConversation: useSelector((state) =>- getIsLongMetabotConversation(state, agentId),+ loadConversation: useCallback(+ (conversationId: string) =>+ dispatch(loadConversationAction({ agentId, conversationId })),+ [agentId, dispatch],),- activeToolCalls: useSelector((state) => getActiveToolCalls(state, agentId)),- debugMode: useSelector(getDebugMode),- reactions: useSelector(getMetabotReactionsState),};};diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-agents-manager.ts b/frontend/src/metabase/metabot/hooks/use-metabot-agents-manager.tsindex 71f767d7302..ba3185e47d8 100644--- a/frontend/src/metabase/metabot/hooks/use-metabot-agents-manager.ts+++ b/frontend/src/metabase/metabot/hooks/use-metabot-agents-manager.ts@@ -9,12 +9,12 @@ import {createAgent as createAgentAction,destroyAgent,getActiveMetabotAgentIds,- resetConversation,+ startNewConversation,} from "../state";type CreatePayload = Parameters<typeof createAgentAction>[0];type DestroyPayload = Parameters<typeof destroyAgent>[0];-type ResetPayload = Parameters<typeof resetConversation>[0];+type StartNewConversationPayload = Parameters<typeof startNewConversation>[0];export const useMetabotAgentsManager = (autoStartAgentIds: MetabotAgentId[],@@ -35,8 +35,8 @@ export const useMetabotAgentsManager = ((p: CreatePayload) => dispatch(createAgentAction(p)),[dispatch],),- resetConversation: useCallback(- (p: ResetPayload) => dispatch(resetConversation(p)),+ startNewConversation: useCallback(+ (p: StartNewConversationPayload) => dispatch(startNewConversation(p)),[dispatch],),destroyAgent: useCallback(diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts b/frontend/src/metabase/metabot/hooks/use-metabot-conversation.tsnew file mode 100644index 00000000000..882d9df73ef--- /dev/null+++ b/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts@@ -0,0 +1,193 @@+import { isFulfilled } from "@reduxjs/toolkit";+import { useCallback } from "react";++import { useMetabotContext } from "metabase/metabot";+import { useDispatch, useSelector } from "metabase/redux";+import { useMaybeLocation } from "metabase/router";+import * as Urls from "metabase/urls";++import { trackMetabotRequestSent } from "../analytics";+import type { MetabotProfileId } from "../constants";+import {+ type MetabotPromptSubmissionResult,+ type MetabotUserChatMessage,+ cancelInflightConversationRequests,+ fetchConversationSnapshot,+ getActiveToolCalls,+ getConversationForkedFrom,+ getConversationTitle,+ getDebugMode,+ getIsConversationProcessing,+ getIsLongConversation,+ getMessages,+ getMetabotId,+ getMetabotReactionsState,+ getMetabotRequestId,+ getProfile,+ retryPrompt,+ setProfileOverride as setProfileOverrideAction,+ submitInput as submitInputAction,+} from "../state";++import { useIsFullPageMetabot } from "./use-is-full-page-metabot";++export type SubmitInputOptions = {+ profile?: MetabotProfileId | undefined;+ focusInput?: boolean;+ onBeforeSubmit?: () => void;+};++/**+ * Drive a conversation by id rather than through a surface. Two surfaces showing the same+ * conversation observe one record, so neither can fall behind the other.+ */+export const useMetabotConversation = (conversationId: string) => {+ const dispatch = useDispatch();+ const { prompt, setPrompt, promptInputRef, getChatContext } =+ useMetabotContext();++ // `null` when rendered outside the app router (e.g. the SDK), where there is+ // no transforms page. Drives the transforms-codegen profile auto-selection+ // that used to read the retired routing slice.+ const location = useMaybeLocation();+ const isTransformsPage =+ location?.pathname.startsWith(Urls.transformList()) ?? false;+ const isFullPageMetabot = useIsFullPageMetabot();++ const metabotRequestId = useSelector((state) =>+ getMetabotRequestId(state, conversationId),+ );++ const prepareRetryIfUnsuccesful = useCallback(+ (result: MetabotPromptSubmissionResult) => {+ if (!result.success && result.shouldRetry) {+ promptInputRef?.current?.focus();+ setPrompt(result.prompt);+ }+ },+ [promptInputRef, setPrompt],+ );++ const setProfileOverride = useCallback(+ (profile: MetabotProfileId | undefined) => {+ dispatch(setProfileOverrideAction({ conversationId, profile }));+ },+ [dispatch, conversationId],+ );++ const submitInput = useCallback(+ async (+ prompt: string | Omit<MetabotUserChatMessage, "id" | "role">,+ options?: SubmitInputOptions,+ ) => {+ setPrompt("");+ options?.onBeforeSubmit?.();++ if (options?.focusInput) {+ promptInputRef?.current?.focus();+ }++ const action = await dispatch(+ submitInputAction({+ ...(typeof prompt === "string"+ ? { type: "text", message: prompt }+ : prompt),+ context: await getChatContext(),+ conversationId,+ metabot_id: metabotRequestId,+ profile: options?.profile,+ isTransformsPage,+ isFullPageMetabot,+ }),+ );++ trackMetabotRequestSent();++ if (isFulfilled(action)) {+ prepareRetryIfUnsuccesful(action.payload);+ }++ return action;+ },+ [+ dispatch,+ getChatContext,+ metabotRequestId,+ prepareRetryIfUnsuccesful,+ conversationId,+ promptInputRef,+ setPrompt,+ isTransformsPage,+ isFullPageMetabot,+ ],+ );++ const retryMessage = useCallback(+ async (messageId: string, options?: { profile?: MetabotProfileId }) => {+ const context = await getChatContext();+ const action = await dispatch(+ retryPrompt({+ messageId,+ context,+ metabot_id: metabotRequestId,+ conversationId,+ profile: options?.profile,+ isTransformsPage,+ isFullPageMetabot,+ }),+ );+ if (isFulfilled(action)) {+ prepareRetryIfUnsuccesful(action.payload);+ }+ },+ [+ dispatch,+ getChatContext,+ metabotRequestId,+ prepareRetryIfUnsuccesful,+ conversationId,+ isTransformsPage,+ isFullPageMetabot,+ ],+ );++ const cancelRequest = useCallback(() => {+ dispatch(cancelInflightConversationRequests(conversationId));+ }, [dispatch, conversationId]);++ const reloadConversation = useCallback(() => {+ dispatch(fetchConversationSnapshot(conversationId));+ }, [dispatch, conversationId]);++ return {+ conversationId,+ prompt,+ setPrompt,+ promptInputRef,+ setProfileOverride,+ submitInput,+ retryMessage,+ cancelRequest,+ reloadConversation,+ metabotId: useSelector(getMetabotId),+ profile: useSelector((state) =>+ getProfile(state, conversationId, isTransformsPage),+ ),+ title: useSelector((state) => getConversationTitle(state, conversationId)),+ forkedFromConversationId: useSelector((state) =>+ getConversationForkedFrom(state, conversationId),+ ),+ messages: useSelector((state) => getMessages(state, conversationId)),+ isDoingScience: useSelector((state) =>+ getIsConversationProcessing(state, conversationId),+ ),+ isLongConversation: useSelector((state) =>+ getIsLongConversation(state, conversationId),+ ),+ activeToolCalls: useSelector((state) =>+ getActiveToolCalls(state, conversationId),+ ),+ debugMode: useSelector(getDebugMode),+ reactions: useSelector(getMetabotReactionsState),+ };+};diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-sql-suggestion.tsx b/frontend/src/metabase/metabot/hooks/use-metabot-sql-suggestion.tsxindex c0278fb90ea..f3006eb9799 100644--- a/frontend/src/metabase/metabot/hooks/use-metabot-sql-suggestion.tsx+++ b/frontend/src/metabase/metabot/hooks/use-metabot-sql-suggestion.tsx@@ -10,7 +10,7 @@ import {addDeveloperMessage,getMetabotSuggestedCodeEdit,removeSuggestedCodeEdit,- resetConversation,+ startNewConversation,} from "metabase/metabot/state";import { useDispatch, useSelector } from "metabase/redux";import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";@@ -41,7 +41,8 @@ export function useMetabotSQLSuggestion({bufferId,onGenerated,}: UseMetabotSQLSuggestionOptions) {- const { isDoingScience, submitInput, cancelRequest } = useMetabotAgent("sql");+ const { isDoingScience, submitInput, cancelRequest, conversationId } =+ useMetabotAgent("sql");const [error, setError] = useState<MetabotAgentTurnDisplayError>();@@ -89,11 +90,11 @@ export function useMetabotSQLSuggestion({const reject = useCallback(() => {dispatch(addDeveloperMessage({- agentId: "sql",+ conversationId,message: `User rejected the following suggestion:\n\n${source}`,}),);- }, [dispatch, source]);+ }, [dispatch, source, conversationId]);const clear = useCallback(() => {dispatch(removeSuggestedCodeEdit(bufferId));@@ -101,7 +102,7 @@ export function useMetabotSQLSuggestion({const reset = useCallback(() => {dispatch(removeSuggestedCodeEdit(bufferId));- dispatch(resetConversation({ agentId: "sql" }));+ dispatch(startNewConversation({ agentId: "sql" }));}, [dispatch, bufferId]);const suggestionModels: SuggestionModel[] = useMemo(diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.tsindex 05543df1222..edee82f132e 100644--- a/frontend/src/metabase/metabot/state/actions.ts+++ b/frontend/src/metabase/metabot/state/actions.ts@@ -47,14 +47,14 @@ import { normalizeFetchedChatMessages } from "../utils/normalize-fetched-chat-meimport { metabot } from "./reducer";import {getAgentRequestMetadata,+ getConversationTitle,getDebugMode,getDeveloperMessage,- getIsCurrentConversation,+ getHasConversation,+ getIsConversationProcessing,getIsPollingForTitle,- getIsProcessing,getMessageIdToRewind,- getMetabotConversation,- getMetabotConversationTitle,+ getMetabotConversationId,getUserPromptForMessageId,} from "./selectors";import type {@@ -93,6 +93,8 @@ export const {updateSuggestedTransformId,createAgent,destroyAgent,+ attachAgentToConversation,+ startNewConversation,addSuggestedCodeEdit,removeSuggestedCodeEdit,setIsPollingForTitle,@@ -106,14 +108,12 @@ const TITLE_PENDING = new Error("Metabot conversation title pending");type PollConversationTitleOptions = {dispatch: ThunkDispatch<State, unknown, UnknownAction>;getState: () => State;- agentId: MetabotAgentId;conversationId: string;};const pollConversationTitle = async ({dispatch,getState,- agentId,conversationId,}: PollConversationTitleOptions) => {dispatch(setIsPollingForTitle({ conversationId, isPollingForTitle: true }));@@ -144,9 +144,8 @@ const pollConversationTitle = async ({return;}- const convo = getMetabotConversation(getState(), agentId);- if (convo.conversationId === conversationId) {- dispatch(setConversationTitle({ agentId, title }));+ if (getHasConversation(getState(), conversationId)) {+ dispatch(setConversationTitle({ conversationId, title }));}dispatch(metabotApi.util.invalidateTags([listTag("metabot-conversations")]),@@ -247,17 +246,17 @@ export const setVisible =export const executeSlashCommand = createAsyncThunk<void,- { command: SlashCommand; agentId: MetabotAgentId }+ { command: SlashCommand; conversationId: string }>("metabase/metabot/executeSlashCommand",- async ({ command, agentId }, { dispatch, getState }) => {+ async ({ command, conversationId }, { dispatch, getState }) => {match(command).with({ cmd: "profile" }, ({ args }) => {if (args.length <= 1) {// cast allows custom overrides for development purposes; the backend validatesdispatch(setProfileOverride({- agentId,+ conversationId,// Unjustified type cast. FIXMEprofile: args[0] as MetabotProfileId | undefined,}),@@ -268,7 +267,7 @@ export const executeSlashCommand = createAsyncThunk<}).with({ cmd: "metabot" }, ({ args }) => {if (args.length <= 1) {- dispatch(setMetabotReqIdOverride({ id: args[0], agentId }));+ dispatch(setMetabotReqIdOverride({ id: args[0], conversationId }));} else {dispatch(addUndo({ message: "/metabot <name>" }));}@@ -288,7 +287,7 @@ export const executeSlashCommand = createAsyncThunk<.otherwise(() => {const handled = PLUGIN_AUDIT.handleMetabotSlashCommand({command,- agentId,+ conversationId,dispatch,getState,});@@ -325,45 +324,48 @@ export const submitInput = createAsyncThunk<MetabotPromptSubmissionResult,Omit<MetabotUserChatMessage, "id" | "role"> & {context: MetabotChatContext;- agentId: MetabotAgentId;+ conversationId: string;metabot_id?: string;profile?: MetabotProfileId;retryMessageId?: string;isTransformsPage?: boolean;+ isFullPageMetabot?: boolean;}>("metabase/metabot/submitInput",async (payload, { dispatch, getState, signal }) => {const state = getState();const {- agentId,+ conversationId,message: rawPrompt,profile,retryMessageId,isTransformsPage,+ isFullPageMetabot,...data} = payload;- const convo = getMetabotConversation(state, agentId);const prompt = rawPrompt.trim();if (prompt === "") {- console.warn("An empty prompt was submitted to conversation: ", agentId);+ console.warn(+ "An empty prompt was submitted to conversation: ",+ conversationId,+ );return { prompt, success: true };}try {- const isProcessing = getIsProcessing(state, agentId);- if (isProcessing) {+ if (getIsConversationProcessing(state, conversationId)) {console.error("Metabot is actively serving a request");return { prompt, success: false, shouldRetry: false };}// if there were from the last prompt, remove the last prompt from the history- const rewindToMessageId = getMessageIdToRewind(state, agentId);+ const rewindToMessageId = getMessageIdToRewind(state, conversationId);if (rewindToMessageId) {dispatch(rewindConversation({- agentId,+ conversationId,messageId: rewindToMessageId,}),);@@ -374,7 +376,7 @@ export const submitInput = createAsyncThunk<await dispatch(executeSlashCommand({command,- agentId,+ conversationId,}),);return { prompt, success: true };@@ -384,20 +386,21 @@ export const submitInput = createAsyncThunk<// altering it by adding the current message the user is wanting to sendconst agentMetadata = getAgentRequestMetadata(getState(),- agentId,+ conversationId,retryMessageId,isTransformsPage ?? false,);const messageId = createMessageId();const userMessageId = retryMessageId ?? uuid();const assistantMessageId = uuid();- const promptWithDevMessage = getDeveloperMessage(state, agentId) + prompt;+ const promptWithDevMessage =+ getDeveloperMessage(state, conversationId) + prompt;dispatch(addUserMessage({id: messageId,..._.omit(data, ["context", "metabot_id"]),message: prompt,- agentId,+ conversationId,}),);@@ -405,13 +408,12 @@ export const submitInput = createAsyncThunk<sendAgentRequest({...data,message: promptWithDevMessage,- agentId,- conversation_id: convo.conversationId,- loadId: getMetabotConversation(getState(), agentId).loadId,+ conversation_id: conversationId,...agentMetadata,user_message_id: userMessageId,assistant_message_id: assistantMessageId,...(profile ? { profile_id: profile } : {}),+ isFullPageMetabot: isFullPageMetabot ?? false,}),);signal.addEventListener("abort", () => {@@ -479,7 +481,7 @@ const findCodeEditBuffer = (export const sendAgentRequest = createAsyncThunk<SendAgentRequestResult,- MetabotAgentRequest & { agentId: MetabotAgentId; loadId: string },+ MetabotAgentRequest & { isFullPageMetabot: boolean },{ rejectValue: SendAgentRequestError }>("metabase/metabot/sendAgentRequest",@@ -487,27 +489,14 @@ export const sendAgentRequest = createAsyncThunk<payload,{ dispatch, getState, signal, rejectWithValue, fulfillWithValue },) => {- const { agentId, loadId, ...request } = payload;-- // Keep the stream alive for persistence, but ignore it after switching conversations.- const dispatchToConvo = (action: Parameters<typeof dispatch>[0]) => {- if (- getIsCurrentConversation(- getState(),- agentId,- request.conversation_id,- loadId,- )- ) {- dispatch(action);- }- };+ const { isFullPageMetabot, ...request } = payload;+ const conversationId = request.conversation_id;let state: MetabotStateContext | undefined;let response: ProcessedChatResponse | undefined;let receivedTitle = false;const hadTitleBeforeTurn = Boolean(- getMetabotConversationTitle(getState(), agentId),+ getConversationTitle(getState(), conversationId),);try {@@ -520,7 +509,7 @@ export const sendAgentRequest = createAsyncThunk<// is upsetting the types, casting for nowbody: request as JSONValue,signal,- sourceId: agentId,+ sourceId: conversationId,},{onDataPart: function handleDataPart(part) {@@ -529,27 +518,25 @@ export const sendAgentRequest = createAsyncThunk<MetabotAgentDataPartMessage,"id" | "role" | "externalId">,- ) => dispatchToConvo(addAgentMessage({ ...message, agentId }));+ ) => dispatch(addAgentMessage({ ...message, conversationId }));match(part)// only update the convo state if the request is successful.with({ type: "data-state" }, (part) => (state = part.data)).with({ type: "data-conversation-title" }, (part) => {receivedTitle = true;- dispatchToConvo(- setConversationTitle({ agentId, title: part.data }),+ dispatch(+ setConversationTitle({ conversationId, title: part.data }),);}).with({ type: "data-todo_list" }, (part) => {pushDataPart({ type: "data_part", part });}).with({ type: "data-code_edit" }, (part) => {- dispatchToConvo(- addSuggestedCodeEdit({ ...part.data, active: true }),- );+ dispatch(addSuggestedCodeEdit({ ...part.data, active: true }));if (part.data.buffer_id === "qb") {- dispatchToConvo(setIsNativeEditorOpen(true));+ dispatch(setIsNativeEditorOpen(true));}pushDataPart({type: "data_part",@@ -570,7 +557,7 @@ export const sendAgentRequest = createAsyncThunk<active: true,suggestionId,};- dispatchToConvo(addSuggestedTransform(suggestedTransform));+ dispatch(addSuggestedTransform(suggestedTransform));const editorTransform = request.context.user_is_viewing.filter(@@ -584,7 +571,8 @@ export const sendAgentRequest = createAsyncThunk<});}).with({ type: "data-generated_entity" }, (part) => {- if (agentId === "ask") {+ // TODO: always push, but let the surface render and/or navigate on its own+ if (isFullPageMetabot) {pushDataPart({ type: "data_part", part });return;}@@ -593,7 +581,7 @@ export const sendAgentRequest = createAsyncThunk<if (isEmbeddingSdk()) {if (part.data.type === "card") {- dispatchToConvo(setNavigateToPath(path));+ dispatch(setNavigateToPath(path));}pushDataPart({ type: "data_part", part });return;@@ -610,9 +598,9 @@ export const sendAgentRequest = createAsyncThunk<);const { tool_call_id, title } = part.data;if (tool_call_id && title) {- dispatchToConvo(+ dispatch(toolCallTitled({- agentId,+ conversationId,toolCallId: tool_call_id,title,}),@@ -622,8 +610,12 @@ export const sendAgentRequest = createAsyncThunk<}).with({ type: "data-tool_title" }, (part) => {const { tool_call_id, title } = part.data;- dispatchToConvo(- toolCallTitled({ agentId, toolCallId: tool_call_id, title }),+ dispatch(+ toolCallTitled({+ conversationId,+ toolCallId: tool_call_id,+ title,+ }),);}).with(@@ -633,9 +625,9 @@ export const sendAgentRequest = createAsyncThunk<() => {},).with({ type: "data-search_results" }, (part) => {- dispatchToConvo(+ dispatch(toolCallSearchResults({- agentId,+ conversationId,toolCallId: part.data.tool_call_id,totalCount: part.data.total_count,results: part.data.results,@@ -645,70 +637,78 @@ export const sendAgentRequest = createAsyncThunk<.exhaustive();},onStart: function handleStart(event) {- dispatchToConvo(+ dispatch(setMessageExternalIds({- agentId,+ conversationId,agentMessageId: event.messageId,userMessageId: event.messageMetadata?.userMessageId,}),);},onTextPart: function handleTextPart(delta) {- dispatchToConvo(- addAgentTextDelta({ agentId, text: delta, nowMs: Date.now() }),+ dispatch(+ addAgentTextDelta({+ conversationId,+ text: delta,+ nowMs: Date.now(),+ }),);},onReasoningStart: function handleReasoningStart() {- dispatchToConvo(reasoningStart({ agentId, nowMs: Date.now() }));+ dispatch(reasoningStart({ conversationId, nowMs: Date.now() }));},onReasoningDelta: function handleReasoningDelta(event) {- dispatchToConvo(- reasoningDelta({ agentId, text: event.delta, nowMs: Date.now() }),+ dispatch(+ reasoningDelta({+ conversationId,+ text: event.delta,+ nowMs: Date.now(),+ }),);},onToolInputStart: function handleToolInputStart(event) {- dispatchToConvo(+ dispatch(toolCallStart({toolCallId: event.toolCallId,toolName: event.toolName,title: event.title,- agentId,+ conversationId,nowMs: Date.now(),}),);},onToolInputAvailable: function handleToolInputAvailable(event) {- dispatchToConvo(+ dispatch(toolCallArgs({toolCallId: event.toolCallId,toolName: event.toolName,title: event.title,args: JSON.stringify(event.input),- agentId,+ conversationId,nowMs: Date.now(),}),);},onToolResultPart: function handleToolResultPart(event) {- dispatchToConvo(+ dispatch(toolCallEnd({toolCallId: event.toolCallId,result:typeof event.output === "string"? event.output: JSON.stringify(event.output),- agentId,+ conversationId,nowMs: Date.now(),}),);},onToolErrorPart: function handleToolErrorPart(event) {- dispatchToConvo(+ dispatch(toolCallEnd({toolCallId: event.toolCallId,result: event.errorText,isError: true,- agentId,+ conversationId,nowMs: Date.now(),}),);@@ -754,8 +754,7 @@ export const sendAgentRequest = createAsyncThunk<void pollConversationTitle({dispatch,getState,- agentId,- conversationId: request.conversation_id,+ conversationId,});}@@ -791,43 +790,54 @@ export const sendAgentRequest = createAsyncThunk<},);-export const cancelInflightAgentRequests = createAsyncThunk(- "metabase/metabot/cancelInflightAgentRequests",- (agentId: MetabotAgentId) => {+export const cancelInflightConversationRequests = createAsyncThunk(+ "metabase/metabot/cancelInflightConversationRequests",+ (conversationId: string) => {findMatchingInflightAiStreamingRequests("/api/metabot/agent-streaming",- agentId,+ conversationId,).forEach((req) => req.abortController.abort());},);+export const cancelInflightAgentRequests = createAsyncThunk(+ "metabase/metabot/cancelInflightAgentRequests",+ (agentId: MetabotAgentId, { dispatch, getState }) => {+ dispatch(+ cancelInflightConversationRequests(+ getMetabotConversationId(getState(), agentId),+ ),+ );+ },+);+const rewindConversation = createAsyncThunk("metabase/metabot/rewindConversation",({- agentId,+ conversationId,messageId,}: {- agentId: MetabotAgentId;+ conversationId: string;messageId: string;},{ dispatch, getState },) => {const promptMessage = getUserPromptForMessageId(getState(),- agentId,+ conversationId,messageId,);if (!promptMessage) {throw new Error(- `Unable to find the prompt for message ${messageId} in conversation with agent ${agentId}`,+ `Unable to find the prompt for message ${messageId} in conversation ${conversationId}`,);}- dispatch(cancelInflightAgentRequests(agentId));+ dispatch(cancelInflightConversationRequests(conversationId));dispatch(metabot.actions.rewindStateToMessageId({- agentId,+ conversationId,messageId: promptMessage.id,}),);@@ -840,36 +850,46 @@ export const retryPrompt = createAsyncThunk<messageId: string;context: MetabotChatContext;metabot_id?: string;- agentId: MetabotAgentId;+ conversationId: string;profile?: MetabotProfileId;isTransformsPage?: boolean;+ isFullPageMetabot?: boolean;}>("metabase/metabot/retryPrompt",async (- { messageId, context, metabot_id, agentId, profile, isTransformsPage },+ {+ messageId,+ context,+ metabot_id,+ conversationId,+ profile,+ isTransformsPage,+ isFullPageMetabot,+ },{ getState, dispatch },) => {const state = getState();- const prompt = getUserPromptForMessageId(state, agentId, messageId);+ const prompt = getUserPromptForMessageId(state, conversationId, messageId);if (!prompt) {throw new Error("Agent message was not proceeded by a user message");}- const isProcessing = getIsProcessing(state, agentId);- if (isProcessing) {+ if (getIsConversationProcessing(state, conversationId)) {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 }));+ dispatch(rewindConversation({ conversationId, messageId: prompt.id }));+ dispatch(cancelInflightConversationRequests(conversationId));+ dispatch(+ metabot.actions.rewindStateToMessageId({ conversationId, messageId }),+ );return await dispatch(submitInput({- agentId,+ conversationId,type: "text",message: prompt.message,context,@@ -877,31 +897,15 @@ export const retryPrompt = createAsyncThunk<profile,retryMessageId: prompt.externalId,isTransformsPage,+ isFullPageMetabot,}),).unwrap();},);-export const resetConversation = createAsyncThunk(- "metabase/metabot/resetConversation",- (payload: { agentId: MetabotAgentId }, { dispatch }) => {- dispatch(cancelInflightAgentRequests(payload.agentId));- dispatch(metabot.actions.resetConversation(payload));- },-);--export const loadConversation = createAsyncThunk(- "metabase/metabot/loadConversation",- async (- {- agentId,- conversationId,- }: { agentId: MetabotAgentId; conversationId: string },- { dispatch },- ) => {- // NOTE: deliberately doesn't cancel the inflight streaming-request;- // as we do not want to record it as an aborted response.-+export const fetchConversationSnapshot = createAsyncThunk(+ "metabase/metabot/fetchConversationSnapshot",+ async (conversationId: string, { dispatch }) => {const { data: detail, error } = await dispatch(metabotApi.endpoints.getMetabotConversation.initiate(conversationId, {forceRefetch: true,@@ -922,7 +926,6 @@ export const loadConversation = createAsyncThunk(dispatch(setConversationSnapshot({- agentId,conversationId: detail.conversation_id,title: detail.title ?? undefined,forkedFromConversationId:@@ -935,6 +938,22 @@ export const loadConversation = createAsyncThunk(},);+export const loadConversation = createAsyncThunk(+ "metabase/metabot/loadConversation",+ async (+ {+ agentId,+ conversationId,+ }: { agentId: MetabotAgentId; conversationId: string },+ { dispatch },+ ) => {+ // NOTE: deliberately doesn't cancel the inflight streaming-request;+ // as we do not want to record it as an aborted response.+ dispatch(attachAgentToConversation({ agentId, conversationId }));+ await dispatch(fetchConversationSnapshot(conversationId));+ },+);+export const forkConversation = createAsyncThunk("metabase/metabot/forkConversation",async (@@ -952,10 +971,18 @@ export const forkConversation = createAsyncThunk(}),).unwrap();+ // attach new converation before setting snapshot so convo being+ // forked will be evicted from the statedispatch(- setConversationSnapshot({+ attachAgentToConversation({agentId,conversationId: conversation.conversation_id,+ }),+ );++ dispatch(+ setConversationSnapshot({+ conversationId: conversation.conversation_id,title: conversation.title ?? undefined,forkedFromConversationId:conversation.forked_from_conversation_id ?? undefined,diff --git a/frontend/src/metabase/metabot/state/reducer-utils.ts b/frontend/src/metabase/metabot/state/reducer-utils.tsindex d4a971a8dda..8995bbd9afc 100644--- a/frontend/src/metabase/metabot/state/reducer-utils.ts+++ b/frontend/src/metabase/metabot/state/reducer-utils.ts@@ -1,4 +1,4 @@-import { type PayloadAction, nanoid } from "@reduxjs/toolkit";+import type { PayloadAction } from "@reduxjs/toolkit";import { merge } from "icepick";import type { WritableDraft } from "immer";import { match } from "ts-pattern";@@ -9,25 +9,31 @@ import {} from "metabase/metabot/constants";import { uuid } from "metabase/utils/uuid";-import type {- MetabotAgentChainOfThoughtMessage,- MetabotAgentId,- MetabotAgentTurnDisplayError,- MetabotAgentTurnError,- MetabotAgentTurnIncompleteMessage,- MetabotConverstationState,- MetabotDebugToolCallMessage,- MetabotSearchResults,- MetabotState,+import {+ type MetabotAgentChainOfThoughtMessage,+ type MetabotAgentId,+ type MetabotAgentState,+ type MetabotAgentTurnDisplayError,+ type MetabotAgentTurnError,+ type MetabotAgentTurnIncompleteMessage,+ type MetabotConversationState,+ type MetabotDebugToolCallMessage,+ type MetabotSearchResults,+ type MetabotState,+ fixedMetabotAgentIds,} from "./types";import { createMessageId } from "./utils";export type ConvoPayloadAction<Value extends Record<string, any> = Record<string, any>,+> = PayloadAction<{ conversationId: string } & Value>;++export type AgentPayloadAction<+ Value extends Record<string, any> = Record<string, any>,> = PayloadAction<{ agentId: MetabotAgentId } & Value>;export const findLastToolCallMessage = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,toolCallId: string,) =>convo.messages.findLast(@@ -36,7 +42,7 @@ export const findLastToolCallMessage = ();export const pushNewToolCall = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,{toolCallId,toolName,@@ -59,7 +65,7 @@ export const pushNewToolCall = (});};-const activeChain = (convo: WritableDraft<MetabotConverstationState>) => {+const activeChain = (convo: WritableDraft<MetabotConversationState>) => {const chain = convo.activeChainId? convo.messages.find((m) => m.id === convo.activeChainId): undefined;@@ -78,7 +84,7 @@ const stampChainSpan = (};const ensureChain = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,nowMs?: number,): WritableDraft<MetabotAgentChainOfThoughtMessage> => {const existing = activeChain(convo);@@ -99,19 +105,19 @@ const ensureChain = (return chain;};-export const openChain = (convo: WritableDraft<MetabotConverstationState>) => {+export const openChain = (convo: WritableDraft<MetabotConversationState>) => {ensureChain(convo);};const dropChain = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,id: string,) => {convo.messages = convo.messages.filter((m) => m.id !== id);};export const startChainReasoning = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,nowMs?: number,) => {ensureChain(convo, nowMs).steps.push({@@ -122,7 +128,7 @@ export const startChainReasoning = (};export const appendChainReasoning = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,text: string,nowMs?: number,) => {@@ -136,7 +142,7 @@ export const appendChainReasoning = (};export const addChainTool = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,{id,name,@@ -165,7 +171,7 @@ export const addChainTool = (};const findChainToolStep = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,toolCallId: string,) => {for (const message of convo.messages) {@@ -182,7 +188,7 @@ const findChainToolStep = (};export const setChainToolSearchResults = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,toolCallId: string,searchResults: MetabotSearchResults,) => {@@ -193,7 +199,7 @@ export const setChainToolSearchResults = (};export const setChainToolTitle = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,toolCallId: string,title: string,) => {@@ -204,7 +210,7 @@ export const setChainToolTitle = (};export const endChainTool = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,id: string,nowMs?: number,) => {@@ -220,7 +226,7 @@ export const endChainTool = (};export const closeChain = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,nowMs?: number,) => {const chain = activeChain(convo);@@ -234,39 +240,20 @@ export const closeChain = (export const getRequestConversation = (state: WritableDraft<MetabotState>,- action: {- meta: {- arg: { agentId: MetabotAgentId; conversation_id: string; loadId: string };- };- },+ action: { meta: { arg: { conversation_id: string } } },) => {- const { agentId, conversation_id, loadId } = action.meta.arg;- const convo = state.conversations[agentId];+ const { conversation_id } = action.meta.arg;+ const convo = state.conversations[conversation_id];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;- }-- if (loadId !== convo.loadId) {- console.warn(- `Metabot conversation ${conversation_id} was reloaded since the request started, ignoring its result`,- );- return undefined;+ console.warn(`Unable to find metabot conversation ${conversation_id}`);}return convo;};-const agentOverridesByAgentId: Partial<- Record<MetabotAgentId, Partial<MetabotConverstationState>>+const conversationDefaultsByAgentId: Partial<+ Record<MetabotAgentId, Partial<MetabotConversationState>>> = {sql: {profileOverride: METABOT_PROFILE_OVERRIDES.SQL,@@ -277,33 +264,43 @@ const agentOverridesByAgentId: Partial<};export const createConversation = (+ overrides?: Partial<MetabotConversationState>,+): MetabotConversationState => ({+ isProcessing: false,+ hasMessagedInSession: false,+ title: undefined,+ messages: [],+ state: {},+ activeToolCalls: [],+ activeChainId: undefined,+ profileOverride: undefined,+ pendingMessageExternalId: undefined,+ forkedFromConversationId: undefined,+ ...overrides,+ conversationId: overrides?.conversationId ?? uuid(),+ experimental: {+ developerMessage: "",+ metabotReqIdOverride: undefined,+ ...overrides?.experimental,+ },+});++export const createConversationForAgent = (agentId: MetabotAgentId,- conversationOverrides?: Partial<MetabotConverstationState>,-): MetabotConverstationState => {- const agentOverrides = agentOverridesByAgentId[agentId] ?? {};- const overrides = merge(agentOverrides, conversationOverrides);+ overrides?: Partial<MetabotConversationState>,+): MetabotConversationState =>+ createConversation(+ merge(conversationDefaultsByAgentId[agentId] ?? {}, overrides ?? {}),+ );- return {- isProcessing: false,- title: undefined,- forkedFromConversationId: undefined,- messages: [],- visible: false,- state: {},- activeToolCalls: [],- activeChainId: undefined,- profileOverride: undefined,- pendingMessageExternalId: undefined,- ...overrides,- conversationId: overrides?.conversationId ?? uuid(),- loadId: overrides?.loadId ?? nanoid(),- experimental: {- developerMessage: "",- metabotReqIdOverride: undefined,- ...overrides?.experimental,- },- };-};+export const createAgentState = (+ conversationId: string,+ overrides?: Partial<MetabotAgentState>,+): MetabotAgentState => ({+ visible: false,+ ...overrides,+ conversationId,+});export const resetReactionState = (state: WritableDraft<MetabotState>,@@ -320,15 +317,56 @@ export const resetReactionState = (.otherwise(() => {});};-export const getConversationOrThrow = (+export const resetReactionStateForConversation = (+ state: WritableDraft<MetabotState>,+ conversationId: string,+) =>+ fixedMetabotAgentIds.forEach((agentId) => {+ if (state.agents[agentId]?.conversationId === conversationId) {+ resetReactionState(state, agentId);+ }+ });++const isConversationReferenced = (+ state: WritableDraft<MetabotState>,+ conversationId: string,+) =>+ Object.values(state.agents).some(+ (agent) => agent?.conversationId === conversationId,+ );++export const evictConversationIfUnused = (+ state: WritableDraft<MetabotState>,+ conversationId: string,+) => {+ const convo = state.conversations[conversationId];+ if (+ convo &&+ !convo.hasMessagedInSession &&+ !isConversationReferenced(state, conversationId)+ ) {+ delete state.conversations[conversationId];+ }+};++export const getAgentOrThrow = (state: WritableDraft<MetabotState>,agentId: MetabotAgentId,-): WritableDraft<MetabotConverstationState> => {- const convo = state.conversations[agentId];+): WritableDraft<MetabotAgentState> => {+ const agent = state.agents[agentId];+ if (!agent) {+ throw new Error(`Could not find metabot agent: ${agentId}`);+ }+ return agent;+};++export const getConversationOrThrow = (+ state: WritableDraft<MetabotState>,+ conversationId: string,+): WritableDraft<MetabotConversationState> => {+ const convo = state.conversations[conversationId];if (!convo) {- throw new Error(- `Could not find metabot conversation with convo id: ${agentId}`,- );+ throw new Error(`Could not find metabot conversation: ${conversationId}`);}return convo;};@@ -336,25 +374,45 @@ export const getConversationOrThrow = (export const convoReducer =<Action extends {- payload: { agentId: MetabotAgentId };+ payload: { conversationId: string };},>(convoReducerFn: (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,action: Action,state: WritableDraft<MetabotState>,) => void,) =>(state: WritableDraft<MetabotState>, action: Action) => {convoReducerFn(- getConversationOrThrow(state, action.payload.agentId),+ getConversationOrThrow(state, action.payload.conversationId),+ action,+ state,+ );+ };++export const agentReducer =+ <+ Action extends {+ payload: { agentId: MetabotAgentId };+ },+ >(+ agentReducerFn: (+ agent: WritableDraft<MetabotAgentState>,+ action: Action,+ state: WritableDraft<MetabotState>,+ ) => void,+ ) =>+ (state: WritableDraft<MetabotState>, action: Action) => {+ agentReducerFn(+ getAgentOrThrow(state, action.payload.agentId),action,state,);};export const appendAgentTurnAborted = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,) => {convo.messages.push({id: createMessageId(),@@ -365,7 +423,7 @@ export const appendAgentTurnAborted = (};export const appendAgentTurnIncomplete = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,finishReason: MetabotAgentTurnIncompleteMessage["finishReason"],) => {convo.messages.push({@@ -378,7 +436,7 @@ export const appendAgentTurnIncomplete = (};export const appendAgentTurnErrored = (- convo: WritableDraft<MetabotConverstationState>,+ convo: WritableDraft<MetabotConversationState>,error: MetabotAgentTurnError,display?: MetabotAgentTurnDisplayError,) => {@@ -393,13 +451,18 @@ export const appendAgentTurnErrored = (};export const getMetabotInitialState = (): MetabotState => {+ const conversations: MetabotState["conversations"] = {};+ const agents: MetabotState["agents"] = {};++ fixedMetabotAgentIds.forEach((agentId) => {+ const convo = createConversationForAgent(agentId);+ conversations[convo.conversationId] = convo;+ agents[agentId] = createAgentState(convo.conversationId);+ });+return {- conversations: {- omnibot: createConversation("omnibot"),- sql: createConversation("sql"),- ask: createConversation("ask"),- explorations: createConversation("explorations"),- },+ conversations,+ agents,reactions: {navigateToPath: null,suggestedCodeEdits: {},diff --git a/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts b/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.tsindex a795af01ac9..efc3e8b7b9b 100644--- a/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts+++ b/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts@@ -9,14 +9,14 @@ import {openChain,startChainReasoning,} from "./reducer-utils";-import type { MetabotConverstationState } from "./types";+import type { MetabotConversationState } from "./types";-const chainOf = (convo: MetabotConverstationState) =>+const chainOf = (convo: MetabotConversationState) =>convo.messages.find((m) => m.type === "chain_of_thought");describe("chain of thought duration timing", () => {it("stamps and advances endedAtMs on each step so the span lives in redux", () => {- const opened = produce(createConversation("omnibot"), (d) => openChain(d));+ const opened = produce(createConversation(), (d) => openChain(d));const started = produce(opened, (d) => startChainReasoning(d, 1000));expect(chainOf(started)).toMatchObject({startedAtMs: 1000,@@ -33,7 +33,7 @@ describe("chain of thought duration timing", () => {});it("keeps the last step's end time when the answer closes the chain without a clock", () => {- const convo = produce(createConversation("omnibot"), (d) => {+ const convo = produce(createConversation(), (d) => {openChain(d);startChainReasoning(d, 1000);appendChainReasoning(d, "x", 3000);@@ -43,7 +43,7 @@ describe("chain of thought duration timing", () => {});it("drops a shell that never gathered a step at turn teardown", () => {- const convo = produce(createConversation("omnibot"), (d) => {+ const convo = produce(createConversation(), (d) => {openChain(d);closeChain(d);});@@ -52,7 +52,7 @@ describe("chain of thought duration timing", () => {});it("advances endedAtMs when a tool ends, so a turn ending on a tool counts its runtime", () => {- const convo = produce(createConversation("omnibot"), (d) => {+ const convo = produce(createConversation(), (d) => {addChainTool(d, { id: "t1", name: "analyze_data", nowMs: 1000 });endChainTool(d, "t1", 9000);});@@ -63,7 +63,7 @@ describe("chain of thought duration timing", () => {});it("leaves a settled chain's span alone when its tool ends late", () => {- const convo = produce(createConversation("omnibot"), (d) => {+ const convo = produce(createConversation(), (d) => {addChainTool(d, { id: "t1", name: "analyze_data", nowMs: 1000 });closeChain(d, 2000); // answer text settled the chainendChainTool(d, "t1", 9000);@@ -74,7 +74,7 @@ describe("chain of thought duration timing", () => {describe("chain tool step dedupe", () => {it("updates the existing step across a closed chain instead of re-adding it", () => {- const convo = produce(createConversation("omnibot"), (d) => {+ const convo = produce(createConversation(), (d) => {// tool-input-start, then answer text closes the chain, then// tool-input-available arrives late with the titleaddChainTool(d, { id: "t1", name: "search", nowMs: 1000 });diff --git a/frontend/src/metabase/metabot/state/reducer.ts b/frontend/src/metabase/metabot/state/reducer.tsindex b4d473e4308..b8cc2997425 100644--- a/frontend/src/metabase/metabot/state/reducer.ts+++ b/frontend/src/metabase/metabot/state/reducer.ts@@ -1,10 +1,15 @@-import { type PayloadAction, createSlice, nanoid } from "@reduxjs/toolkit";-import { castDraft } from "immer";+import {+ type PayloadAction,+ type UnknownAction,+ createSlice,+} from "@reduxjs/toolkit";+import { type WritableDraft, castDraft } from "immer";import _ from "underscore";import type { SearchResultItem } from "metabase/api/ai-streaming/schemas";import { logout } from "metabase/redux/auth";-import { uuid } from "metabase/utils/uuid";+import { LOCATION_CHANGE, type Location, matchPath } from "metabase/router";+import * as Urls from "metabase/urls";import type {MetabotCodeEdit,MetabotStateContext,@@ -16,59 +21,111 @@ import type { MetabotProfileId } from "../constants";import { sendAgentRequest } from "./actions";import {+ type AgentPayloadAction,type ConvoPayloadAction,addChainTool,+ agentReducer,appendAgentTurnAborted,appendAgentTurnErrored,appendAgentTurnIncomplete,appendChainReasoning,closeChain,convoReducer,+ createAgentState,createConversation,+ createConversationForAgent,endChainTool,+ evictConversationIfUnused,findLastToolCallMessage,+ getAgentOrThrow,getMetabotInitialState,getRequestConversation,openChain,pushNewToolCall,resetReactionState,+ resetReactionStateForConversation,setChainToolSearchResults,setChainToolTitle,startChainReasoning,} from "./reducer-utils";import type {MetabotAgentChatMessage,+ MetabotAgentId,MetabotChatMessage,+ MetabotState,MetabotToolCall,MetabotUserChatMessage,} from "./types";import { createMessageId, hasInProgressMessage } from "./utils";+const isLocationChange = (+ action: UnknownAction,+): action is PayloadAction<Location, typeof LOCATION_CHANGE> =>+ action.type === LOCATION_CHANGE;++const startNewConversationForAgent = (+ state: WritableDraft<MetabotState>,+ agentId: MetabotAgentId,+) => {+ const agent = getAgentOrThrow(state, agentId);+ const previousConversationId = agent.conversationId;+ const convo = createConversationForAgent(agentId);+ state.conversations[convo.conversationId] = castDraft(convo);+ agent.conversationId = convo.conversationId;+ resetReactionState(state, agentId);+ evictConversationIfUnused(state, previousConversationId);+};++const attachAgent = (+ state: WritableDraft<MetabotState>,+ agentId: MetabotAgentId,+ conversationId: string,+) => {+ const agent = getAgentOrThrow(state, agentId);+ if (agent.conversationId === conversationId) {+ return;+ }+ const previousConversationId = agent.conversationId;+ state.conversations[conversationId] ??= castDraft(+ createConversationForAgent(agentId, { conversationId }),+ );+ agent.conversationId = conversationId;+ resetReactionState(state, agentId);+ evictConversationIfUnused(state, previousConversationId);+};+export const metabot = createSlice({name: "metabase/metabot",initialState: getMetabotInitialState(),reducers: {// TOP-LEVEL STATE REDUCERS- createAgent: (state, action: ConvoPayloadAction<{ visible?: boolean }>) => {+ createAgent: (state, action: AgentPayloadAction<{ 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);+ if (state.agents[agentId]) {+ console.warn("Agent already exists for agentId: ", agentId);+ return;}+ const convo = createConversationForAgent(agentId);+ state.conversations[convo.conversationId] = castDraft(convo);+ state.agents[agentId] = createAgentState(convo.conversationId, options);},- destroyAgent: (state, action: ConvoPayloadAction) => {+ destroyAgent: (state, action: AgentPayloadAction) => {const { agentId } = action.payload;- delete state.conversations[agentId];+ const conversationId = state.agents[agentId]?.conversationId;+ delete state.agents[agentId];resetReactionState(state, agentId);+ if (conversationId) {+ evictConversationIfUnused(state, conversationId);+ }},- 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);+ startNewConversation: (state, action: AgentPayloadAction) => {+ startNewConversationForAgent(state, action.payload.agentId);+ },+ attachAgentToConversation: (+ state,+ action: AgentPayloadAction<{ conversationId: string }>,+ ) => {+ attachAgent(state, action.payload.agentId, action.payload.conversationId);},setDebugMode: (state, action: PayloadAction<boolean>) => {state.debugMode = action.payload;@@ -109,7 +166,8 @@ export const metabot = createSlice({convo,action: ConvoPayloadAction<Omit<MetabotUserChatMessage, "role">>,) => {- const { id, message, agentId, ...rest } = action.payload;+ const { id, message, conversationId, ...rest } = action.payload;+ convo.hasMessagedInSession = true;// Unjustified type cast. FIXMEconvo.messages.push({ id, role: "user", ...rest, message } as any);},@@ -309,22 +367,22 @@ export const metabot = createSlice({state.isProcessing = action.payload.processing;},),- setVisible: convoReducer(- (state, action: ConvoPayloadAction<{ visible: boolean }>) => {- state.visible = action.payload.visible;+ setVisible: agentReducer(+ (agent, action: AgentPayloadAction<{ visible: boolean }>) => {+ agent.visible = action.payload.visible;},),setMetabotReqIdOverride: convoReducer(- (state, action: ConvoPayloadAction<{ id: string | undefined }>) => {- state.experimental.metabotReqIdOverride = action.payload.id;+ (convo, action: ConvoPayloadAction<{ id: string | undefined }>) => {+ convo.experimental.metabotReqIdOverride = action.payload.id;},),setProfileOverride: convoReducer((- state,+ convo,action: ConvoPayloadAction<{ profile: MetabotProfileId | undefined }>,) => {- state.profileOverride = action.payload.profile;+ convo.profileOverride = action.payload.profile;},),// REACTIONS REDUCERS@@ -397,48 +455,51 @@ export const metabot = createSlice({) => {delete state.reactions.suggestedCodeEdits[action.payload];},- setConversationSnapshot: convoReducer(- (- convo,- action: ConvoPayloadAction<{- messages: MetabotChatMessage[];- state?: MetabotStateContext;- activeToolCalls?: MetabotToolCall[];- conversationId: string;- title?: string;- forkedFromConversationId?: string;- }>,- state,- ) => {- const {- agentId,- messages,- state: snapshotState,- activeToolCalls,- conversationId,- title,- forkedFromConversationId,- } = action.payload;+ setConversationSnapshot: (+ state,+ action: PayloadAction<{+ messages: MetabotChatMessage[];+ state?: MetabotStateContext;+ activeToolCalls?: MetabotToolCall[];+ conversationId: string;+ title?: string;+ forkedFromConversationId?: string;+ }>,+ ) => {+ const {+ messages = [],+ state: snapshotState,+ activeToolCalls,+ conversationId,+ title,+ forkedFromConversationId,+ } = action.payload;- convo.messages = castDraft(messages ?? []);- convo.state = snapshotState ?? {};- convo.activeToolCalls = activeToolCalls ?? [];- convo.activeChainId = undefined;- convo.conversationId = conversationId ?? uuid();- convo.loadId = nanoid();- convo.title = title;- convo.forkedFromConversationId = forkedFromConversationId;- convo.isProcessing = hasInProgressMessage(messages ?? []);- if (convo.isProcessing) {- openChain(convo); // resuming mid-response- }- convo.stateBeforeTurn = undefined;- convo.pendingMessageExternalId = undefined;+ const convo =+ state.conversations[conversationId] ??+ castDraft(createConversation({ conversationId }));- // NOTE: live reactions aren't reconstructed from a fetched snapshot- resetReactionState(state, agentId);- },- ),+ convo.messages = castDraft(messages);+ convo.state = snapshotState ?? {};+ convo.activeToolCalls = activeToolCalls ?? [];+ convo.activeChainId = undefined;+ convo.title = title;+ convo.forkedFromConversationId = forkedFromConversationId;+ convo.isProcessing = hasInProgressMessage(messages);+ if (convo.isProcessing) {+ openChain(convo); // resuming mid-response+ }+ convo.stateBeforeTurn = undefined;+ convo.pendingMessageExternalId = undefined;+ state.conversations[conversationId] = convo;++ // NOTE: live reactions aren't reconstructed from a fetched snapshot+ resetReactionStateForConversation(state, conversationId);++ // a snapshot can land after every agent moved on (e.g. rapid history+ // selections) — don't let it resurrect an evicted conversation+ evictConversationIfUnused(state, conversationId);+ },},extraReducers: (builder) => {builder@@ -450,6 +511,7 @@ export const metabot = createSlice({const convo = getRequestConversation(state, action);if (convo) {convo.isProcessing = true;+ convo.hasMessagedInSession = true;convo.stateBeforeTurn = convo.state;convo.activeChainId = undefined;openChain(convo);@@ -518,6 +580,22 @@ export const metabot = createSlice({closeChain(convo);convo.isProcessing = false;}+ })+ // The URL owns which conversation the full-page ask agent is on: a+ // conversation route attaches the agent, and the new-question ask route+ // starts a fresh conversation. Same-path navigations emit LOCATION_CHANGE+ // too, so re-entering the ask route always resets.+ .addMatcher(isLocationChange, (state, action) => {+ const pathname = action.payload.pathname;+ const convoId = matchPath(+ `/${Urls.CONVERSATION_BASE_PATH}/:convoId`,+ pathname,+ )?.params.convoId;+ if (convoId) {+ attachAgent(state, "ask", convoId);+ } else if (matchPath(Urls.newQuestion({ mode: "ask" }), pathname)) {+ startNewConversationForAgent(state, "ask");+ }});},});diff --git a/frontend/src/metabase/metabot/state/selectors.ts b/frontend/src/metabase/metabot/state/selectors.tsindex d49ff28aa53..e2427342916 100644--- a/frontend/src/metabase/metabot/state/selectors.ts+++ b/frontend/src/metabase/metabot/state/selectors.ts@@ -32,7 +32,7 @@ export const getMetabotState = (state: State) => {export const getActiveMetabotAgentIds = createSelector(getMetabotState,// Unjustified type cast. FIXME- (state) => Object.keys(state.conversations) as MetabotAgentId[],+ (state) => Object.keys(state.agents) as MetabotAgentId[],);export const getMetabotId = () =>@@ -92,49 +92,69 @@ export const getIsSuggestedTransformActive = createSelector(const getAgentId = (_: State, agentId: MetabotAgentId) => agentId;-export const getMetabotConversation = createSelector(+export const getMetabotAgent = createSelector([getMetabotState, getAgentId],(state, agentId) => {- const convo = state.conversations[agentId];- if (!convo) {- throw new Error(`No conversation exists for agent: ${agentId}`);+ const agent = state.agents[agentId];+ if (!agent) {+ throw new Error(`No metabot agent exists: ${agentId}`);}- return convo;+ return agent;},);export const getMetabotConversationId = createSelector(- getMetabotConversation,- (convo) => convo.conversationId,+ getMetabotAgent,+ (agent) => agent.conversationId,);-export const getIsCurrentConversation = (- state: State,- agentId: MetabotAgentId,- conversationId: string,- loadId: string,-) => {- const convo = getMetabotConversation(state, agentId);- return convo.conversationId === conversationId && convo.loadId === loadId;-};+export const getMetabotConversation = createSelector(+ [getMetabotState, getMetabotConversationId],+ (state, conversationId) => {+ const convo = state.conversations[conversationId];+ if (!convo) {+ throw new Error(`No conversation exists: ${conversationId}`);+ }+ return convo;+ },+);++export const getHasConversation = (state: State, conversationId: string) =>+ Boolean(getMetabotState(state).conversations[conversationId]);export const getMetabotVisible = createSelector(- getMetabotConversation,- (convo) => convo.visible,+ getMetabotAgent,+ (agent) => agent.visible,+);++export const getConversation = createSelector(+ [getMetabotState, (_state: State, conversationId: string) => conversationId],+ (state, conversationId) => {+ const convo = state.conversations[conversationId];+ if (!convo) {+ throw new Error(`No conversation exists: ${conversationId}`);+ }+ return convo;+ },+);++export const getConversationTitle = createSelector(+ getConversation,+ (convo) => convo.title,);export const getMessages = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.messages,);-export const getMetabotConversationTitle = createSelector(- getMetabotConversation,- (convo) => convo.title,+export const getIsConversationEmpty = createSelector(+ getMessages,+ (messages) => messages.length === 0,);-export const getMetabotConversationForkedFrom = createSelector(- getMetabotConversation,+export const getConversationForkedFrom = createSelector(+ getConversation,(convo) => convo.forkedFromConversationId,);@@ -147,12 +167,12 @@ export const getIsPollingForTitle = createSelector();export const getDeveloperMessage = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.experimental.developerMessage,);export const getActiveToolCalls = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.activeToolCalls,);@@ -231,8 +251,8 @@ export const getMessageIdToRewind = createSelector(},);-export const getIsProcessing = createSelector(- getMetabotConversation,+export const getIsConversationProcessing = createSelector(+ getConversation,(convo) => convo.isProcessing,);@@ -242,7 +262,7 @@ export const getIsConversationInProgress = createSelector();export const getMetabotRequestState = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.state,);@@ -256,40 +276,33 @@ export const getConversationChart = createSelector(},);-export const getIsLongMetabotConversation = createSelector(- getMessages,- (messages) => {- const totalMessageLength = messages.reduce((sum, msg) => {- return sum + ("message" in msg ? msg.message.length : 0);- }, 0);- return totalMessageLength >= LONG_CONVO_MSG_LENGTH_THRESHOLD;- },-);+export const getIsLongConversation = createSelector(getMessages, (messages) => {+ const totalMessageLength = messages.reduce((sum, msg) => {+ return sum + ("message" in msg ? msg.message.length : 0);+ }, 0);+ return totalMessageLength >= LONG_CONVO_MSG_LENGTH_THRESHOLD;+});export const getMetabotReqIdOverride = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.experimental.metabotReqIdOverride,);-export const getMetabotRequestId = (state: State, agentId: MetabotAgentId) => {- const metabotReqIdOverride = getMetabotReqIdOverride(state, agentId);- return (- metabotReqIdOverride ??- (isEmbedding() ? METABOT_REQUEST_IDS.EMBEDDED : undefined)- );-};+export const getMetabotRequestId = (state: State, conversationId: string) =>+ getMetabotReqIdOverride(state, conversationId) ??+ (isEmbedding() ? METABOT_REQUEST_IDS.EMBEDDED : undefined);export const getProfileOverride = createSelector(- getMetabotConversation,+ getConversation,(convo) => convo.profileOverride,);export const getProfile = (state: State,- agentId: MetabotAgentId,+ conversationId: string,isTransformsPage: boolean,): MetabotProfileId | undefined => {- const profileOverride = getProfileOverride(state, agentId);+ const profileOverride = getProfileOverride(state, conversationId);const debugMode = getDebugMode(state);return match({ debugMode, isTransformsPage }).returnType<MetabotProfileId | undefined>()@@ -308,14 +321,14 @@ export const getAgentRequestMetadata = createSelector([(state: State,- agentId: MetabotAgentId,+ conversationId: string,_retryMessageId: string | undefined,isTransformsPage: boolean,- ) => getProfile(state, agentId, isTransformsPage),+ ) => getProfile(state, conversationId, isTransformsPage),getLastAgentMessageExternalId,(_state: State,- _agentId: MetabotAgentId,+ _conversationId: string,retryMessageId: string | undefined,) => retryMessageId,],diff --git a/frontend/src/metabase/metabot/state/selectors.unit.spec.ts b/frontend/src/metabase/metabot/state/selectors.unit.spec.tsindex ac2ca1c50f6..fe5df351e45 100644--- a/frontend/src/metabase/metabot/state/selectors.unit.spec.ts+++ b/frontend/src/metabase/metabot/state/selectors.unit.spec.ts@@ -16,11 +16,7 @@ function setup(messages: MetabotChatMessage[]): State {setupEnterprisePlugins();const state = getMetabotInitialState();- const visibleState = assocIn(- state,- ["conversations", "omnibot", "visible"],- true,- );+ const visibleState = assocIn(state, ["agents", "omnibot", "visible"], true);const withMessages = assocIn(visibleState,["conversations", "omnibot", "messages"],diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.tsindex b5950a590ff..56b79bce5a1 100644--- a/frontend/src/metabase/metabot/state/types.ts+++ b/frontend/src/metabase/metabot/state/types.ts@@ -164,14 +164,13 @@ export type MetabotReactionsState = {suggestedTransforms: MetabotSuggestedTransform[];};-export interface MetabotConverstationState {+export interface MetabotConversationState {conversationId: string;- loadId: string;title: string | undefined;forkedFromConversationId: string | undefined;isProcessing: boolean;+ hasMessagedInSession: boolean;messages: MetabotChatMessage[];- visible: boolean;state: MetabotStateContext;stateBeforeTurn?: MetabotStateContext;activeToolCalls: MetabotToolCall[];@@ -184,6 +183,11 @@ export interface MetabotConverstationState {};}+export interface MetabotAgentState {+ conversationId: string;+ visible: boolean;+}+export const fixedMetabotAgentIds = ["omnibot","sql",@@ -195,7 +199,8 @@ type FixedMetabotAgentId = (typeof fixedMetabotAgentIds)[number];export type MetabotAgentId = FixedMetabotAgentId | `test_${number}`;export interface MetabotState {- conversations: Record<MetabotAgentId, MetabotConverstationState | undefined>;+ conversations: Record<string, MetabotConversationState | undefined>;+ agents: Partial<Record<MetabotAgentId, MetabotAgentState>>;reactions: MetabotReactionsState;titlePollingConversationIds: string[];debugMode: boolean;diff --git a/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsxindex 9ed024657ca..ff141f041e3 100644--- a/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx@@ -21,6 +21,7 @@ import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import {assertConversation,continueResponseButton,+ conversationIdForAgent,enterChatMessage,input,queryContinueResponseButton,@@ -303,11 +304,7 @@ describe("AgentMessage", () => {]);expect(await input()).toHaveTextContent("How many orders?");- const conversationId =- store.getState().metabot.conversations.omnibot?.conversationId;- if (!conversationId) {- throw new Error("expected an active omnibot conversation");- }+ const conversationId = conversationIdForAgent(store);const reloaded: ["user" | "agent", string][] = [["user", "How many orders?"],["agent", "There are 42 orders."],diff --git a/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx b/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsxindex 36a6092c00a..7a4fc754b86 100644--- a/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx@@ -3,9 +3,9 @@ import _ from "underscore";import { act, waitFor } from "__support__/ui";import {+ attachAgentToConversation,getMetabotConversation,getMetabotRequestState,- setConversationSnapshot,} from "metabase/metabot/state";import {@@ -21,6 +21,7 @@ import {setup,showMetabot,stopResponseButton,+ testConversationId,whoIsYourFavoriteResponse,} from "./utils";@@ -28,7 +29,7 @@ describe("metabot > convo state", () => {it("should update the convo state on a successful request", async () => {const { store } = setup();const getConvoReqState = () =>- getMetabotRequestState(store.getState(), "omnibot");+ getMetabotRequestState(store.getState(), testConversationId("omnibot"));mockAgentEndpoint({stream: createMockSSEStream(@@ -48,7 +49,7 @@ describe("metabot > convo state", () => {it("should not update the convo state on a failed request", async () => {const { store } = setup();const getConvoReqState = () =>- getMetabotRequestState(store.getState(), "omnibot");+ getMetabotRequestState(store.getState(), testConversationId("omnibot"));mockAgentEndpoint({events: [@@ -65,7 +66,7 @@ describe("metabot > convo state", () => {it("should preserve conversation state if aborted response didn't contain a state data object", async () => {const { store } = setup();const getConvoReqState = () =>- getMetabotRequestState(store.getState(), "omnibot");+ getMetabotRequestState(store.getState(), testConversationId("omnibot"));mockAgentEndpoint({events: [@@ -121,11 +122,14 @@ describe("metabot > convo state", () => {});await enterChatMessage("hi");await userEvent.click(await stopResponseButton());- const reqState = getMetabotRequestState(store.getState(), "omnibot");+ const reqState = getMetabotRequestState(+ store.getState(),+ testConversationId("omnibot"),+ );expect(reqState).toEqual({ testing: 123 });});- it("should drop streamed output once the user has switched away, even after switching back", async () => {+ it("should keep streaming into a conversation the surface has navigated away from", async () => {const { store } = setup();const { conversationId } = getMetabotConversation(store.getState(),@@ -151,28 +155,30 @@ describe("metabot > convo state", () => {["agent", "first half"],]);- const reload = (id: string) =>+ act(() => {store.dispatch(- setConversationSnapshot({+ attachAgentToConversation({agentId: "omnibot",- conversationId: id,- messages: [- { id: "u1", role: "user", type: "text", message: "stream me" },- ],- activeToolCalls: [],+ conversationId: "some-other-conversation",}),);-- act(() => {- reload("some-other-conversation");- reload(conversationId);});+ await assertConversation([]);await act(async () => {pause1.resolve();});- await assertConversation([["user", "stream me"]]);+ act(() => {+ store.dispatch(+ attachAgentToConversation({ agentId: "omnibot", conversationId }),+ );+ });++ await assertConversation([+ ["user", "stream me"],+ ["agent", "first half second half"],+ ]);});it("should keep the conversation thread when metabot is hidden or opened", async () => {@@ -192,7 +198,7 @@ describe("metabot > convo state", () => {expect(reqBody.parent_message_id).toBe("msg_test_favorite");});- it("should reset the conversation when the reset button is clicked", async () => {+ it("should start a new conversation when the new conversation button is clicked", async () => {const { store } = setup();const getState = () => getMetabotConversation(store.getState(), "omnibot");mockAgentEndpoint({ events: whoIsYourFavoriteResponse });diff --git a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts b/frontend/src/metabase/metabot/tests/fork.unit.spec.tsindex 4d4c5162ae9..5e5d12fa97a 100644--- a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts+++ b/frontend/src/metabase/metabot/tests/fork.unit.spec.ts@@ -6,6 +6,7 @@ import { forkConversation } from "metabase/metabot/state";import * as Urls from "metabase/urls";import {+ conversationIdForAgent,conversationTitle,createMockSSEStream,createPauses,@@ -66,9 +67,7 @@ describe("metabot > fork", () => {);await waitFor(() =>- expect(- store.getState().metabot.conversations.omnibot?.conversationId,- ).toBe("forked-convo-id"),+ expect(conversationIdForAgent(store)).toBe("forked-convo-id"),);expect(await screen.findByText("Conversation forked")).toBeInTheDocument();@@ -77,8 +76,7 @@ describe("metabot > fork", () => {it("shows an error toast and keeps the original conversation when forking fails", async () => {const { store, lastMessage } = await setupWithReply();- const originalConversationId =- store.getState().metabot.conversations.omnibot?.conversationId;+ const originalConversationId = conversationIdForAgent(store);mockForkEndpoint({}, 400);await userEvent.click(await forkButton(lastMessage));@@ -86,9 +84,7 @@ describe("metabot > fork", () => {expect(await screen.findByText("Failed to fork conversation"),).toBeInTheDocument();- expect(store.getState().metabot.conversations.omnibot?.conversationId).toBe(- originalConversationId,- );+ expect(conversationIdForAgent(store)).toBe(originalConversationId);});it("navigates to the forked conversation when forking on the ask page", async () => {@@ -111,6 +107,7 @@ describe("metabot > fork", () => {Urls.metabotConversation("forked-convo-id"),),);+ expect(conversationIdForAgent(store, "ask")).toBe("forked-convo-id");});it("does not offer to fork earlier messages while a response is streaming", async () => {diff --git a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsxindex 52d9852ee74..bacba5cb53c 100644--- a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx@@ -4,18 +4,15 @@ import fetchMock from "fetch-mock";import { setupGetMetabotConversationTitleEndpoint } from "__support__/server-mocks";import { act, renderHookWithProviders, waitFor } from "__support__/ui";import type { State } from "metabase/redux/store";-import { checkNotNull } from "metabase/utils/types";import { useMetabotAgentsManager } from "../hooks";-import {- type MetabotAgentId,- getMessages,- getMetabotConversationTitle,- metabotActions,- submitInput,-} from "../state";+import { type MetabotAgentId, metabotActions, submitInput } from "../state";-import { mockAgentEndpoint } from "./utils";+import {+ conversationIdForAgent,+ convoForAgent,+ mockAgentEndpoint,+} from "./utils";const titlePath = (conversationId: string) =>`path:/api/metabot/conversations/${conversationId}/title`;@@ -47,7 +44,7 @@ function setup(}type BaseInput = Parameters<typeof submitInput>[0];-type Input = Omit<BaseInput, "message" | "agentId">;+type Input = Omit<BaseInput, "message" | "conversationId">;const input: Input = {type: "text",context: {@@ -59,9 +56,6 @@ const input: Input = {type TestStore = ReturnType<typeof setup>["store"];-const conversationIdFor = (store: TestStore, agentId: MetabotAgentId) =>- checkNotNull(store.getState().metabot.conversations[agentId]).conversationId;-const sendMessage = async (store: TestStore,agentId: MetabotAgentId,@@ -75,7 +69,13 @@ const sendMessage = async (],});await act(async () => {- await store.dispatch(submitInput({ ...input, message, agentId }));+ await store.dispatch(+ submitInput({+ ...input,+ message,+ conversationId: conversationIdForAgent(store, agentId),+ }),+ );});};@@ -97,7 +97,11 @@ describe("multi-convo support", () => {{ type: "data-conversation-title", data: "T1" },],});- const msg1 = { ...input, message: "test1", agentId: "test_1" } as const;+ const msg1 = {+ ...input,+ message: "test1",+ conversationId: conversationIdForAgent(store, "test_1"),+ } as const;await store.dispatch(submitInput(msg1));mockAgentEndpoint({@@ -108,18 +112,21 @@ describe("multi-convo support", () => {{ type: "data-conversation-title", data: "T2" },],});- const msg2 = { ...input, message: "test2", agentId: "test_2" } as const;+ const msg2 = {+ ...input,+ message: "test2",+ conversationId: conversationIdForAgent(store, "test_2"),+ } as const;await act(async () => {await store.dispatch(submitInput(msg2));});// ASSERT- const state = store.getState();- expect(getMessages(state, "test_1")).toMatchObject([+ expect(convoForAgent(store, "test_1").messages).toMatchObject([{ message: "test1", role: "user", type: "text" },{ message: "Test 1 response", role: "agent", type: "text" },]);- expect(getMessages(state, "test_2")).toMatchObject([+ expect(convoForAgent(store, "test_2").messages).toMatchObject([{ message: "test2", role: "user", type: "text" },{ message: "Test 2 response", role: "agent", type: "text" },]);@@ -134,7 +141,7 @@ describe("multi-convo support", () => {expect(hook.current.activeAgentIds).toContain(agentId);});- it("should be able to reset a conversation", async () => {+ it("should be able to start a new conversation", async () => {const { hook, store } = setup({ agentIds: ["test_1"] });mockAgentEndpoint({events: [@@ -145,14 +152,18 @@ describe("multi-convo support", () => {],});await store.dispatch(- submitInput({ ...input, message: "test", agentId: "test_1" }),+ submitInput({+ ...input,+ message: "test",+ conversationId: conversationIdForAgent(store, "test_1"),+ }),);- expect(getMessages(store.getState(), "test_1")).toHaveLength(2);+ expect(convoForAgent(store, "test_1").messages).toHaveLength(2);- await act(() => hook.current.resetConversation({ agentId: "test_1" }));+ await act(() => hook.current.startNewConversation({ agentId: "test_1" }));expect(hook.current.activeAgentIds).toContain("test_1");- expect(getMessages(store.getState(), "test_1")).toHaveLength(0);+ expect(convoForAgent(store, "test_1").messages).toHaveLength(0);});it("should be able to remove a conversation", async () => {@@ -169,11 +180,11 @@ describe("multi-convo support", () => {title: null,});const { store } = setup({ agentIds: ["sql"] });- const conversationId = conversationIdFor(store, "sql");+ const conversationId = conversationIdForAgent(store, "sql");await sendMessage(store, "sql", "fix my sql");- expect(getMessages(store.getState(), "sql")).toHaveLength(2);+ expect(convoForAgent(store, "sql").messages).toHaveLength(2);expect(fetchMock.callHistory.calls(titlePath(conversationId))).toHaveLength(0,);@@ -185,7 +196,7 @@ describe("multi-convo support", () => {title: null,});const { store } = setup({ agentIds: ["test_1"] });- const conversationId = conversationIdFor(store, "test_1");+ const conversationId = conversationIdForAgent(store, "test_1");store.dispatch(metabotActions.setIsPollingForTitle({conversationId,@@ -195,7 +206,7 @@ describe("multi-convo support", () => {await sendMessage(store, "test_1");- expect(getMessages(store.getState(), "test_1")).toHaveLength(2);+ expect(convoForAgent(store, "test_1").messages).toHaveLength(2);expect(fetchMock.callHistory.calls(titlePath(conversationId))).toHaveLength(0,);@@ -226,9 +237,7 @@ describe("multi-convo support", () => {});await waitFor(() =>- expect(getMetabotConversationTitle(store.getState(), "test_1")).toBe(- "A late title",- ),+ expect(convoForAgent(store, "test_1").title).toBe("A late title"),);jest.useRealTimers();@@ -240,7 +249,7 @@ describe("multi-convo support", () => {title: "A title",});const { store } = setup({ agentIds: ["test_1"] });- const conversationId = conversationIdFor(store, "test_1");+ const conversationId = conversationIdForAgent(store, "test_1");store.dispatch(metabotActions.setIsPollingForTitle({conversationId: "a-conversation-the-agent-has-left",diff --git a/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx b/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsxindex bb3882eaa1a..f33070ce514 100644--- a/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx@@ -27,7 +27,12 @@ import { createSampleDatabase } from "metabase-types/api/mocks/presets";import { MetabotProvider } from "../context";import { sendAgentRequest } from "../state/actions";-import { getMetabotInitialState } from "../state/reducer-utils";++import {+ convoForAgent,+ createTestMetabotState,+ testConversationId,+} from "./utils";jest.mock("metabase/api/ai-streaming", () => ({aiStreamingQuery: jest.fn(),@@ -109,8 +114,8 @@ describe("query builder code edits from omnibot", () => {questions: [TEST_NATIVE_CARD],}),metabot: assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "title"],+ createTestMetabotState(),+ ["conversations", testConversationId("omnibot"), "title"],"SQL edit",),} as any);@@ -132,17 +137,15 @@ describe("query builder code edits from omnibot", () => {getState: () => State;};- const convo = checkNotNull(- typedStore.getState().metabot.conversations.omnibot,- );+ const convo = convoForAgent(typedStore);+ const { conversationId } = convo;await act(async () => {await typedStore.dispatch(sendAgentRequest({- agentId: "omnibot",message: "Please rewrite this query",conversation_id: convo.conversationId,- loadId: convo.loadId,+ isFullPageMetabot: false,context: {user_is_viewing: [{@@ -176,7 +179,7 @@ describe("query builder code edits from omnibot", () => {});expect(- typedStore.getState().metabot.conversations.omnibot?.messages,+ typedStore.getState().metabot.conversations[conversationId]?.messages,).toEqual(expect.arrayContaining([expect.objectContaining({diff --git a/frontend/src/metabase/metabot/tests/reaction-state.unit.spec.tsx b/frontend/src/metabase/metabot/tests/reaction-state.unit.spec.tsxindex 40313814d14..0fe3aa33f9c 100644--- a/frontend/src/metabase/metabot/tests/reaction-state.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/reaction-state.unit.spec.tsx@@ -11,7 +11,7 @@ import { createMockTransform } from "metabase-types/api/mocks";import { newConversationButton, setup } from "./utils";describe("metabot > reaction state", () => {- it("should clear navigateToPath and suggestedTransforms when resetting omnibot conversation", async () => {+ it("should clear navigateToPath and suggestedTransforms when starting a new omnibot conversation", async () => {const { store } = setup();const getReactions = () => getMetabotReactionsState(store.getState());diff --git a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts b/frontend/src/metabase/metabot/tests/reducer.unit.spec.tsindex 632687a1daf..c3ebf8e2b91 100644--- a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts+++ b/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts@@ -9,6 +9,7 @@ import {metabotActions,metabotReducer,} from "metabase/metabot/state";+import { LOCATION_CHANGE } from "metabase/router";import type { MetabotSuggestedTransform } from "metabase-types/api";import { createMockTransform } from "metabase-types/api/mocks/transform";@@ -19,6 +20,13 @@ import {getRequestConversation,} from "../state/reducer-utils";+import {+ conversationIdForAgent,+ convoForAgent,+ createTestMetabotState,+ testConversationId,+} from "./utils";+const createMockSuggestedTransform = (overrides: Partial<MetabotSuggestedTransform>,): MetabotSuggestedTransform => ({@@ -34,25 +42,12 @@ const createTestStore = (initialState?: Partial<MetabotState>) =>metabot: metabotReducer,},preloadedState: {- metabot: { ...getMetabotInitialState(), ...initialState },+ metabot: { ...createTestMetabotState(), ...initialState },},});-const requestAction = (- arg: Partial<{- agentId: "test_1";- conversation_id: string;- loadId: string;- }> = {},-) => ({- meta: {- arg: {- agentId: "test_1" as const,- conversation_id: "matching-id",- loadId: "load-1",- ...arg,- },- },+const requestAction = (arg: Partial<{ conversation_id: string }> = {}) => ({+ meta: { arg: { conversation_id: "matching-id", ...arg } },});describe("metabot reducer", () => {@@ -254,21 +249,153 @@ describe("metabot reducer", () => {});});- describe("the full-page `ask` conversation", () => {- it("exists in the initial state with the nlq profile", () => {+ describe("agents and conversations", () => {+ it("seeds each agent with its own conversation record", () => {const state = getMetabotInitialState();- expect(state.conversations.ask).toBeDefined();- expect(state.conversations.ask?.profileOverride).toBe(- METABOT_PROFILE_OVERRIDES.NLQ,+ const conversationIds = Object.values(state.agents).map(+ (agent) => agent?.conversationId,+ );++ expect(new Set(conversationIds).size).toBe(conversationIds.length);+ conversationIds.forEach((id) =>+ expect(state.conversations[id!]).toBeDefined(),+ );+ });++ it("re-applies the agent's profile default when it opens a new conversation", () => {+ const store = createTestStore();+ store.dispatch(metabotActions.startNewConversation({ agentId: "sql" }));++ expect(convoForAgent(store, "sql").profileOverride).toBe(+ METABOT_PROFILE_OVERRIDES.SQL,+ );+ });++ it("applies the agent's profile default to a conversation it attaches to", () => {+ const store = createTestStore();+ store.dispatch(+ metabotActions.attachAgentToConversation({+ agentId: "ask",+ conversationId: "convo-from-url",+ }),+ );++ expect(convoForAgent(store, "ask")).toMatchObject({+ conversationId: "convo-from-url",+ profileOverride: METABOT_PROFILE_OVERRIDES.NLQ,+ });+ });++ it("evicts a conversation an agent walked away from without using", () => {+ const store = createTestStore();+ const abandoned = conversationIdForAgent(store, "omnibot");++ store.dispatch(+ metabotActions.startNewConversation({ agentId: "omnibot" }),+ );++ expect(store.getState().metabot.conversations[abandoned]).toBeUndefined();+ });++ it("keeps a conversation another agent still points at", () => {+ const store = createTestStore();+ const shared = conversationIdForAgent(store, "omnibot");+ store.dispatch(+ metabotActions.attachAgentToConversation({+ agentId: "sql",+ conversationId: shared,+ }),);++ store.dispatch(+ metabotActions.startNewConversation({ agentId: "omnibot" }),+ );++ expect(store.getState().metabot.conversations[shared]).toBeDefined();});- it("can be reset independently and keeps the nlq profile", () => {+ it("does not keep a conversation when a snapshot arrives after every agent has moved on", () => {const store = createTestStore();- store.dispatch(metabotActions.resetConversation({ agentId: "ask" }));- const convo = store.getState().metabot.conversations.ask;- expect(convo).toBeDefined();- expect(convo?.profileOverride).toBe(METABOT_PROFILE_OVERRIDES.NLQ);+ store.dispatch(+ metabotActions.attachAgentToConversation({+ agentId: "ask",+ conversationId: "convo-a",+ }),+ );+ store.dispatch(+ metabotActions.attachAgentToConversation({+ agentId: "ask",+ conversationId: "convo-b",+ }),+ );++ // the fetch kicked off by loadConversation("convo-a") lands after the+ // agent already walked away, e.g. two rapid history selections+ store.dispatch(+ metabotActions.setConversationSnapshot({+ conversationId: "convo-a",+ messages: [],+ }),+ );++ expect(store.getState().metabot.conversations["convo-a"]).toBeUndefined();+ });++ it("keeps an abandoned conversation that was written to this session", () => {+ const store = createTestStore();+ const abandoned = conversationIdForAgent(store, "omnibot");+ store.dispatch(+ metabotActions.addUserMessage({+ conversationId: abandoned,+ id: "u1",+ type: "text",+ message: "hi",+ }),+ );++ store.dispatch(+ metabotActions.startNewConversation({ agentId: "omnibot" }),+ );++ expect(store.getState().metabot.conversations[abandoned]).toBeDefined();+ });+ });++ describe("location changes", () => {+ const locationChange = (pathname: string) => ({+ type: LOCATION_CHANGE,+ payload: { pathname, search: "", hash: "", state: undefined, key: "t" },+ });++ it("attaches the ask agent to the conversation in the URL", () => {+ const store = createTestStore();+ store.dispatch(locationChange("/metabot/conversation/convo-from-url"));++ expect(conversationIdForAgent(store, "ask")).toBe("convo-from-url");+ expect(+ store.getState().metabot.conversations["convo-from-url"],+ ).toBeDefined();+ });++ it("starts a fresh ask conversation on each navigation to the ask page", () => {+ const store = createTestStore();+ const seeded = conversationIdForAgent(store, "ask");++ store.dispatch(locationChange("/question/ask"));+ const first = conversationIdForAgent(store, "ask");+ expect(first).not.toBe(seeded);++ store.dispatch(locationChange("/question/ask"));+ expect(conversationIdForAgent(store, "ask")).not.toBe(first);+ });++ it("leaves the ask agent alone on unrelated routes", () => {+ const store = createTestStore();+ const seeded = conversationIdForAgent(store, "ask");++ store.dispatch(locationChange("/dashboard/1"));++ expect(conversationIdForAgent(store, "ask")).toBe(seeded);});});@@ -286,8 +413,8 @@ describe("metabot reducer", () => {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" }),+ state.conversations["stored-id"] = createDraft(+ createConversation({ conversationId: "stored-id" }),);expect(getRequestConversation(@@ -297,57 +424,41 @@ describe("metabot reducer", () => {).toBeUndefined();});- it("should return undefined if the conversation was reloaded since the request started", () => {- const state = createDraft(getMetabotInitialState());- state.conversations.test_1 = createDraft(- createConversation("test_1", {- conversationId: "matching-id",- loadId: "load-2",- }),- );- expect(getRequestConversation(state, requestAction())).toBeUndefined();- });-- it("should return conversation if agentId, request conversation_id and loadId match", () => {+ it("should return the conversation the request targets", () => {const state = createDraft(getMetabotInitialState());const convo = createDraft(- createConversation("test_1", {- conversationId: "matching-id",- loadId: "load-1",- }),+ createConversation({ conversationId: "matching-id" }),);- state.conversations.test_1 = convo;+ state.conversations["matching-id"] = convo;expect(getRequestConversation(state, requestAction())).toBe(convo);});});describe("tool calls", () => {- const agentId = "omnibot" as const;+ const conversationId = testConversationId("omnibot");const getToolCallMessages = (store: ReturnType<typeof createTestStore>) =>- store- .getState()- .metabot.conversations.omnibot?.messages.filter(- (m) => m.type === "tool_call",- );+ convoForAgent(store, "omnibot").messages.filter(+ (m) => m.type === "tool_call",+ );it("toolCallStart is idempotent for the same toolCallId", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",}),);store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",}),);- const convo = store.getState().metabot.conversations.omnibot;+ const convo = convoForAgent(store, "omnibot");expect(getToolCallMessages(store)).toHaveLength(1);expect(convo?.activeToolCalls).toHaveLength(1);});@@ -356,21 +467,21 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",}),);store.dispatch(metabotActions.toolCallArgs({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",args: '{"foo":1}',}),);- const convo = store.getState().metabot.conversations.omnibot;+ const convo = convoForAgent(store, "omnibot");expect(getToolCallMessages(store)).toEqual([expect.objectContaining({id: "x",@@ -386,14 +497,14 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallArgs({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",args: '{"foo":1}',}),);- const convo = store.getState().metabot.conversations.omnibot;+ const convo = convoForAgent(store, "omnibot");expect(getToolCallMessages(store)).toEqual([expect.objectContaining({id: "x",@@ -409,21 +520,21 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "x",toolName: "analyze_data",}),);store.dispatch(metabotActions.toolCallEnd({- agentId,+ conversationId,toolCallId: "x",result: "boom",isError: true,}),);- const convo = store.getState().metabot.conversations.omnibot;+ const convo = convoForAgent(store, "omnibot");expect(getToolCallMessages(store)).toEqual([expect.objectContaining({id: "x",@@ -440,17 +551,21 @@ describe("metabot reducer", () => {});describe("chain of thought", () => {- const agentId = "omnibot" as const;+ const conversationId = testConversationId("omnibot");const getConvo = (store: ReturnType<typeof createTestStore>) =>- store.getState().metabot.conversations.omnibot;+ convoForAgent(store, "omnibot");const getChain = (store: ReturnType<typeof createTestStore>) =>- getConvo(store)?.messages.find((m) => m.type === "chain_of_thought");+ getConvo(store).messages.find((m) => m.type === "chain_of_thought");it("accumulates reasoning deltas into one chain step", () => {const store = createTestStore();- store.dispatch(metabotActions.reasoningStart({ agentId }));- store.dispatch(metabotActions.reasoningDelta({ agentId, text: "Think" }));- store.dispatch(metabotActions.reasoningDelta({ agentId, text: "ing" }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));+ store.dispatch(+ metabotActions.reasoningDelta({ conversationId, text: "Think" }),+ );+ store.dispatch(+ metabotActions.reasoningDelta({ conversationId, text: "ing" }),+ );const chain = getChain(store);expect(chain?.type === "chain_of_thought" && chain.steps).toEqual([@@ -461,17 +576,21 @@ describe("metabot reducer", () => {it("interleaves tool calls between reasoning blocks in order", () => {const store = createTestStore();- store.dispatch(metabotActions.reasoningStart({ agentId }));- store.dispatch(metabotActions.reasoningDelta({ agentId, text: "look" }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));+ store.dispatch(+ metabotActions.reasoningDelta({ conversationId, text: "look" }),+ );store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "t1",toolName: "search",}),);- store.dispatch(metabotActions.reasoningStart({ agentId }));- store.dispatch(metabotActions.reasoningDelta({ agentId, text: "now" }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));+ store.dispatch(+ metabotActions.reasoningDelta({ conversationId, text: "now" }),+ );const chain = getChain(store);expect(chain?.type === "chain_of_thought" && chain.steps).toEqual([@@ -485,13 +604,17 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "t1",toolName: "search",}),);store.dispatch(- metabotActions.toolCallEnd({ agentId, toolCallId: "t1", result: "ok" }),+ metabotActions.toolCallEnd({+ conversationId,+ toolCallId: "t1",+ result: "ok",+ }),);const chain = getChain(store);@@ -502,16 +625,20 @@ describe("metabot reducer", () => {it("persists the chain but closes it when the answer text starts", () => {const store = createTestStore();- store.dispatch(metabotActions.reasoningStart({ agentId }));- store.dispatch(metabotActions.reasoningDelta({ agentId, text: "hmm" }));- store.dispatch(metabotActions.addAgentTextDelta({ agentId, text: "hi" }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));+ store.dispatch(+ metabotActions.reasoningDelta({ conversationId, text: "hmm" }),+ );+ store.dispatch(+ metabotActions.addAgentTextDelta({ conversationId, text: "hi" }),+ );// the chain message stays in history, and its id is releasedexpect(getChain(store)).toBeDefined();expect(getConvo(store)?.activeChainId).toBeUndefined();// later reasoning starts a fresh chain after the answer text- store.dispatch(metabotActions.reasoningStart({ agentId }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));const chains = getConvo(store)?.messages.filter((m) => m.type === "chain_of_thought",);@@ -522,15 +649,17 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "t1",toolName: "search",}),);- store.dispatch(metabotActions.addAgentTextDelta({ agentId, text: "hi" }));+ store.dispatch(+ metabotActions.addAgentTextDelta({ conversationId, text: "hi" }),+ );store.dispatch(metabotActions.toolCallSearchResults({- agentId,+ conversationId,toolCallId: "t1",totalCount: 1,results: [{ id: 1, type: "table", name: "orders" }],@@ -547,16 +676,18 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "t1",toolName: "save_entity",}),);- store.dispatch(metabotActions.addAgentTextDelta({ agentId, text: "hi" }));+ store.dispatch(+ metabotActions.addAgentTextDelta({ conversationId, text: "hi" }),+ );// the saved card's link only exists once the tool finishesstore.dispatch(metabotActions.toolCallTitled({- agentId,+ conversationId,toolCallId: "t1",title: "[Sales by Month](metabase://question/5)",}),@@ -576,14 +707,14 @@ describe("metabot reducer", () => {const store = createTestStore();store.dispatch(metabotActions.toolCallStart({- agentId,+ conversationId,toolCallId: "t1",toolName: "search",}),);store.dispatch(metabotActions.toolCallArgs({- agentId,+ conversationId,toolCallId: "t1",toolName: "search",title: "Searching revenue",@@ -599,11 +730,10 @@ describe("metabot reducer", () => {it("releases the active chain id when a snapshot replaces the conversation", () => {const store = createTestStore();- store.dispatch(metabotActions.reasoningStart({ agentId }));+ store.dispatch(metabotActions.reasoningStart({ conversationId }));store.dispatch(metabotActions.setConversationSnapshot({- agentId,- conversationId: "snap-1",+ conversationId,messages: [],}),);diff --git a/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx b/frontend/src/metabase/metabot/tests/retry.unit.spec.tsxindex 6788f7943b7..9d3b44656e1 100644--- a/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx@@ -11,21 +11,23 @@ import {retryPrompt,submitInput,} from "metabase/metabot/state";-import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import type { State } from "metabase/redux/store";import { checkNotNull } from "metabase/utils/types";import { isUuid } from "metabase/utils/uuid";import {chatMessages,+ conversationIdForAgent,createMockSSEStream,createPauses,+ createTestMetabotState,enterChatMessage,lastChatMessage,lastReqBody,mockAgentEndpoint,setup,stopResponseButton,+ testConversationId,whoIsYourFavoriteResponse,} from "./utils";@@ -68,12 +70,8 @@ describe("metabot > retry", () => {it("should reuse the conversation profileOverride when retrying a response", async () => {const metabotInitialState = assocIn(- assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "visible"],- true,- ),- ["conversations", "omnibot", "profileOverride"],+ assocIn(createTestMetabotState(), ["agents", "omnibot", "visible"], true),+ ["conversations", testConversationId("omnibot"), "profileOverride"],"nlq",);setup({ metabotInitialState });@@ -113,6 +111,7 @@ describe("metabot > retry", () => {void,UnknownAction>;+ const conversationId = conversationIdForAgent(store, "explorations");const firstSpy = mockAgentEndpoint({events: turnEvents({@@ -127,7 +126,7 @@ describe("metabot > retry", () => {type: "text",message: "first prompt",context: emptyContext,- agentId: "explorations",+ conversationId,profile: "explorations",}),);@@ -135,7 +134,7 @@ describe("metabot > retry", () => {expect((await lastReqBody(firstSpy)).profile_id).toBe("explorations");const messageId = checkNotNull(- getMessages(store.getState(), "explorations").at(-1),+ getMessages(store.getState(), conversationId).at(-1),).id;const retrySpy = mockAgentEndpoint({@@ -150,7 +149,7 @@ describe("metabot > retry", () => {retryPrompt({messageId,context: emptyContext,- agentId: "explorations",+ conversationId,profile: "explorations",}),);@@ -247,7 +246,7 @@ describe("metabot > retry", () => {it("should rewind convo state to before the retried turn", async () => {const { store } = setup();const getConvoReqState = () =>- getMetabotRequestState(store.getState(), "omnibot");+ getMetabotRequestState(store.getState(), testConversationId("omnibot"));mockAgentEndpoint({events: [diff --git a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsxindex 3c37fab3e90..f74fd1d2537 100644--- a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx@@ -12,10 +12,7 @@ import { act, fireEvent, screen, waitFor, within } from "__support__/ui";import { LONG_CONVO_MSG_LENGTH_THRESHOLD } from "metabase/metabot/constants";import { useMetabotAgent } from "metabase/metabot/hooks";import { metabotActions } from "metabase/metabot/state";-import {- createConversation,- getMetabotInitialState,-} from "metabase/metabot/state/reducer-utils";+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import { logout } from "metabase/redux/auth";import * as domModule from "metabase/utils/dom";import {@@ -35,6 +32,7 @@ import {conversationTitle,createMockSSEStream,createPauses,+ createTestMetabotState,enterChatMessage,hideMetabot,input,@@ -44,6 +42,7 @@ import {queryConversationTitle,setup,showMetabot,+ testConversationId,whoIsYourFavoriteResponse,} from "./utils";@@ -55,7 +54,12 @@ describe("metabot > ui", () => {it("does not render header actions unless they are provided", async () => {setup({- ui: <MetabotChat config={{ agentId: "ask", suggestionModels: [] }} />,+ ui: (+ <MetabotChat+ conversationId={testConversationId("omnibot")}+ config={{ suggestionModels: [] }}+ />+ ),});expect(await screen.findByTestId("metabot-chat-input")).toBeInTheDocument();@@ -251,7 +255,7 @@ describe("metabot > ui", () => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId: testConversationId("omnibot"),id: "user-1",type: "text",message: "first line\nsecond line",@@ -276,7 +280,7 @@ describe("metabot > ui", () => {store.dispatch(metabotActions.addUserMessage({- agentId: "omnibot",+ conversationId: testConversationId("omnibot"),id: "user-2",type: "text",message: "first line\n\nsecond line",@@ -306,7 +310,7 @@ describe("metabot > ui", () => {id: "1",type: "text",message: longMsg,- agentId: "omnibot",+ conversationId: testConversationId("omnibot"),}),);});@@ -321,7 +325,7 @@ describe("metabot > ui", () => {id: "2",type: "text",message: longMsg,- agentId: "omnibot",+ conversationId: testConversationId("omnibot"),}),);});@@ -472,14 +476,8 @@ describe("metabot > ui", () => {});it("polls for the title when the stream ends without one", async () => {- const conversationId = "abcdabcd-abcd-abcd-abcd-abcdabcdabcd";- setup({- metabotInitialState: assocIn(- getMetabotInitialState(),- ["conversations", "omnibot"],- createConversation("omnibot", { conversationId, visible: true }),- ),- });+ setup({ conversationTitle: null });+ const conversationId = testConversationId("omnibot");let titleReady = false;fetchMock.removeRoute("metabot-conversation-title");@@ -567,11 +565,11 @@ describe("metabot > ui", () => {it("filters conversations by the current agent's profile", async () => {const metabotInitialState = assocIn(assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "visible"],+ createTestMetabotState(),+ ["agents", "omnibot", "visible"],true,),- ["conversations", "omnibot", "profileOverride"],+ ["conversations", testConversationId("omnibot"), "profileOverride"],"nlq",);@@ -664,7 +662,6 @@ describe("metabot > ui", () => {act(() => {store.dispatch(metabotActions.setConversationSnapshot({- agentId: "omnibot",conversationId: "current-conversation",messages: [{diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsxindex be54fa88b78..296b1dd448d 100644--- a/frontend/src/metabase/metabot/tests/utils.tsx+++ b/frontend/src/metabase/metabot/tests/utils.tsx@@ -1,7 +1,6 @@import type { ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import { assocIn } from "icepick";import { setupEnterprisePlugins } from "__support__/enterprise";import {@@ -30,6 +29,7 @@ import {import type { State } from "metabase/redux/store";import { createMockState } from "metabase/redux/store/mocks";import { Route } from "metabase/router";+import { checkNotNull } from "metabase/utils/types";import type {MetabotConversation,MetabotInfo,@@ -48,13 +48,74 @@ import { MetabotProvider } from "../context";import {type MetabotAgentId,type MetabotState,+ fixedMetabotAgentIds,metabotReducer,setVisible,} from "../state";-import { getMetabotInitialState } from "../state/reducer-utils";+import {+ createAgentState,+ createConversationForAgent,+ getMetabotInitialState,+} from "../state/reducer-utils";export { createMockReadableStream, createMockSSEStream, createPauses };+type MetabotStoreLike = { getState: () => { metabot: MetabotState } };++const agentIn = (state: MetabotState, agentId: MetabotAgentId) =>+ checkNotNull(state.agents[agentId]);++const convoIn = (state: MetabotState, conversationId: string) =>+ checkNotNull(state.conversations[conversationId]);++export const conversationIdForAgent = (+ store: MetabotStoreLike,+ agentId: MetabotAgentId = "omnibot",+) => agentIn(store.getState().metabot, agentId).conversationId;++export const convoForAgent = (+ store: MetabotStoreLike,+ agentId: MetabotAgentId = "omnibot",+) => convoIn(store.getState().metabot, conversationIdForAgent(store, agentId));++// make ids easer to address than production's random uuids+export const testConversationId = (agentId: MetabotAgentId) =>+ `convo-${agentId}`;++export const createTestMetabotState = ({+ visibleAgentIds = [],+ conversationTitle,+}: {+ visibleAgentIds?: MetabotAgentId[];+ conversationTitle?: string;+} = {}): MetabotState => {+ const agentConversations = fixedMetabotAgentIds.map((agentId) => ({+ agentId,+ conversationId: testConversationId(agentId),+ }));++ return {+ ...getMetabotInitialState(),+ conversations: Object.fromEntries(+ agentConversations.map(({ agentId, conversationId }) => [+ conversationId,+ createConversationForAgent(agentId, {+ conversationId,+ title: conversationTitle,+ }),+ ]),+ ),+ agents: Object.fromEntries(+ agentConversations.map(({ agentId, conversationId }) => [+ agentId,+ createAgentState(conversationId, {+ visible: visibleAgentIds.includes(agentId),+ }),+ ]),+ ),+ };+};+const mockReducedMotion = () => {window.matchMedia = (query: string) =>// jsdom has no matchMedia; this stub only needs the fields our code reads.@@ -304,22 +365,12 @@ export function setup(initialRoute,} = options || {};- const visibleState = assocIn(- getMetabotInitialState(),- ["conversations", "omnibot", "visible"],- true,- );const metabotState =metabotInitialState ??- Object.keys(visibleState.conversations).reduce(- (state, agentId) =>- assocIn(- state,- ["conversations", agentId, "title"],- conversationTitle || undefined,- ),- visibleState,- );+ createTestMetabotState({+ visibleAgentIds: ["omnibot"],+ conversationTitle: conversationTitle || undefined,+ });fetchMock.get(`path:/api/metabot/metabot/${FIXED_METABOT_IDS.DEFAULT}/prompt-suggestions`,diff --git a/frontend/src/metabase/plugins/oss/audit.ts b/frontend/src/metabase/plugins/oss/audit.tsindex 369e5772fbe..660298dfc4f 100644--- a/frontend/src/metabase/plugins/oss/audit.ts+++ b/frontend/src/metabase/plugins/oss/audit.ts@@ -1,10 +1,7 @@import type { ComponentType, ReactNode } from "react";import type { LinkProps } from "metabase/common/components/Link";-import type {- MetabotAgentId,- SlashCommand,-} from "metabase/metabot/state/types";+import type { SlashCommand } from "metabase/metabot/state/types";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type { Dispatch, GetState } from "metabase/redux/store";import type Question from "metabase-lib/v1/Question";@@ -17,7 +14,7 @@ import type {export type MetabotSlashCommandHandler = (args: {command: SlashCommand;- agentId: MetabotAgentId;+ conversationId: string;dispatch: Dispatch;getState: GetState;}) => boolean;diff --git a/frontend/src/metabase/query_builder/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx b/frontend/src/metabase/query_builder/components/MetabotQueryBuilder/MetabotQueryBuilder.tsxindex eabf476dc62..f0e6c05b986 100644--- a/frontend/src/metabase/query_builder/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx+++ b/frontend/src/metabase/query_builder/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx@@ -1,10 +1,5 @@-import { useMount } from "react-use";-import { MetabotAsk } from "metabase/metabot/components/MetabotAsk";-import {- useMetabotAgent,- useUserMetabotPermissions,-} from "metabase/metabot/hooks";+import { useUserMetabotPermissions } from "metabase/metabot/hooks";import { QueryBuilder } from "metabase/query_builder/containers/QueryBuilder";import { useSelector } from "metabase/redux";import { getSettingsLoading } from "metabase/settings";@@ -15,9 +10,6 @@ import { getSettingsLoading } from "metabase/settings";export const MetabotQueryBuilder = () => {const { hasNlqAccess, isLoading } = useUserMetabotPermissions();const areSettingsLoading = useSelector(getSettingsLoading);- const { createNewConversation } = useMetabotAgent("ask");-- useMount(createNewConversation);// Wait until settings and metabot permissions are both resolved before// deciding which view to render. Otherwise QueryBuilder may mount brieflydiff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.unit.spec.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.unit.spec.tsxindex afa1d6c6905..1cdaf59d6a3 100644--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.unit.spec.tsx+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.unit.spec.tsx@@ -56,7 +56,7 @@ describe("NativeQueryEditor", () => {// Unjustified type cast. FIXMEstoreInitialState: createMockState({metabot: {- conversations: {+ agents: {omnibot: {visible: isMetabotSidebarOpen,},