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] Updated conversation styling (#82385)
Sloan Sparger1cc6b8954eed
diff --git a/e2e/test/scenarios/metabot/metabot.cy.spec.ts b/e2e/test/scenarios/metabot/metabot.cy.spec.tsindex 5d4fb37c22e..d6b3f1df113 100644--- a/e2e/test/scenarios/metabot/metabot.cy.spec.ts+++ b/e2e/test/scenarios/metabot/metabot.cy.spec.ts@@ -44,12 +44,10 @@ describe("Metabot UI", () => {cy.findByTestId("metabot-chat-inner-messages").children().then(($children) => {- const contentHeight = Array.from($children).reduce(- (sum, child) => {- return sum + child.clientHeight;- },- 0,- );+ // span from the first child to the last so inter-message margins count+ const contentHeight =+ $children[$children.length - 1].getBoundingClientRect().bottom -+ $children[0].getBoundingClientRect().top;expect(containerHeight).not.to.equal(undefined);// we can get some subpixel differences, this isn't a big dealexpect(contentHeight).to.be.closeTo(containerHeight ?? 0, 1);diff --git a/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.tsindex 271b4e353ed..d2d722640ec 100644--- a/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts+++ b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts@@ -14,7 +14,7 @@ const cancelButton = () => cy.findByTestId("metabot-inline-sql-cancel");const errorMessage = () => cy.findByTestId("metabot-inline-sql-error");const acceptButton = () => cy.findByTestId("accept-proposed-changes-button");const rejectButton = () => cy.findByTestId("reject-proposed-changes-button");-const generatingLoader = () => cy.findByTestId("metabot-inline-sql-generating");+const generatingLoader = () => cy.findByLabelText("Stop generating");describe("Native SQL generation", () => {it("should show setup guidance when metabot is not configured", () => {diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsxindex 4c5ef899827..5207cbd8f4c 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx@@ -60,6 +60,7 @@ export function MetabotChatHistory() {{hasMessages ? (<Messagesmessages={chatMessages}+ size="md"onRetryMessage={metabot.retryMessage}onContinueMessage={metabot.submitInput}isDoingScience={metabot.isDoingScience}diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.module.css b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.module.cssindex 35c9aee8c1d..849416a9beb 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.module.css+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.module.css@@ -81,7 +81,7 @@/* Prompt suggestions */.promptSuggestionsContainer {flex-shrink: 0;- max-width: 30rem;+ max-width: 22.5rem;}.promptSuggestionButton {@@ -91,10 +91,9 @@line-height: 1.4;padding: 0.5rem 0.75rem;width: fit-content;- border-radius: 8px;- border: 1px solid var(--mb-color-border-neutral);- background-color: var(--mb-color-background_page-primary);- color: var(--mb-color-text-secondary);+ border-radius: var(--mantine-radius-sm);+ background-color: var(--mb-color-background_surface-brand-subtle);+ color: var(--mb-color-icon-primary);font-size: 0.875rem;}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 a82776eccce..79854e0462d 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@@ -109,13 +109,16 @@ export const useMetabot = (): UseMetabotResult => {() =>agent.messages.filter((m) => m.status.type === "errored")- .map(- (m) =>- (m.status.type === "errored" && m.status.display) || {- type: "message",- message: t`Something went wrong`,- },- ),+ .map((m) => {+ const display = m.status.type === "errored" && m.status.display;+ if (!display) {+ return { type: "message", message: t`Something went wrong` };+ }+ return {+ type: display.type === "aborted" ? "message" : display.type,+ message: display.message,+ };+ }),[agent.messages],);diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsxindex 0ffbf9459a7..0eb5f4f28ea 100644--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx@@ -199,6 +199,7 @@ export function ConversationDetailPage() {<Card withBorder shadow="none" p="xxl"><Messagesmessages={messages}+ size="md"getExtraActions={getExtraActions}isDoingScience={false}debug@@ -301,6 +302,7 @@ function FeedbackCard({{agentResponse && (<AgentMessagemessage={agentResponse}+ size="md"debug={false}readonlyhideActionsdiff --git a/frontend/src/metabase/common/components/Link/Link.tsx b/frontend/src/metabase/common/components/Link/Link.tsxindex 6e85a47a07d..4df320c6c16 100644--- a/frontend/src/metabase/common/components/Link/Link.tsx+++ b/frontend/src/metabase/common/components/Link/Link.tsx@@ -14,6 +14,7 @@ export const Link = ({tooltip,variant,className,+ tabIndex,...props}: LinkProps): JSX.Element => {const styleClassName = cx(S.link, {@@ -35,7 +36,7 @@ export const Link = ({className={linkClassName}to={to}disabled={disabled}- tabIndex={disabled ? -1 : undefined}+ tabIndex={disabled ? -1 : tabIndex}aria-disabled={disabled}>{children}diff --git a/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx b/frontend/src/metabase/common/components/Link/Link.unit.spec.tsxindex 9ec8b5e9b5e..29b57824662 100644--- a/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx@@ -48,6 +48,23 @@ const tree = ();describe("Link", () => {+ it("skips links with tabIndex -1 during keyboard navigation", async () => {+ render(+ <>+ <input aria-label="Prompt" />+ <Link to="/" tabIndex={-1}>+ Mention+ </Link>+ <button>Send</button>+ </>,+ );++ await userEvent.click(screen.getByRole("textbox", { name: "Prompt" }));+ await userEvent.tab();++ expect(screen.getByRole("button", { name: "Send" })).toHaveFocus();+ });+it("should render correctly", () => {render(<Link to="/">Home</Link>);diff --git a/frontend/src/metabase/common/components/MetadataInfo/Popover/Popover.tsx b/frontend/src/metabase/common/components/MetadataInfo/Popover/Popover.tsxindex 85d47084b31..1455c465107 100644--- a/frontend/src/metabase/common/components/MetadataInfo/Popover/Popover.tsx+++ b/frontend/src/metabase/common/components/MetadataInfo/Popover/Popover.tsx@@ -22,9 +22,15 @@ const POPOVER_CLOSE_DELAY = POPOVER_FAST_OPEN_DELAY + 30;import { Dropdown, WidthBound } from "./Popover.styled";+const DEFAULT_MIDDLEWARES: HoverCardProps["middlewares"] = {+ size: true,+ shift: true,+ flip: false,+};+export type PopoverProps = Pick<HoverCardProps,- "children" | "position" | "disabled"+ "children" | "position" | "disabled" | "radius" | "middlewares" | "offset"> & {width?: number;content: ReactNode;@@ -34,6 +40,9 @@ export type PopoverProps = Pick<export function Popover({position = "bottom-start",disabled,+ radius,+ offset,+ middlewares = DEFAULT_MIDDLEWARES,content,openDelay = POPOVER_SLOW_OPEN_DELAY,width,@@ -57,15 +66,13 @@ export function Popover({<HoverCardposition={position}disabled={disabled}+ radius={radius}+ offset={offset}openDelay={group.shouldDelay ? openDelay : POPOVER_FAST_OPEN_DELAY}closeDelay={POPOVER_CLOSE_DELAY}onOpen={handleOpen}onClose={handleClose}- middlewares={{- size: true,- shift: true,- flip: false,- }}+ middlewares={middlewares}><HoverCard.Target>{children}</HoverCard.Target><Dropdowndiff --git a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsxindex a3e1fe942d2..cb749bf5af6 100644--- a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx@@ -288,6 +288,7 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {><Messagesmessages={messages}+ size="md"onRetryMessage={(id) =>retryMessage(id, { profile: "explorations" })}diff --git a/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.module.css b/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.module.cssindex c000381f256..970a8e9a609 100644--- a/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.module.css+++ b/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.module.css@@ -1,3 +1,25 @@+.page {+ position: relative;+ background-color: var(--mb-color-background-primary);+ background-image: url("../../../metabot/components/MetabotAsk/metabot-ask-background.svg");+ background-position: right bottom;+ background-repeat: no-repeat;+ background-size: auto 17.875rem;++ &::before {+ position: absolute;+ right: 90rem;+ bottom: 0;+ width: 90rem;+ height: 17.875rem;+ background: url("../../../metabot/components/MetabotAsk/metabot-ask-background.svg")+ right bottom / auto 17.875rem no-repeat;+ content: "";+ pointer-events: none;+ transform: scaleX(-1);+ }+}+.inputContainer {:global(.ProseMirror) {min-height: 7rem;diff --git a/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.tsx b/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.tsxindex 3f5f13e5ea4..6066e3b6211 100644--- a/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationEntry/NewExplorationEntry.tsx@@ -83,7 +83,7 @@ export function NewExplorationEntry({ selection }: NewExplorationEntryProps) {}, [prompt, submitInput, goToPlanPage]);return (- <Stack h="100%" bg="background-primary" align="center" p="2rem">+ <Stack h="100%" align="center" p="2rem" className={S.page}><Stack w="100%" maw="42rem" align="flex-start" gap="xl" mih={0}>{hasNlqAccess && (<Buttondiff --git a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.module.css b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.module.cssindex 346899a2c92..547af3e4f5a 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.module.css+++ b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.module.css@@ -8,9 +8,15 @@}.aiMarkdown {- line-height: 1.5;+ font-size: 0.875rem;+ line-height: 1.5rem;min-width: 0;max-width: 100%;++ .large & {+ font-size: 1rem;+ line-height: 1.75rem;+ }}.aiMarkdown > :last-child {@@ -125,7 +131,8 @@background: var(--mb-color-background_surface-secondary);color: var(--mb-color-text-primary);padding: 0.125rem 0.375rem;- border-color: var(--mb-color-border-neutral-strong);+ border-color: var(--mb-color-border-neutral-subtle);+ border-radius: 6px;}.aiMarkdown pre code {@@ -151,11 +158,11 @@.aiMarkdown li {margin-bottom: 0.5rem;- line-height: 1.5;+ line-height: inherit;}.aiMarkdown li p {- line-height: 1.5;+ line-height: inherit;}.aiMarkdown li > ul,@@ -163,6 +170,11 @@margin-top: 0.5rem;}+.link {+ text-decoration: underline dotted;+ text-underline-offset: 0.125rem;+}+.smartLink {color: var(--mb-color-core-brand);font-weight: 700;@@ -172,10 +184,15 @@}.smartLinkInner {- border-bottom: 1px solid var(--mb-color-border-brand);+ text-decoration: underline dotted;+ text-underline-offset: 0.125rem;}.icon {margin-bottom: -0.125rem;margin-right: 0.25rem;}++.large [data-smart-link="token"] {+ padding-inline: 0.375rem;+}diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.tsxindex 25433be8b5c..123c9f8d7e7 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.tsx+++ b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.tsx@@ -9,17 +9,23 @@ import {} from "react";import { t } from "ttag";+import { mbProtocolModelToSuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";import { ActionIcon, CopyButton, Icon, Tooltip } from "metabase/ui";import { parseMetabaseProtocolLink } from "metabase/urls";import S from "./AIMarkdown.module.css";import { StreamingMarkdown } from "./StreamingMarkdown";import { InternalLink } from "./components/InternalLink";-import { MarkdownSmartLink } from "./components/MarkdownSmartLink";+import {+ MarkdownSmartLink,+ type MarkdownSmartLinkTarget,+} from "./components/MarkdownSmartLink";+import { parseEntityPath } from "./parseEntityPath";type AIMarkdownProps = {children: string;className?: string;+ size?: "md" | "lg";isStreaming?: boolean;onInternalLinkClick?: (link: string) => void;singleNewlinesAreParagraphs?: boolean;@@ -74,6 +80,27 @@ const MarkdownCodeBlock = ({);};+const parseEntityLink = (+ href: string | undefined,+): MarkdownSmartLinkTarget | undefined => {+ if (!href) {+ return undefined;+ }++ const protocolLink = parseMetabaseProtocolLink(href);+ if (protocolLink) {+ return protocolLink.model === "chart"+ ? protocolLink+ : {+ id: protocolLink.id,+ model: mbProtocolModelToSuggestionModel(protocolLink.model),+ };+ }++ const path = parseEntityPath(href);+ return path && { ...path, href };+};+const getComponents = ({onInternalLinkClick,}: Pick<AIMarkdownProps, "onInternalLinkClick">) => ({@@ -88,20 +115,24 @@ const getComponents = ({node?: any;[key: string]: any;}) => {- const parsed = parseMetabaseProtocolLink(node.properties.href);- if (parsed) {+ const entity = parseEntityLink(node.properties.href);+ if (entity) {return (<MarkdownSmartLinkonInternalLinkClick={onInternalLinkClick}name={String(node.children?.[0]?.value ?? "")}- {...parsed}+ {...entity}/>);}if (href?.startsWith("/")) {return (- <InternalLink onInternalLinkClick={onInternalLinkClick} href={href}>+ <InternalLink+ onInternalLinkClick={onInternalLinkClick}+ href={href}+ className={S.link}+ >{children}</InternalLink>);@@ -109,7 +140,13 @@ const getComponents = ({// For external links, set target and rel explicitlyreturn (- <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ {...rest}+ className={S.link}+ >{children}</a>);@@ -127,6 +164,7 @@ const getComponents = ({export const AIMarkdown = memo(({className,+ size = "md",onInternalLinkClick,children,isStreaming = false,@@ -142,7 +180,9 @@ export const AIMarkdown = memo(: children;return (- <div className={cx(S.aiMarkdownRoot, className)}>+ <div+ className={cx(S.aiMarkdownRoot, size === "lg" && S.large, className)}+ ><StreamingMarkdownblockClassName={S.aiMarkdown}components={components}diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsxindex 659d6daf461..6bafaa790c2 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx@@ -1,14 +1,24 @@-import { screen, waitFor } from "@testing-library/react";+import { screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";import { assocIn } from "icepick";import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupCardEndpoints,+ setupLibraryEndpoints,+ setupTableEndpoints,+} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";import { renderWithProviders } from "__support__/ui";import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";-import { createMockCard } from "metabase-types/api/mocks";+import {+ createMockCard,+ createMockCollection,+ createMockField,+ createMockTable,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";import { AIMarkdown } from "./AIMarkdown";@@ -25,11 +35,34 @@ const setup = ({ conversationCharts }: { conversationCharts?: Record<string, unknown> } = {},) => {setupEnterprisePlugins();- const settings = mockSettings({ "site-url": "http://localhost:3000" });+ const settings = mockSettings({+ "site-url": "http://localhost:3000",+ "token-features": createMockTokenFeatures({ library: true }),+ });- fetchMock.get(- "path:/api/card/123",- createMockCard({ id: 123, name: "Test Question" }),+ setupLibraryEndpoints(true);+ setupCardEndpoints(createMockCard({ id: 123, name: "Test Question" }));+ setupCardEndpoints(+ createMockCard({+ id: 456,+ name: "ARR",+ type: "metric",+ collection: createMockCollection({ type: "library-metrics" }),+ }),+ );+ setupTableEndpoints(+ createMockTable({+ id: 5,+ display_name: "Orders",+ description: "Confirmed orders",+ is_published: true,+ collection: createMockCollection({+ id: 10,+ name: "Data",+ type: "library-data",+ }),+ fields: [createMockField({ id: 1 }), createMockField({ id: 2 })],+ }),);const metabot = conversationCharts@@ -62,32 +95,69 @@ const countElements = (container: HTMLElement, selector: string) =>container.querySelectorAll(selector).length;/* eslint-enable testing-library/no-node-access */+const findSmartLink = async (kind: string) => {+ const link = await screen.findByTestId("smart-link");+ await waitFor(() => expect(link).toHaveAttribute("data-smart-link", kind));+ return link;+};+describe("AIMarkdown", () => {beforeEach(() => {jest.mocked(navigator.clipboard.writeText).mockClear();});- it("should render internal links for Metabase protocol links", async () => {- setup({ children: "[My Question](metabase://question/123)" });+ it.each([+ {+ href: "metabase://question/123",+ kind: "link",+ resolvedHref: "/question/123-test-question",+ },+ {+ href: "metabase://metric/456",+ kind: "token",+ resolvedHref: "/metric/456",+ },+ { href: "/table/5", kind: "token", resolvedHref: "/table/5-orders" },+ ])("renders $href as a smart $kind", async ({ href, kind, resolvedHref }) => {+ setup({ children: `See [Name](${href})` });++ const link = await findSmartLink(kind);+ expect(link).toHaveAttribute("href", resolvedHref);+ });- // Wait for the component to render- const link = await screen.findByText("My Question");- expect(link).toBeInTheDocument();+ it("should render other internal links unchanged", async () => {+ setup({ children: "See [Settings](/admin/settings)" });- // Verify it's rendered as a smart link by checking for the icon- expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();+ const link = await screen.findByRole("link", { name: "Settings" });+ expect(link).toHaveAttribute("href", "/admin/settings");+ expect(screen.queryByTestId("smart-link")).not.toBeInTheDocument();});- it("should render a metric mention as a smart link to the metric", async () => {- fetchMock.get(- "path:/api/card/456",- createMockCard({ id: 456, name: "Revenue", type: "metric" }),- );- setup({ children: "[Revenue](metabase://metric/456)" });+ it("shows a hover card with the entity details for a Library token", async () => {+ setup({ children: "[Orders](/table/5)" });+ await userEvent.hover(await findSmartLink("token"));++ const card = await screen.findByTestId("metabot-hover-card");+ expect(card).toHaveTextContent("Table");+ expect(card).toHaveTextContent("Orders");+ expect(card).toHaveTextContent("Confirmed orders");+ expect(await within(card).findByText("2 fields")).toBeInTheDocument();expect(- await screen.findByRole("link", { name: /Revenue/ }),- ).toHaveAttribute("href", "/metric/456");+ await within(card).findByRole("link", { name: "Library" }),+ ).toHaveAttribute("href", "/collection/6464-library");+ expect(within(card).getByRole("link", { name: "Data" })).toHaveAttribute(+ "href",+ "/collection/10-data",+ );+ });++ it("does not show a hover card for a plain link", async () => {+ setup({ children: "[My Question](metabase://question/123)" });++ await userEvent.hover(await findSmartLink("link"));++ expect(screen.queryByTestId("metabot-hover-card")).not.toBeInTheDocument();});it("should render a generated-chart mention as a smart link chip", async () => {diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsxindex d9813d0111e..0b0eb42d8cc 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx+++ b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx@@ -1,67 +1,60 @@import type { ComponentProps } from "react";-import { match } from "ts-pattern";import { EntityIcon } from "metabase/common/components/EntityIcon";import { useGetIcon } from "metabase/hooks/use-icon";+import { MetabotHoverCard } from "metabase/metabot/components/MetabotHoverCard";import { getConversationChart } from "metabase/metabot/state";import { useSelector } from "metabase/redux";-import { useEntityData } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data";-import { entityToUrlableModel } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";+import { EntitySmartLink } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink";import {- type MetabaseProtocolEntityModel,- type ParsedMetabaseProtocolLink,- conversationChartUrl,- modelToUrl,-} from "metabase/urls";+ type SmartLinkEntityRef,+ useSmartLinkEntity,+} from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity";+import { conversationChartUrl } from "metabase/urls";import S from "../AIMarkdown.module.css";import { InternalLink } from "./InternalLink";+export type MarkdownSmartLinkTarget =+ | (SmartLinkEntityRef & { href?: string })+ | { id: string; model: "chart" };+type MarkdownSmartLinkProps = {onInternalLinkClick?: (href: string) => void;name: string;-} & ParsedMetabaseProtocolLink;+} & MarkdownSmartLinkTarget;export const MarkdownSmartLink = (props: MarkdownSmartLinkProps) =>props.model === "chart" ? (<ChartSmartLink {...props} />) : (- <EntitySmartLink {...props} />+ <EntityMention {...props} />);-const EntitySmartLink = ({+const EntityMention = ({onInternalLinkClick,id,name,model,-}: {+ href,+}: SmartLinkEntityRef & {onInternalLinkClick?: (href: string) => void;- id: number;name: string;- model: MetabaseProtocolEntityModel;+ href?: string;}) => {- const getIcon = useGetIcon();- const entityModel = match(model)- .with("model", () => "dataset" as const)- .with("question", () => "card" as const)- .otherwise((x) => x);- const icon = getIcon({ model: entityModel });-- const { entity, isLoading, error } = useEntityData(id, entityModel);-- const entityUrl =- !isLoading && !error && entity- ? (modelToUrl(entityToUrlableModel(entity, entityModel)) ?? "")- : ""; // fallback to linking to nothing+ const { libraryEntity } = useSmartLinkEntity({ id, model, href });return (- <SmartLinkChip- onInternalLinkClick={onInternalLinkClick}- href={entityUrl}- icon={icon}- name={name}- />+ <MetabotHoverCard entity={libraryEntity}>+ <EntitySmartLink+ id={id}+ model={model}+ name={name}+ href={href}+ onNavigate={onInternalLinkClick}+ />+ </MetabotHoverCard>);};diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.ts b/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.tsnew file mode 100644index 00000000000..50e4a943d60--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.ts@@ -0,0 +1,30 @@+import type { SmartLinkEntityRef } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity";+import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";++const ENTITY_PATH_PATTERNS: { pattern: RegExp; model: SuggestionModel }[] = [+ { pattern: /^\/question\/(\d+)(?:[-/?#]|$)/, model: "card" },+ { pattern: /^\/model\/(\d+)(?:[-/?#]|$)/, model: "dataset" },+ { pattern: /^\/metric\/(\d+)(?:[-/?#]|$)/, model: "metric" },+ { pattern: /^\/dashboard\/(\d+)(?:[-/?#]|$)/, model: "dashboard" },+ { pattern: /^\/document\/(\d+)(?:[-/?#]|$)/, model: "document" },+ { pattern: /^\/table\/(\d+)(?:[-/?#]|$)/, model: "table" },+ {+ pattern:+ /^\/data-studio\/library\/tables\/\d+\/measures\/(\d+)(?:[-/?#]|$)/,+ model: "measure",+ },+ {+ pattern: /^\/question#\?db=\d+&table=\d+&segment=(\d+)$/,+ model: "segment",+ },+];++export function parseEntityPath(href: string): SmartLinkEntityRef | undefined {+ for (const { pattern, model } of ENTITY_PATH_PATTERNS) {+ const match = href.match(pattern);+ if (match) {+ return { id: parseInt(match[1], 10), model };+ }+ }+ return undefined;+}diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.unit.spec.ts b/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.unit.spec.tsnew file mode 100644index 00000000000..d17a3e6baa6--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIMarkdown/parseEntityPath.unit.spec.ts@@ -0,0 +1,29 @@+import { parseEntityPath } from "./parseEntityPath";++describe("parseEntityPath", () => {+ it.each([+ ["/question/12", { id: 12, model: "card" }],+ ["/question/12-orders", { id: 12, model: "card" }],+ ["/model/3", { id: 3, model: "dataset" }],+ ["/metric/7", { id: 7, model: "metric" }],+ ["/dashboard/9", { id: 9, model: "dashboard" }],+ ["/document/4", { id: 4, model: "document" }],+ ["/table/5", { id: 5, model: "table" }],+ ["/table/5-orders", { id: 5, model: "table" }],+ ["/data-studio/library/tables/5/measures/8", { id: 8, model: "measure" }],+ ["/question#?db=1&table=5&segment=6", { id: 6, model: "segment" }],+ ])("parses %s", (href, expected) => {+ expect(parseEntityPath(href)).toEqual(expected);+ });++ it.each([+ "/question#?db=1&table=5",+ "/question#eyJ",+ "/browse/databases/1",+ "/collection/3",+ "https://example.com/table/5",+ "/tables/5",+ ])("returns undefined for %s", (href) => {+ expect(parseEntityPath(href)).toBeUndefined();+ });+});diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.cssindex c4cb8972bae..65d792aef66 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.module.css@@ -1,18 +1,3 @@.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_page-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 ef91f12abb7..e27243ace08 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.tsx@@ -76,10 +76,10 @@ export const MetabotAsk = () => {</>) : (<Box pos="relative" h="100%" w="100%">- <Box className={S.topFade} /><MetabotChatconversationId={conversationId}agentId="ask"+ size="lg"onNewConversation={() =>navigate(Urls.newQuestion({ mode: "ask" }))}diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.css b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.cssindex 0c693471fe8..5d7d6eb9fff 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.css+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.module.css@@ -2,24 +2,43 @@display: flex;flex-direction: column;align-items: center;- height: 100%;+ flex: 1;+ min-height: 0;width: 100%;background: var(--mb-color-background-primary);+ background-image: url("./metabot-ask-background.svg");+ background-position: right bottom;+ background-repeat: no-repeat;+ background-size: auto 17.875rem;position: relative;padding: 2rem;gap: 1.5rem;++ &::before {+ position: absolute;+ right: 90rem;+ bottom: 0;+ width: 90rem;+ height: 17.875rem;+ background: url("./metabot-ask-background.svg") right bottom / auto+ 17.875rem no-repeat;+ content: "";+ pointer-events: none;+ transform: scaleX(-1);+ }}.inputWrapper {width: 100%;max-width: 42rem;+ padding-bottom: 4rem;}.inputContainer {display: flex;flex-direction: column;padding: 0.5rem 1rem 1rem;- border-radius: 0.75rem;+ border-radius: var(--mantine-radius-sm);box-shadow:0 0 0 1px var(--mb-color-border-neutral),0 4px 24px rgba(0, 0, 0, 0.08);@@ -47,6 +66,7 @@.sendButton {color: var(--mb-color-background_page-primary);+ border-radius: var(--mantine-radius-xs);&:disabled,&:disabled:hover {@@ -60,27 +80,55 @@.promptSuggestionsContainer {display: flex;flex-direction: column;- align-items: flex-start;- gap: 0.25rem;+ align-items: stretch;+ gap: 0;width: 100%;min-height: 10.75rem;+ background: var(--mb-color-background-primary);+ border-radius: var(--mantine-radius-sm);+ box-shadow: var(--mantine-shadow-xs);}.promptSuggestion {- padding: 0.5rem 0.75rem;+ width: 100%;+ padding: 1rem;font-size: 0.875rem;color: var(--mb-color-text-secondary);cursor: pointer;- border-radius: 0.5rem;+ border: 1px solid var(--mb-color-border-neutral-subtle);+ border-bottom-color: transparent;+ border-radius: 0;opacity: 0;animation: fade-in 300ms ease forwards;transition:background 150ms ease,color 150ms ease;+ &:first-child {+ border-radius: var(--mantine-radius-sm) var(--mantine-radius-sm) 0 0;+ }++ &:not(:first-child) {+ margin-top: -1px;+ }++ &:last-child {+ border-radius: 0 0 var(--mantine-radius-sm) var(--mantine-radius-sm);+ border-bottom-color: var(--mb-color-border-neutral-subtle);+ }++ &:only-child {+ border-radius: var(--mantine-radius-sm);+ }+&:hover {- background: var(--mb-color-background_page-secondary);+ background: var(--mb-color-background_surface-primary-hover);color: var(--mb-color-text-primary);+ border-bottom-color: var(--mb-color-border-neutral-subtle);+ }++ &:hover + & {+ border-top-color: transparent;}}diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsxindex 2fd473e849b..3969696f51b 100644--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotGreeting.tsx@@ -68,6 +68,7 @@ export const MetabotGreeting = ({{ skip: !canUseNlq },);const suggestedPrompts = suggestedPromptsReq.currentData?.prompts;+ const showSuggestions = canUseNlq && suggestedPrompts?.length !== 0;const handleSubmit = () => metabot.submitInput(metabot.prompt);const inputDisabled =@@ -106,7 +107,6 @@ export const MetabotGreeting = ({value={metabot.prompt}autoFocusdisabled={metabot.isDoingScience}- placeholder={t`Ask about your data, and type @ to mention an item`}onChange={metabot.setPrompt}onSubmit={handleSubmit}onStop={metabot.cancelRequest}@@ -131,23 +131,37 @@ export const MetabotGreeting = ({</Box></Paper>- <Box- className={S.promptSuggestionsContainer}- data-testid="metabot-prompt-suggestions"- >- {canUseNlq- ? suggestedPrompts?.map(({ prompt }, index) => (+ {showSuggestions && (+ <Stack gap="md">+ <Text fz="xs" c="text-secondary" mt="1.5rem">+ {t`Suggestions`}+ </Text>+ <Box+ className={S.promptSuggestionsContainer}+ data-testid="metabot-prompt-suggestions"+ >+ {suggestedPrompts?.map(({ prompt }, index) => (<UnstyledButtonkey={index}className={S.promptSuggestion}style={{ animationDelay: `${index * 75}ms` }}onClick={() => metabot.submitInput(prompt)}>- <Text>{prompt}</Text>+ <Flex align="flex-start" gap="sm">+ <Icon+ name="bolt"+ size={16}+ c="icon-brand"+ flex="0 0 auto"+ style={{ marginTop: "4px" }}+ />+ <Text>{prompt}</Text>+ </Flex></UnstyledButton>- ))- : null}- </Box>+ ))}+ </Box>+ </Stack>+ )}</Stack><AIProviderConfigurationModalopened={isAiProviderConfigurationModalOpen}diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/metabot-ask-background.svg b/frontend/src/metabase/metabot/components/MetabotAsk/metabot-ask-background.svgnew file mode 100644index 00000000000..c578e9007b4--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAsk/metabot-ask-background.svg@@ -0,0 +1,51 @@+<svg width="1440" height="286" viewBox="0 0 1440 286" fill="none" xmlns="http://www.w3.org/2000/svg">+ <g clip-path="url(#clip)">+ <path d="m1152.36 15.52 97.24 64-34.4.68-62.84-64.68Z" fill="#509EE3" fill-opacity=".12" stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M1022.59 130.6c-4.58 0-9.02 1.56-12.59 4.42l-11.36 9.08a20.15 20.15 0 0 1-12.59 4.42H805.78c-3.98 0-7.87 1.18-11.18 3.39l-35.24 23.49h657.76l-44.21-44.8h-350.32Z" fill="#509EE3" fill-opacity=".12"/>+ <path d="m690.4 175.4 50.35-33.56a28.8 28.8 0 0 1 15.97-4.84H949.1c6.54 0 12.88-2.23 17.99-6.31l16.22-12.98a28.8 28.8 0 0 1 17.99-6.31h333.1" stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="m888.8 137 55.79-50.21a28.8 28.8 0 0 1 19.26-7.39h289.26c7.97 0 15.58 3.3 21.03 9.12l21.42 22.88h46.36c7.7 0 15.08 3.09 20.49 8.57l55.14 55.86" stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M1440 175H-225" stroke="#509EE3" stroke-width="1.25" stroke-linecap="round"/>+ <g fill="none" stroke="#509EE3" stroke-width="1.25">+ <circle cx="791.6" cy="129" r="4.8"/>+ <circle cx="830" cy="129" r="4.8"/>+ <circle cx="690.4" cy="174.6" r="2.4"/>+ <circle cx="888.8" cy="136.2" r="2.4"/>+ <circle cx="1215.2" cy="80.2" r="2.4"/>+ <circle cx="1295.2" cy="112.2" r="2.4"/>+ </g>+ <g stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">+ <path d="M791.6 133.8v3.2M830 133.8v3.2"/>+ <path d="M1084.8 229.8s-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2"/>+ <path d="M618.4 239.4s-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2"/>+ <path d="M768.8 217s-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2"/>+ <path d="M1267.2 212.2s-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2"/>+ </g>+ <g stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">+ <g fill="none">+ <path d="M1074.4 169h12.8l-6.4-25.6-6.4 25.6ZM1042.4 169h12.8l-6.4-25.6-6.4 25.6ZM1010.4 169h12.8l-6.4-25.6-6.4 25.6Z"/>+ <circle cx="933.6" cy="156.2" r="12.8"/>+ <circle cx="1178.4" cy="157" r="12.8"/>+ <circle cx="1245.6" cy="141" r="22.4"/>+ </g>+ <path d="M1080.8 162.6v12.8M1048.8 162.6v12.8M1016.8 162.6v12.8M933.6 162.6v12.8M1178.4 163.4v12.8M1245.6 131.4v44.8M1245.6 150.6l-12.8-12.8"/>+ <path d="m1101.16 79.52-19.2-.01-19.2-38.39 38.4 38.4Z" fill="#509EE3" fill-opacity=".12"/>+ <path d="m1062.76 41.12 19.2 38.4h-57.6l38.4-38.4Z"/>+ <path d="m1152.36 15.52 64 64h-128l64-64Z" fill="none"/>+ <path d="m1049.96 76.32 3.2-12.8 3.2 12.8h-6.4ZM1006.76 76.32l3.2-12.8 3.2 12.8h-6.4ZM983.56 76.32l3.2-12.8 3.2 12.8h-6.4Z" fill="none"/>+ <path d="M1053.16 76.32v3.2M1009.96 76.32v3.2M986.76 76.32v3.2M1163.56 27.3l-4.8 4.8-6.4-6.4-6.4 6.4-4.8-4.8"/>+ </g>+ <g stroke="#509EE3" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">+ <path d="m887.64 193.13 19.2 51.2h-57.6l38.4-51.2Z" fill="none"/>+ <path d="m887.64 193.13-25.6 51.2h-12.8l38.4-51.2Z" fill="#509EE3" fill-opacity=".12"/>+ <path d="M887.64 193.13v57.6"/>+ <path d="M945.25 253.93s-4.3 3.2-9.6 3.2-9.61-3.2-9.61-3.2-4.29 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2-4.3 3.2-9.6 3.2-9.6-3.2-9.6-3.2"/>+ <path d="M868.45 253.93s4.3 3.2 9.6 3.2 9.6-3.2 9.6-3.2 4.3 3.2 9.6 3.2c1.2 0 2.35-.17 3.41-.43l2.99-5.97h-48l6.09 6.1c3.89-.8 6.71-2.9 6.71-2.9Z" fill="none"/>+ <path d="M906.85 250.73h-54.4"/>+ </g>+ </g>+ <defs>+ <clipPath id="clip">+ <path fill="white" d="M0 0h1440v286H0z"/>+ </clipPath>+ </defs>+</svg>diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.cssindex 0ba5dc71938..892b598a1c2 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.css+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.css@@ -1,41 +1,36 @@-.sourceDataHeader {- box-sizing: border-box;- border-bottom: 1px solid var(--mb-color-border-neutral);-}--.sourceDataHeader[data-expanded="false"] {- border-bottom-color: transparent;-}+.sources [data-smart-link="link"] {+ color: var(--mb-color-text-primary);-.sourceDataHeader:focus-visible {- outline: 2px solid var(--mb-color-input-focus);- outline-offset: -2px;+ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-brand-hover);+ }}-.sourceDataRow:not(:last-child) {- border-bottom: 1px solid var(--mb-color-border-neutral);-}+.feedbackButton[data-variant="subtle"] {+ color: var(--mb-color-text-primary);-.sourceFeedbackButton {- color: var(--mb-color-text-secondary);- background-color: var(--mb-color-background_surface-primary);- border-color: var(--mb-color-border-neutral);-}+ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-primary);+ background-color: var(--mb-color-background_surface-primary-hover);+ }-.sourceFeedbackButton:hover {- color: var(--mb-color-text-primary);- background-color: var(--mb-color-background_surface-hover);+ &[data-active="true"] {+ color: var(--mb-color-text-brand);+ }}-.sourceFeedbackButton[data-active="true"] {- color: var(--mb-color-core-brand);+.feedbackList {+ overflow: hidden;}-.sourceItemLink:hover .sourceItemTitleText {- color: var(--mb-color-core-brand);-}+.feedbackRow {+ &:not(:last-child) {+ border-bottom: 1px solid var(--mb-color-border-neutral-subtle);+ }-.sourceItemLink:focus-visible {- outline: 2px solid var(--mb-color-input-focus);- outline-offset: 2px;+ &:hover {+ background-color: var(--mb-color-background_page-secondary);+ }}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsxindex 95824808ca6..b11caa1929a 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx@@ -46,6 +46,7 @@ type AgentDataPartProps = {readonly: boolean;debug: boolean;conversationId: string;+ size: "md" | "lg";};export const AgentDataPart = ({@@ -54,6 +55,7 @@ export const AgentDataPart = ({readonly,debug,conversationId,+ size,}: AgentDataPartProps) =>match(dataPart).with({ part: { type: "data-todo_list" } }, ({ part }) => (@@ -102,6 +104,7 @@ export const AgentDataPart = ({value={part.data}readonly={readonly}conversationId={conversationId}+ size={size}/><GeneratedCardTablePillsvalue={part.data}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsxindex 380150b7c7c..bf21c2e5cb6 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx@@ -1,41 +1,45 @@-import { Fragment, useMemo, useState } from "react";-import { t } from "ttag";+import { useMemo, useState } from "react";+import { P, match } from "ts-pattern";+import { msgid, ngettext, t } from "ttag";import {skipToken,useExtractSourcesQuery,- useGetCardQuery,useGetDatabaseQuery,useGetFieldTableIdsQuery,- useGetTableQuery,} from "metabase/api";import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";-import { ForwardRefLink } from "metabase/common/components/Link";+import { EntityIcon } from "metabase/common/components/EntityIcon";import { useToast } from "metabase/common/hooks";import { deserializeCardFromQuery } from "metabase/common/utils/card";+import { useGetIcon } from "metabase/hooks/use-icon";import { getMetabotId } from "metabase/metabot/state";import {getCollectionLocationLabel,- getCollectionLocationParts,- getDatabaseLocationParts,+ getDatabaseLocationLabel,} from "metabase/metabot/utils/source-location";import { useSelector } from "metabase/redux";+import { EntitySmartLink } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink";+import { useEntityData } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data";import {ActionIcon,- Collapse,+ Box,+ Button,Flex,+ Group,Icon,+ Modal,Skeleton,+ Stack,Text,Tooltip,UnstyledButton,} from "metabase/ui";-import * as Urls from "metabase/urls";+import { getName } from "metabase/utils/name";import * as Lib from "metabase-lib";import Question from "metabase-lib/v1/Question";import type {DatasetQuery,- IconName,MetabotCodeEdit,MetabotCodeEditorBufferContext,MetabotSourceFeedback,@@ -47,6 +51,8 @@ import { useSubmitMetabotSourceFeedbackMutation } from "../../api";import S from "./MetabotAgentDataPart.module.css";+type SourceRef = { id: number; model: "table" | "card" };+type DecodedQuery =| {kind: "mbql";@@ -65,6 +71,11 @@ type DecodedQuery =const uniqueNumbers = (ids: number[]) =>Array.from(new Set(ids)).sort((a, b) => a - b);+const toSourceRefs = (tableIds: number[], cardIds: number[]): SourceRef[] => [+ ...tableIds.map((id) => ({ id, model: "table" as const })),+ ...cardIds.map((id) => ({ id, model: "card" as const })),+];+type SourceFeedbackTarget = Pick<MetabotSourceFeedback,"source_id" | "source_type"@@ -98,175 +109,87 @@ const decodeQuery = (datasetQuery: DatasetQuery | undefined): DecodedQuery => {const question = Question.create({ dataset_query: datasetQuery });const query = question.query();- const tableIds = uniqueNumbers(Lib.allSourceTableIds(query));- const cardIds = uniqueNumbers(Lib.allSourceCardIds(query));- const fieldIds = uniqueNumbers(Lib.allFieldIds(query));-return {kind: "mbql",- tableIds,- cardIds,- fieldIds,+ tableIds: uniqueNumbers(Lib.allSourceTableIds(query)),+ cardIds: uniqueNumbers(Lib.allSourceCardIds(query)),+ fieldIds: uniqueNumbers(Lib.allFieldIds(query)),};} catch {return { kind: "none" };}};-const SourceItem = ({- iconName,- label,- location,- messageId,- source,- to,-}: {- iconName: IconName;- label: string;- location?: {- parts: string[];- };- messageId?: string;- source: SourceFeedbackTarget;- to: string;-}) => {- return (- <Flex- className={S.sourceDataRow}- align="center"- justify="space-between"- gap="sm"- w="100%"- mih="3.25rem"- p="0.5rem"- bg="background_page-secondary"- >- <ForwardRefLink- aria-label={label}- className={S.sourceItemLink}- style={{- display: "inline-flex",- maxWidth: "100%",- minWidth: 0,- color: "var(--mb-color-text-primary)",- textDecoration: "none",- borderRadius: "0.25rem",- }}- to={to}- href={to}- >- <Flex direction="column" miw={0} maw="100%">- <Flex gap="sm" align="center" miw={0} maw="100%">- <Icon- name={iconName}- size={12}- c="text-primary"- style={{ display: "block", flexShrink: 0 }}- aria-hidden- />- <Text- component="span"- className={S.sourceItemTitleText}- miw={0}- style={{- overflow: "hidden",- fontSize: "0.75rem",- fontWeight: 700,- lineHeight: 1.5,- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {label}- </Text>- </Flex>- {location && (- <Flex- align="center"- gap="0.25rem"- maw="100%"- miw={0}- pl="1.25rem"- c="text-secondary"- >- {location.parts.map((part, index) => (- <Fragment key={`${part}-${index}`}>- {index > 0 && (- <Icon- name="chevronright"- size={8}- c="text-secondary"- style={{ display: "block", flexShrink: 0 }}- aria-hidden- />- )}- <Text- component="span"- miw={0}- c="text-secondary"- style={{- overflow: "hidden",- fontSize: "0.75rem",- lineHeight: 1.5,- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {part}- </Text>- </Fragment>- ))}- </Flex>- )}- </Flex>- </ForwardRefLink>- {messageId && (- <SourceFeedbackButtons messageId={messageId} source={source} />- )}- </Flex>- );+type Source = {+ name: string;+ location: string;+ iconModel: "table" | "dataset" | "metric" | "card";+ feedbackTarget: SourceFeedbackTarget;};-const SourceItemSkeleton = ({ hasFeedback }: { hasFeedback?: boolean }) => {- return (- <Flex- className={S.sourceDataRow}- align="center"- justify="space-between"- gap="sm"- w="100%"- mih="3.25rem"- p="0.5rem"- bg="background_page-secondary"- aria-hidden- data-testid="metabot-source-item-skeleton"- >- <Flex direction="column" gap="0.375rem" miw={0} maw="100%">- <Flex gap="sm" align="center" miw={0} maw="100%">- <Skeleton w={12} h={12} radius="xxs" />- <Skeleton w="7rem" h="0.75rem" radius="xxs" />- </Flex>- <Flex pl="1.25rem">- <Skeleton w="10rem" h="0.75rem" radius="xxs" />- </Flex>- </Flex>- {hasFeedback && (- <Flex gap="xxs" align="center" style={{ flexShrink: 0 }}>- <Skeleton w={24} h={24} radius="xs" />- <Skeleton w={24} h={24} radius="xs" />- </Flex>- )}- </Flex>+const useSource = ({ id, model }: SourceRef) => {+ const data = useEntityData(id, model);+ const databaseId = data.model === "table" ? data.entity?.db_id : undefined;+ const { data: database } = useGetDatabaseQuery(+ databaseId != null ? { id: databaseId } : skipToken,);++ return match(data)+ .returnType<Source | undefined>()+ .with({ model: "table", entity: P.nonNullable }, ({ entity }) => ({+ name: entity.display_name,+ location: entity.collection?.name+ ? getCollectionLocationLabel(entity.collection.name)+ : getDatabaseLocationLabel({+ databaseName: database?.name ?? "",+ schema: entity.schema,+ }),+ iconModel: "table",+ feedbackTarget: { source_id: id, source_type: "table" },+ }))+ .with({ model: "card", entity: P.nonNullable }, ({ entity }) => ({+ name: entity.name,+ location: getCollectionLocationLabel(entity.collection?.name),+ iconModel: match(entity.type)+ .returnType<Source["iconModel"]>()+ .with("model", () => "dataset")+ .with("metric", () => "metric")+ .otherwise(() => "card"),+ feedbackTarget: {+ source_id: id,+ source_type: entity.type === "model" ? "model" : "card",+ },+ }))+ .otherwise(() => undefined);+};++const SourceSkeleton = () => (+ <Skeleton h="1.25rem" w="6rem" data-testid="metabot-source-item-skeleton" />+);++const SourceLink = ({ id, model }: SourceRef) => {+ const { entity, isLoading, error } = useEntityData(id, model);++ if (isLoading) {+ return <SourceSkeleton />;+ }+ if (error || !entity) {+ return null;+ }++ return <EntitySmartLink id={id} model={model} name={getName(entity)} />;};const SourceFeedbackButtons = ({messageId,source,+ size,}: {messageId: string;source: SourceFeedbackTarget;+ size: "sm" | "md";}) => {+ const iconSize = size === "sm" ? 12 : 16;const [feedback, setFeedback] = useState<boolean | null>(null);const [sendToast] = useToast();const metabotId = useSelector(getMetabotId);@@ -295,197 +218,215 @@ const SourceFeedbackButtons = ({};return (- <Flex gap="xxs" align="center" style={{ flexShrink: 0 }}>+ <Group gap={size === "sm" ? 0 : "sm"} wrap="nowrap"><Tooltip label={t`Source is correct`}><ActionIconaria-label={t`Source is correct`}size={24}- variant="default"- className={S.sourceFeedbackButton}- data-active={feedback === true || undefined}+ variant="subtle"bdrs="xs"- style={{- boxShadow: "0 1px 3px 0 #00000012",- }}+ className={S.feedbackButton}+ data-active={feedback === true || undefined}disabled={isLoading}- onClick={() => {- void submitFeedback(true);- }}+ onClick={() => void submitFeedback(true)}>- <Icon name="thumbs_up" size={12} />+ <Icon name="thumbs_up" size={iconSize} /></ActionIcon></Tooltip><Tooltip label={t`Source is wrong`}><ActionIconaria-label={t`Source is wrong`}size={24}- variant="default"- className={S.sourceFeedbackButton}- data-active={feedback === false || undefined}+ variant="subtle"bdrs="xs"- style={{- boxShadow: "0 1px 3px 0 #00000012",- }}+ className={S.feedbackButton}+ data-active={feedback === false || undefined}disabled={isLoading}- onClick={() => {- void submitFeedback(false);- }}+ onClick={() => void submitFeedback(false)}>- <Icon name="thumbs_down" size={12} />+ <Icon name="thumbs_down" size={iconSize} /></ActionIcon></Tooltip>- </Flex>+ </Group>);};-const TableSourceRow = ({- id,+const SingleSourceFeedback = ({messageId,+ source: ref,}: {- id: number;- messageId?: string;+ messageId: string;+ source: SourceRef;}) => {- const { data: table, isLoading, isError } = useGetTableQuery({ id });- const {- data: database,- isLoading: isLoadingDatabase,- isError: isErrorDatabase,- } = useGetDatabaseQuery(- table?.db_id != null ? { id: table?.db_id } : skipToken,- );+ const source = useSource(ref);- if (isLoading || isLoadingDatabase) {- return <SourceItemSkeleton hasFeedback={Boolean(messageId)} />;- }-- if (isError || isErrorDatabase || !database || !table) {- return null;- }-- const location = table?.collection?.name- ? {- parts: getCollectionLocationParts(table.collection.name),- }- : {- parts: getDatabaseLocationParts({- databaseName: database.name,- schema: table?.schema,- }),- };-- return (- <SourceItem- iconName="table"- label={table.display_name}- location={location}+ return source ? (+ <SourceFeedbackButtonsmessageId={messageId}- source={{ source_id: id, source_type: "table" }}- to={Urls.table({ id, name: table.display_name })}+ source={source.feedbackTarget}+ size="sm"/>- );+ ) : null;};-const CardPill = ({ id, messageId }: { id: number; messageId?: string }) => {- const { data: card, isLoading, isError } = useGetCardQuery({ id });-- if (isLoading) {- return <SourceItemSkeleton hasFeedback={Boolean(messageId)} />;- }+const SourceFeedbackRow = ({+ messageId,+ source: ref,+}: {+ messageId: string;+ source: SourceRef;+}) => {+ const getIcon = useGetIcon();+ const source = useSource(ref);- if (isError || !card) {+ if (!source) {return null;}- const iconName: IconName =- card.type === "model"- ? "model"- : card.type === "metric"- ? "metric"- : "table2";-return (- <SourceItem- iconName={iconName}- label={card?.name}- location={{- parts: [getCollectionLocationLabel(card.collection?.name)],- }}- messageId={messageId}- source={{- source_id: id,- source_type: card.type === "model" ? "model" : "card",- }}- to={Urls.card(card)}- />+ <Flex+ align="center"+ justify="space-between"+ gap="sm"+ px="lg"+ py="md"+ className={S.feedbackRow}+ >+ <Stack gap="xxs" miw={0}>+ <Group gap="sm" wrap="nowrap">+ <EntityIcon+ {...getIcon({ model: source.iconModel })}+ size="0.75rem"+ c="brand"+ />+ <Text fz="md" lh="sm" fw="bold" truncate>+ {source.name}+ </Text>+ </Group>+ <Text fz="sm" lh="lg" c="text-secondary" pl="1.25rem" truncate>+ {source.location}+ </Text>+ </Stack>+ <SourceFeedbackButtons+ messageId={messageId}+ source={source.feedbackTarget}+ size="md"+ />+ </Flex>);};-const SourceDataSection = ({ children }: { children: React.ReactNode }) => {- const [isExpanded, setIsExpanded] = useState(true);-- return (- <Flex- direction="column"- miw={0}- w="100%"- bg="background_page-secondary"- style={{- borderRadius: "0.5rem",- overflow: "hidden",- border: "1px solid var(--mb-color-border-neutral)",- }}- >- <UnstyledButton- aria-label={- isExpanded ? t`Collapse data sources` : t`Expand data sources`- }- aria-expanded={isExpanded}- className={S.sourceDataHeader}- data-expanded={isExpanded}- type="button"- w="100%"- mih="1.75rem"- px="0.5rem"- bg="background_page-primary"- onClick={() => setIsExpanded((isExpanded) => !isExpanded)}+const SourceFeedbackModal = ({+ messageId,+ sources,+ onClose,+}: {+ messageId: string;+ sources: SourceRef[];+ onClose: () => void;+}) => (+ <Modal+ opened+ onClose={onClose}+ size="lg"+ title={t`Give feedback`}+ data-testid="metabot-source-feedback-modal"+ >+ <Stack gap="lg">+ <Stack+ gap={0}+ bdrs="sm"+ bd="1px solid var(--mb-color-border-neutral)"+ className={S.feedbackList}>- <Flex align="center" justify="space-between" w="100%">- <Flex gap="sm" align="center" miw={0}>- <Icon name="database" size={12} c="text-secondary" aria-hidden />- <Text- component="span"- miw={0}- c="text-secondary"- fz="0.75rem"- lh="0.75rem"- style={{- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {t`Data sources used`}- </Text>- </Flex>- <Icon- name={isExpanded ? "chevronup" : "chevrondown"}- size={12}- c="text-secondary"- style={{ flexShrink: 0 }}- aria-hidden+ {sources.map((source) => (+ <SourceFeedbackRow+ key={`${source.model}-${source.id}`}+ messageId={messageId}+ source={source}/>- </Flex>- </UnstyledButton>- <Collapse in={isExpanded} mah="11rem" style={{ overflow: "auto" }}>- <Flex direction="column" w="100%">- {children}- </Flex>- </Collapse>- </Flex>+ ))}+ </Stack>+ <Group justify="flex-end">+ <Button variant="filled" onClick={onClose}>{t`Done`}</Button>+ </Group>+ </Stack>+ </Modal>+);++const SourcesSection = ({+ messageId,+ sources,+ isLoading,+}: {+ messageId?: string;+ sources: SourceRef[];+ isLoading?: boolean;+}) => {+ const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);++ if (!isLoading && sources.length === 0) {+ return null;+ }++ return (+ <Stack gap="lg" className={S.sources}>+ <Stack gap="sm">+ <Text fz="sm" lh="lg" c="text-secondary">+ {ngettext(+ msgid`Data source used`,+ `Data sources used`,+ sources.length,+ )}+ </Text>+ {isLoading ? (+ <SourceSkeleton />+ ) : (+ <Group gap="xxs" mih="1.5rem">+ {sources.map((source, index) => (+ <Group+ key={`${source.model}-${source.id}`}+ gap="xxxs"+ wrap="nowrap"+ >+ <SourceLink {...source} />+ {index < sources.length - 1 && <Text component="span">,</Text>}+ </Group>+ ))}+ {messageId && sources.length === 1 && (+ <Box ml="xxs">+ <SingleSourceFeedback+ messageId={messageId}+ source={sources[0]}+ />+ </Box>+ )}+ </Group>+ )}+ </Stack>+ {messageId && !isLoading && sources.length > 1 && (+ <UnstyledButton+ fz="sm"+ fw="bold"+ c="text-brand"+ w="fit-content"+ onClick={() => setIsFeedbackOpen(true)}+ >+ {t`Give feedback`}+ </UnstyledButton>+ )}+ {messageId && isFeedbackOpen && (+ <SourceFeedbackModal+ messageId={messageId}+ sources={sources}+ onClose={() => setIsFeedbackOpen(false)}+ />+ )}+ </Stack>);};-const MbqlSourcesRow = ({+const MbqlSources = ({tableIds,cardIds,fieldIds,@@ -496,53 +437,26 @@ const MbqlSourcesRow = ({fieldIds: number[];messageId?: string;}) => {- const {- data: fieldTableIdsResponse,- isLoading,- isError,- } = useGetFieldTableIdsQuery(+ const { data, isLoading, isError } = useGetFieldTableIdsQuery(fieldIds.length > 0 ? { field_ids: fieldIds } : skipToken,);- if (isLoading) {- const skeletonCount = Math.max(- 4,- tableIds.length + cardIds.length + fieldIds.length,- );-- return (- <SourceDataSection>- {Array.from({ length: skeletonCount }, (_, index) => (- <SourceItemSkeleton- key={`source-skeleton-${index}`}- hasFeedback={Boolean(messageId)}- />- ))}- </SourceDataSection>- );- }-if (isError) {return null;}- const allTableIds = uniqueNumbers(- tableIds.concat(fieldTableIdsResponse?.table_ids ?? []),- );+ const allTableIds = uniqueNumbers(tableIds.concat(data?.table_ids ?? []));return (- <SourceDataSection>- {allTableIds.map((id) => (- <TableSourceRow key={`t-${id}`} id={id} messageId={messageId} />- ))}- {cardIds.map((id) => (- <CardPill id={id} key={id} messageId={messageId} />- ))}- </SourceDataSection>+ <SourcesSection+ messageId={messageId}+ sources={toSourceRefs(allTableIds, cardIds)}+ isLoading={isLoading}+ />);};-const NativeSourcesRow = ({+const NativeSources = ({databaseId,messageId,sql,@@ -558,52 +472,16 @@ const NativeSourcesRow = ({sql,...(templateTags ? { template_tags: templateTags } : {}),});- const { data: database } = useGetDatabaseQuery({ id: databaseId });- const tables = data?.tables ?? [];- const cardIds = data?.card_ids ?? [];-- if (isLoading) {- return (- <SourceDataSection>- <SourceItemSkeleton hasFeedback={Boolean(messageId)} />- </SourceDataSection>- );- }-- if (tables.length === 0 && cardIds.length === 0) {- return null;- }return (- <SourceDataSection>- {tables.map((table) => {- const label = table.display_name || table.name;- const databaseName = database?.name;- const location = databaseName- ? {- parts: getDatabaseLocationParts({- databaseName,- schema: table.schema,- }),- }- : undefined;-- return (- <SourceItem- key={table.id}- iconName="table"- label={label}- location={location}- messageId={messageId}- source={{ source_id: table.id, source_type: "table" }}- to={Urls.table({ id: table.id, name: label })}- />- );- })}- {cardIds.map((id) => (- <CardPill id={id} key={`c-${id}`} messageId={messageId} />- ))}- </SourceDataSection>+ <SourcesSection+ messageId={messageId}+ sources={toSourceRefs(+ (data?.tables ?? []).map((table) => table.id),+ data?.card_ids ?? [],+ )}+ isLoading={isLoading}+ />);};@@ -622,7 +500,7 @@ const DatasetQueryTablePills = ({if (decoded.kind === "native") {return (- <NativeSourcesRow+ <NativeSourcesdatabaseId={decoded.databaseId}messageId={messageId}sql={decoded.sql}@@ -640,7 +518,7 @@ const DatasetQueryTablePills = ({}return (- <MbqlSourcesRow+ <MbqlSourcestableIds={decoded.tableIds}cardIds={decoded.cardIds}fieldIds={decoded.fieldIds}@@ -697,7 +575,7 @@ export const CodeEditTablePills = ({}return (- <NativeSourcesRow+ <NativeSourcesdatabaseId={databaseId}messageId={messageId}sql={value.value}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsxindex 72a9037b40c..b125cf86a35 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx@@ -1,7 +1,7 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";import { FIXED_METABOT_IDS } from "metabase/metabot/constants";import type {@@ -108,6 +108,7 @@ const setupNativeEndpoints = ({ delay = 0 }: { delay?: number } = {}) => {},{ delay },);+ fetchMock.get(`path:/api/table/${ORDERS_TABLE.id}`, ORDERS_TABLE);fetchMock.get("path:/api/database/1", DATABASE);};@@ -341,7 +342,7 @@ describe("MetabotAgentDataSourcePills", () => {);});- it("does not show Library in a model source path for normal collections", async () => {+ it("collects feedback for several sources via a modal", async () => {const sql = "SELECT * FROM {{#4-revenue_model}}";const templateTags: TemplateTags = {"#4-revenue_model": {@@ -353,7 +354,16 @@ describe("MetabotAgentDataSourcePills", () => {},};fetchMock.post(EXTRACT_SOURCES_ENDPOINT, {- tables: [],+ tables: [+ {+ id: ORDERS_TABLE.id,+ name: ORDERS_TABLE.name,+ schema: ORDERS_TABLE.schema,+ display_name: ORDERS_TABLE.display_name,+ description: null,+ columns: [],+ },+ ],card_ids: [4],});fetchMock.get(@@ -368,10 +378,12 @@ describe("MetabotAgentDataSourcePills", () => {}),}),);- fetchMock.get("path:/api/database/1", DATABASE);+ setupTableEndpoints(ORDERS_TABLE);+ fetchMock.post(SOURCE_FEEDBACK_ENDPOINT, 204);renderWithProviders(<GeneratedCardTablePills+ messageId="message-11"value={createNativeCard(sql, 1, templateTags)}/>,);@@ -379,8 +391,40 @@ describe("MetabotAgentDataSourcePills", () => {expect(await screen.findByRole("link", { name: "Revenue Model" }),).toBeInTheDocument();- expect(screen.getByText("Marketing & Growth")).toBeInTheDocument();- expect(screen.queryByText("Library")).not.toBeInTheDocument();+ expect(+ screen.queryByLabelText("Source is correct"),+ ).not.toBeInTheDocument();++ await userEvent.click(+ screen.getByRole("button", { name: "Give feedback" }),+ );++ const modal = await screen.findByRole("dialog");+ expect(within(modal).getByText("Marketing & Growth")).toBeInTheDocument();+ expect(within(modal).getByText(/Sample Database/)).toBeInTheDocument();+ expect(within(modal).queryByText("Library")).not.toBeInTheDocument();++ await userEvent.click(+ within(modal).getAllByRole("button", { name: "Source is wrong" })[1],+ );+ await waitFor(() =>+ expect(+ fetchMock.callHistory.calls(SOURCE_FEEDBACK_ENDPOINT, {+ body: {+ metabot_id: FIXED_METABOT_IDS.DEFAULT,+ message_id: "message-11",+ source_id: 4,+ source_type: "model",+ positive: false,+ },+ }),+ ).toHaveLength(1),+ );++ await userEvent.click(within(modal).getByRole("button", { name: "Done" }));+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );});it("shows source links without feedback buttons when message id is not provided", async () => {@@ -395,6 +439,7 @@ describe("MetabotAgentDataSourcePills", () => {const sourceLink = await screen.findByRole("link", { name: "Orders" });expect(sourceLink).toHaveAttribute("href", "/table/2-orders");+ expect(fetchMock.callHistory.calls("path:/api/database/1")).toHaveLength(0);expect(screen.queryByLabelText("Source is correct"),).not.toBeInTheDocument();diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsxindex 768fe314513..55e85da881d 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx@@ -7,6 +7,8 @@ import { AIMarkdown } from "metabase/metabot/components/AIMarkdown";import type { MetabotAgentChainOfThoughtMessage } from "metabase/metabot/state";import { Collapse, Icon, Stack, Text, UnstyledButton } from "metabase/ui";+import { MetabotResponseLoader } from "../MetabotResponseLoader";+import S from "./MetabotChainOfThought.module.css";import { MetabotToolProgress } from "./MetabotToolProgress";import { ReasoningStep } from "./ReasoningStep";@@ -34,7 +36,12 @@ export const MetabotChainOfThought = ({if (!supportsReasoning) {return <MetabotToolProgress part={part} />;}- return <ChainOfThought part={part} />;+ return (+ <>+ {!part.finished && <MetabotResponseLoader />}+ <ChainOfThought part={part} />+ </>+ );};const ChainOfThought = ({diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsxindex 90396254359..20b4cb46524 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx@@ -236,7 +236,7 @@ describe("MetabotChainOfThought", () => {expect(screen.getByText("Searched for sales data")).toBeInTheDocument();});- it("renders a metabase:// link title as a clickable entity link with an icon", async () => {+ it("renders a metabase:// link title as a clickable entity link", async () => {setup(chain({steps: [@@ -256,10 +256,10 @@ describe("MetabotChainOfThought", () => {await userEvent.click(screen.getByRole("button"));// the row reads past tense with the entity inline ("Read Orders")expect(await screen.findByText("Read")).toHaveTextContent("Read Orders");- expect(await screen.findByText("Orders")).toBeInTheDocument();- expect(- await screen.findByRole("img", { name: /dashboard icon/ }),- ).toBeInTheDocument();+ expect(await screen.findByRole("link", { name: "Orders" })).toHaveAttribute(+ "href",+ expect.stringContaining("/dashboard/123"),+ );});it("labels a settled save_entity step with a clickable Saved link", async () => {diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsxindex 4aa11452491..6b526b43b8f 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx@@ -3,7 +3,9 @@ import { match } from "ts-pattern";import Animation from "metabase/css/core/animation.module.css";import type { MetabotAgentChainOfThoughtMessage } from "metabase/metabot/state";-import { Loader, Stack } from "metabase/ui";+import { Stack } from "metabase/ui";++import { MetabotResponseLoader } from "../MetabotResponseLoader";import S from "./MetabotChainOfThought.module.css";import { ResourceGroupStep, ToolStep } from "./ToolStep";@@ -22,6 +24,7 @@ export const MetabotToolProgress = ({return (<Stack gap="0.5rem" data-testid="metabot-tool-progress">+ <MetabotResponseLoader />{buildDisplayItems(part.steps).map((item) =>match(item).with({ kind: "resourceGroup" }, ({ steps, index }) => (@@ -45,12 +48,6 @@ export const MetabotToolProgress = ({.with({ kind: "reasoning" }, () => null).exhaustive(),)}- <Loader- type="dots"- size="lg"- color="core-brand"- data-testid="metabot-response-loader"- /></Stack>);};diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/utils.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/utils.tsxindex f588ec518fb..bb3ccb3f250 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/utils.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/utils.tsx@@ -7,9 +7,10 @@ import { isEmbedding } from "metabase/embedding/config";import { MarkdownSmartLink } from "metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink";import { getToolMessage } from "metabase/metabot/constants";import type { MetabotChainStep } from "metabase/metabot/state";+import type { SmartLinkEntityRef } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity";+import { mbProtocolModelToSuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";import {METABSE_PROTOCOL_MD_LINK,- type MetabaseProtocolEntityModel,parseMetabaseProtocolMarkdownLink,} from "metabase/urls";import { isNotNull } from "metabase/utils/types";@@ -51,12 +52,7 @@ export const isHiddenTool = (name: string) => {export type TitleSegment =| { type: "text"; text: string }- | {- type: "link";- id: number;- name: string;- model: MetabaseProtocolEntityModel;- };+ | ({ type: "link"; name: string } & SmartLinkEntityRef);export const splitTitle = (title: string): TitleSegment[] => {const re = new RegExp(METABSE_PROTOCOL_MD_LINK.source, "g");@@ -70,7 +66,12 @@ export const splitTitle = (title: string): TitleSegment[] => {const parsed = parseMetabaseProtocolMarkdownLink(match[0]);segments.push(parsed- ? { type: "link", ...parsed }+ ? {+ type: "link",+ id: parsed.id,+ name: parsed.name,+ model: mbProtocolModelToSuggestionModel(parsed.model),+ }: { type: "text", text: match.groups?.name ?? match[0] },);lastIndex = start + match[0].length;diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.cssindex 7857d649270..ea9c0cd8102 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.module.css@@ -9,7 +9,7 @@.header {/* top padding is set to visually align w/ the dashboard action buttons */- padding: 1.25rem 1.5rem 1rem;+ padding: 1.25rem 1.5rem 0.5rem;display: flex;align-items: center;gap: 1rem;@@ -32,7 +32,7 @@display: flex;align-items: center;gap: 0.5rem;- border-radius: 0.5rem;+ border-radius: var(--mantine-radius-sm);box-shadow: 0 3px 6px 0 #0000000d;min-height: 3rem;border: 1px solid var(--mb-color-border-neutral);@@ -44,28 +44,67 @@.inputContainerLoading {background: var(--mb-color-background_page-secondary);++ &:focus-within {+ border-color: var(--mb-color-border-neutral);+ }}.messagesScrollArea {position: relative;flex: 1;min-height: 0;++ &::before {+ position: absolute;+ top: 0;+ right: 1rem;+ left: 1rem;+ z-index: 1;+ height: 1.5rem;+ background: linear-gradient(+ to bottom,+ var(--mb-color-background_page-primary),+ transparent 100%+ );+ content: "";+ pointer-events: none;+ }++ &::after {+ position: absolute;+ right: 1rem;+ bottom: 0;+ left: 1rem;+ height: 2rem;+ background: linear-gradient(+ to bottom,+ transparent,+ var(--mb-color-background_page-primary) 95%+ );+ content: "";+ pointer-events: none;+ }}.messagesContainer {- padding: var(--metabot-chat-messages-padding-top, 1rem) 0 1.5rem;+ padding: 1.5rem 0;height: 100%;display: flex;flex-direction: column;overflow: auto;scrollbar-gutter: stable both-edges;++ .large & {+ padding: 1.5rem 0;+ }}.messages {display: flex;flex-direction: column;width: 100%;- max-width: 48rem;+ max-width: 49.5rem;margin-inline: auto;padding-inline: 1.5rem;}@@ -75,6 +114,10 @@flex-direction: column;gap: 0.25rem;min-width: 0;++ &:empty {+ display: none;+ }}.messageContainerUser {@@ -85,30 +128,50 @@width: fit-content;}-.messageContainerUser :global(.smart-link) {- border: 1px solid var(--mb-color-border-brand);- position: relative;- bottom: -2px;+.messageUser [data-smart-link="token"] {+ background: var(--mb-color-background_surface-secondary);++ &:hover,+ &:focus-visible {+ background: var(--mb-color-background_surface-secondary-hover);+ }+}++.messageUser [data-smart-link-icon] {+ color: var(--mb-color-text-secondary);+}++.messageUser [data-smart-link="link"] {+ color: var(--mb-color-text-primary);++ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-brand-hover);+ }}.message {- font-size: 0.875rem;- line-height: 1.4 !important;min-width: 0;}.messageUser {- padding: 0.5rem 1rem;+ padding: 0.75rem 1rem;border-radius: 1rem;- background: var(--mb-color-background_page-secondary);+ background: var(--mb-color-background_surface-secondary);max-width: 100%;overflow: hidden;}.messageActions {+ margin-top: 0.5rem;+ color: var(--mb-color-icon-primary);opacity: 0;transition: all 150ms linear;min-height: 1rem;++ button:hover {+ background-color: var(--mb-color-background_surface-primary-hover);+ }}.messageContainer:hover .messageActions,@@ -142,7 +205,7 @@opacity: 1;}-.messageContainerAgent + .messageContainerAgent {+.messageContainer + .messageContainer {margin-top: var(--mantine-spacing-lg);}@@ -152,15 +215,44 @@min-height: 106px;flex-shrink: 0;width: 100%;- max-width: 48rem;+ max-width: 49.5rem;margin-inline: auto;- padding-inline: 1rem;+ padding-inline: 1.5rem;+}++.promptSuggestionsHidden {+ pointer-events: none;++ .promptSuggestionButton {+ opacity: 0;++ &:nth-child(2) {+ transition-delay: 25ms;+ }++ &:nth-child(3) {+ transition-delay: 50ms;+ }+ }}.promptSuggestionButton {display: block;+ align-self: flex-start;height: auto;text-align: start;+ line-height: 1.4;+ padding: 0.75rem;+ max-width: 22.5rem;+ transition:+ background-color 150ms ease,+ opacity 100ms ease;++ &:hover {+ background-color: var(+ --mb-color-background_surface-brand-subtle-hover+ ) !important;+ }span {text-wrap-mode: wrap;@@ -170,9 +262,9 @@.footerContainer {display: flex;flex-direction: column;- padding: 0 1rem;+ padding: 0 1.5rem;width: 100%;- max-width: 48rem;+ max-width: 37.5rem;margin-inline: auto;}@@ -187,11 +279,12 @@display: grid;grid-template-columns: 1fr auto 1fr;align-items: center;- min-height: 2rem;- padding: 0 0.25rem;+ min-height: 2.5rem;+ padding: 0.75rem 0.25rem;> :first-child {grid-column: 2;+ line-height: 1rem;}}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsxindex ec36f819a30..fd395598c2b 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx@@ -8,12 +8,21 @@ import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProvimport { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";import { MetabotLongChatNotice } from "metabase/metabot/components/MetabotChat/MetabotLongChatNotice";import { useSetting } from "metabase/settings";-import { Box, Button, Flex, Paper, Stack, Text } from "metabase/ui";+import {+ Box,+ Flex,+ Icon,+ Paper,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";import { useGetSuggestedMetabotPromptsQuery } from "../../api";import { useMetabotConversation, useUserMetabotPermissions } from "../../hooks";import type { MetabotAgentId } from "../../state";import type { MetabotChatConfig } from "../Metabot";+import { METABOT_HOVER_CARD_BOUNDARY_ATTR } from "../MetabotHoverCard";import Styles from "./MetabotChat.module.css";import { MetabotChatEditor } from "./MetabotChatEditor";@@ -39,6 +48,7 @@ export const MetabotChat = ({config = defaultConfig,className,headerActions,+ size = "md",}: {conversationId: string;agentId?: MetabotAgentId;@@ -46,6 +56,7 @@ export const MetabotChat = ({config?: MetabotChatConfig;className?: string;headerActions?: ReactNode;+ size?: "md" | "lg";}) => {const [isAiProviderConfigurationModalOpen,@@ -88,7 +99,10 @@ export const MetabotChat = ({const shouldShowHeader = headerActions || title;return (- <Box className={cx(Styles.container, className)} data-testid="metabot-chat">+ <Box+ className={cx(Styles.container, size === "lg" && Styles.large, className)}+ data-testid="metabot-chat"+ >{shouldShowHeader && (<Box className={Styles.header} data-testid="metabot-chat-header">{title && (@@ -115,6 +129,7 @@ export const MetabotChat = ({ref={scrollContainerRef}className={Styles.messagesContainer}data-testid="metabot-chat-messages"+ {...{ [METABOT_HOVER_CARD_BOUNDARY_ATTR]: "" }}>{!hasMessages && !metabot.isDoingScience && (<>@@ -147,19 +162,34 @@ export const MetabotChat = ({{isConfigured && (<Stackgap="sm"- className={Styles.promptSuggestionsContainer}+ className={cx(+ Styles.promptSuggestionsContainer,+ metabot.prompt.length > 0 && Styles.promptSuggestionsHidden,+ )}data-testid="metabot-prompt-suggestions"><>{suggestedPrompts.map(({ prompt }, index) => (- <Box key={index}>- <Button- onClick={() => metabot.submitInput(prompt)}- className={Styles.promptSuggestionButton}- >- {prompt}- </Button>- </Box>+ <UnstyledButton+ key={index}+ fz="sm"+ onClick={() => metabot.submitInput(prompt)}+ className={Styles.promptSuggestionButton}+ bg="background_surface-brand-subtle"+ bdrs="sm"+ lh="xl"+ >+ <Flex gap="sm">+ <Icon+ name="bolt"+ size={16}+ c="icon-brand"+ flex="0 0 auto"+ style={{ transform: "translateY(1px)" }}+ />+ <Box>{prompt}</Box>+ </Flex>+ </UnstyledButton>))}</></Stack>@@ -186,6 +216,7 @@ export const MetabotChat = ({debug={metabot.debugMode}agentId={agentId}conversationId={metabot.conversationId}+ size={size}/>{/* filler - height gets set via ref mutation */}<div ref={fillerRef} data-testid="metabot-message-filler" />@@ -215,7 +246,6 @@ export const MetabotChat = ({value={metabot.prompt}autoFocusisResponding={metabot.isDoingScience}- placeholder={t`How can I help? Type @ to mention items.`}onChange={metabot.setPrompt}onSubmit={() => metabot.submitInput(metabot.prompt)}onStop={metabot.cancelRequest}@@ -227,7 +257,7 @@ export const MetabotChat = ({)}</Box><Box className={Styles.footerRow}>- <Text fz="sm" c="text-secondary" ta="center">+ <Text fz="sm" c="text-disabled" ta="center">{t`${metabotName} isn't perfect. Double-check results.`}</Text>{metabot.contextWindowPercentUsage > 50 &&diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.cssindex 5cd73d848ab..1074d1b84ce 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css@@ -4,6 +4,7 @@width: 100%;height: 100%;min-height: 46px;+ gap: 0.25rem;}.contentWrapper {@@ -14,56 +15,6 @@}.button {- margin: 0 -0.25rem calc(0.5rem - 1px) 2px;- background: var(--mb-color-core-brand);- border-radius: 6px;- width: 2rem;- height: 2rem;- display: flex;- justify-content: center;- align-items: center;+ margin: 0 -0.25rem calc(0.5rem - 1px) 0;align-self: flex-end;- transition:- opacity 300ms ease,- background 150ms ease,- transform 150ms ease;-- &:hover,- &:active {- opacity: 0.7;- }-- &:active {- transform: scale(0.9);- }-}--.buttonHidden {- opacity: 0;- transition: opacity 0ms ease;- user-select: none;- cursor: default;-- &:hover,- &:active {- opacity: 0;- }-}--.buttonResponding {- border: 1px solid var(--mb-color-core-brand);- background: transparent;-}--.sendIcon {- color: var(--mb-color-background_page-primary);- width: 0.8rem;- transition: color 150ms ease;-}--.stopIcon {- color: var(--mb-color-core-brand);- width: 0.7rem;- height: 0.7rem;- transition: color 150ms ease;}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsxindex 17905c91e03..f10c501ad28 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx@@ -1,4 +1,3 @@-import cx from "classnames";import { forwardRef } from "react";import type { MetabotPromptInputRef } from "metabase/metabot";@@ -6,7 +5,8 @@ import {MetabotPromptInput,type MetabotPromptInputProps,} from "metabase/metabot/components/MetabotPromptInput";-import { Box, Icon, UnstyledButton } from "metabase/ui";+import { MetabotSendButton } from "metabase/metabot/components/MetabotSendButton";+import { Box } from "metabase/ui";import S from "./MetabotChatEditor.module.css";@@ -35,23 +35,12 @@ export const MetabotChatEditor = forwardRef<data-testid="metabot-chat-input"/></Box>- <UnstyledButton- className={cx(- S.button,- isResponding && S.buttonResponding,- props.value.length === 0 && !isResponding && S.buttonHidden,- )}+ <MetabotSendButton+ className={S.button}+ isResponding={isResponding}+ isHidden={props.value.length === 0 && !isResponding}onClick={isResponding ? props.onStop : props.onSubmit}- data-testid={- isResponding ? "metabot-stop-response" : "metabot-send-message"- }- >- {isResponding ? (- <Icon className={S.stopIcon} name="stop" />- ) : (- <Icon className={S.sendIcon} name="arrow_up" />- )}- </UnstyledButton>+ /></Box>);});diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsxindex 83e020edbf8..4d815105e94 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx@@ -32,7 +32,6 @@ import {Flex,type FlexProps,Icon,- Loader,Text,Tooltip,} from "metabase/ui";@@ -46,6 +45,7 @@ import { AgentToolCallPart } from "./MetabotAgentToolCallPart";import { MetabotChainOfThought } from "./MetabotChainOfThought";import Styles from "./MetabotChat.module.css";import { MetabotFeedbackModal } from "./MetabotFeedbackModal";+import { MetabotResponseLoader } from "./MetabotResponseLoader";const isUserVisibleDataPart = (part: MetabotDataPart): boolean =>match(part)@@ -118,11 +118,11 @@ const CopyAction = ({ text }: { text: string }) => {return (<Tooltip label={clipboard.copied ? t`Copied!` : t`Copy`}><ActionIcon- h="sm"+ size="1.5rem"data-testid="metabot-chat-message-copy"onClick={() => clipboard.copy(text)}>- <Icon name="copy" size="1rem" />+ <Icon name="copy" size="0.9rem" c="icon-primary" /></ActionIcon></Tooltip>);@@ -132,6 +132,7 @@ interface UserMessageProps extends Omit<FlexProps, "onCopy"> {message: MetabotMessage;hideActions: boolean;extraActions?: ReactNode;+ size: "md" | "lg";}export const UserMessage = ({@@ -139,6 +140,7 @@ export const UserMessage = ({className,hideActions,extraActions,+ size,...props}: UserMessageProps) => {const text = useMessageText(message);@@ -153,6 +155,7 @@ export const UserMessage = ({<AIMarkdownclassName={cx(Styles.message, Styles.messageUser)}singleNewlinesAreParagraphs+ size={size}>{text}</AIMarkdown>@@ -169,27 +172,28 @@ export const UserMessage = ({interface FeedbackButtonProps {disabled: boolean;icon: IconName;+ iconSize: string;onClick: () => void;hasBeenClicked: boolean;}const FeedbackButton = forwardRef<HTMLButtonElement, FeedbackButtonProps>(function FeedbackButton(- { disabled, icon, onClick, hasBeenClicked, ...props },+ { disabled, icon, iconSize, onClick, hasBeenClicked, ...props },ref,) {return (<ActionIcononClick={onClick}disabled={disabled}- h="sm"+ size="1.5rem"{...props}ref={ref}><Iconname={icon}- size="1rem"- c={hasBeenClicked ? "core-brand" : "currentColor"}+ size={iconSize}+ c={hasBeenClicked ? "core-brand" : "icon-primary"}/></ActionIcon>);@@ -206,6 +210,7 @@ type AgentPartProps = {supportsReasoning: boolean;onInternalLinkClick?: (link: string) => void;onToolCallSelect?: (part: MetabotDebugToolCallMessage) => void;+ size: "md" | "lg";};const AgentPart = ({@@ -218,6 +223,7 @@ const AgentPart = ({supportsReasoning,onInternalLinkClick,onToolCallSelect,+ size,}: AgentPartProps) =>match(part).with({ type: "text" }, (p) => (@@ -225,6 +231,7 @@ const AgentPart = ({className={Styles.message}onInternalLinkClick={onInternalLinkClick}isStreaming={isStreaming}+ size={size}>{p.message}</AIMarkdown>@@ -236,6 +243,7 @@ const AgentPart = ({debug={debug}readonly={readonly}conversationId={conversationId}+ size={size}/>)).with({ type: "tool_call" }, (p) => (@@ -264,6 +272,7 @@ interface AgentMessageProps extends Omit<FlexProps, "onCopy"> {onFork?: (messageId: string) => void;isForking?: boolean;onToolCallSelect?: (part: MetabotDebugToolCallMessage) => void;+ size: "md" | "lg";}type MessageActionsProps = {@@ -303,6 +312,7 @@ const MessageActions = ({<FeedbackButtondata-testid="metabot-chat-message-thumbs-up"icon="thumbs_up"+ iconSize="0.9rem"hasBeenClicked={submittedFeedback === "positive"}disabled={!!submittedFeedback}onClick={() => setFeedbackMessage({ messageId, positive: true })}@@ -312,6 +322,7 @@ const MessageActions = ({<FeedbackButtondata-testid="metabot-chat-message-thumbs-down"icon="thumbs_down"+ iconSize="0.9rem"hasBeenClicked={submittedFeedback === "negative"}disabled={!!submittedFeedback}onClick={() => setFeedbackMessage({ messageId, positive: false })}@@ -325,10 +336,10 @@ const MessageActions = ({<Tooltip key="retry" label={t`Retry`}><ActionIcononClick={onRetry}- h="sm"+ size="1.5rem"data-testid="metabot-chat-message-retry">- <Icon name="revert" size="1rem" />+ <Icon name="revert" size="0.9rem" c="icon-primary" /></ActionIcon></Tooltip>,);@@ -342,13 +353,13 @@ const MessageActions = ({actions.push(<Tooltip key="fork" label={t`Fork conversation`}><ActionIcon- h="sm"+ size="1.5rem"data-testid="metabot-chat-message-fork"loading={isForking}disabled={isForking}onClick={() => onFork(messageId)}>- <Icon name="git_branch" size="1rem" />+ <Icon name="git_branch" size="0.9rem" c="icon-primary" /></ActionIcon></Tooltip>,);@@ -383,6 +394,7 @@ export const AgentMessage = ({onFork,isForking,onToolCallSelect,+ size,...props}: AgentMessageProps) => {const messageId = message.externalId ?? "";@@ -449,6 +461,7 @@ export const AgentMessage = ({supportsReasoning={supportsReasoning}onInternalLinkClick={onInternalLinkClick}onToolCallSelect={onToolCallSelect}+ size={size}/>{index === actionsIndex && actions}</PartContainer>@@ -589,14 +602,7 @@ const MessageStatus = ({onContinue={onContinue}/>))- .with({ type: "in_progress" }, () => (- <Loader- type="dots"- size="lg"- color="core-brand"- data-testid="metabot-response-loader"- />- ))+ .with({ type: "in_progress" }, () => <MetabotResponseLoader />).exhaustive();const AbortedTurnAlert = ({@@ -700,6 +706,7 @@ export const Messages = ({getExtraActions,renderAfterMessage,onToolCallSelect,+ size,}: {messages: MetabotMessage[];onRetryMessage?: (messageId: string) => void;@@ -715,6 +722,7 @@ export const Messages = ({getExtraActions?: (messageId: string) => ReactNode;renderAfterMessage?: (message: MetabotMessage) => ReactNode;onToolCallSelect?: (message: MetabotDebugToolCallMessage) => void;+ size: "md" | "lg";}) => {const dispatch = useDispatch();const [sendToast] = useToast();@@ -807,12 +815,14 @@ export const Messages = ({onInternalLinkClick={onInternalLinkClick}supportsReasoning={supportsReasoning}onToolCallSelect={onToolCallSelect}+ size={size}/>) : (<UserMessagemessage={message}hideActions={isDoingScience && isLastMessage}extraActions={getExtraActions?.(message.id)}+ size={size}/>)}{renderAfterMessage?.(message)}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.cssindex 8f033cca032..af8c7abaf9c 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css@@ -1,12 +1,21 @@.container {border: 1px solid var(--mb-color-border-neutral);- border-radius: 0.5rem;+ border-radius: var(--mantine-radius-sm);+ padding-bottom: 0.5rem;overflow: hidden;background: var(--mb-color-background_surface-primary);++ &.large {+ padding-bottom: 1rem;+ }}.header {- padding: 0.5rem 0.75rem;+ padding: 0.5rem 1rem;++ .large & {+ padding: 1rem 1.5rem 0.5rem;+ }}.title {@@ -22,4 +31,8 @@.viz {height: 18rem;position: relative;++ .large & {+ height: 21rem;+ }}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsxindex 216865a7384..08198e529ec 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx@@ -1,4 +1,5 @@import { useClipboard, useDisclosure } from "@mantine/hooks";+import cx from "classnames";import { useMemo, useState } from "react";import { P, match } from "ts-pattern";import { t } from "ttag";@@ -51,10 +52,12 @@ export function MetabotInlineChart({value,readonly = false,conversationId,+ size,}: {value: GeneratedCard;readonly?: boolean;conversationId: string;+ size: "md" | "lg";}) {const { id: chartId, title, description, display, query } = value;const datasetQuery = query.query;@@ -128,7 +131,10 @@ export function MetabotInlineChart({const chartError = datasetError ?? requestError;return (- <Box className={S.container} data-testid="metabot-inline-chart">+ <Box+ className={cx(S.container, size === "lg" && S.large)}+ data-testid="metabot-inline-chart"+ ><Flex className={S.header} align="center" gap="sm"><AnchorclassName={S.title}@@ -136,6 +142,8 @@ export function MetabotInlineChart({to={link}target="_blank"fw="bold"+ size="md"+ lh="1rem"flex={1}miw={0}truncatediff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsxindex 6f1aa9bcff5..24b38340011 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx@@ -84,6 +84,7 @@ function setup(value={{ ...value, ...valueOverrides }}readonly={readonly}conversationId="convo-1"+ size="md"/>,);}@@ -269,6 +270,7 @@ describe("MetabotInlineChart", () => {value={value}readonly={false}conversationId="convo-1"+ size="md"/>}/>,diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.module.cssnew file mode 100644index 00000000000..01599bf3372--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.module.css@@ -0,0 +1,51 @@+.root {+ display: flex;+ align-items: center;+ height: 1.5rem;+ padding-left: 0.4375rem;+}++.dots {+ --bright: var(--mb-color-icon-primary);+ --dim: var(--mb-color-border-strong);++ width: 0.25rem;+ aspect-ratio: 1;+ border-radius: 50%;+ animation: dots 350ms infinite linear alternate;++ [data-mantine-color-scheme="dark"] & {+ --bright: rgba(255, 255, 255, 0.74);+ --dim: rgba(255, 255, 255, 0.22);+ }+}++@keyframes dots {+ 0% {+ box-shadow:+ 0.4375rem 0 var(--bright),+ -0.4375rem 0 var(--dim);+ background: var(--bright);+ }++ 33% {+ box-shadow:+ 0.4375rem 0 var(--bright),+ -0.4375rem 0 var(--dim);+ background: var(--dim);+ }++ 66% {+ box-shadow:+ 0.4375rem 0 var(--dim),+ -0.4375rem 0 var(--bright);+ background: var(--dim);+ }++ 100% {+ box-shadow:+ 0.4375rem 0 var(--dim),+ -0.4375rem 0 var(--bright);+ background: var(--bright);+ }+}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.tsxnew file mode 100644index 00000000000..7e436ee3e6f--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotResponseLoader.tsx@@ -0,0 +1,14 @@+import { t } from "ttag";++import S from "./MetabotResponseLoader.module.css";++export const MetabotResponseLoader = () => (+ <div+ className={S.root}+ role="status"+ aria-label={t`Loading`}+ data-testid="metabot-response-loader"+ >+ <div className={S.dots} />+ </div>+);diff --git a/frontend/src/metabase/metabot/components/MetabotChat/hooks.ts b/frontend/src/metabase/metabot/components/MetabotChat/hooks.tsindex be0321e0052..9e0126bf9fc 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/hooks.ts+++ b/frontend/src/metabase/metabot/components/MetabotChat/hooks.ts@@ -7,24 +7,21 @@ export function calculateFillerHeight(const scrollContent = Array.from(scrollContainerEl.children?.[0]?.children ?? [],);- const lastUserMessageIndex = scrollContent.findLastIndex(+ const lastUserMessageEl = scrollContent.findLast((el) => el.getAttribute("data-message-role") === "user",);- const currentPromptEls = scrollContent.slice(lastUserMessageIndex);- const validEls = currentPromptEls.filter((node) => node);- const nonFillerElsHeight = validEls.reduce((sum, node) => {- return node === fillerEl ? sum : sum + node.clientHeight;- }, 0);-- // when the container is scrollable, we need to factor in the top padding as well- const containerHeight = scrollContainerEl.clientHeight;+ const turnStartEl = lastUserMessageEl ?? fillerEl;+ const turnHeight =+ fillerEl.getBoundingClientRect().top -+ turnStartEl.getBoundingClientRect().top;+const style = getComputedStyle(scrollContainerEl);const paddingAdjustment =parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);- const contentHeight = containerHeight - paddingAdjustment;+ const contentHeight =+ scrollContainerEl.getBoundingClientRect().height - paddingAdjustment;- // subtract 1px to prevent a scrollbar appearing due to rounding issues- return Math.max(0, Math.floor(contentHeight - nonFillerElsHeight - 1));+ return Math.max(0, Math.floor(contentHeight - turnHeight));}function resizeFillerArea(diff --git a/frontend/src/metabase/metabot/components/MetabotChat/hooks.unit.spec.ts b/frontend/src/metabase/metabot/components/MetabotChat/hooks.unit.spec.tsindex a2e63864ab6..ebbfe105947 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/hooks.unit.spec.ts+++ b/frontend/src/metabase/metabot/components/MetabotChat/hooks.unit.spec.ts@@ -2,25 +2,25 @@ import { calculateFillerHeight } from "./hooks";type MessageSpec = {role: "user" | "agent";- clientHeight: number;+ height: number;+ marginTop?: number;};-const setClientHeight = (el: HTMLElement, value: number) => {- Object.defineProperty(el, "clientHeight", {- configurable: true,- value,- });+const setRect = (el: HTMLElement, rect: { top: number; height: number }) => {+ el.getBoundingClientRect = () =>+ // jsdom has no layout; only top and height are read by the code under test+ ({ ...rect, bottom: rect.top + rect.height }) as DOMRect;};type SetupOpts = {- containerClientHeight: number;+ containerHeight: number;paddingTop?: string;paddingBottom?: string;messages: MessageSpec[];};const setup = ({- containerClientHeight,+ containerHeight,paddingTop = "0px",paddingBottom = "0px",messages,@@ -29,19 +29,22 @@ const setup = ({const inner = document.createElement("div");container.appendChild(inner);- setClientHeight(container, containerClientHeight);+ setRect(container, { top: 0, height: containerHeight });container.style.paddingTop = paddingTop;container.style.paddingBottom = paddingBottom;- for (const { role, clientHeight } of messages) {+ let top = parseFloat(paddingTop);+ for (const { role, height, marginTop = 0 } of messages) {const el = document.createElement("div");el.setAttribute("data-message-role", role);- setClientHeight(el, clientHeight);+ top += marginTop;+ setRect(el, { top, height });+ top += height;inner.appendChild(el);}const fillerEl = document.createElement("div");- setClientHeight(fillerEl, 0);+ setRect(fillerEl, { top, height: 0 });inner.appendChild(fillerEl);return { container, fillerEl };@@ -50,39 +53,53 @@ const setup = ({describe("calculateFillerHeight", () => {it("fills the space below the current turn so the prompt can reach the top", () => {const { container, fillerEl } = setup({- containerClientHeight: 500,+ containerHeight: 500,messages: [- { role: "agent", clientHeight: 100 },- { role: "user", clientHeight: 40 },- { role: "agent", clientHeight: 120 },+ { role: "agent", height: 100 },+ { role: "user", height: 40 },+ { role: "agent", height: 120 },],});- // 500 - (40 + 120) - 1 = 339 (only the last turn counts)- expect(calculateFillerHeight(container, fillerEl)).toBe(339);+ // 500 - (40 + 120) = 340 (only the last turn counts)+ expect(calculateFillerHeight(container, fillerEl)).toBe(340);});it("accounts for the scroll container's vertical padding", () => {const { container, fillerEl } = setup({- containerClientHeight: 500,+ containerHeight: 500,paddingTop: "16px",paddingBottom: "24px",messages: [- { role: "user", clientHeight: 40 },- { role: "agent", clientHeight: 120 },+ { role: "user", height: 40 },+ { role: "agent", height: 120 },+ ],+ });++ // 500 - 40 (padding) - 160 (turn) = 300+ expect(calculateFillerHeight(container, fillerEl)).toBe(300);+ });++ it("includes margins between messages and rounds sub-pixel sizes down", () => {+ const { container, fillerEl } = setup({+ containerHeight: 500,+ messages: [+ { role: "user", height: 40.25 },+ { role: "agent", height: 120.5 },+ { role: "agent", height: 60, marginTop: 16 },],});- // 500 - 40 (padding) - 160 (turn) - 1 = 299- expect(calculateFillerHeight(container, fillerEl)).toBe(299);+ // 500 - (40.25 + 120.5 + 16 + 60) = 263.25 -> 263+ expect(calculateFillerHeight(container, fillerEl)).toBe(263);});it("never returns a negative height when the turn is taller than the viewport", () => {const { container, fillerEl } = setup({- containerClientHeight: 200,+ containerHeight: 200,messages: [- { role: "user", clientHeight: 40 },- { role: "agent", clientHeight: 400 },+ { role: "user", height: 40 },+ { role: "agent", height: 400 },],});diff --git a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsxindex 08a277242a0..8b6637e61f8 100644--- a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx@@ -210,9 +210,7 @@ describe("MetabotConversationPage", () => {expect(await screen.findByText("Loaded question")).toBeInTheDocument();expect(await screen.findByText("Thinking")).toBeInTheDocument();- expect(- screen.queryByTestId("metabot-response-loader"),- ).not.toBeInTheDocument();+ expect(screen.getByTestId("metabot-response-loader")).toBeInTheDocument();expect(screen.getByTestId("metabot-stop-response")).toBeInTheDocument();expect(screen.queryByTestId("metabot-send-message"),diff --git a/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.module.css b/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.module.cssnew file mode 100644index 00000000000..8098b314e37--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.module.css@@ -0,0 +1,21 @@+.clip {+ overflow: hidden;+}++.text {+ overflow-wrap: anywhere;+}++.crumb {+ color: inherit;++ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-brand-hover);+ text-decoration: underline dotted;+ }+}++.crumbs {+ justify-content: flex-end;+}diff --git a/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.tsx b/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.tsxnew file mode 100644index 00000000000..0fd9e7aec4e--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotHoverCard/MetabotHoverCard.tsx@@ -0,0 +1,190 @@+import type { ReactNode } from "react";+import { useCallback, useMemo, useState } from "react";+import { msgid, ngettext, t } from "ttag";++import { useGetTableQueryMetadataQuery } from "metabase/api";+import { EntityIcon } from "metabase/common/components/EntityIcon";+import { Link } from "metabase/common/components/Link";+import { Popover } from "metabase/common/components/MetadataInfo/Popover";+import { getTranslatedEntityName } from "metabase/common/utils/model-names";+import { useGetIcon } from "metabase/hooks/use-icon";+import { PLUGIN_LIBRARY } from "metabase/plugins";+import type { LibraryEntity } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity";+import { Breadcrumbs, Center, Divider, Group, Stack, Text } from "metabase/ui";+import * as Urls from "metabase/urls";+import { isNotNull } from "metabase/utils/types";+import type { LibraryCollection, TableId } from "metabase-types/api";+import { isConcreteTableId } from "metabase-types/api";++import S from "./MetabotHoverCard.module.css";++const WIDTH = 320;+const CARD_PADDING_PX = 16;+const OFFSET = { mainAxis: 8, alignmentAxis: -CARD_PADDING_PX };++export const METABOT_HOVER_CARD_BOUNDARY_ATTR =+ "data-metabot-hover-card-boundary";++const useBoundaryMiddlewares = () => {+ const [boundary, setBoundary] = useState<HTMLElement | null>(null);+ const targetRef = useCallback((node: HTMLElement | null) => {+ setBoundary(+ node?.closest<HTMLElement>(`[${METABOT_HOVER_CARD_BOUNDARY_ATTR}]`) ??+ null,+ );+ }, []);++ const middlewares = useMemo(+ () => ({+ flip: boundary ? { boundary } : true,+ shift: boundary ? { boundary } : true,+ size: true,+ }),+ [boundary],+ );++ return { targetRef, middlewares };+};++type Crumb = { name: string; href?: string };++const getLocationCrumbs = (+ { collection, parentTable }: LibraryEntity,+ library: LibraryCollection | undefined,+): Crumb[] => {+ const libraryCrumb = {+ name: t`Library`,+ href:+ library &&+ Urls.modelToUrl({+ id: library.id,+ model: "collection",+ name: library.name,+ }),+ };+ const collectionCrumb = collection && {+ name: collection.name,+ href: Urls.collection(collection),+ };+ const tableCrumb = parentTable && {+ name: parentTable.display_name,+ href: isConcreteTableId(parentTable.id)+ ? Urls.table({ id: parentTable.id, name: parentTable.display_name })+ : undefined,+ };++ return [libraryCrumb, collectionCrumb, tableCrumb].filter(isNotNull);+};++export function MetabotHoverCard({+ entity,+ children,+}: {+ entity: LibraryEntity | undefined;+ children: ReactNode;+}) {+ const { targetRef, middlewares } = useBoundaryMiddlewares();+ const { data: library } = PLUGIN_LIBRARY.useGetLibraryCollection({+ skip: !entity,+ });++ return (+ <Popover+ disabled={!entity}+ width={WIDTH}+ radius="md"+ offset={OFFSET}+ middlewares={middlewares}+ content={+ entity && <MetabotHoverCardContent entity={entity} library={library} />+ }+ >+ <span ref={targetRef}>{children}</span>+ </Popover>+ );+}++function MetabotHoverCardContent({+ entity,+ library,+}: {+ entity: LibraryEntity;+ library: LibraryCollection | undefined;+}) {+ const getIcon = useGetIcon();++ return (+ <Stack+ gap={0}+ bg="background_surface-primary"+ c="text-primary"+ bdrs="md"+ className={S.clip}+ data-testid="metabot-hover-card"+ >+ <Stack gap="lg" p="lg">+ <Group gap="xs" c="text-brand" fz="sm" fw="bold">+ <EntityIcon {...getIcon({ model: entity.model })} size="0.75rem" />+ {getTranslatedEntityName(entity.model)}+ </Group>+ <Stack gap="xxs" className={S.text}>+ <Text fz="md" fw="bold">+ {entity.name}+ </Text>+ {entity.description && (+ <Text fz="md" c="text-secondary">+ {entity.description}+ </Text>+ )}+ </Stack>+ {entity.model === "table" && <TableFieldsPill tableId={entity.id} />}+ </Stack>+ <Divider />+ <Breadcrumbs+ separator="/"+ px="lg"+ py="sm"+ fz="sm"+ c="text-secondary"+ className={S.crumbs}+ >+ {getLocationCrumbs(entity, library).map((crumb, index) => (+ <Crumb key={index} {...crumb} />+ ))}+ </Breadcrumbs>+ </Stack>+ );+}++function Crumb({ name, href }: Crumb) {+ return href ? (+ <Link to={href} target="_blank" className={S.crumb}>+ {name}+ </Link>+ ) : (+ <span>{name}</span>+ );+}++function TableFieldsPill({ tableId }: { tableId: TableId }) {+ const { data: table } = useGetTableQueryMetadataQuery({ id: tableId });+ const fieldCount = table?.fields?.length;++ if (fieldCount == null) {+ return null;+ }++ return (+ <Center+ h="1.5rem"+ w="fit-content"+ px="xs"+ fz="sm"+ bdrs="xs"+ bg="background_page-secondary"+ c="text-secondary"+ >+ {ngettext(msgid`${fieldCount} field`, `${fieldCount} fields`, fieldCount)}+ </Center>+ );+}diff --git a/frontend/src/metabase/metabot/components/MetabotHoverCard/index.ts b/frontend/src/metabase/metabot/components/MetabotHoverCard/index.tsnew file mode 100644index 00000000000..ee11263dddb--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotHoverCard/index.ts@@ -0,0 +1,4 @@+export {+ METABOT_HOVER_CARD_BOUNDARY_ATTR,+ MetabotHoverCard,+} from "./MetabotHoverCard";diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.cssindex de29cdda329..df1afa92166 100644--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css@@ -1,31 +1,51 @@.widget {- padding: 4px 0;+ padding: 0.75rem 0;+ padding-left: 0.375rem;}.container {- max-width: 55rem;+ max-width: 37.5rem;+ min-height: 5.5rem;display: flex;flex-direction: column;gap: 0.25rem;- padding: 0.5rem 0.75rem 0.75rem;+ padding: 0.25rem 1rem 0.5rem;margin-bottom: 0.125rem;background: var(--mb-color-background_page-primary);border: 1px solid var(--mb-color-border-neutral);- border-radius: 0.5rem;- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);+ border-radius: var(--mantine-radius-sm);+ box-shadow: 0 2px 8px transparent;+ transition: box-shadow 150ms ease;++ &:has(.inputContainer :focus) {+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);+ }+}++.cancelButton {+ color: var(--mb-color-text-secondary);++ &:hover {+ color: var(--mb-color-text-brand);+ }+}++.submitButton {+ margin-left: -0.5rem;+ position: relative;+ right: -0.5rem;+ bottom: 0;}.inputContainer {min-height: 1.5rem;+ flex: 1;}.inputContainer :global(.ProseMirror) {font-family: var(--mb-default-font-family);- font-size: 0.75rem;+ font-size: var(--mantine-font-size-md);+ color: var(--mb-color-text-secondary);min-height: 1.25rem;padding: 0.25rem 0.125rem;}--.cancelButton {- order: -1;-}diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsxindex 8b4782ed310..ae670d12160 100644--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx@@ -7,11 +7,12 @@ import type { MetabotPromptInputRef } from "metabase/metabot";import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";import { MetabotManagedProviderLimitHoverCard } from "metabase/metabot/components/MetabotManagedProviderLimit";import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";+import { MetabotSendButton } from "metabase/metabot/components/MetabotSendButton";import { useUserMetabotPermissions } from "metabase/metabot/hooks";import type { MetabotAgentTurnDisplayError } from "metabase/metabot/state";import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";import { useSetting } from "metabase/settings";-import { Box, Button, Flex, Icon, Loader, Tooltip } from "metabase/ui";+import { Box, Button, Flex, Tooltip } from "metabase/ui";import type { DatabaseId } from "metabase-types/api";import { AIProviderConfigurationNotice } from "../AIProviderConfigurationNotice";@@ -55,7 +56,9 @@ export const MetabotInlineSQLPrompt = ({useUserMetabotPermissions();const metabotName = useSetting("metabot-name");- const isSubmitDisabled = !canUseSqlGeneration || !value.trim() || isLoading;+ const isLocked = error?.type === "locked";+ const isSubmitDisabled =+ !canUseSqlGeneration || !value.trim() || isLoading || isLocked;const handleSubmit = useCallback(async () => {const prompt = promptInputRef.current?.getValue?.().trim() ?? "";@@ -116,53 +119,52 @@ export const MetabotInlineSQLPrompt = ({</Box>)}- <Flex justify="space-between" align="center" gap="sm" mt="xxs">+ <Flex+ direction="row-reverse"+ justify="space-between"+ align="center"+ gap="sm"+ mt="xxs"+ >+ {canUseSqlGeneration && (+ <Tooltip+ label={isLoading ? t`Stop generating` : t`Send to ${metabotName}`}+ >+ <MetabotSendButton+ className={S.submitButton}+ data-testid="metabot-inline-sql-generate"+ aria-label={+ isLoading ? t`Stop generating` : t`Send to ${metabotName}`+ }+ isResponding={isLoading}+ onClick={isLoading ? cancelRequest : handleSubmit}+ disabled={!isLoading && isSubmitDisabled}+ />+ </Tooltip>+ )}<Boxdata-testid="metabot-inline-sql-error"- w="100%"+ pr="0.125rem"+ ta="right"+ flex={1}+ miw={0}fz="sm"- c="feedback-negative"+ c={error?.type === "aborted" ? "text-secondary" : "feedback-negative"}>- {error?.type === "locked" ? (- <MetabotManagedProviderLimitHoverCard />- ) : (- error?.message- )}+ {isLocked ? <MetabotManagedProviderLimitHoverCard /> : error?.message}</Box>- <Flex gap="xxs" flex="1 0 auto">- {canUseSqlGeneration && (- <Tooltip disabled={isLoading} label={t`Send to ${metabotName}`}>- <Button- data-testid="metabot-inline-sql-generate"- variant="filled"- px="0"- w="2rem"- leftSection={- isLoading ? (- <Loader- size="xs"- color="text-disabled"- data-testid="metabot-inline-sql-generating"- />- ) : (- <Icon name="send" />- )- }- onClick={handleSubmit}- disabled={isSubmitDisabled}- />- </Tooltip>- )}- <Button- className={S.cancelButton}- data-testid="metabot-inline-sql-cancel"- variant="subtle"- color="neutral"- onClick={handleClose}- >- {t`Cancel`}- </Button>- </Flex>+ <Button+ className={S.cancelButton}+ data-testid="metabot-inline-sql-cancel"+ fz="sm"+ px="sm"+ ml="-sm"+ fw="normal"+ variant="subtle"+ onClick={handleClose}+ >+ {t`Cancel`}+ </Button></Flex><AIProviderConfigurationModalopened={isAiProviderConfigurationModalOpen}diff --git a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsxindex 30f077091b9..017b311fe3f 100644--- a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx+++ b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx@@ -51,7 +51,7 @@ export const MetabotPromptInput = forwardRef<({value,- placeholder = t`How can I help? Type @ to mention items.`,+ placeholder = t`Ask about your data. Type @ to mention items.`,autoFocus,disabled,suggestionConfig,diff --git a/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.ts b/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.tsindex 3b7338b0650..a287f7bd75b 100644--- a/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.ts+++ b/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.ts@@ -11,6 +11,7 @@ import { mbProtocolModelToSuggestionModel } from "metabase/rich_text_editing/tipimport {METABSE_PROTOCOL_MD_LINK,createMetabaseProtocolLink,+ parseMetabaseProtocolMarkdownLink,} from "metabase/urls";function serializeNodes(nodes: JSONContent[]): string {@@ -85,8 +86,11 @@ export function parseMetabotMessageToTiptapDoc(text: string): JSONContent {let lastIndex = 0;for (const match of line.matchAll(MENTION_REGEX)) {- const [fullMatch, label, mbProtocolModel, entityId] = match;- const model = mbProtocolModelToSuggestionModel(mbProtocolModel);+ const [fullMatch] = match;+ const link = parseMetabaseProtocolMarkdownLink(fullMatch);+ if (!link) {+ continue;+ }// Add text before the mentionif (match.index > lastIndex) {@@ -98,7 +102,11 @@ export function parseMetabotMessageToTiptapDoc(text: string): JSONContent {pContent.push({type: "smartLink",- attrs: { label, model, entityId },+ attrs: {+ label: link.name,+ model: mbProtocolModelToSuggestionModel(link.model),+ entityId: link.id,+ },});lastIndex = match.index + fullMatch.length;diff --git a/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.unit.spec.ts b/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.unit.spec.tsindex f4a9535ae9a..dc4a2ed3e7e 100644--- a/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.unit.spec.ts+++ b/frontend/src/metabase/metabot/components/MetabotPromptInput/utils.unit.spec.ts@@ -16,7 +16,7 @@ describe("MetabotChatEditor > utils", () => {content: [{type: "smartLink",- attrs: { label: "test", model: "table", entityId: "1" },+ attrs: { label: "test", model: "table", entityId: 1 },},],},@@ -121,7 +121,7 @@ describe("MetabotChatEditor > utils", () => {content: [{type: "smartLink",- attrs: { label: "test", model: "table", entityId: "1" },+ attrs: { label: "test", model: "table", entityId: 1 },},],},diff --git a/frontend/src/metabase/metabot/components/MetabotSendButton.module.css b/frontend/src/metabase/metabot/components/MetabotSendButton.module.cssnew file mode 100644index 00000000000..5c23211db77--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotSendButton.module.css@@ -0,0 +1,72 @@+.button {+ background: var(--mb-color-core-brand);+ border-radius: var(--mantine-radius-xs);+ width: 2rem;+ height: 2rem;+ display: flex;+ justify-content: center;+ align-items: center;+ flex-shrink: 0;+ transition:+ opacity 300ms ease,+ background 150ms ease,+ transform 150ms ease;++ &:hover:not(:disabled),+ &:active:not(:disabled) {+ opacity: 0.7;+ }++ &:active:not(:disabled) {+ transform: scale(0.9);+ }++ &:disabled {+ background: var(--mb-color-background_surface-disabled);+ cursor: not-allowed;++ .sendIcon {+ color: var(--mb-color-icon-disabled);+ }+ }+}++.buttonHidden {+ opacity: 0;+ transition: opacity 0ms ease;+ user-select: none;+ cursor: default;++ &:hover,+ &:active {+ opacity: 0;+ }+}++.buttonResponding {+ border: none;+ background: var(--mb-color-background_surface-secondary);++ &:hover,+ &:focus-visible {+ opacity: 1;+ border: 1px solid var(--mb-color-core-brand);++ .stopIcon {+ color: var(--mb-color-core-brand);+ }+ }+}++.sendIcon {+ color: var(--mb-color-background_page-primary);+ width: 0.8rem;+ transition: color 150ms ease;+}++.stopIcon {+ color: var(--mb-color-text-primary);+ width: 0.7rem;+ height: 0.7rem;+ transition: color 75ms ease;+}diff --git a/frontend/src/metabase/metabot/components/MetabotSendButton.tsx b/frontend/src/metabase/metabot/components/MetabotSendButton.tsxnew file mode 100644index 00000000000..0ab49a3883f--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotSendButton.tsx@@ -0,0 +1,39 @@+import cx from "classnames";+import { type ComponentPropsWithoutRef, forwardRef } from "react";++import { Icon, UnstyledButton } from "metabase/ui";++import S from "./MetabotSendButton.module.css";++type MetabotSendButtonProps = ComponentPropsWithoutRef<"button"> & {+ isResponding?: boolean;+ isHidden?: boolean;+};++export const MetabotSendButton = forwardRef<+ HTMLButtonElement,+ MetabotSendButtonProps+>(function MetabotSendButton(+ { isResponding = false, isHidden = false, className, ...props },+ ref,+) {+ return (+ <UnstyledButton+ ref={ref}+ className={cx(S.button, className, {+ [S.buttonResponding]: isResponding,+ [S.buttonHidden]: isHidden,+ })}+ data-testid={+ isResponding ? "metabot-stop-response" : "metabot-send-message"+ }+ {...props}+ >+ {isResponding ? (+ <Icon className={S.stopIcon} name="stop" />+ ) : (+ <Icon className={S.sendIcon} name="arrow_up" />+ )}+ </UnstyledButton>+ );+});diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.tsindex 288db4b4c80..b8a3bdace42 100644--- a/frontend/src/metabase/metabot/state/actions.ts+++ b/frontend/src/metabase/metabot/state/actions.ts@@ -415,14 +415,28 @@ export const submitInput = createAsyncThunk<const result = await sendMessageRequestPromise;if (isRejected(result)) {+ const metabotName = getSetting(getState(), "metabot-name");return {prompt: rawPrompt,success: false,shouldRetry: result.payload?.shouldRetry ?? true,- error:- result.payload?.type === "error"- ? result.payload.display- : undefined,+ error: match(result)+ .returnType<MetabotAgentTurnDisplayError | undefined>()+ .with(+ P.union(+ { payload: { type: "abort" } },+ { meta: { aborted: true } },+ ),+ () => ({+ type: "aborted",+ message: t`Response from ${metabotName} was interrupted`,+ }),+ )+ .with(+ { payload: { type: "error" } },+ ({ payload }) => payload.display,+ )+ .otherwise(() => undefined),};}diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.tsindex bcc2df5d78d..304be7cfe4c 100644--- a/frontend/src/metabase/metabot/state/types.ts+++ b/frontend/src/metabase/metabot/state/types.ts@@ -71,7 +71,7 @@ export type MetabotDebugToolCallMessage = {};export type MetabotAgentTurnDisplayError = {- type: "alert" | "locked" | "message";+ type: "alert" | "locked" | "message" | "aborted";message: string;};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 d614c2abe89..dede5df3af1 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@@ -58,6 +58,7 @@ const setup = (debug={false}readonly={false}conversationId="convo-1"+ size="md"setFeedbackMessage={() => {}}submittedFeedback={undefined}message={{@@ -81,6 +82,7 @@ describe("AgentMessage", () => {it("hides the action bar on the last agent message while processing", () => {renderWithProviders(<Messages+ size="md"messages={[createMockMetabotTextMessage("user", "hi"),createMockMetabotTextMessage("agent", "hello"),@@ -100,6 +102,7 @@ describe("AgentMessage", () => {it("hides the copy action when the agent response has no text", () => {renderWithProviders(<Messages+ size="md"messages={[createMockMetabotTextMessage("user", "hi"),createMockMetabotMessage({@@ -160,6 +163,7 @@ describe("AgentMessage", () => {it("shows feedback ratings in an interactive conversation", async () => {renderWithProviders(<Messages+ size="md"messages={conversation}isDoingScience={false}debug={false}@@ -175,6 +179,7 @@ describe("AgentMessage", () => {it("hides feedback ratings in a read-only conversation", () => {renderWithProviders(<Messages+ size="md"messages={conversation}isDoingScience={false}debug={false}@@ -471,6 +476,7 @@ describe("UserMessage chart mentions", () => {renderWithProviders(<Messages+ size="md"messages={[createMockMetabotTextMessage("user",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 bd38f8dc581..26709530221 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@@ -26,7 +26,10 @@ import {createMockUser,createMockUserMetabotPermissions,} from "metabase-types/api/mocks";-import { createSampleDatabase } from "metabase-types/api/mocks/presets";+import {+ createOrdersTable,+ createSampleDatabase,+} from "metabase-types/api/mocks/presets";import { MetabotProvider } from "../context";import { getMetabotState } from "../state";@@ -46,6 +49,7 @@ jest.mock("metabase/api/ai-streaming", () => ({const mockedAiStreamingQuery = jest.mocked(aiStreamingQuery);const TEST_DB = createSampleDatabase();+const ORDERS_TABLE = createOrdersTable();const INITIAL_SQL = "SELECT 1";const SUGGESTED_SQL = "SELECT * FROM ORDERS";@@ -73,6 +77,7 @@ const ChatMessagesProbe = () => {return (<Messages+ size="md"messages={messages}isDoingScience={false}debug={false}@@ -93,16 +98,17 @@ describe("query builder code edits from omnibot", () => {fetchMock.post("path:/api/llm/extract-sources", {tables: [{- id: 2,- name: "ORDERS",- schema: "PUBLIC",- display_name: "Orders",+ id: ORDERS_TABLE.id,+ name: ORDERS_TABLE.name,+ schema: ORDERS_TABLE.schema,+ display_name: ORDERS_TABLE.display_name,description: null,columns: [],},],card_ids: [],});+ fetchMock.get(`path:/api/table/${ORDERS_TABLE.id}`, ORDERS_TABLE);fetchMock.get(`path:/api/database/${TEST_DB.id}`, TEST_DB);});diff --git a/frontend/src/metabase/metabot/utils/source-location.ts b/frontend/src/metabase/metabot/utils/source-location.tsindex 81ec3d3083a..fc854eab006 100644--- a/frontend/src/metabase/metabot/utils/source-location.ts+++ b/frontend/src/metabase/metabot/utils/source-location.ts@@ -10,14 +10,3 @@ export const getDatabaseLocationLabel = ({export const getCollectionLocationLabel = (collectionName?: string | null) =>collectionName || t`Our analytics`;--export const getDatabaseLocationParts = ({- databaseName,- schema,-}: {- databaseName: string;- schema?: string | null;-}) => (schema ? [databaseName, schema] : [databaseName]);--export const getCollectionLocationParts = (collectionName?: string | null) =>- collectionName ? [t`Library`, collectionName] : [t`Library`];diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.module.css b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.module.cssnew file mode 100644index 00000000000..a43a4672b15--- /dev/null+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.module.css@@ -0,0 +1,39 @@+.link {+ color: var(--mb-color-text-brand);+ text-decoration: underline dotted;+ text-underline-offset: 0.125rem;+ outline: none;+ transition: color 200ms;++ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-brand-hover);+ }+}++.token {+ display: inline-flex;+ align-items: baseline;+ gap: 0.25rem;+ padding-inline: 0.25rem;+ border-radius: 0.375rem;+ line-height: 1.4;+ vertical-align: baseline;+ text-decoration: none;+ outline: none;+ color: var(--mb-color-text-primary);+ background: var(--mb-color-background_surface-brand-subtle);+ transition: background-color 200ms;++ &:hover,+ &:focus-visible {+ color: var(--mb-color-text-primary);+ background: var(--mb-color-background_surface-brand-subtle-hover);+ }+}++.tokenIcon {+ flex-shrink: 0;+ align-self: center;+ color: var(--mb-color-text-brand);+}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.tsxnew file mode 100644index 00000000000..98774e62e09--- /dev/null+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.tsx@@ -0,0 +1,69 @@+import type { AnchorHTMLAttributes } from "react";++import { EntityIcon } from "metabase/common/components/EntityIcon";+import { Link } from "metabase/common/components/Link";+import { useGetIcon } from "metabase/hooks/use-icon";++import S from "./EntitySmartLink.module.css";+import {+ type SmartLinkEntityRef,+ useSmartLinkEntity,+} from "./use-smart-link-entity";++export type EntitySmartLinkProps = SmartLinkEntityRef & {+ name: string;+ href?: string;+ onNavigate?: (href: string) => void;+} & Pick<AnchorHTMLAttributes<HTMLAnchorElement>, "onMouseUp" | "tabIndex">;++export function EntitySmartLink({+ id,+ model,+ name: label,+ href: fallbackHref,+ onNavigate,+ ...anchorProps+}: EntitySmartLinkProps) {+ const getIcon = useGetIcon();+ const { href, libraryEntity } = useSmartLinkEntity({+ id,+ model,+ href: fallbackHref,+ });+ const name = libraryEntity ? libraryEntity.name : label;+ const linkProps = {+ ...anchorProps,+ target: "_blank",+ rel: "noreferrer",+ "data-testid": "smart-link",+ "data-smart-link": libraryEntity ? "token" : "link",+ className: libraryEntity ? S.token : S.link,+ };+ const content = (+ <>+ {libraryEntity && (+ <EntityIcon+ {...getIcon({ model: libraryEntity.model })}+ size="0.75rem"+ className={S.tokenIcon}+ data-smart-link-icon+ />+ )}+ {name}+ </>+ );++ if (onNavigate) {+ return (+ <a {...linkProps} onClick={() => onNavigate(href)}>+ {content}+ </a>+ );+ }++ return (+ <Link {...linkProps} to={href}>+ {content}+ </Link>+ );+}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.unit.spec.tsxnew file mode 100644index 00000000000..b64246aa48a--- /dev/null+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/EntitySmartLink.unit.spec.tsx@@ -0,0 +1,191 @@+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupCardEndpoints,+ setupMeasureEndpoint,+ setupSegmentEndpoint,+ setupTableEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { createMockState } from "__support__/state";+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import {+ createMockCard,+ createMockCollection,+ createMockMeasure,+ createMockSegment,+ createMockSettings,+ createMockTable,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import type { SuggestionModel } from "../shared/types";++import { EntitySmartLink, type EntitySmartLinkProps } from "./EntitySmartLink";++const LABEL = "the label";+const PUBLISHED_TABLE_ID = 5;+const UNPUBLISHED_TABLE_ID = 6;++const publishedTable = createMockTable({+ id: PUBLISHED_TABLE_ID,+ db_id: 1,+ display_name: "Orders",+ is_published: true,+ collection: createMockCollection({ id: 10, type: "library-data" }),+});+const unpublishedTable = createMockTable({+ id: UNPUBLISHED_TABLE_ID,+ db_id: 1,+ display_name: "Products",+ is_published: false,+});+const libraryMetric = createMockCard({+ id: 20,+ name: "ARR",+ type: "metric",+ collection: createMockCollection({ id: 11, type: "library-metrics" }),+});+const regularMetric = createMockCard({+ id: 21,+ name: "Churn",+ type: "metric",+ collection: createMockCollection({ id: 12, name: "Finance" }),+});+const model = createMockCard({+ id: 30,+ name: "Orders + People",+ type: "model",+});+const measure = createMockMeasure({+ id: 40,+ name: "Sum of Total",+ table_id: PUBLISHED_TABLE_ID,+});+const segment = createMockSegment({+ id: 50,+ name: "EU Customers",+ table_id: PUBLISHED_TABLE_ID,+});++const setup = (props: Pick<EntitySmartLinkProps, "id" | "model" | "href">) => {+ setupEnterpriseOnlyPlugin("library");+ setupTableEndpoints(publishedTable);+ setupTableEndpoints(unpublishedTable);+ setupCardEndpoints(libraryMetric);+ setupCardEndpoints(regularMetric);+ setupCardEndpoints(model);+ setupMeasureEndpoint(measure);+ setupSegmentEndpoint(segment);++ const settings = createMockSettings({+ "token-features": createMockTokenFeatures({ library: true }),+ });++ renderWithProviders(<EntitySmartLink name={LABEL} {...props} />, {+ storeInitialState: createMockState({ settings: mockSettings(settings) }),+ });+};++const findSmartLink = async (kind: "token" | "link") => {+ const link = await screen.findByTestId("smart-link");+ await waitFor(() => expect(link).toHaveAttribute("data-smart-link", kind));+ return link;+};++describe("EntitySmartLink", () => {+ it.each<{+ entity: string;+ id: number;+ model: SuggestionModel;+ kind: "token" | "link";+ name: string;+ href: string;+ }>([+ {+ entity: "published table",+ id: PUBLISHED_TABLE_ID,+ model: "table",+ kind: "token",+ name: "Orders",+ href: "/table/5-orders",+ },+ {+ entity: "unpublished table",+ id: UNPUBLISHED_TABLE_ID,+ model: "table",+ kind: "link",+ name: "Products",+ href: "/table/6-products",+ },+ {+ entity: "Library metric",+ id: libraryMetric.id,+ model: "metric",+ kind: "token",+ name: "ARR",+ href: "/metric/20",+ },+ {+ entity: "metric outside the Library",+ id: regularMetric.id,+ model: "metric",+ kind: "link",+ name: "Churn",+ href: "/metric/21",+ },+ {+ entity: "model",+ id: model.id,+ model: "dataset",+ kind: "link",+ name: "Orders + People",+ href: "/model/30-orders-people",+ },+ {+ entity: "measure on a published table",+ id: measure.id,+ model: "measure",+ kind: "token",+ name: "Sum of Total",+ href: "/data-studio/library/tables/5/measures/40",+ },+ {+ entity: "segment on a published table",+ id: segment.id,+ model: "segment",+ kind: "token",+ name: "EU Customers",+ href: "/question#?db=1&table=5&segment=50",+ },+ ])(+ "renders a $entity as a $kind",+ async ({ id, model, kind, name, href }) => {+ setup({ id, model });++ const link = await findSmartLink(kind);+ const isToken = kind === "token";++ // tokens show the asset's own name; links keep the text they were written with+ expect(link).toHaveTextContent(isToken ? name : LABEL);+ expect(link).toHaveAttribute("href", href);+ expect(link).toHaveAttribute("target", "_blank");+ expect(within(link).queryByRole("img") !== null).toBe(isToken);+ },+ );++ it("keeps the given href when the entity cannot be loaded", async () => {+ fetchMock.get("path:/api/dashboard/999", 404);+ setup({ id: 999, model: "dashboard", href: "/dashboard/999" });++ const link = await findSmartLink("link");+ await waitFor(() =>+ expect(fetchMock.callHistory.called("path:/api/dashboard/999")).toBe(+ true,+ ),+ );+ expect(link).toHaveTextContent(LABEL);+ expect(link).toHaveAttribute("href", "/dashboard/999");+ });+});diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsxindex 8a9337b3083..4c9417f6de7 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx@@ -8,10 +8,6 @@ import { memo, useEffect } from "react";import { t } from "ttag";import { isObject } from "underscore";-import { EntityIcon } from "metabase/common/components/EntityIcon";-import { Link } from "metabase/common/components/Link";-import type { IconModel, ObjectWithModel } from "metabase/common/utils/icon";-import { useGetIcon } from "metabase/hooks/use-icon";import { useDispatch } from "metabase/redux";import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";import { Icon } from "metabase/ui";@@ -19,14 +15,15 @@ import {METABSE_PROTOCOL_MD_LINK,parseMetabaseProtocolMarkdownLink,} from "metabase/urls";-import { modelToUrl } from "metabase/urls/modelToUrl";import { extractEntityId } from "metabase/urls/utils";+import { getName } from "metabase/utils/name";import type {Card,Collection,Dashboard,Database,Document,+ Measure,MentionableUser,Segment,Table,@@ -35,12 +32,12 @@ import type {} from "metabase-types/api";import {- entityToUrlableModel,isMentionableUser,mbProtocolModelToSuggestionModel,} from "../shared/suggestionUtils";import type { SuggestionModel } from "../shared/types";+import { EntitySmartLink } from "./EntitySmartLink";import styles from "./SmartLinkNode.module.css";import { useEntityData } from "./use-entity-data";@@ -54,6 +51,7 @@ export type SmartLinkEntity =| Document| WritebackAction| Segment+ | Measure| MentionableUser;// Utility function to parse entity URLs and extract entityId and model@@ -289,7 +287,6 @@ export const SmartLink = Node.create<{export const SmartLinkComponent = memo(({ node, updateAttributes }: NodeViewProps) => {- const getIcon = useGetIcon();const { entityId, model, label } = node.attrs;const {@@ -347,7 +344,7 @@ export const SmartLinkComponent = memo();}- if (model === "user" && isMentionableUser(entity)) {+ if (isMentionableUser(entity)) {return (<NodeViewWrapper as="span" data-type="smart-link"><span className={styles.userMention}>@{entity.common_name}</span>@@ -355,38 +352,18 @@ export const SmartLinkComponent = memo();}- const entityUrlableModel = entityToUrlableModel(entity, model);- const entityUrl = modelToUrl(entityUrlableModel);-- const iconData =- entity === cachedEntity- ? getIcon(cachedEntity)- : getIcon(- entityToObjectWithModel(- // Unjustified type cast. FIXME- entity as NonNullable<typeof networkEntity>,- model,- ),- );-return (<NodeViewWrapper as="span" data-type="smart-link">- <Link- to={entityUrl || "#"}- target="_blank"- rel="noreferrer"+ <EntitySmartLink+ id={cachedEntity.id}+ model={model}+ name={getName(entity)}tabIndex={-1}onMouseUp={(e) => {// Stop tiptap from opening this link twicee.stopPropagation();}}- className={styles.smartLink}- >- <span className={styles.smartLinkInner}>- <EntityIcon {...iconData} className={styles.icon} />- {getName(entity)}- </span>- </Link>+ /></NodeViewWrapper>);},@@ -402,27 +379,3 @@ export const SmartLinkComponent = memo();SmartLinkComponent.displayName = "SmartLinkComponent";--function entityToObjectWithModel(- entity: SmartLinkEntity,- model: SuggestionModel | null,-): ObjectWithModel {- return {- // Unjustified type cast. FIXME- model: ((entity as Dashboard).model || model || "") as IconModel,- // Unjustified type cast. FIXME- display: (entity as Card).display,- // Unjustified type cast. FIXME- is_personal: (entity as Collection).is_personal,- };-}--function getName(entity: { name?: string; display_name?: string }) {- if ("display_name" in entity && entity.display_name !== "") {- return entity.display_name;- }- if ("name" in entity && entity.name !== "") {- return entity.name;- }- return "";-}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.tsindex 22b4482a1bf..6ad4f290a90 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.ts@@ -5,6 +5,7 @@ import {useGetDashboardQuery,useGetDatabaseQuery,useGetDocumentQuery,+ useGetMeasureQuery,useGetSegmentQuery,useGetTableQuery,useGetTransformQuery,@@ -70,6 +71,10 @@ export const useEntityData = (skip: !entityId || model !== "segment",});+ const measureQuery = useGetMeasureQuery(entityId!, {+ skip: !entityId || model !== "measure",+ });+const usersQuery = useListMentionsQuery(undefined, {skip: !entityId || model !== "user",});@@ -80,74 +85,90 @@ export const useEntityData = (case "dataset":case "metric":return {+ model,entity: cardQuery.data,isLoading: cardQuery.isLoading,error: cardQuery.error,};case "dashboard":return {+ model,entity: dashboardQuery.data,isLoading: dashboardQuery.isLoading,error: dashboardQuery.error,};case "collection":return {+ model,entity: collectionQuery.data,isLoading: collectionQuery.isLoading,error: collectionQuery.error,};case "table":return {+ model,entity: tableQuery.data,isLoading: tableQuery.isLoading,error: tableQuery.error,};case "database":return {+ model,entity: databaseQuery.data,isLoading: databaseQuery.isLoading,error: databaseQuery.error,};case "document":return {+ model,entity: documentQuery.data,isLoading: documentQuery.isLoading,error: documentQuery.error,};case "transform":return {+ model,entity: transformQuery.data,isLoading: transformQuery.isLoading,error: transformQuery.error,};case "action":return {+ model,entity: actionQuery.data,isLoading: actionQuery.isLoading,error: actionQuery.error,};case "segment":return {+ model,entity: segmentQuery.data,isLoading: segmentQuery.isLoading,error: segmentQuery.error,};+ case "measure":+ return {+ model,+ entity: measureQuery.data,+ isLoading: measureQuery.isLoading,+ error: measureQuery.error,+ };case "user": {const user = usersQuery.data?.data.find((user) => user.id === entityId);return {+ model,entity: user ? { ...user, name: user.common_name } : null,isLoading: usersQuery.isLoading,error: usersQuery.error,};}case "indexed-entity":- case "measure":case "exploration":case null:- return { entity: null, isLoading: false, error: null };+ return { model, entity: null, isLoading: false, error: null };default:assertUnreachable(model);- return { entity: null, isLoading: false, error: null };+ return { model, entity: null, isLoading: false, error: null };}};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity.tsnew file mode 100644index 00000000000..199bfcba969--- /dev/null+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-smart-link-entity.ts@@ -0,0 +1,198 @@+import { P, match } from "ts-pattern";++import { useGetTableQuery } from "metabase/api";+import { PLUGIN_LIBRARY } from "metabase/plugins";+import * as Urls from "metabase/urls";+import { getName } from "metabase/utils/name";+import type {+ CardId,+ Collection,+ MeasureId,+ SegmentId,+ Table,+ TableId,+} from "metabase-types/api";+import { isConcreteTableId } from "metabase-types/api";++import {+ entityToUrlableModel,+ isMentionableUser,+} from "../shared/suggestionUtils";+import type { SuggestionModel } from "../shared/types";++import { useEntityData } from "./use-entity-data";++export type SmartLinkEntityRef = {+ id: number;+ model: SuggestionModel;+};++export type LibraryEntityModel = "table" | "metric" | "measure" | "segment";++export type LibraryEntity = {+ model: LibraryEntityModel;+ id: TableId | CardId | MeasureId | SegmentId;+ name: string;+ description: string | null;+ collection: Collection | null | undefined;+ parentTable?: Table;+};++export type SmartLinkEntityInfo = {+ entityName?: string;+ href: string;+ isLoading: boolean;+ libraryEntity?: LibraryEntity;+};++type EntityData = ReturnType<typeof useEntityData>;++const getLibraryEntity = (+ data: EntityData,+ parentTable: Table | undefined,+): LibraryEntity | undefined =>+ match(data)+ .with({ model: "table", entity: { is_published: true } }, ({ entity }) => ({+ model: "table" as const,+ id: entity.id,+ name: entity.display_name,+ description: entity.description,+ collection: entity.collection,+ }))+ .with(+ {+ model: P.union("card", "dataset", "metric"),+ entity: {+ type: "metric",+ collection: { type: P.when(PLUGIN_LIBRARY.isLibraryCollectionType) },+ },+ },+ ({ entity }) => ({+ model: "metric" as const,+ id: entity.id,+ name: entity.name,+ description: entity.description,+ collection: entity.collection,+ }),+ )+ .with({ model: "measure", entity: P.nonNullable }, ({ entity }) =>+ parentTable?.is_published+ ? {+ model: "measure" as const,+ id: entity.id,+ name: entity.name,+ description: entity.description,+ collection: parentTable.collection,+ parentTable,+ }+ : undefined,+ )+ .with({ model: "segment", entity: P.nonNullable }, ({ entity }) =>+ parentTable?.is_published+ ? {+ model: "segment" as const,+ id: entity.id,+ name: entity.name,+ description: entity.description,+ collection: parentTable.collection,+ parentTable,+ }+ : undefined,+ )+ .with(+ {+ model: P.union(+ "table",+ "card",+ "dataset",+ "metric",+ "measure",+ "segment",+ "dashboard",+ "collection",+ "database",+ "document",+ "transform",+ "action",+ "user",+ "indexed-entity",+ "exploration",+ null,+ ),+ },+ () => undefined,+ )+ .exhaustive();++const getEntityHref = (+ data: EntityData,+ parentTable: Table | undefined,+): string | undefined =>+ match(data)+ .with({ model: "table", entity: P.nonNullable }, ({ entity }) =>+ isConcreteTableId(entity.id)+ ? Urls.table({ id: entity.id, name: entity.display_name })+ : Urls.modelToUrl(entityToUrlableModel(entity, "table")),+ )+ .with({ model: "measure", entity: P.nonNullable }, ({ entity }) =>+ Urls.dataStudioPublishedTableMeasure(entity.table_id, entity.id),+ )+ .with({ model: "segment", entity: P.nonNullable }, ({ entity }) =>+ parentTable+ ? Urls.tableRowsQuery(+ parentTable.db_id,+ entity.table_id,+ undefined,+ entity.id,+ )+ : undefined,+ )+ .with(+ {+ model: P.union(+ "card",+ "dataset",+ "metric",+ "dashboard",+ "collection",+ "database",+ "document",+ "transform",+ "action",+ "user",+ ),+ entity: P.nonNullable,+ },+ ({ model, entity }) =>+ Urls.modelToUrl(entityToUrlableModel(entity, model)),+ )+ .with({ entity: P.nullish }, () => undefined)+ .exhaustive();++export function useSmartLinkEntity({+ id,+ model,+ href: fallbackHref,+}: SmartLinkEntityRef & { href?: string }): SmartLinkEntityInfo {+ const data = useEntityData(id, model);+ const { entity, isLoading } = data;+ const parentTableId = match(data)+ .with(+ { model: P.union("measure", "segment"), entity: P.nonNullable },+ ({ entity }) => entity.table_id,+ )+ .otherwise(() => undefined);+ const { data: parentTable } = useGetTableQuery(+ { id: parentTableId! },+ { skip: parentTableId == null },+ );++ return {+ entityName: isMentionableUser(entity)+ ? entity.common_name+ : getName(entity),+ href: getEntityHref(data, parentTable) || fallbackHref || "",+ isLoading,+ libraryEntity: getLibraryEntity(data, parentTable),+ };+}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils.tsindex d64aa42b07a..67f65880a09 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils.ts@@ -62,19 +62,25 @@ export function isMentionableUser(value: unknown): value is MentionableUser {return isObject(value) && typeof value.common_name === "string";}-export function mbProtocolModelToSuggestionModel(inputModel: string): string {- // dom nodes record strings and it's better to not to error the input with invalid- // data. casting here still afford some amount of internal type awareness as these- // two types might diverge in the future.- const model: SuggestionModel = match(- // Unjustified type cast. FIXME- inputModel as MetabaseProtocolEntityModel,- )+export function mbProtocolModelToSuggestionModel(+ model: MetabaseProtocolEntityModel,+): SuggestionModel {+ return match(model).with("model", () => "dataset" as const).with("question", () => "card" as const)- .otherwise((x) => x);-- return model;+ .with(+ "collection",+ "dashboard",+ "database",+ "document",+ "measure",+ "metric",+ "segment",+ "table",+ "transform",+ (model) => model,+ )+ .exhaustive();}export function getBrowseAllItemIndex(diff --git a/frontend/src/metabase/urls/metabase-protocol.ts b/frontend/src/metabase/urls/metabase-protocol.tsindex 2a10b7f464e..be1007148b4 100644--- a/frontend/src/metabase/urls/metabase-protocol.ts+++ b/frontend/src/metabase/urls/metabase-protocol.ts@@ -14,6 +14,8 @@ export const METABASE_PROTOCOL_ENTITY_MODELS = ["document","model","metric",+ "measure",+ "segment","database","table","transform",diff --git a/frontend/src/metabase/urls/metabase-protocol.unit.spec.ts b/frontend/src/metabase/urls/metabase-protocol.unit.spec.tsindex b037096177f..8f424b5b49b 100644--- a/frontend/src/metabase/urls/metabase-protocol.unit.spec.ts+++ b/frontend/src/metabase/urls/metabase-protocol.unit.spec.ts@@ -23,10 +23,18 @@ describe("parseMetabaseProtocolLink", () => {id: 111,model: "model",});- expect(parseMetabaseProtocolLink("metabase://metric/222")).toEqual({- id: 222,+ expect(parseMetabaseProtocolLink("metabase://metric/5")).toEqual({+ id: 5,model: "metric",});+ expect(parseMetabaseProtocolLink("metabase://measure/6")).toEqual({+ id: 6,+ model: "measure",+ });+ expect(parseMetabaseProtocolLink("metabase://segment/7")).toEqual({+ id: 7,+ model: "segment",+ });});it("should return undefined for invalid protocol", () => {diff --git a/resources/metabot/prompts/shared/prompt_snippets/communication.selmer b/resources/metabot/prompts/shared/prompt_snippets/communication.selmerindex 1532b9ed0fd..729f6bfd991 100644--- a/resources/metabot/prompts/shared/prompt_snippets/communication.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/communication.selmer@@ -1,5 +1,5 @@# Communicating with the user-Link every entity you reference. The format is `[Descriptive name](metabase://<type>/<id>)` where `<type>` is one of `chart`, `metric`, `model`, `table`, `dashboard`, or `question`. Use human-readable names ("Regional Sales Analysis", not "Chart 123"). When you build a chart, always include its link in your final message.+Link every entity you reference. The format is `[Descriptive name](metabase://<type>/<id>)` where `<type>` is one of `chart`, `metric`, `model`, `table`, `measure`, `segment`, `dashboard`, or `question`. Use human-readable names ("Regional Sales Analysis", not "Chart 123"). When you build a chart, always include its link in your final message.Keep final messages brief: the chart link, one or two sentences on how you translated the question (which data source, the filter or grouping used), and any disclosures. The user is looking at the visualization — they don't need a narrated tour of the query.diff --git a/src/metabase/metabot/agent/links.clj b/src/metabase/metabot/agent/links.cljindex b735fa7285e..1830daff10c 100644--- a/src/metabase/metabot/agent/links.clj+++ b/src/metabase/metabot/agent/links.clj@@ -3,15 +3,11 @@Converts internal metabase:// links to proper Metabase URLs using agent memory state."(:require[buddy.core.codecs :as codecs]- [clojure.core.memoize :as memoize][clojure.string :as str]- [metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata][metabase.lib.schema][metabase.metabot.db :as metabot.db][metabase.system.core :as system]- [metabase.util :as u][metabase.util.json :as json][metabase.util.log :as log]))@@ -26,6 +22,7 @@"dashboard" "/dashboard""document" "/document""question" "/question"+ "table" "/table""transform" "/data-studio/transforms"});;; Query/Chart URL Generation@@ -130,31 +127,26 @@(log/warn "Unknown entity type for link" {:type entity-type :id entity-id})nil)))-(def ^:private resolve-table-link- "Resolve a metabase://table/{id} link to an ad-hoc question URL.- Looks up the table's database_id and generates a /question#<base64> URL- with a query using that table as the source table.-- Results are cached for 10 minutes."- (memoize/ttl- (fn [table-id]- (let [parsed-id (cond- (int? table-id) table-id- (string? table-id) (parse-long table-id)- :else nil)]- (if-not parsed-id- (do- (log/warn "Invalid table id for link resolution" {:table-id table-id})- nil)- (if-let [db-id (metabot.db/table-database-id parsed-id)]- (let [mp (lib-be/application-database-metadata-provider db-id)- table (lib.metadata/table mp parsed-id)- query (lib/query mp table)]- (str "/question#" (query->url-hash query)))- (do- (log/warn "Table not found for link resolution" {:table-id parsed-id})- nil)))))- :ttl/threshold (u/minutes->ms 10)))+(defn- resolve-measure-link+ "Resolve a metabase://measure/{id} link to the measure's Data Studio page, or nil when the measure is+ unknown."+ [entity-id]+ (let [measure-id (parse-long entity-id)+ table-id (some-> measure-id metabot.db/measure-table-id)]+ (if table-id+ (str "/data-studio/library/tables/" table-id "/measures/" measure-id)+ (log/warn "Measure not found for link resolution" {:measure-id entity-id}))))++(defn- resolve-segment-link+ "Resolve a metabase://segment/{id} link to an ad-hoc question on the segment's table filtered by the+ segment, or nil when the segment is unknown."+ [entity-id]+ (let [segment-id (parse-long entity-id)+ table-id (some-> segment-id metabot.db/segment-table-id)+ db-id (some-> table-id metabot.db/table-database-id)]+ (if db-id+ (str "/question#?db=" db-id "&table=" table-id "&segment=" segment-id)+ (log/warn "Segment not found for link resolution" {:segment-id entity-id}))));;; Main Link Resolution@@ -169,7 +161,9 @@- metabase://metric/{id} - Links to metrics- metabase://dashboard/{id} - Links to dashboards- metabase://document/{id} - Links to documents- - metabase://table/{id} - Links to tables (as questions)+ - metabase://table/{id} - Links to tables+ - metabase://measure/{id} - Links to measures+ - metabase://segment/{id} - Links to segments (as questions)- metabase://transform/{id} - Links to transformsReturns the resolved URL or nil if resolution fails."@@ -182,7 +176,8 @@"query" (resolve-query-link entity-id queries-state)"chart" (resolve-chart-link entity-id charts-state queries-state)"question" (resolve-entity-link "question" entity-id)- "table" (resolve-table-link entity-id)+ "measure" (resolve-measure-link entity-id)+ "segment" (resolve-segment-link entity-id);; For other types, use simple path mapping(resolve-entity-link entity-type entity-id))))))diff --git a/test/metabase/metabot/agent/links_test.clj b/test/metabase/metabot/agent/links_test.cljindex 69e2540024d..3029490d85a 100644--- a/test/metabase/metabot/agent/links_test.clj+++ b/test/metabase/metabot/agent/links_test.clj@@ -3,6 +3,7 @@[clojure.string :as str][clojure.test :refer :all][metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu][metabase.metabot.agent.links :as links]@@ -138,12 +139,34 @@(is (= "/data-studio/transforms/202" (links/resolve-metabase-uri "metabase://transform/202" {} {})))))(deftest ^:parallel resolve-metabase-uri-table-link-test- (testing "resolves table links to ad-hoc question URLs"- (let [result (links/resolve-metabase-uri (str "metabase://table/" (mt/id :venues)) {} {})]- (is (string? result))- (is (str/starts-with? result "/question#"))))- (testing "returns nil for non-existent table"- (is (nil? (links/resolve-metabase-uri "metabase://table/999999999" {} {})))))+ (testing "resolves table links to the table page"+ (is (= (str "/table/" (mt/id :venues))+ (links/resolve-metabase-uri (str "metabase://table/" (mt/id :venues)) {} {})))))++(deftest resolve-metabase-uri-measure-link-test+ (let [mp (mt/metadata-provider)]+ (mt/with-temp [:model/Measure {measure-id :id} {:name "Venue Count"+ :table_id (mt/id :venues)+ :definition (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count)))}]+ (testing "resolves measure links to the measure's Data Studio page"+ (is (= (str "/data-studio/library/tables/" (mt/id :venues) "/measures/" measure-id)+ (links/resolve-metabase-uri (str "metabase://measure/" measure-id) {} {}))))))+ (testing "returns nil for non-existent or malformed measure ids"+ (is (nil? (links/resolve-metabase-uri "metabase://measure/999999999" {} {})))+ (is (nil? (links/resolve-metabase-uri "metabase://measure/abc" {} {})))))++(deftest resolve-metabase-uri-segment-link-test+ (let [mp (mt/metadata-provider)]+ (mt/with-temp [:model/Segment {segment-id :id} {:name "Cheap Venues"+ :table_id (mt/id :venues)+ :definition (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/filter (lib/< (lib.metadata/field mp (mt/id :venues :price)) 2)))}]+ (testing "resolves segment links to an ad-hoc question filtered by the segment"+ (is (= (str "/question#?db=" (mt/id) "&table=" (mt/id :venues) "&segment=" segment-id)+ (links/resolve-metabase-uri (str "metabase://segment/" segment-id) {} {}))))))+ (testing "returns nil for non-existent segment"+ (is (nil? (links/resolve-metabase-uri "metabase://segment/999999999" {} {})))))(deftest ^:parallel resolve-metabase-uri-unknown-entity-type-test(testing "returns nil for unknown entity types"diff --git a/test/metabase/metabot/agent/markdown_link_buffer_test.clj b/test/metabase/metabot/agent/markdown_link_buffer_test.cljindex d5508eb5d7b..5fdad206e6c 100644--- a/test/metabase/metabot/agent/markdown_link_buffer_test.clj+++ b/test/metabase/metabot/agent/markdown_link_buffer_test.clj@@ -121,14 +121,10 @@(is (= "" flushed)))))(deftest ^:parallel resolve-table-link-test- (testing "resolves metabase://table links to ad-hoc question URLs"+ (testing "resolves metabase://table links to table URLs"(let [table-id (mt/id :venues)[output flushed] (process (str "[Users Table](metabase://table/" table-id ")"))]- (is (re-find #"\[Users Table\]\(/question#.+\)" output))- (is (= "" flushed))))- (testing "falls back to link text for unknown table"- (let [[output flushed] (process "[Unknown Table](metabase://table/999999999)")]- (is (= "Unknown Table" output))+ (is (= (str "[Users Table](/table/" table-id ")") output))(is (= "" flushed)))))(deftest ^:parallel resolve-entity-link-test