The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: full screen ai exploration page (#75502)
Maksym Yakubych55682e2e8c26
diff --git a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.tsindex de7cf60beea..2353599e155 100644--- a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts+++ b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts@@ -5,8 +5,6 @@ const { ORDERS_ID } = SAMPLE_DATABASE;const { H } = cy;-const metabotPromptInput = () => cy.get(".ProseMirror[contenteditable=true]");-const allOrdersQuestion = {dataset_query: {database: SAMPLE_DB_ID,@@ -30,12 +28,11 @@ describe("Metabot Query Builder", () => {H.updateSetting("llm-anthropic-api-key", "");cy.visit("/question/ask");cy.url().should("include", "/question/ask");- cy.get("main")- .findByText("To use AI exploration, please", { exact: false })- .should("be.visible");+ cy.findByRole("button", { name: "connect to a model" }).should(+ "be.visible",+ );cy.findByRole("button", { name: "connect to a model" }).click();cy.findByTestId("ai-provider-configuration-modal").should("be.visible");- cy.findByTestId("metabot-send-message").should("be.disabled");});it("should redirect to notebook when metabot-enabled? is false", () => {@@ -46,7 +43,7 @@ describe("Metabot Query Builder", () => {);cy.visit("/question/ask");cy.url().should("include", "/question#");- cy.findByTestId("metabot-send-message").should("not.exist");+ cy.findByTestId("metabot-chat").should("not.exist");});it("should not show AI exploration in new button when metabot is disabled", () => {@@ -58,43 +55,40 @@ describe("Metabot Query Builder", () => {H.popover().findByText("AI exploration").should("not.exist");});- it("should be able to successfully generate a notebook query", () => {- // visit home page- cy.visit("/");+ it("should render the agent's reply inline without leaving the page", () => {+ cy.visit("/question/ask");+ H.metabotChatInput().should("be.visible");- // go to new button and click "AI exploration"- H.newButton("AI exploration").click();+ H.mockMetabotResponse({+ body: mockTextOnlyResponse("Here's what I found."),+ });+ H.sendMetabotMessage("Tell me about my data");++ // the reply renders inline in the full-page conversation...+ cy.wait("@metabotAgent").then(({ request }) => {+ // the full-page conversation uses the nlq profile+ expect(request.body.profile_id).to.equal("nlq");+ });+ H.lastChatMessage().should("have.text", "Here's what I found.");- // should show page+ // ...and we stay on the /ask pagecy.url().should("include", "/question/ask");- cy.findByTestId("metabot-send-message").should("be.visible");+ });- // should have disabled send button- cy.findByTestId("metabot-send-message").should("be.disabled");+ it("should navigate to a question when the agent returns a navigate_to", () => {+ cy.visit("/");- // should be able to type into the input- metabotPromptInput().type("Show me all orders");+ // go to new button and click "AI exploration"+ H.newButton("AI exploration").click();+ cy.url().should("include", "/question/ask");+ cy.findByTestId("metabot-chat").should("not.exist");- // should be able to send promptconst questionHash = H.adhocQuestionHash(allOrdersQuestion);H.mockMetabotResponse({body: mockNavigateToResponse(`/question#${questionHash}`),delay: 100,});- cy.findByTestId("metabot-send-message").click();-- // should see loading state, send button should be disabled- cy.findByTestId("metabot-send-message").should("be.disabled");- cy.findByTestId("metabot-send-message").should(- "have.attr",- "data-loading",- "true",- );-- // request body should include nlq profile- cy.wait("@metabotAgent").then(({ request }) => {- expect(request.body.profile_id).to.eq("nlq");- });+ H.sendMetabotMessage("Show me all orders");// when we receive a navigate_to, we should be taken to a questioncy.url().should("include", "/question#");@@ -109,7 +103,7 @@ describe("Metabot Query Builder", () => {// visit AI exploration pagecy.visit("/question/ask");- cy.findByTestId("metabot-send-message").should("be.visible");+ H.metabotChatInput().should("be.visible");// click suggested promptconst questionHash = H.adhocQuestionHash(allOrdersQuestion);@@ -127,91 +121,16 @@ describe("Metabot Query Builder", () => {it("should handle errors", () => {// visit AI exploration pagecy.visit("/question/ask");- cy.findByTestId("metabot-send-message").should("be.visible");-- // mock the agent request to fail- H.mockMetabotResponse({ statusCode: 500 });-- // send a prompt- metabotPromptInput().type("Show me all orders");- cy.findByTestId("metabot-send-message").click();-- // should show error- cy.get("main")- .findByText("Something went wrong. Please try again.")- .should("be.visible");- });-- it("should handle getting no navigate_to", () => {- // visit AI exploration page- cy.visit("/question/ask");- cy.findByTestId("metabot-send-message").should("be.visible");+ H.metabotChatInput().should("be.visible");- // mock a response without a navigate_to data part- H.mockMetabotResponse({- body: mockTextOnlyResponse("I need more information to help you."),- });+ // mock the agent request to stream an error+ H.mockMetabotResponse({ body: mockErrorResponse });// send a prompt- metabotPromptInput().type("Show me something");- cy.findByTestId("metabot-send-message").click();- cy.wait("@metabotAgent");-- // should be taken to /question/notebook with the sidebar open- cy.url().should("include", "/question/notebook");- H.assertChatVisibility("visible");- });-- it("should not reuse the nlq profile after falling back to notebook chat", () => {- cy.intercept("POST", "/api/metabot/agent-streaming", (req) => {- req.reply({- statusCode: 200,- body: mockTextOnlyResponse("ok"),- headers: {- "content-type": "text/event-stream; charset=utf-8",- },- });- }).as("metabotAgent");-- cy.visit("/");- H.newButton("AI exploration").click();- cy.url().should("include", "/question/ask");-- metabotPromptInput().type("Show me all orders");- cy.findByTestId("metabot-send-message").click();-- cy.wait("@metabotAgent").then(({ request }) => {- expect(request.body.profile_id).to.eq("nlq");- });+ H.sendMetabotMessage("Show me all orders");- cy.url().should("include", "/question/notebook");- H.assertChatVisibility("visible");-- H.sendMetabotMessage("Try again");-- cy.wait("@metabotAgent").then(({ request }) => {- expect(request.body.profile_id).to.be.undefined;- });- });-- it("should cancel requests if the user leaves the page", () => {- // visit AI exploration page- cy.visit("/question/ask");- cy.findByTestId("metabot-send-message").should("be.visible");-- // send a prompt with a delayed response- H.mockMetabotResponse({- body: mockTextOnlyResponse("This should be canceled"),- delay: 2000,- });- metabotPromptInput().type("Show me something");- cy.findByTestId("metabot-send-message").click();-- // click on the logo in the app bar to leave the page- cy.findByTestId("main-logo-link").click();-- // check that the agent request was canceled- cy.get("@metabotAgent").its("state").should("eq", "Errored");+ // should show an error message inline+ H.lastChatMessage().should("contain.text", "Something went wrong");});});@@ -223,3 +142,6 @@ d:{"finishReason":"stop","usage":{"promptTokens":100,"completionTokens":10}}`;const mockTextOnlyResponse = (text: string) =>`0:"${text}"d:{"finishReason":"stop","usage":{"promptTokens":100,"completionTokens":10}}`;++const mockErrorResponse = `3:"Anthropic API key expired or invalid"+d:{"finishReason":"error","usage":{}}`;diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsxindex b5ed97da8df..0dd4d5a2167 100644--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx@@ -3,7 +3,7 @@ import { useMemo } from "react";import { t } from "ttag";import { ForwardRefLink } from "metabase/common/components/Link";-import { getNewMenuItemAIExploration } from "metabase/metabot/components/NewMenuItemAIExploration";+import { NewMenuItemAIExploration } from "metabase/metabot/components/NewMenuItemAIExploration";import { useUserMetabotPermissions } from "metabase/metabot/hooks";import { useDispatch, useSelector } from "metabase/redux";import { setOpenModal } from "metabase/redux/ui";@@ -47,13 +47,10 @@ export const NewItemMenuView = ({const menuItems = useMemo(() => {const items = [];- const aiExplorationItem = getNewMenuItemAIExploration(- hasDataAccess,- collectionId,- hasNlqAccess,- );- if (aiExplorationItem) {- items.push(aiExplorationItem);+ if (hasDataAccess && hasNlqAccess) {+ items.push(+ <NewMenuItemAIExploration key="nlq" collectionId={collectionId} />,+ );}if (hasDataAccess) {diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsxindex 9e9f608c85f..a69207c3412 100644--- a/frontend/src/metabase/metabot/components/Metabot.tsx+++ b/frontend/src/metabase/metabot/components/Metabot.tsx@@ -4,15 +4,26 @@ import { t } from "ttag";import MetabotFailure from "assets/img/metabot-failure.svg?component";import ErrorBoundary from "metabase/ErrorBoundary";+import { metabotApi } from "metabase/api";+import { idTag } from "metabase/api/tags";import {+ useIsAskPage,useMetabotAgent,useUserMetabotPermissions,} from "metabase/metabot/hooks";import { Sidebar } from "metabase/nav/containers/MainNavbar/MainNavbar.styled";-import { useSelector } from "metabase/redux";+import { useDispatch, useSelector } from "metabase/redux";import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";import { getUser } from "metabase/selectors/user";-import { Box, Button, Flex, Text } from "metabase/ui";+import {+ ActionIcon,+ Box,+ Button,+ Flex,+ Icon,+ Text,+ Tooltip,+} from "metabase/ui";import { trackMetabotChatOpened } from "../analytics";import type { MetabotAgentId } from "../state";@@ -47,12 +58,49 @@ const MetabotErrorFallback = ({ onRetry }: { onRetry: () => void }) => {);};+const MetabotSidebarActions = ({ agentId }: { agentId: MetabotAgentId }) => {+ const metabot = useMetabotAgent(agentId);+ const { isConfigured } = useUserMetabotPermissions();+ const dispatch = useDispatch();++ const handleResetChat = () => {+ metabot.resetConversation();+ dispatch(+ metabotApi.util.invalidateTags([+ idTag("metabot-prompt-suggestions", metabot.metabotId),+ ]),+ );+ };++ const handleCloseChat = () => {+ metabot.setPrompt("");+ metabot.setVisible(false);+ };++ return (+ <Flex gap="sm">+ {isConfigured && (+ <Tooltip label={t`Clear conversation`} position="bottom">+ <ActionIcon+ onClick={handleResetChat}+ data-testid="metabot-reset-chat"+ >+ <Icon c="text-primary" name="revert" />+ </ActionIcon>+ </Tooltip>+ )}+ <ActionIcon onClick={handleCloseChat} data-testid="metabot-close-chat">+ <Icon c="text-primary" name="close" />+ </ActionIcon>+ </Flex>+ );+};+// TODO: add test coverage for theseexport interface MetabotConfig {agentId?: MetabotAgentId;emptyText?: string;hideSuggestedPrompts?: boolean;- preventClose?: boolean;preventRetryMessage?: boolean;suggestionModels: SuggestionModel[];}@@ -63,8 +111,10 @@ export interface MetabotProps {}export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {- const { visible, setVisible } = useMetabotAgent(config?.agentId ?? "omnibot");+ const agentId = config?.agentId ?? "omnibot";+ const { visible, setVisible } = useMetabotAgent(agentId);const [errorBoundaryKey, setErrorBoundaryKey] = useState(0);+ const isAskPage = useIsAskPage();const handleRetry = () => setErrorBoundaryKey((prev) => prev + 1);@@ -72,13 +122,16 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {return tinykeys(window, {"$mod+e": (e) => {e.preventDefault(); // prevent FF from opening bookmark menu+ if (isAskPage) {+ return;+ }if (!visible) {trackMetabotChatOpened("keyboard_shortcut");}setVisible(!visible);},});- }, [visible, setVisible]);+ }, [visible, setVisible, isAskPage]);useEffect(function closeViaPropChange() {@@ -103,7 +156,10 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {width="30rem"aria-hidden={!visible}>- <MetabotChat config={config} />+ <MetabotChat+ config={config}+ headerActions={<MetabotSidebarActions agentId={agentId} />}+ /></Sidebar></ErrorBoundary>);diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsxindex e1787d58c4d..e188088664d 100644--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx@@ -1,6 +1,7 @@import { t } from "ttag";import {+ useIsAskPage,useMetabotAgent,useMetabotName,useUserMetabotPermissions,@@ -23,6 +24,7 @@ export function MetabotAppBarButton({const { hasMetabotAccess } = useUserMetabotPermissions();const metabot = useMetabotAgent("omnibot");const metabotName = useMetabotName();+ const isAskPage = useIsAskPage();if (!hasMetabotAccess) {return null;@@ -43,7 +45,8 @@ export function MetabotAppBarButton({<ActionIconclassName={className}variant="subtle"- c="text-primary"+ c={isAskPage ? "text-tertiary" : "text-primary"}+ opacity={isAskPage ? 0.5 : undefined}bd="1px solid var(--mb-color-border)"p="sm"h="2.25rem"@@ -51,6 +54,7 @@ export function MetabotAppBarButton({aria-label={label}onClick={handleClick}{...rest}+ disabled={isAskPage}><MetabotIcon /></ActionIcon>diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsxindex 3d21b3ff184..68cb4d4c08c 100644--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx@@ -1,10 +1,15 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";+import { Route } from "react-router";import { setupEnterprisePlugins } from "__support__/enterprise";import { mockSettings } from "__support__/settings";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { createMockState } from "metabase/redux/store/mocks";+import {+ createMockLocation,+ createMockRoutingState,+ createMockState,+} from "metabase/redux/store/mocks";import type { UserMetabotPermissions } from "metabase-types/api";import { createMockUserMetabotPermissions } from "metabase-types/api/mocks";@@ -16,10 +21,12 @@ function setup({isMetabotEnabled = true,isConfigured = true,permissionOverrides,+ pathname = "/",}: {isMetabotEnabled?: boolean;isConfigured?: boolean;permissionOverrides?: Partial<UserMetabotPermissions>;+ pathname?: string;} = {}) {fetchMock.get("path:/api/metabot/permissions/user-permissions",@@ -32,13 +39,22 @@ function setup({});setupEnterprisePlugins();- const { store } = renderWithProviders(+ const TestComponent = () => (<MetabotProvider><MetabotAppBarButton />- </MetabotProvider>,+ </MetabotProvider>+ );++ const { store } = renderWithProviders(+ <Route path="*" component={TestComponent} />,{+ withRouter: true,+ initialRoute: pathname,storeInitialState: createMockState({settings,+ routing: createMockRoutingState({+ locationBeforeTransitions: createMockLocation({ pathname }),+ }),}),},);@@ -79,6 +95,20 @@ describe("MetabotAppBarButton", () => {).not.toBeInTheDocument();});+ it("should disable the button on the full-page AI exploration (/question/ask) surface", async () => {+ setup({ isMetabotEnabled: true, pathname: "/question/ask" });+ expect(+ await screen.findByRole("button", { name: /Chat with Metabot/ }),+ ).toBeDisabled();+ });++ it("should not disable the button on other question pages", async () => {+ setup({ isMetabotEnabled: true, pathname: "/question/123" });+ expect(+ await screen.findByRole("button", { name: /Chat with Metabot/ }),+ ).toBeEnabled();+ });+it("should toggle metabot visibility when clicked", async () => {const { store } = setup({ isMetabotEnabled: true });diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.cssindex 2623459a260..1e8b82debf1 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css@@ -1,158 +1,18 @@-.page {- display: flex;- flex-direction: column;- height: 100%;- width: 100%;- background: var(--mb-color-background-primary);- position: relative;-}--/* Empty state - centered layout */-.centeredContainer {- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- flex: 1;- padding: 2rem;- gap: 1.5rem;-}--.greeting {- display: flex;- align-items: center;- flex-direction: column;- gap: 0.75rem;-- @media screen and (--breakpoint-min-sm) {- flex-direction: row;- }-}--.greetingIcon {- width: 2.5rem;- height: 2.5rem;-}--.inputWrapper {- width: 100%;- max-width: 42rem;-}--.inputContainer {- display: flex;- flex-direction: column;- padding: 0.5rem 1rem 1rem;- border-radius: 0.75rem;- box-shadow:- 0 0 0 1px var(--mb-color-border),- 0 4px 24px rgba(0, 0, 0, 0.08);- min-height: 7rem;- transition:- box-shadow 150ms ease,- background 1s ease-in-out;-- &:focus-within {- box-shadow:- 0 0 0 1px var(--mb-color-border),- 0 4px 24px rgba(0, 0, 0, 0.12);- }-}--.inputContainerLoading {- background: var(--mb-color-background-secondary);- animation: pulse 5s ease-in-out 1s infinite;-}--.editorWrapper {- flex: 1;- min-width: 0;- width: 100%;-}--.inputActions {- display: flex;- justify-content: space-between;- align-items: flex-end;-}--.sendButton {- color: var(--mb-color-background-primary);-- &:disabled,- &:disabled:hover {- background-color: var(--mb-color-core-brand);- color: var(--mb-color-text-primary-inverse);- border-color: var(--mb-color-core-brand);- opacity: 0.35;- }-}--.promptSuggestionsContainer {- display: flex;- flex-direction: column;- align-items: flex-start;- gap: 0.25rem;- width: 100%;- min-height: 10.75rem;-}--.promptSuggestion {- padding: 0.5rem 0.75rem;- font-size: 0.875rem;- color: var(--mb-color-text-secondary);- cursor: pointer;- border-radius: 0.5rem;- transition:- background 150ms ease,- color 150ms ease,- opacity 150ms ease;-- &:hover {- background: var(--mb-color-background-secondary);- color: var(--mb-color-text-primary);- }-}--.promptSuggestionShow {- opacity: 0;- animation: fade-in 300ms ease forwards;-}--.promptSuggestionHide {- opacity: 1;- animation: fade-out 200ms ease forwards;- cursor: default;- user-select: none;-}--@keyframes fade-in {- from {- opacity: 0;- }-- to {- opacity: 1;- }-}--@keyframes fade-out {- from {- opacity: 1;- }-- to {- opacity: 0;- }-}--@keyframes pulse {- 0%,- 100% {- background: var(--mb-color-background-secondary);- }-- 50% {- background: var(--mb-color-background-tertiary);- }+.chat {+ --metabot-chat-messages-padding-top: 2rem;+}++.topFade {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ height: 1rem;+ background: linear-gradient(+ to bottom,+ var(--mb-color-background-primary),+ transparent+ );+ pointer-events: none;+ z-index: 1;}diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsxindex b18fb34a029..0d2f2a5d597 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx@@ -1,277 +1,51 @@-import { useDisclosure } from "@mantine/hooks";-import { isFulfilled, isRejected } from "@reduxjs/toolkit";-import cx from "classnames";-import { useEffect, useState } from "react";-import { push } from "react-router-redux";-import { isMatching } from "ts-pattern";-import { t } from "ttag";-import _ from "underscore";+import { useEffect } from "react";-import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";-import { MetabotLogo } from "metabase/common/components/MetabotLogo";-import { useSetting } from "metabase/common/hooks";-import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";-import { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";-import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";-import {- useMetabotAgent,- useUserMetabotPermissions,-} from "metabase/metabot/hooks";-import { useDispatch } from "metabase/redux";-import { useRouter } from "metabase/router";-import {- ActionIcon,- Box,- Icon,- Paper,- Stack,- Text,- UnstyledButton,-} from "metabase/ui";-import * as Urls from "metabase/urls";+import type { MetabotConfig } from "metabase/metabot/components/Metabot";+import { MetabotChat } from "metabase/metabot/components/MetabotChat";+import { useMetabotAgent } from "metabase/metabot/hooks";+import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";+import { Box, Flex } from "metabase/ui";import S from "./MetabotAsk.module.css";+import { MetabotGreeting } from "./MetabotGreeting";-const defaultSuggestionModels = [+const SUGGESTION_MODELS: SuggestionModel[] = ["dataset","metric","card","table","database","dashboard",-] as const;+];-const getTitleText = () => {- return _.sample([- t`What would you like to know?`,- t`What do you want to explore?`,- t`What are you looking to learn?`,- ]);+const askConfig: MetabotConfig = {+ agentId: "ask",+ suggestionModels: SUGGESTION_MODELS,};-type SubmitInputResult = Awaited<- ReturnType<ReturnType<typeof useMetabotAgent>["submitInput"]>->;--const responseHasNavigateTo = (action: SubmitInputResult) =>- isFulfilled(action) &&- action.payload.data?.processedResponse.data?.some(- isMatching({ type: "navigate_to" }),- );-export const MetabotAsk = () => {- const { canUseNlq } = useUserMetabotPermissions();- const [- isAiProviderConfigurationModalOpen,- {- close: closeAiProviderConfigurationModal,- open: openAiProviderConfigurationModal,- },- ] = useDisclosure(false);-- const dispatch = useDispatch();- const {- setVisible,- resetConversation,- metabotId,- isDoingScience,- prompt,- setPrompt,- promptInputRef,- submitInput,- cancelRequest,- } = useMetabotAgent();-- const [title] = useState(getTitleText);- const [hasError, setHasError] = useState(false);- const showIllustrations = useSetting("metabot-show-illustrations");-- const suggestedPromptsReq = useGetSuggestedMetabotPromptsQuery({- metabot_id: metabotId,- limit: 4,- sample: true,- });- const suggestedPrompts = suggestedPromptsReq.currentData?.prompts;- const suggestedPromptCount = suggestedPrompts?.length ?? 0;-- const handleSubmitPrompt = async (prompt: string) => {- // start new nlq convo- resetConversation();- setHasError(false);-- // work around to show prompt during loading state - this is due to- // normally we want the prompt to be cleared in a conversation- // but in this case we want to show it in the input while responding- // so it looks like we're processing the prompt / suggested prompt- const req = submitInput(prompt, {- profile: "nlq",- preventOpenSidebar: true,- });- setPrompt(prompt);- const action = await req;- setPrompt("");-- if (isRejected(action)) {- return setHasError(true);- }-- if (!action.payload.success) {- if (action.payload.shouldRetry) {- setPrompt(prompt);- }- return setHasError(true);- }-- // as a fallback, if we receive no new query, we'll take the user- // to an empty notebook query and show the chat sidebar as it's- // highly likely the chat contains a response asking for clarification- if (!responseHasNavigateTo(action)) {- dispatch(- push(- Urls.newQuestion({- mode: "notebook",- creationType: "custom_question",- cardType: "question",- }),- ),- );- setVisible(true);- }- };-- const handleEditorSubmit = () => handleSubmitPrompt(prompt);-- const inputDisabled = prompt.trim().length === 0 || isDoingScience;+ const { setVisible: setSidebarVisible } = useMetabotAgent("omnibot");+ const { messages, isDoingScience } = useMetabotAgent("ask");useEffect(- function autoCloseMetabotOnMount() {- setVisible(false);+ function closeSidebarOnMount() {+ setSidebarVisible(false);},- [setVisible],+ [setSidebarVisible],);- const { router, routes } = useRouter();- const currentRoute = routes.at(-1);- useEffect(- function cancelRequestOnRouteLeave() {- return router.setRouteLeaveHook(currentRoute, (nextLocation) => {- const isNavigatingToQuestion =- nextLocation?.pathname.startsWith("/question");- if (isDoingScience) {- if (isNavigatingToQuestion) {- // we want to open the sidebar at this point as the agent could be sending a- // navigate_to before the response has been fully completed- setVisible(true);- } else {- cancelRequest();- resetConversation(); // clear any partial response and reset profile- }- }- return true;- });- },- [- router,- currentRoute,- setVisible,- cancelRequest,- resetConversation,- isDoingScience,- ],- );+ const showGreeting = messages.length === 0 && !isDoingScience;return (- <Box className={S.page}>- <Box className={S.centeredContainer}>- <Box className={S.greeting}>- {showIllustrations && <MetabotLogo className={S.greetingIcon} />}- <Text fz={{ base: "xl", sm: 32 }} fw={600} c="text-primary">- {title}- </Text>+ <Flex h="100%" w="100%" justify="center" bg="background-primary">+ {showGreeting ? (+ <MetabotGreeting agentId="ask" suggestionModels={SUGGESTION_MODELS} />+ ) : (+ <Box pos="relative" h="100%" w="100%">+ <Box className={S.topFade} />+ <MetabotChat config={askConfig} className={S.chat} /></Box>-- <Stack gap="lg" className={S.inputWrapper}>- <Paper- className={cx(- S.inputContainer,- isDoingScience && S.inputContainerLoading,- )}- >- <Box className={S.editorWrapper}>- {!canUseNlq ? (- <AIProviderConfigurationNotice- py="0.5rem"- featureName={t`AI exploration`}- inline- onConfigureAi={openAiProviderConfigurationModal}- />- ) : (- <MetabotPromptInput- ref={promptInputRef}- value={prompt}- autoFocus- disabled={isDoingScience}- placeholder={t`Ask about your data, and type @ to mention an item`}- onChange={setPrompt}- onSubmit={handleEditorSubmit}- onStop={cancelRequest}- suggestionConfig={{- suggestionModels: [...defaultSuggestionModels],- }}- />- )}- </Box>- <Box className={S.inputActions}>- {hasError ? (- <Text c="error" ta="center">- {t`Something went wrong. Please try again.`}- </Text>- ) : (- <div />- )}- <ActionIcon- className={S.sendButton}- variant="filled"- size="2rem"- disabled={!canUseNlq || inputDisabled}- loading={isDoingScience}- onClick={handleEditorSubmit}- data-testid="metabot-send-message"- aria-label={t`Send`}- >- <Icon name="arrow_up" />- </ActionIcon>- </Box>- </Paper>-- <Box className={S.promptSuggestionsContainer}>- {canUseNlq- ? suggestedPrompts?.map(({ prompt: suggestedPrompt }, index) => (- <UnstyledButton- key={index}- className={cx(S.promptSuggestion, {- [S.promptSuggestionShow]: !isDoingScience,- [S.promptSuggestionHide]: isDoingScience,- })}- style={{- animationDelay: isDoingScience- ? `${(suggestedPromptCount - index - 1) * 50}ms`- : `${index * 75}ms`,- }}- onClick={() => handleSubmitPrompt(suggestedPrompt)}- disabled={isDoingScience}- >- <Text>{suggestedPrompt}</Text>- </UnstyledButton>- ))- : null}- </Box>- </Stack>- </Box>- <AIProviderConfigurationModal- opened={isAiProviderConfigurationModalOpen}- onClose={closeAiProviderConfigurationModal}- />- </Box>+ )}+ </Flex>);};diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsxindex caac17d5d4b..aa7ac48bd85 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx@@ -1,106 +1,73 @@-import { Route } from "react-router";+import { assocIn } from "icepick";++import { screen } from "__support__/ui";+import { getMetabotVisible } from "metabase/metabot/state";+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";+import { createMockUser } from "metabase-types/api/mocks";-import { setupBookmarksEndpoints } from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen } from "__support__/ui";-import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";import {- useMetabotAgent,- useUserMetabotPermissions,-} from "metabase/metabot/hooks";-import { createMockState } from "metabase/redux/store/mocks";+ enterChatMessage,+ mockAgentEndpoint,+ setup,+ whoIsYourFavoriteResponse,+} from "../../tests/utils";import { MetabotAsk } from "./MetabotAsk";-jest.mock("metabase/api", () => ({- ...jest.requireActual("metabase/api"),- useGetSuggestedMetabotPromptsQuery: jest.fn(),-}));--jest.mock("metabase/metabot/hooks", () => ({- ...jest.requireActual("metabase/metabot/hooks"),- useMetabotAgent: jest.fn(),- useUserMetabotPermissions: jest.fn(),-}));--type SetupOptions = {- showIllustrations?: boolean;- prompt?: string;- suggestedPrompts?: { prompt: string }[];-};--function setup({- showIllustrations = true,- prompt = "",- suggestedPrompts = [],-}: SetupOptions = {}) {- jest.mocked(useUserMetabotPermissions).mockReturnValue({- hasNlqAccess: true,- canUseNlq: true,- } as any);+const greetingTitle =+ /What would you like to know\?|What do you want to explore\?|What are you looking to learn\?/;- setupBookmarksEndpoints([]);-- jest.mocked(useMetabotAgent).mockReturnValue({- setVisible: jest.fn(),- resetConversation: jest.fn(),- submitInput: jest.fn(),- cancelRequest: jest.fn(),- setPrompt: jest.fn(),- metabotId: "default",- isDoingScience: false,- prompt,- promptInputRef: { current: null },- } as any);- jest.mocked(useGetSuggestedMetabotPromptsQuery).mockReturnValue({- currentData: { prompts: suggestedPrompts },- } as any);+describe("MetabotAsk", () => {+ it("shows the greeting and closes the global Metabot sidebar", async () => {+ const metabotInitialState = assocIn(+ getMetabotInitialState(),+ ["conversations", "omnibot", "visible"],+ true,+ );++ const { store } = setup({+ ui: <MetabotAsk />,+ metabotInitialState,+ promptSuggestions: [{ prompt: "Show me all orders" }],+ });- const settings = mockSettings({- "metabot-show-illustrations": showIllustrations,+ expect(await screen.findByText(greetingTitle)).toBeInTheDocument();+ expect(await screen.findByText("Show me all orders")).toBeInTheDocument();+ expect(screen.getByTestId("metabot-chat-input")).toBeInTheDocument();+ expect(screen.queryByTestId("metabot-chat")).not.toBeInTheDocument();+ expect(getMetabotVisible(store.getState(), "omnibot")).toBe(false);});- return renderWithProviders(<Route path="/" component={MetabotAsk} />, {- withRouter: true,- storeInitialState: createMockState({ settings }),- });-}+ it("replaces the greeting with the conversation after sending a message", async () => {+ setup({ ui: <MetabotAsk /> });+ mockAgentEndpoint({ textChunks: whoIsYourFavoriteResponse });-describe("MetabotAsk", () => {- beforeEach(() => {- jest.clearAllMocks();- });+ expect(await screen.findByText(greetingTitle)).toBeInTheDocument();- it("renders the Metabot illustration when metabot-show-illustrations is true", () => {- setup({ showIllustrations: true });- expect(screen.getByRole("img", { name: "Metabot" })).toBeInTheDocument();- });+ await enterChatMessage("Who is your favorite?");- it("hides the Metabot illustration when metabot-show-illustrations is false", () => {- setup({ showIllustrations: false });expect(- screen.queryByRole("img", { name: "Metabot" }),- ).not.toBeInTheDocument();+ await screen.findByText("Who is your favorite?"),+ ).toBeInTheDocument();+ expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();+ expect(screen.queryByText(greetingTitle)).not.toBeInTheDocument();});- it("renders suggested prompts when the API returns them", () => {+ it("shows the AI provider setup notice in the greeting when not configured", async () => {setup({- suggestedPrompts: [- { prompt: "Show me top customers" },- { prompt: "How many orders this month?" },- ],+ ui: <MetabotAsk />,+ currentUser: createMockUser({ is_superuser: true }),+ isConfigured: false,});- expect(screen.getByText("Show me top customers")).toBeInTheDocument();- expect(screen.getByText("How many orders this month?")).toBeInTheDocument();- });- it("disables the send button when the prompt is empty", () => {- setup({ prompt: "" });- expect(screen.getByTestId("metabot-send-message")).toBeDisabled();- });-- it("enables the send button when the prompt is non-empty", () => {- setup({ prompt: "anything" });- expect(screen.getByTestId("metabot-send-message")).toBeEnabled();+ expect(+ await screen.findByText("To use AI exploration, please", {+ exact: false,+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "connect to a model" }),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("metabot-chat-input")).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.css b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.cssnew file mode 100644index 00000000000..d7078754a3d--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.css@@ -0,0 +1,109 @@+.centeredContainer {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ flex: 1;+ padding: 2rem;+ gap: 1.5rem;+}++.greeting {+ display: flex;+ align-items: center;+ flex-direction: column;+ gap: 0.75rem;++ @media screen and (--breakpoint-min-sm) {+ flex-direction: row;+ }+}++.greetingIcon {+ width: 2.5rem;+ height: 2.5rem;+}++.inputWrapper {+ width: 100%;+ max-width: 42rem;+}++.inputContainer {+ display: flex;+ flex-direction: column;+ padding: 0.5rem 1rem 1rem;+ border-radius: 0.75rem;+ box-shadow:+ 0 0 0 1px var(--mb-color-border),+ 0 4px 24px rgba(0, 0, 0, 0.08);+ min-height: 7rem;+ transition: box-shadow 150ms ease;++ &:focus-within {+ box-shadow:+ 0 0 0 1px var(--mb-color-border),+ 0 4px 24px rgba(0, 0, 0, 0.12);+ }+}++.editorWrapper {+ flex: 1;+ min-width: 0;+ width: 100%;+}++.inputActions {+ display: flex;+ justify-content: flex-end;+ align-items: flex-end;+}++.sendButton {+ color: var(--mb-color-background-primary);++ &:disabled,+ &:disabled:hover {+ background-color: var(--mb-color-brand);+ color: var(--mb-color-text-primary-inverse);+ border-color: var(--mb-color-brand);+ opacity: 0.35;+ }+}++.promptSuggestionsContainer {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 0.25rem;+ width: 100%;+ min-height: 10.75rem;+}++.promptSuggestion {+ padding: 0.5rem 0.75rem;+ font-size: 0.875rem;+ color: var(--mb-color-text-secondary);+ cursor: pointer;+ border-radius: 0.5rem;+ opacity: 0;+ animation: fade-in 300ms ease forwards;+ transition:+ background 150ms ease,+ color 150ms ease;++ &:hover {+ background: var(--mb-color-background-secondary);+ color: var(--mb-color-text-primary);+ }+}++@keyframes fade-in {+ from {+ opacity: 0;+ }++ to {+ opacity: 1;+ }+}diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsxnew file mode 100644index 00000000000..11d1b79e1c9--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx@@ -0,0 +1,147 @@+import { useDisclosure } from "@mantine/hooks";+import { useState } from "react";+import { t } from "ttag";+import _ from "underscore";++import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";+import { MetabotLogo } from "metabase/common/components/MetabotLogo";+import { useSetting } from "metabase/common/hooks";+import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";+import { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";+import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";+import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";+import {+ ActionIcon,+ Box,+ Icon,+ Paper,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";++import { useMetabotAgent, useUserMetabotPermissions } from "../../hooks";+import type { MetabotAgentId } from "../../state";++import S from "./MetabotGreeting.module.css";++const SUGGESTED_PROMPTS_LIMIT = 4;++const getTitleText = () => {+ return _.sample([+ t`What would you like to know?`,+ t`What do you want to explore?`,+ t`What are you looking to learn?`,+ ]);+};++interface MetabotGreetingProps {+ agentId: MetabotAgentId;+ suggestionModels: SuggestionModel[];+}++export const MetabotGreeting = ({+ agentId,+ suggestionModels,+}: MetabotGreetingProps) => {+ const [title] = useState(getTitleText);+ const [+ isAiProviderConfigurationModalOpen,+ {+ close: closeAiProviderConfigurationModal,+ open: openAiProviderConfigurationModal,+ },+ ] = useDisclosure(false);+ const metabot = useMetabotAgent(agentId);+ const showIllustrations = useSetting("metabot-show-illustrations");+ const { isConfigured } = useUserMetabotPermissions();++ const suggestedPromptsReq = useGetSuggestedMetabotPromptsQuery(+ {+ metabot_id: metabot.metabotId,+ limit: SUGGESTED_PROMPTS_LIMIT,+ sample: true,+ },+ { skip: !isConfigured },+ );+ const suggestedPrompts = suggestedPromptsReq.currentData?.prompts ?? [];++ const handleSubmit = () => metabot.submitInput(metabot.prompt);+ const inputDisabled =+ metabot.prompt.trim().length === 0 || metabot.isDoingScience;++ return (+ <Box className={S.centeredContainer} data-testid="metabot-empty-chat-info">+ <Box className={S.greeting}>+ {showIllustrations && <MetabotLogo className={S.greetingIcon} />}+ <Text fz={{ base: "xl", sm: 32 }} fw={600} c="text-primary">+ {title}+ </Text>+ </Box>++ <Stack gap="lg" className={S.inputWrapper}>+ <Paper className={S.inputContainer}>+ <Box className={S.editorWrapper}>+ {!isConfigured ? (+ <AIProviderConfigurationNotice+ py="0.5rem"+ featureName={t`AI exploration`}+ inline+ onConfigureAi={openAiProviderConfigurationModal}+ />+ ) : (+ <MetabotPromptInput+ ref={metabot.promptInputRef}+ value={metabot.prompt}+ autoFocus+ disabled={metabot.isDoingScience}+ placeholder={t`Ask about your data, and type @ to mention an item`}+ onChange={metabot.setPrompt}+ onSubmit={handleSubmit}+ onStop={metabot.cancelRequest}+ suggestionConfig={{ suggestionModels }}+ data-testid="metabot-chat-input"+ />+ )}+ </Box>+ <Box className={S.inputActions}>+ <ActionIcon+ className={S.sendButton}+ variant="filled"+ size="2rem"+ disabled={!isConfigured || inputDisabled}+ loading={metabot.isDoingScience}+ onClick={handleSubmit}+ data-testid="metabot-send-message"+ aria-label={t`Send`}+ >+ <Icon name="arrow_up" />+ </ActionIcon>+ </Box>+ </Paper>++ <Box+ className={S.promptSuggestionsContainer}+ data-testid="metabot-prompt-suggestions"+ >+ {isConfigured &&+ suggestedPrompts.map(({ prompt }, index) => (+ <UnstyledButton+ key={index}+ className={S.promptSuggestion}+ style={{ animationDelay: `${index * 75}ms` }}+ onClick={() => metabot.submitInput(prompt)}+ >+ <Text>{prompt}</Text>+ </UnstyledButton>+ ))}+ </Box>+ </Stack>++ <AIProviderConfigurationModal+ opened={isAiProviderConfigurationModalOpen}+ onClose={closeAiProviderConfigurationModal}+ />+ </Box>+ );+};diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.cssindex 29b4d1bf9b7..a3afd300921 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css@@ -12,7 +12,7 @@padding: 1.25rem 1.5rem 1rem;display: flex;align-items: center;- justify-content: space-between;+ justify-content: flex-end;}.inputContainer {@@ -34,18 +34,28 @@background: var(--mb-color-background-secondary);}+.messagesScrollArea {+ position: relative;+ flex: 1;+ min-height: 0;+}+.messagesContainer {- padding: 1rem 1rem 1.5rem;+ padding: var(--metabot-chat-messages-padding-top, 1rem) 0 1.5rem;height: 100%;display: flex;flex-direction: column;overflow: auto;+ scrollbar-gutter: stable both-edges;}.messages {display: flex;flex-direction: column;- padding-inline: 0.5rem;+ width: 100%;+ max-width: 48rem;+ margin-inline: auto;+ padding-inline: 1.5rem;}.messageContainer {@@ -129,6 +139,10 @@* this prevents a jump once suggestions have loaded in most cases */min-height: 106px;flex-shrink: 0;+ width: 100%;+ max-width: 48rem;+ margin-inline: auto;+ padding-inline: 1rem;}.promptSuggestionButton {@@ -146,4 +160,7 @@.textInputContainer {padding: 0 1rem 1rem;+ width: 100%;+ max-width: 48rem;+ margin-inline: auto;}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsxindex d33cfbe8a27..94ea5a78d64 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx@@ -1,6 +1,6 @@import { useDisclosure } from "@mantine/hooks";import cx from "classnames";-import { useMemo } from "react";+import { type ReactNode, useMemo } from "react";import { t } from "ttag";import EmptyDashboardBot from "assets/img/dashboard-empty.svg?component";@@ -9,17 +9,7 @@ import { useSetting } from "metabase/common/hooks";import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";import { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";import { MetabotResetLongChatButton } from "metabase/metabot/components/MetabotChat/MetabotResetLongChatButton";-import {- ActionIcon,- Box,- Button,- Flex,- Icon,- Paper,- Stack,- Text,- Tooltip,-} from "metabase/ui";+import { Box, Button, Flex, Paper, Stack, Text } from "metabase/ui";import {useMetabotAgent,@@ -48,8 +38,12 @@ const defaultConfig: MetabotConfig = {export const MetabotChat = ({config = defaultConfig,+ className,+ headerActions,}: {config?: MetabotConfig;+ className?: string;+ headerActions?: ReactNode;}) => {const [isAiProviderConfigurationModalOpen,@@ -80,134 +74,106 @@ export const MetabotChat = ({return suggestedPromptsReq.currentData?.prompts ?? [];}, [suggestedPromptsReq.currentData?.prompts]);- const handleResetChat = () => {- metabot.resetConversation();- suggestedPromptsReq.refetch();- };-- const handleClose = () => {- metabot.setPrompt("");- metabot.setVisible(false);- };-const handleEditorSubmit = () => metabot.submitInput(metabot.prompt);return (- <Box className={Styles.container} data-testid="metabot-chat">- {/* header */}- <Box ref={headerRef} className={Styles.header}>- <Flex align-items="center">- <Text lh={1} fz="sm" c="text-secondary">- {t`${metabotName} isn't perfect. Double-check results.`}- </Text>- </Flex>+ <Box className={cx(Styles.container, className)} data-testid="metabot-chat">+ {headerActions && (+ <Box ref={headerRef} className={Styles.header}>+ {headerActions}+ </Box>+ )}- <Flex gap="sm">- {isConfigured && (- <Tooltip label={t`Clear conversation`} position="bottom">- <ActionIcon- onClick={handleResetChat}- data-testid="metabot-reset-chat"+ {/* chat messages */}+ <Box className={Styles.messagesScrollArea}>+ <Box+ ref={scrollContainerRef}+ className={Styles.messagesContainer}+ data-testid="metabot-chat-messages"+ >+ {!hasMessages && !metabot.isDoingScience && (+ <>+ {/* empty state */}+ <Flex+ h="100%"+ gap="md"+ px="md"+ direction="column"+ align="center"+ justify="center"+ data-testid="metabot-empty-chat-info">- <Icon c="text-primary" name="revert" />- </ActionIcon>- </Tooltip>- )}- {!config.preventClose && (- <ActionIcon onClick={handleClose} data-testid="metabot-close-chat">- <Icon c="text-primary" name="close" />- </ActionIcon>+ {showIllustrations && (+ <Box component={EmptyDashboardBot} w="6rem" />+ )}+ {!isConfigured ? (+ <AIProviderConfigurationNotice+ featureName={metabotName}+ onConfigureAi={openAiProviderConfigurationModal}+ />+ ) : (+ <Text c="text-tertiary" maw="12rem" ta="center" lh="lg">+ {config.emptyText ??+ (showIllustrations+ ? t`I can help you explore your metrics and models.`+ : t`Explore your metrics and models with AI.`)}+ </Text>+ )}+ </Flex>+ {isConfigured && !config.hideSuggestedPrompts && (+ <Stack+ gap="sm"+ className={Styles.promptSuggestionsContainer}+ data-testid="metabot-prompt-suggestions"+ >+ <>+ {suggestedPrompts.map(({ prompt }, index) => (+ <Box key={index}>+ <Button+ fz="sm"+ size="xs"+ onClick={() => metabot.submitInput(prompt)}+ className={Styles.promptSuggestionButton}+ >+ {prompt}+ </Button>+ </Box>+ ))}+ </>+ </Stack>+ )}+ </>)}- </Flex>- </Box>- {/* chat messages */}- <Box- ref={scrollContainerRef}- className={Styles.messagesContainer}- data-testid="metabot-chat-messages"- >- {!hasMessages && !metabot.isDoingScience && (- <>- {/* empty state */}- <Flex- h="100%"- gap="md"- direction="column"- align="center"- justify="center"- data-testid="metabot-empty-chat-info"+ {(hasMessages || metabot.isDoingScience) && (+ <Box+ className={Styles.messages}+ data-testid="metabot-chat-inner-messages">- {showIllustrations && (- <Box component={EmptyDashboardBot} w="6rem" />+ {/* conversation messages */}+ <Messages+ messages={metabot.messages}+ onRetryMessage={+ config.preventRetryMessage ? undefined : metabot.retryMessage+ }+ isDoingScience={metabot.isDoingScience}+ debug={metabot.debugMode}+ />+ {/* loading */}+ {metabot.isDoingScience && (+ <MetabotThinking toolCalls={metabot.activeToolCalls} />)}- {!isConfigured ? (- <AIProviderConfigurationNotice- featureName={metabotName}- onConfigureAi={openAiProviderConfigurationModal}+ {/* filler - height gets set via ref mutation */}+ <div ref={fillerRef} data-testid="metabot-message-filler" />+ {/* long convo warning */}+ {metabot.isLongConversation && (+ <MetabotResetLongChatButton+ onResetConversation={metabot.resetConversation}/>- ) : (- <Text c="text-tertiary" maw="12rem" ta="center" lh="lg">- {config.emptyText ??- (showIllustrations- ? t`I can help you explore your metrics and models.`- : t`Explore your metrics and models with AI.`)}- </Text>)}- </Flex>- {isConfigured && !config.hideSuggestedPrompts && (- <Stack- gap="sm"- className={Styles.promptSuggestionsContainer}- data-testid="metabot-prompt-suggestions"- >- <>- {suggestedPrompts.map(({ prompt }, index) => (- <Box key={index}>- <Button- fz="sm"- size="xs"- onClick={() => metabot.submitInput(prompt)}- className={Styles.promptSuggestionButton}- >- {prompt}- </Button>- </Box>- ))}- </>- </Stack>- )}- </>- )}-- {(hasMessages || metabot.isDoingScience) && (- <Box- className={Styles.messages}- data-testid="metabot-chat-inner-messages"- >- {/* conversation messages */}- <Messages- messages={metabot.messages}- onRetryMessage={- config.preventRetryMessage ? undefined : metabot.retryMessage- }- isDoingScience={metabot.isDoingScience}- debug={metabot.debugMode}- />- {/* loading */}- {metabot.isDoingScience && (- <MetabotThinking toolCalls={metabot.activeToolCalls} />- )}- {/* filler - height gets set via ref mutation */}- <div ref={fillerRef} data-testid="metabot-message-filler" />- {/* long convo warning */}- {metabot.isLongConversation && (- <MetabotResetLongChatButton- onResetConversation={metabot.resetConversation}- />- )}- </Box>- )}+ </Box>+ )}+ </Box></Box>{isConfigured && (@@ -227,9 +193,14 @@ export const MetabotChat = ({onChange={metabot.setPrompt}onSubmit={handleEditorSubmit}onStop={metabot.cancelRequest}- suggestionConfig={{ suggestionModels: config.suggestionModels }}+ suggestionConfig={{+ suggestionModels: config.suggestionModels,+ }}/></Paper>+ <Text mt="sm" pb="0.5rem" fz="sm" c="text-secondary" ta="center">+ {t`${metabotName} isn't perfect. Double-check results.`}+ </Text></Box>)}<AIProviderConfigurationModaldiff --git a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsxindex 8316567f0ae..777c118654e 100644--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx@@ -1,22 +1,23 @@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";-export function getNewMenuItemAIExploration(- hasDataAccess: boolean,- collectionId?: CollectionId,- canUseNlq?: boolean,-) {- if (!hasDataAccess || !canUseNlq) {- return undefined;- }+interface NewMenuItemAIExplorationProps {+ collectionId?: CollectionId;+}++export function NewMenuItemAIExploration({+ collectionId,+}: NewMenuItemAIExplorationProps) {+ const dispatch = useDispatch();return (<Menu.Item- key="nlq"component={ForwardRefLink}to={Urls.newQuestion({mode: "ask",@@ -24,6 +25,7 @@ export function getNewMenuItemAIExploration(cardType: "question",})}leftSection={<Icon name="comment" />}+ onClick={() => 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 adc13297991..31177deb792 100644--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx@@ -1,30 +1,60 @@-import { getNewMenuItemAIExploration } from "./NewMenuItemAIExploration";+import userEvent from "@testing-library/user-event";+import { assocIn } from "icepick";+import { Route } from "react-router";-describe("getNewMenuItemAIExploration", () => {- it("should return undefined when hasDataAccess is false", () => {- const result = getNewMenuItemAIExploration(false, undefined, true);- expect(result).toBeUndefined();- });+import { renderWithProviders, screen } from "__support__/ui";+import { getMessages, metabotReducer } from "metabase/metabot/state";+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";+import { createMockState } from "metabase/redux/store/mocks";+import { Menu } from "metabase/ui";- it("should return undefined when canUseNlq is false", () => {- const result = getNewMenuItemAIExploration(true, undefined, false);- expect(result).toBeUndefined();- });+import { NewMenuItemAIExploration } from "./NewMenuItemAIExploration";- it("should return undefined when canUseNlq is undefined", () => {- const result = getNewMenuItemAIExploration(true, undefined, undefined);- expect(result).toBeUndefined();- });+function setup() {+ const metabotInitialState = assocIn(+ getMetabotInitialState(),+ ["conversations", "ask", "messages"],+ [{ id: "1", role: "user", type: "text", message: "hi" }],+ );++ const TestComponent = () => (+ <Menu opened>+ <Menu.Dropdown>+ <NewMenuItemAIExploration />+ </Menu.Dropdown>+ </Menu>+ );++ const { store } = renderWithProviders(+ <Route path="*" component={TestComponent} />,+ {+ withRouter: true,+ storeInitialState: createMockState({ metabot: metabotInitialState }),+ customReducers: { metabot: metabotReducer },+ },+ );- it("should return a Menu.Item when hasDataAccess and canUseNlq are true", () => {- const result = getNewMenuItemAIExploration(true, undefined, true);- expect(result).not.toBeUndefined();- expect(result?.key).toBe("nlq");+ return { store };+}++describe("NewMenuItemAIExploration", () => {+ it("links to the ask mode question page", () => {+ setup();++ expect(+ screen.getByRole("menuitem", { name: /AI exploration/ }),+ ).toHaveAttribute("href", "/question/ask");});- it("should link to the ask mode question page", () => {- const result = getNewMenuItemAIExploration(true, 123, true);- expect(result).not.toBeUndefined();- expect(result?.props?.to).toBe("/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);});});diff --git a/frontend/src/metabase/metabot/constants.ts b/frontend/src/metabase/metabot/constants.tsindex 32a76c0c97e..057670e81e6 100644--- a/frontend/src/metabase/metabot/constants.ts+++ b/frontend/src/metabase/metabot/constants.ts@@ -77,6 +77,7 @@ export function renderMetabotProfileLabel(id: string): string {export const METABOT_PROFILE_OVERRIDES = {DEFAULT: undefined,+ NLQ: "nlq",SQL: "sql",TRANSFORMS_CODEGEN: "transforms_codegen",} as const satisfies Record<string, MetabotProfileId | undefined>;diff --git a/frontend/src/metabase/metabot/hooks/index.ts b/frontend/src/metabase/metabot/hooks/index.tsindex 1677860edd0..3e45fd9fcba 100644--- a/frontend/src/metabase/metabot/hooks/index.ts+++ b/frontend/src/metabase/metabot/hooks/index.ts@@ -1,3 +1,4 @@+export { useIsAskPage } from "./use-is-ask-page";export { useMetabotEnabledEmbeddingAware } from "./use-metabot-embedding-aware-enabled";export { useMetabotAgent } from "./use-metabot-agent";export { useMetabotAgentsManager } from "./use-metabot-agents-manager";diff --git a/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts b/frontend/src/metabase/metabot/hooks/use-is-ask-page.tsnew file mode 100644index 00000000000..8a624413f45--- /dev/null+++ b/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts@@ -0,0 +1,8 @@+import { useSelector } from "metabase/redux";+import { getLocation } from "metabase/selectors/routing";+import * as Urls from "metabase/urls";++export function useIsAskPage() {+ const { pathname } = useSelector(getLocation);+ return pathname === Urls.newQuestion({ mode: "ask" });+}diff --git a/frontend/src/metabase/metabot/state/reducer-utils.ts b/frontend/src/metabase/metabot/state/reducer-utils.tsindex 9ce73820476..99e0cdf20d1 100644--- a/frontend/src/metabase/metabot/state/reducer-utils.ts+++ b/frontend/src/metabase/metabot/state/reducer-utils.ts@@ -49,6 +49,9 @@ const agentOverridesByAgentId: Partial<sql: {profileOverride: METABOT_PROFILE_OVERRIDES.SQL,},+ ask: {+ profileOverride: METABOT_PROFILE_OVERRIDES.NLQ,+ },};export const createConversation = (@@ -156,6 +159,7 @@ export const getMetabotInitialState = (): MetabotState => {conversations: {omnibot: createConversation("omnibot"),sql: createConversation("sql"),+ ask: createConversation("ask"),},reactions: {navigateToPath: null,diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.tsindex 7af33aec29c..a934840f953 100644--- a/frontend/src/metabase/metabot/state/types.ts+++ b/frontend/src/metabase/metabot/state/types.ts@@ -125,7 +125,7 @@ export interface MetabotConverstationState {};}-export const fixedMetabotAgentIds = ["omnibot", "sql"] as const;+export const fixedMetabotAgentIds = ["omnibot", "sql", "ask"] as const;type FixedMetabotAgentId = (typeof fixedMetabotAgentIds)[number];export type MetabotAgentId = FixedMetabotAgentId | `test_${number}`;diff --git a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts b/frontend/src/metabase/metabot/tests/reducer.unit.spec.tsindex 5115f45feae..fc8b9a5c0df 100644--- a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts+++ b/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts@@ -6,11 +6,13 @@ import {activateSuggestedTransform,addSuggestedTransform,deactivateSuggestedTransform,+ metabotActions,metabotReducer,} from "metabase/metabot/state";import type { MetabotSuggestedTransform } from "metabase-types/api";import { createMockTransform } from "metabase-types/api/mocks/transform";+import { METABOT_PROFILE_OVERRIDES } from "../constants";import {createConversation,getMetabotInitialState,@@ -235,6 +237,24 @@ describe("metabot reducer", () => {});});+ describe("the full-page `ask` conversation", () => {+ it("exists in the initial state with the nlq profile", () => {+ const state = getMetabotInitialState();+ expect(state.conversations.ask).toBeDefined();+ expect(state.conversations.ask?.profileOverride).toBe(+ METABOT_PROFILE_OVERRIDES.NLQ,+ );+ });++ it("can be reset independently and keeps the nlq profile", () => {+ 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);+ });+ });+describe("getRequestConversation", () => {it("should return undefined if no matching convo", () => {const state = createDraft(getMetabotInitialState());diff --git a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsxindex 9df03febee4..540ce66b43a 100644--- a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx@@ -11,6 +11,7 @@ import * as domModule from "metabase/utils/dom";import { createMockUser } from "metabase-types/api/mocks";import { Metabot } from "../components/Metabot";+import { MetabotChat } from "../components/MetabotChat";import {assertNotVisible,@@ -34,11 +35,14 @@ describe("metabot > ui", () => {await assertVisible();});- it("should warn that metabot can be inaccurate", async () => {- setup();- expect(- await screen.findByText("Metabot isn't perfect. Double-check results."),- ).toBeInTheDocument();+ it("does not render header actions unless they are provided", async () => {+ setup({+ ui: <MetabotChat config={{ agentId: "ask", suggestionModels: [] }} />,+ });++ expect(await screen.findByTestId("metabot-chat-input")).toBeInTheDocument();+ expect(screen.queryByTestId("metabot-reset-chat")).not.toBeInTheDocument();+ expect(screen.queryByTestId("metabot-close-chat")).not.toBeInTheDocument();});it("should show a setup prompt and disable chat input when metabot is not configured", async () => {