Skip to content

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

feat: improve saving the charts (#76757)

Maksym Yakubychccfc4fe28022
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 1c93c104dfa..02f0f0d4340 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1324,6 +1324,7 @@
documents
driver
entity-retrieval
+ events
interestingness
legacy-mbql
lib
@@ -1336,6 +1337,8 @@
permissions
premium-features
pulse
+ queries
+ query-permissions
query-processor
request
search
@@ -1361,6 +1364,7 @@
:model/DashboardCard
:model/DashboardTab
:model/Database
+ :model/Document
:model/Field
:model/Glossary
:model/Measure
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
index 92482bc7c57..cc913ec1c54 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
@@ -12,8 +12,10 @@ import S from "./MetabotQuestion.module.css";
const isQuestionNavigationMessage = (message: MetabotChatMessage) =>
message.type === "data_part" && message.part.type === "data-navigate_to";
+const AGENT_ID = "omnibot";
+
export function MetabotChatHistory() {
- const metabot = useMetabotAgent();
+ const metabot = useMetabotAgent(AGENT_ID);
const { messages } = metabot;
const { setNavigateToPath } = useMetabotReactions();
const scrollContainerRef = useRef<HTMLDivElement>(null);
@@ -48,6 +50,7 @@ export function MetabotChatHistory() {
onRetryMessage={metabot.retryMessage}
isDoingScience={metabot.isDoingScience}
debug={metabot.debugMode}
+ conversationId={metabot.conversationId}
onInternalLinkClick={setNavigateToPath}
/>
) : null}
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
index 4fba7b48b4e..7bbe820d8ed 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
@@ -121,6 +121,7 @@ export function ConversationDetailPage({ params }: WithRouterProps) {
key={item.id}
feedback={item}
chatMessages={feedbackChatMessages}
+ conversationId={convoId}
/>
))}
</Stack>
@@ -143,6 +144,7 @@ export function ConversationDetailPage({ params }: WithRouterProps) {
isDoingScience={false}
debug
readonly
+ conversationId={convoId}
/>
</Card>
</Stack>
@@ -179,9 +181,11 @@ function StatCard({ label, value }: { label: string; value: string }) {
function FeedbackCard({
feedback,
chatMessages,
+ conversationId,
}: {
feedback: ConversationFeedback;
chatMessages: MetabotChatMessage[];
+ conversationId: string;
}) {
const agentResponse = feedback.external_id
? chatMessages.find(
@@ -222,6 +226,7 @@ function FeedbackCard({
message={agentResponse}
debug
readonly
+ conversationId={conversationId}
hideActions
getCopyText={noopGetCopyText}
submittedFeedback={undefined}
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 86c759401ab..b5f9cbda740 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -78,6 +78,8 @@ export interface Card<
dashboard_id: DashboardId | null;
document_id?: DocumentId | null;
document?: CardDocumentInfo | null;
+ metabot_conversation_id?: string | null;
+ metabot_chart_id?: string | null;
dashboard_count: number | null;
parameter_usage_count?: number | null;
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 7a066fc5cc3..6ff86788ef1 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -2,7 +2,9 @@ import type {
CardDisplayType,
CardId,
CardType,
+ CreateCardRequest,
DashboardId,
+ DatabaseId,
DatasetQuery,
DraftTransform,
PaginationResponse,
@@ -335,11 +337,19 @@ export interface MetabotGenerateContentRequest {
}
export interface MetabotGenerateContentResponse {
- draft_card: (UnsavedCard & { name?: string }) | null;
+ draft_card: (UnsavedCard & { name?: string; database_id: DatabaseId }) | null;
description: string;
error: string | null;
}
+/* Metabot v3 - Conversations */
+
+export interface SaveMetabotEntityRequest {
+ conversation_id: string;
+ chart_id: string;
+ card: CreateCardRequest;
+}
+
/* Metabot v3 - Data Part Types */
export type MetabotTodoItem = {
diff --git a/frontend/src/metabase/api/ai-streaming/schemas.ts b/frontend/src/metabase/api/ai-streaming/schemas.ts
index e7a6d952183..625ff427e34 100644
--- a/frontend/src/metabase/api/ai-streaming/schemas.ts
+++ b/frontend/src/metabase/api/ai-streaming/schemas.ts
@@ -40,6 +40,7 @@ export const knownDataPartTypes = [
"data-code_edit",
"data-transform_suggestion",
"data-generated_entity",
+ "data-entity_saved",
"data-adhoc_viz",
"data-static_viz",
] as const satisfies readonly KnownDataPart["type"][];
@@ -64,12 +65,24 @@ export type GeneratedCard = {
type: "card";
id: string;
title: string;
+ description?: string;
query: GeneratedQuery;
display?: CardDisplayType;
};
export type GeneratedEntity = GeneratedCard;
+export type SavedEntityDestination =
+ | { type: "collection"; id: number | null }
+ | { type: "dashboard"; id: number }
+ | { type: "document"; id: number };
+
+export type EntitySavedValue = {
+ chart_id: string;
+ card_id: number;
+ destination: SavedEntityDestination;
+};
+
export type KnownDataPart =
| { type: "data-navigate_to"; data: string }
| { type: "data-state"; data: Record<string, unknown> }
@@ -77,6 +90,7 @@ export type KnownDataPart =
| { type: "data-transform_suggestion"; data: SuggestedTransform }
| { type: "data-code_edit"; data: MetabotCodeEdit }
| { type: "data-generated_entity"; data: GeneratedEntity }
+ | { type: "data-entity_saved"; data: EntitySavedValue }
| { type: "data-adhoc_viz"; data: AdhocVizValue }
| { type: "data-static_viz"; data: StaticVizValue };
diff --git a/frontend/src/metabase/api/metabot.ts b/frontend/src/metabase/api/metabot.ts
index 3ed1089ece9..01d84defbef 100644
--- a/frontend/src/metabase/api/metabot.ts
+++ b/frontend/src/metabase/api/metabot.ts
@@ -1,4 +1,5 @@
import type {
+ Card,
DeleteSuggestedMetabotPromptRequest,
MetabotFeedback,
MetabotGenerateContentRequest,
@@ -10,6 +11,7 @@ import type {
MetabotSlackSettings,
MetabotSourceFeedback,
RegenerateSuggestedMetabotPromptsResponse,
+ SaveMetabotEntityRequest,
SuggestedMetabotPromptsRequest,
SuggestedMetabotPromptsResponse,
UpdateMetabotSettingsRequest,
@@ -121,6 +123,14 @@ export const metabotApi = Api.injectEndpoints({
body: params,
}),
}),
+ saveMetabotEntity: builder.mutation<Card, SaveMetabotEntityRequest>({
+ query: ({ conversation_id, ...body }) => ({
+ method: "POST",
+ url: `/api/metabot/conversations/${conversation_id}/saved-entity`,
+ body,
+ }),
+ invalidatesTags: (_, error) => invalidateTags(error, [listTag("card")]),
+ }),
submitMetabotFeedback: builder.mutation<void, MetabotFeedback>({
query: (params) => ({
method: "POST",
@@ -168,6 +178,7 @@ export const {
useDeleteSuggestedMetabotPromptMutation,
useRegenerateSuggestedMetabotPromptsMutation,
useLazyMetabotGenerateContentQuery,
+ useSaveMetabotEntityMutation,
useSubmitMetabotFeedbackMutation,
useSubmitMetabotSourceFeedbackMutation,
useUpdateMetabotSlackSettingsMutation,
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
index e9b856139e2..392c9109aeb 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContentView.tsx
@@ -55,6 +55,7 @@ import UploadOverlay from "../UploadOverlay";
import { CollectionMain, CollectionRoot } from "./CollectionContent.styled";
import { CollectionItemsTable } from "./CollectionItemsTable";
+import { useCollectionChartPaste } from "./use-collection-chart-paste";
const itemKeyFn = (item: CollectionItem) => `${item.id}:${item.model}`;
@@ -86,6 +87,8 @@ export const CollectionContentView = ({
const dispatch = useDispatch();
const [deleteCollection] = useDeleteCollectionMutation();
+ useCollectionChartPaste(collection);
+
const { data: pinnedItemsData, isLoading: loading } =
useListCollectionItemsQuery({
id: collectionId,
diff --git a/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.ts b/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.ts
new file mode 100644
index 00000000000..3516a9ae6cd
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.ts
@@ -0,0 +1,68 @@
+import { useCallback, useRef } from "react";
+import { t } from "ttag";
+
+import { useCreateCardMutation } from "metabase/api";
+import { canonicalCollectionId } from "metabase/common/collections/utils";
+import { useChartPasteListener } from "metabase/common/hooks/use-chart-paste-listener";
+import type { ChartClipboardPayload } from "metabase/common/utils/chart-clipboard";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import type { Collection } from "metabase-types/api";
+
+const PASTE_TOAST_ID = "collection-chart-paste";
+
+export function useCollectionChartPaste(collection: Collection) {
+ const dispatch = useDispatch();
+ const [createCard] = useCreateCardMutation();
+ const isPastingRef = useRef(false);
+
+ const { id, name, can_write } = collection;
+
+ const handlePasteChart = useCallback(
+ async (payload: ChartClipboardPayload) => {
+ if (isPastingRef.current) {
+ return;
+ }
+ isPastingRef.current = true;
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: null,
+ timeout: null,
+ message: t`Saving chart to ${name}…`,
+ }),
+ );
+ try {
+ await createCard({
+ name: payload.name,
+ description: payload.description ?? null,
+ display: payload.display,
+ dataset_query: payload.dataset_query,
+ visualization_settings: payload.visualization_settings,
+ collection_id: canonicalCollectionId(id),
+ }).unwrap();
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: "check_filled",
+ message: t`Chart saved to ${name}`,
+ }),
+ );
+ } catch {
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: "warning",
+ toastColor: "error",
+ message: t`Couldn't save the chart to this collection`,
+ }),
+ );
+ } finally {
+ isPastingRef.current = false;
+ }
+ },
+ [createCard, dispatch, id, name],
+ );
+
+ useChartPasteListener(Boolean(can_write), handlePasteChart);
+}
diff --git a/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.unit.spec.tsx
new file mode 100644
index 00000000000..6e1c92caab8
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionContent/use-collection-chart-paste.unit.spec.tsx
@@ -0,0 +1,107 @@
+import { act } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, waitFor } from "__support__/ui";
+import { serializeChartClipboard } from "metabase/common/utils/chart-clipboard";
+import type { Collection } from "metabase-types/api";
+import { createMockCard, createMockCollection } from "metabase-types/api/mocks";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import { useCollectionChartPaste } from "./use-collection-chart-paste";
+
+const datasetQuery = createMockStructuredDatasetQuery();
+
+const chartText = serializeChartClipboard(
+ {
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ "https://metabase.example",
+);
+
+function TestComponent({ collection }: { collection: Collection }) {
+ useCollectionChartPaste(collection);
+ return null;
+}
+
+function setup({ canWrite = true }: { canWrite?: boolean } = {}) {
+ const collection = createMockCollection({
+ id: 10,
+ name: "My Collection",
+ can_write: canWrite,
+ });
+ return renderWithProviders(<TestComponent collection={collection} />);
+}
+
+function paste(text: string) {
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", {
+ value: { getData: () => text },
+ });
+ window.dispatchEvent(event);
+}
+
+describe("useCollectionChartPaste", () => {
+ it("creates a card in the collection from a pasted chart", async () => {
+ fetchMock.post("path:/api/card", createMockCard({ id: 5 }), {
+ name: "create-card",
+ matchPartialBody: true,
+ body: { display: "bar", collection_id: 10, dataset_query: datasetQuery },
+ });
+
+ setup({ canWrite: true });
+ act(() => {
+ paste(chartText);
+ });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("create-card")).toBe(true);
+ });
+ });
+
+ it("shows an in-progress toast and ignores repeated pastes while saving", async () => {
+ fetchMock.post("path:/api/card", createMockCard({ id: 5 }), {
+ name: "create-card",
+ delay: 100,
+ });
+
+ const { store } = setup({ canWrite: true });
+ act(() => {
+ paste(chartText);
+ paste(chartText);
+ });
+
+ await waitFor(() => {
+ expect(store.getState().undo).toContainEqual(
+ expect.objectContaining({ message: "Saving chart to My Collection…" }),
+ );
+ });
+
+ await waitFor(() => {
+ expect(store.getState().undo).toContainEqual(
+ expect.objectContaining({ message: "Chart saved to My Collection" }),
+ );
+ });
+ expect(fetchMock.callHistory.calls("create-card")).toHaveLength(1);
+ });
+
+ it("does nothing in a read-only collection", () => {
+ fetchMock.post("path:/api/card", createMockCard({ id: 5 }));
+
+ setup({ canWrite: false });
+ paste(chartText);
+
+ expect(fetchMock.callHistory.called("path:/api/card")).toBe(false);
+ });
+
+ it("ignores pastes that are not charts", () => {
+ fetchMock.post("path:/api/card", createMockCard({ id: 5 }));
+
+ setup({ canWrite: true });
+ paste("just some text");
+
+ expect(fetchMock.callHistory.called("path:/api/card")).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/common/hooks/use-chart-paste-listener.ts b/frontend/src/metabase/common/hooks/use-chart-paste-listener.ts
new file mode 100644
index 00000000000..941db19751d
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-chart-paste-listener.ts
@@ -0,0 +1,37 @@
+import { useCallback, useEffect } from "react";
+
+import {
+ type ChartClipboardPayload,
+ isEditablePasteTarget,
+ parseChartClipboard,
+} from "metabase/common/utils/chart-clipboard";
+
+export function useChartPasteListener(
+ enabled: boolean,
+ onPasteChart: (payload: ChartClipboardPayload) => void,
+) {
+ const handlePaste = useCallback(
+ (event: ClipboardEvent) => {
+ if (isEditablePasteTarget(event.target)) {
+ return;
+ }
+ const payload = parseChartClipboard(
+ event.clipboardData?.getData("text/plain"),
+ );
+ if (!payload) {
+ return;
+ }
+ event.preventDefault();
+ onPasteChart(payload);
+ },
+ [onPasteChart],
+ );
+
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+ window.addEventListener("paste", handlePaste);
+ return () => window.removeEventListener("paste", handlePaste);
+ }, [enabled, handlePaste]);
+}
diff --git a/frontend/src/metabase/common/utils/chart-clipboard.ts b/frontend/src/metabase/common/utils/chart-clipboard.ts
new file mode 100644
index 00000000000..58e55003915
--- /dev/null
+++ b/frontend/src/metabase/common/utils/chart-clipboard.ts
@@ -0,0 +1,71 @@
+import { P, isMatching } from "ts-pattern";
+
+import * as Urls from "metabase/urls";
+import type { Card, CardDisplayType, DatasetQuery } from "metabase-types/api";
+import { isCardDisplayType } from "metabase-types/api";
+
+import { deserializeCardFromUrl } from "./card";
+
+const ADHOC_QUESTION_HASH_REGEX = /\/question#([A-Za-z0-9_=-]+)/;
+
+export type ChartClipboardPayload = Pick<
+ Card,
+ "name" | "dataset_query" | "visualization_settings"
+> &
+ Partial<Pick<Card, "description">> & {
+ display: CardDisplayType;
+ };
+
+export function serializeChartClipboard(
+ payload: ChartClipboardPayload,
+ siteUrl: string,
+): string {
+ const path = Urls.card(
+ { ...payload, displayIsLocked: true },
+ { includeDisplayIsLocked: true },
+ );
+ return `${siteUrl.replace(/\/$/, "")}${path}`;
+}
+
+const CHART_CLIPBOARD_CARD_PATTERN = {
+ display: P.when(isCardDisplayType),
+ dataset_query: P.when(
+ (value): value is DatasetQuery =>
+ typeof value === "object" && value !== null,
+ ),
+};
+
+export function parseChartClipboard(
+ text: string | null | undefined,
+): ChartClipboardPayload | null {
+ const hash = text?.match(ADHOC_QUESTION_HASH_REGEX)?.[1];
+ if (!hash) {
+ return null;
+ }
+ try {
+ const card: Card = deserializeCardFromUrl(hash);
+ if (!isMatching(CHART_CLIPBOARD_CARD_PATTERN, card)) {
+ return null;
+ }
+ return {
+ name: card.name ?? "",
+ description: card.description ?? undefined,
+ display: card.display,
+ dataset_query: card.dataset_query,
+ visualization_settings: card.visualization_settings ?? {},
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function isEditablePasteTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) {
+ return false;
+ }
+ return (
+ target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.isContentEditable
+ );
+}
diff --git a/frontend/src/metabase/common/utils/chart-clipboard.unit.spec.ts b/frontend/src/metabase/common/utils/chart-clipboard.unit.spec.ts
new file mode 100644
index 00000000000..cef023c9e23
--- /dev/null
+++ b/frontend/src/metabase/common/utils/chart-clipboard.unit.spec.ts
@@ -0,0 +1,107 @@
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import { deserializeCardFromUrl, serializeCardForUrl } from "./card";
+import {
+ parseChartClipboard,
+ serializeChartClipboard,
+} from "./chart-clipboard";
+
+const datasetQuery = createMockStructuredDatasetQuery();
+const SITE_URL = "https://metabase.example";
+
+describe("chart-clipboard", () => {
+ it("serializes a chart as an ad-hoc question link that the QB deserializer can read", () => {
+ const text = serializeChartClipboard(
+ {
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ SITE_URL,
+ );
+
+ expect(text).toMatch(new RegExp(`^${SITE_URL}/question#[A-Za-z0-9_=-]+$`));
+ const hash = text.split("#")[1];
+ expect(deserializeCardFromUrl(hash)).toEqual({
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ displayIsLocked: true,
+ });
+ });
+
+ it("round-trips a serialized chart payload", () => {
+ const text = serializeChartClipboard(
+ {
+ name: "Orders by month",
+ description: "Monthly count of orders.",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ SITE_URL,
+ );
+
+ expect(parseChartClipboard(text)).toEqual({
+ name: "Orders by month",
+ description: "Monthly count of orders.",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ });
+ });
+
+ it("does not double up the slash when the site url has a trailing slash", () => {
+ const text = serializeChartClipboard(
+ {
+ name: "Orders",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ `${SITE_URL}/`,
+ );
+
+ expect(text.startsWith(`${SITE_URL}/question#`)).toBe(true);
+ });
+
+ it("parses any ad-hoc question link produced by the QB serializer", () => {
+ const hash = serializeCardForUrl(
+ {
+ name: "Orders by month",
+ description: null,
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ displayIsLocked: true,
+ },
+ { includeDisplayIsLocked: true },
+ );
+
+ expect(parseChartClipboard(`${SITE_URL}/question#${hash}`)).toEqual({
+ name: "Orders by month",
+ description: undefined,
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ });
+ });
+
+ it("returns null for clipboard content that is not a chart link", () => {
+ expect(parseChartClipboard("just some text")).toBeNull();
+ expect(
+ parseChartClipboard("https://metabase.example/question/123"),
+ ).toBeNull();
+ expect(parseChartClipboard("")).toBeNull();
+ expect(parseChartClipboard(null)).toBeNull();
+ expect(parseChartClipboard(undefined)).toBeNull();
+ });
+
+ it("returns null for a chart link with a malformed hash", () => {
+ expect(
+ parseChartClipboard(`${SITE_URL}/question#not-valid-base64!!`),
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
index abe54b0e999..4cc470b5687 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
@@ -29,11 +29,14 @@ import { RefreshWidget } from "../RefreshWidget";
import S from "./Dashboard.module.css";
import { Grid, ParametersList } from "./components";
+import { useDashboardChartPaste } from "./use-dashboard-chart-paste";
const DashboardDefaultView = ({ className }: { className?: string }) => {
const { dashboard, isEditing, isFullscreen, isSharing, selectedTabId } =
useDashboardContext();
+ useDashboardChartPaste();
+
const isHeaderVisible = useSelector(getIsHeaderVisible);
const currentTabDashcards = useMemo(() => {
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.ts b/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.ts
new file mode 100644
index 00000000000..88c3beae41d
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.ts
@@ -0,0 +1,81 @@
+import { useCallback, useRef } from "react";
+import { t } from "ttag";
+
+import { useCreateCardMutation } from "metabase/api";
+import { useChartPasteListener } from "metabase/common/hooks/use-chart-paste-listener";
+import type { ChartClipboardPayload } from "metabase/common/utils/chart-clipboard";
+import { addCardToDashboard } from "metabase/dashboard/actions";
+import { useDashboardContext } from "metabase/dashboard/context";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+
+const PASTE_TOAST_ID = "dashboard-chart-paste";
+
+export function useDashboardChartPaste() {
+ const dispatch = useDispatch();
+ const [createCard] = useCreateCardMutation();
+ const { dashboard, isEditing, selectedTabId } = useDashboardContext();
+ const isPastingRef = useRef(false);
+
+ const dashboardId = dashboard?.id ?? null;
+
+ const handlePasteChart = useCallback(
+ async (payload: ChartClipboardPayload) => {
+ if (dashboardId == null || isPastingRef.current) {
+ return;
+ }
+ isPastingRef.current = true;
+ const savedTabId =
+ typeof selectedTabId === "number" && selectedTabId > 0
+ ? selectedTabId
+ : undefined;
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: null,
+ timeout: null,
+ message: t`Adding chart to dashboard…`,
+ }),
+ );
+ try {
+ const card = await createCard({
+ name: payload.name,
+ description: payload.description ?? null,
+ display: payload.display,
+ dataset_query: payload.dataset_query,
+ visualization_settings: payload.visualization_settings,
+ dashboard_id: dashboardId,
+ dashboard_tab_id: savedTabId,
+ }).unwrap();
+ await dispatch(
+ addCardToDashboard({
+ dashId: dashboardId,
+ tabId: selectedTabId ?? null,
+ cardId: card.id,
+ }),
+ );
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: "check_filled",
+ message: t`Chart added to dashboard`,
+ }),
+ );
+ } catch {
+ dispatch(
+ addUndo({
+ id: PASTE_TOAST_ID,
+ icon: "warning",
+ toastColor: "error",
+ message: t`Couldn't add the chart to this dashboard`,
+ }),
+ );
+ } finally {
+ isPastingRef.current = false;
+ }
+ },
+ [dispatch, createCard, dashboardId, selectedTabId],
+ );
+
+ useChartPasteListener(isEditing && dashboardId != null, handlePasteChart);
+}
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.unit.spec.tsx b/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.unit.spec.tsx
new file mode 100644
index 00000000000..9faabe572ab
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/Dashboard/use-dashboard-chart-paste.unit.spec.tsx
@@ -0,0 +1,171 @@
+import { act } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import {
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupDatabasesEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, waitFor } from "__support__/ui";
+import { serializeChartClipboard } from "metabase/common/utils/chart-clipboard";
+import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
+import { getDashcards } from "metabase/dashboard/selectors";
+import { createMockDashboardState } from "metabase/redux/store/mocks";
+import type { Card } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockDashboard,
+ createMockDataset,
+} from "metabase-types/api/mocks";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import { useDashboardChartPaste } from "./use-dashboard-chart-paste";
+
+const TEST_DB = createSampleDatabase();
+const datasetQuery = createMockStructuredDatasetQuery();
+
+const CREATED_CARD = createMockCard({
+ id: 99,
+ display: "bar",
+ dataset_query: datasetQuery,
+});
+
+const chartText = serializeChartClipboard(
+ {
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ "https://metabase.example",
+);
+
+function TestComponent() {
+ useDashboardChartPaste();
+ return null;
+}
+
+function setup({
+ isEditing = true,
+ selectedTabId = null,
+}: { isEditing?: boolean; selectedTabId?: number | null } = {}) {
+ const dashboard = createMockDashboard({ id: 7 });
+ const dashboardState = createMockDashboardState({
+ dashboardId: dashboard.id,
+ dashboards: {
+ [dashboard.id]: { ...dashboard, dashcards: [] },
+ },
+ editingDashboard: dashboard,
+ dashcards: {},
+ });
+
+ const { store } = renderWithProviders(
+ <MockDashboardContext
+ dashboard={dashboard}
+ isEditing={isEditing}
+ selectedTabId={selectedTabId}
+ >
+ <TestComponent />
+ </MockDashboardContext>,
+ { storeInitialState: { dashboard: dashboardState } },
+ );
+
+ return { store };
+}
+
+function paste(text: string) {
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", {
+ value: { getData: () => text },
+ });
+ window.dispatchEvent(event);
+}
+
+function setupCardMocks(card: Card) {
+ setupDatabasesEndpoints([TEST_DB]);
+ setupCardEndpoints(card);
+ setupCardQueryEndpoints(card, createMockDataset());
+ setupCardQueryMetadataEndpoint(
+ card,
+ createMockCardQueryMetadata({ databases: [TEST_DB] }),
+ );
+}
+
+describe("useDashboardChartPaste", () => {
+ it("creates a dashboard card from a pasted chart while editing", async () => {
+ setupCardMocks(CREATED_CARD);
+ fetchMock.post("path:/api/card", CREATED_CARD, {
+ name: "create-card",
+ matchPartialBody: true,
+ body: {
+ display: "bar",
+ dashboard_id: 7,
+ dashboard_tab_id: 3,
+ dataset_query: datasetQuery,
+ },
+ });
+
+ const { store } = setup({ isEditing: true, selectedTabId: 3 });
+ act(() => {
+ paste(chartText);
+ });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("create-card")).toBe(true);
+ });
+ await waitFor(() => {
+ const dashcards = Object.values(getDashcards(store.getState()));
+ expect(dashcards).toContainEqual(
+ expect.objectContaining({ card_id: 99, dashboard_tab_id: 3 }),
+ );
+ });
+ });
+
+ it("shows an in-progress toast and ignores repeated pastes while saving", async () => {
+ setupCardMocks(CREATED_CARD);
+ fetchMock.post("path:/api/card", CREATED_CARD, {
+ name: "create-card",
+ delay: 100,
+ });
+
+ const { store } = setup({ isEditing: true });
+ act(() => {
+ paste(chartText);
+ paste(chartText);
+ });
+
+ await waitFor(() => {
+ expect(store.getState().undo).toContainEqual(
+ expect.objectContaining({ message: "Adding chart to dashboard…" }),
+ );
+ });
+
+ await waitFor(() => {
+ expect(store.getState().undo).toContainEqual(
+ expect.objectContaining({ message: "Chart added to dashboard" }),
+ );
+ });
+ expect(fetchMock.callHistory.calls("create-card")).toHaveLength(1);
+ });
+
+ it("does nothing when not editing", () => {
+ fetchMock.post("path:/api/card", CREATED_CARD);
+
+ setup({ isEditing: false });
+ paste(chartText);
+
+ expect(fetchMock.callHistory.called("path:/api/card")).toBe(false);
+ });
+
+ it("ignores pastes that are not charts", () => {
+ fetchMock.post("path:/api/card", CREATED_CARD);
+
+ setup({ isEditing: true });
+ paste("just some text");
+
+ expect(fetchMock.callHistory.called("path:/api/card")).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/documents/components/Editor/Editor.tsx b/frontend/src/metabase/documents/components/Editor/Editor.tsx
index 35be0964ab1..11dc345cac5 100644
--- a/frontend/src/metabase/documents/components/Editor/Editor.tsx
+++ b/frontend/src/metabase/documents/components/Editor/Editor.tsx
@@ -11,7 +11,7 @@ import { DND_IGNORE_CLASS_NAME } from "metabase/common/components/dnd";
import { getMentionsCache } from "metabase/documents/selectors";
import { isMetabotBlock } from "metabase/documents/utils/editorNodeUtils";
import { getMentionsCacheKey } from "metabase/documents/utils/mentionsUtils";
-import { useSelector, useStore } from "metabase/redux";
+import { useDispatch, useSelector, useStore } from "metabase/redux";
import type { State } from "metabase/redux/store";
import type { CardEmbedRef } from "metabase/redux/store/documents";
import { EditorBubbleMenu } from "metabase/rich_text_editing/tiptap/components/EditorBubbleMenu/EditorBubbleMenu";
@@ -44,6 +44,7 @@ import { DocumentBlockShell } from "./DocumentBlockShell";
import { DocumentEditorHostProvider } from "./DocumentEditorHost";
import DropCursorS from "./DropCursor.module.css";
import S from "./Editor.module.css";
+import { createChartPasteExtension } from "./chart-paste-extension";
import { useCardEmbedsTracking, useQuestionSelection } from "./hooks";
const BUBBLE_MENU_DISALLOWED_NODES: string[] = [
@@ -108,6 +109,7 @@ export const Editor: React.FC<EditorProps> = React.memo(
}) => {
const siteUrl = useSelector((state) => getSetting(state, "site-url"));
const { getState } = useStore();
+ const dispatch = useDispatch();
const extensions = useMemo(
() => [
@@ -164,8 +166,9 @@ export const Editor: React.FC<EditorProps> = React.memo(
}),
ResizeNode,
HandleEditorDrop,
+ createChartPasteExtension(dispatch),
],
- [siteUrl, getState],
+ [siteUrl, getState, dispatch],
);
const editor = useEditor(
diff --git a/frontend/src/metabase/documents/components/Editor/chart-paste-extension.ts b/frontend/src/metabase/documents/components/Editor/chart-paste-extension.ts
new file mode 100644
index 00000000000..37025fd0ab8
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/chart-paste-extension.ts
@@ -0,0 +1,77 @@
+import type { JSONContent } from "@tiptap/core";
+import { Extension } from "@tiptap/core";
+import { Plugin } from "@tiptap/pm/state";
+import type { EditorView } from "@tiptap/pm/view";
+
+import { parseChartClipboard } from "metabase/common/utils/chart-clipboard";
+import {
+ createDraftCard,
+ generateDraftCardId,
+} from "metabase/documents/documents.slice";
+import { buildDraftCard } from "metabase/rich_text_editing/tiptap/extensions/shared/draft-card";
+import { wrapCardEmbed } from "metabase/rich_text_editing/tiptap/extensions/shared/layout";
+
+type DispatchDraftCard = (action: ReturnType<typeof createDraftCard>) => void;
+
+export function materializePastedChart(
+ text: string | null | undefined,
+ dispatch: DispatchDraftCard,
+): JSONContent | null {
+ const payload = parseChartClipboard(text);
+ if (!payload) {
+ return null;
+ }
+ const draftId = generateDraftCardId();
+ dispatch(
+ createDraftCard({
+ originalCard: buildDraftCard({
+ id: draftId,
+ name: payload.name,
+ display: payload.display,
+ dataset_query: payload.dataset_query,
+ visualization_settings: payload.visualization_settings,
+ description: payload.description,
+ database_id: payload.dataset_query.database ?? undefined,
+ }),
+ modifiedData: {},
+ draftId,
+ }),
+ );
+ return wrapCardEmbed({ type: "cardEmbed", attrs: { id: draftId } });
+}
+
+function isPastingIntoCodeNode(view: EditorView) {
+ const pasteTarget = view.state.selection.$head.parent;
+ return Boolean(pasteTarget.type.spec.code);
+}
+
+export function createChartPasteExtension(dispatch: DispatchDraftCard) {
+ return Extension.create({
+ name: "chartPaste",
+
+ addProseMirrorPlugins() {
+ const { editor } = this;
+
+ return [
+ new Plugin({
+ props: {
+ handlePaste: (view, event) => {
+ if (!editor.isEditable || isPastingIntoCodeNode(view)) {
+ return false;
+ }
+ const node = materializePastedChart(
+ event.clipboardData?.getData("text/plain"),
+ dispatch,
+ );
+ if (!node) {
+ return false;
+ }
+ editor.commands.insertContent(node);
+ return true;
+ },
+ },
+ }),
+ ];
+ },
+ });
+}
diff --git a/frontend/src/metabase/documents/components/Editor/chart-paste-extension.unit.spec.tsx b/frontend/src/metabase/documents/components/Editor/chart-paste-extension.unit.spec.tsx
new file mode 100644
index 00000000000..c11df8b2679
--- /dev/null
+++ b/frontend/src/metabase/documents/components/Editor/chart-paste-extension.unit.spec.tsx
@@ -0,0 +1,49 @@
+import { renderWithProviders } from "__support__/ui";
+import { serializeChartClipboard } from "metabase/common/utils/chart-clipboard";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import { materializePastedChart } from "./chart-paste-extension";
+
+const datasetQuery = createMockStructuredDatasetQuery();
+
+const chartText = serializeChartClipboard(
+ {
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ "https://metabase.example",
+);
+
+describe("materializePastedChart", () => {
+ it("registers a draft card and returns a cardEmbed node for a pasted chart", () => {
+ const { store } = renderWithProviders(<div />);
+
+ const node = materializePastedChart(chartText, store.dispatch);
+ const draftId = node?.content?.[0]?.attrs?.id;
+
+ expect(draftId).toBeLessThan(0);
+ expect(node).toEqual({
+ type: "resizeNode",
+ content: [{ type: "cardEmbed", attrs: { id: draftId } }],
+ });
+ expect(store.getState().documents.draftCards[draftId]).toEqual(
+ expect.objectContaining({
+ id: draftId,
+ name: "Orders by month",
+ display: "bar",
+ dataset_query: datasetQuery,
+ type: "question",
+ }),
+ );
+ });
+
+ it("returns null and registers no draft card for non-chart content", () => {
+ const { store } = renderWithProviders(<div />);
+
+ expect(materializePastedChart("just some text", store.dispatch)).toBeNull();
+ expect(materializePastedChart(undefined, store.dispatch)).toBeNull();
+ expect(Object.keys(store.getState().documents.draftCards)).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx
index 3e96cd138d7..f906199fc7f 100644
--- a/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/AIMarkdown/AIMarkdown.unit.spec.tsx
@@ -1,16 +1,22 @@
import { screen } 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 { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
import { createMockState } from "metabase/redux/store/mocks";
import { createMockCard } from "metabase-types/api/mocks";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
import { AIMarkdown } from "./AIMarkdown";
-const setup = (props: { children: string }) => {
+const setup = (
+ props: { children: string },
+ { conversationCharts }: { conversationCharts?: Record<string, unknown> } = {},
+) => {
setupEnterprisePlugins();
const settings = mockSettings({ "site-url": "http://localhost:3000" });
@@ -19,8 +25,14 @@ const setup = (props: { children: string }) => {
createMockCard({ id: 123, name: "Test Question" }),
);
+ const metabot = conversationCharts
+ ? assocIn(getMetabotInitialState(), ["conversations", "omnibot", "state"], {
+ charts: conversationCharts,
+ })
+ : getMetabotInitialState();
+
return renderWithProviders(<AIMarkdown {...props} />, {
- storeInitialState: createMockState({ settings }),
+ storeInitialState: createMockState({ settings, metabot }),
});
};
@@ -40,6 +52,30 @@ describe("AIMarkdown", () => {
expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();
});
+ it("should render a generated-chart mention as a smart link chip", async () => {
+ setup(
+ { children: "[Orders by month](metabase://chart/chart-1)" },
+ {
+ conversationCharts: {
+ "chart-1": {
+ queries: [createMockStructuredDatasetQuery()],
+ visualization_settings: { chart_type: "bar" },
+ },
+ },
+ },
+ );
+
+ expect(await screen.findByText("Orders by month")).toBeInTheDocument();
+ expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();
+ });
+
+ it("should still render the chart mention chip when the chart is not in conversation state", async () => {
+ setup({ children: "[Orders by month](metabase://chart/chart-1)" });
+
+ expect(await screen.findByText("Orders by month")).toBeInTheDocument();
+ expect(screen.getByRole("img", { name: /icon/ })).toBeInTheDocument();
+ });
+
it("should render GFM tables", async () => {
setup({
children: `
diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx
index 7ed036b78c2..6d2a76f6d23 100644
--- a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx
+++ b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx
@@ -1,17 +1,35 @@
+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 type { MetabaseProtocolEntityModel } from "metabase/metabot/utils/links";
+import { getConversationChart } from "metabase/metabot/state";
+import type {
+ MetabaseProtocolEntityModel,
+ ParsedMetabaseProtocolLink,
+} from "metabase/metabot/utils/links";
+import { useSelector } from "metabase/redux";
import { useEntityData } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";
import { entityToUrlableModel } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";
-import { modelToUrl } from "metabase/urls";
+import { conversationChartUrl, modelToUrl } from "metabase/urls";
import S from "../AIMarkdown.module.css";
import { InternalLink } from "./InternalLink";
-export const MarkdownSmartLink = ({
+type MarkdownSmartLinkProps = {
+ onInternalLinkClick?: (href: string) => void;
+ name: string;
+} & ParsedMetabaseProtocolLink;
+
+export const MarkdownSmartLink = (props: MarkdownSmartLinkProps) =>
+ props.model === "chart" ? (
+ <ChartSmartLink {...props} />
+ ) : (
+ <EntitySmartLink {...props} />
+ );
+
+const EntitySmartLink = ({
onInternalLinkClick,
id,
name,
@@ -37,17 +55,82 @@ export const MarkdownSmartLink = ({
: ""; // fallback to linking to nothing
return (
- <InternalLink
+ <SmartLinkChip
onInternalLinkClick={onInternalLinkClick}
href={entityUrl}
- target="_blank"
- rel="noreferrer"
- className={S.smartLink}
- >
- <span className={S.smartLinkInner}>
- <EntityIcon {...icon} className={S.icon} />
- {name}
+ icon={icon}
+ name={name}
+ />
+ );
+};
+
+const ChartSmartLink = ({
+ onInternalLinkClick,
+ id,
+ name,
+}: {
+ onInternalLinkClick?: (href: string) => void;
+ id: string;
+ name: string;
+ model: "chart";
+}) => {
+ const getIcon = useGetIcon();
+ const chart = useSelector((state) => getConversationChart(state, id));
+ const icon = getIcon({
+ model: "card",
+ display: chart?.visualization_settings?.chart_type ?? "table",
+ });
+ const href = chart ? conversationChartUrl(chart) : undefined;
+
+ if (!href) {
+ return (
+ <span className={S.smartLink}>
+ <SmartLinkChipContent icon={icon} name={name} />
</span>
- </InternalLink>
+ );
+ }
+
+ return (
+ <SmartLinkChip
+ onInternalLinkClick={onInternalLinkClick}
+ href={href}
+ icon={icon}
+ name={name}
+ />
);
};
+
+const SmartLinkChipContent = ({
+ icon,
+ name,
+}: {
+ icon: ComponentProps<typeof EntityIcon>;
+ name: string;
+}) => (
+ <span className={S.smartLinkInner}>
+ <EntityIcon {...icon} className={S.icon} />
+ {name}
+ </span>
+);
+
+const SmartLinkChip = ({
+ onInternalLinkClick,
+ href,
+ icon,
+ name,
+}: {
+ onInternalLinkClick?: (href: string) => void;
+ href: string;
+ icon: ComponentProps<typeof EntityIcon>;
+ name: string;
+}) => (
+ <InternalLink
+ onInternalLinkClick={onInternalLinkClick}
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ className={S.smartLink}
+ >
+ <SmartLinkChipContent icon={icon} name={name} />
+ </InternalLink>
+);
diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsx
index 600036eebae..7f1c7583d19 100644
--- a/frontend/src/metabase/metabot/components/Metabot.tsx
+++ b/frontend/src/metabase/metabot/components/Metabot.tsx
@@ -98,7 +98,7 @@ const MetabotSidebarActions = ({ agentId }: { agentId: MetabotAgentId }) => {
// TODO: add test coverage for these
export interface MetabotConfig {
- agentId?: MetabotAgentId;
+ agentId: MetabotAgentId;
emptyText?: string;
hideSuggestedPrompts?: boolean;
preventRetryMessage?: boolean;
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx
index b8cbfd72d16..1492eed5998 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx
@@ -2,12 +2,31 @@ import { useClipboard } from "@mantine/hooks";
import cx from "classnames";
import { useMemo } from "react";
import { match } from "ts-pattern";
-import { t } from "ttag";
+import { jt, t } from "ttag";
+import {
+ skipToken,
+ useGetCardQuery,
+ useGetCollectionQuery,
+ useGetDashboardQuery,
+ useGetDocumentQuery,
+} from "metabase/api";
+import type { EntitySavedValue } from "metabase/api/ai-streaming/schemas";
import { CodeEditor } from "metabase/common/components/CodeEditor";
import { ForwardRefLink } from "metabase/common/components/Link";
import type { MetabotAgentDataPartMessage } from "metabase/metabot/state";
-import { ActionIcon, Badge, Box, Flex, Icon, Stack, Text } from "metabase/ui";
+import {
+ ActionIcon,
+ Anchor,
+ Badge,
+ Box,
+ Flex,
+ Icon,
+ Skeleton,
+ Stack,
+ Text,
+} from "metabase/ui";
+import * as Urls from "metabase/urls";
import type { MetabotCodeEdit } from "metabase-types/api";
import {
@@ -23,12 +42,14 @@ type AgentDataPartMessageProps = {
message: MetabotAgentDataPartMessage;
readonly: boolean;
debug: boolean;
+ conversationId: string;
};
export const AgentDataPartMessage = ({
message,
readonly,
debug,
+ conversationId,
}: AgentDataPartMessageProps) =>
match(message)
.with({ part: { type: "data-todo_list" } }, ({ part }) => (
@@ -73,10 +94,20 @@ export const AgentDataPartMessage = ({
({ part }) => (
<Stack gap="md">
{debug && <DataPartJsonCard type={part.type} value={part.data} />}
- <MetabotInlineChart value={part.data} />
+ <MetabotInlineChart
+ value={part.data}
+ readonly={readonly}
+ conversationId={conversationId}
+ />
</Stack>
),
)
+ .with({ part: { type: "data-entity_saved" } }, ({ part }) => (
+ <Stack gap="md">
+ {debug && <DataPartJsonCard type={part.type} value={part.data} />}
+ <EntitySavedMessage value={part.data} />
+ </Stack>
+ ))
.with({ part: { type: "data-adhoc_viz" } }, ({ part }) =>
debug ? <DataPartJsonCard type={part.type} value={part.data} /> : null,
)
@@ -88,6 +119,92 @@ export const AgentDataPartMessage = ({
return null;
});
+const EntitySavedMessage = ({ value }: { value: EntitySavedValue }) => {
+ const { destination } = value;
+
+ const { data: card, isLoading: isCardLoading } = useGetCardQuery({
+ id: value.card_id,
+ ignore_error: true,
+ });
+ const { data: collection, isLoading: isCollectionLoading } =
+ useGetCollectionQuery(
+ destination.type === "collection"
+ ? { id: destination.id ?? "root", ignore_error: true }
+ : skipToken,
+ );
+ const { data: dashboard, isLoading: isDashboardLoading } =
+ useGetDashboardQuery(
+ destination.type === "dashboard"
+ ? { id: destination.id, ignore_error: true }
+ : skipToken,
+ );
+ const { data: document, isLoading: isDocumentLoading } = useGetDocumentQuery(
+ destination.type === "document" ? { id: destination.id } : skipToken,
+ );
+ const container = match(destination)
+ .with({ type: "dashboard" }, () =>
+ dashboard
+ ? { name: dashboard.name, url: Urls.dashboard(dashboard) }
+ : null,
+ )
+ .with({ type: "document" }, () =>
+ document ? { name: document.name, url: Urls.document(document) } : null,
+ )
+ .with({ type: "collection" }, () =>
+ collection
+ ? { name: collection.name, url: Urls.collection(collection) }
+ : null,
+ )
+ .exhaustive();
+
+ if (
+ isCardLoading ||
+ isCollectionLoading ||
+ isDashboardLoading ||
+ isDocumentLoading
+ ) {
+ return <Skeleton h="1rem" w="18rem" data-testid="entity-saved-loading" />;
+ }
+
+ if (card == null) {
+ return null;
+ }
+
+ const target = container && (
+ <Anchor
+ key="target"
+ component={ForwardRefLink}
+ to={container.url}
+ target="_blank"
+ fw="bold"
+ >
+ {container.name}
+ </Anchor>
+ );
+ const chartName = (
+ <Anchor
+ key="name"
+ component={ForwardRefLink}
+ to={Urls.card(card)}
+ target="_blank"
+ fw="bold"
+ >
+ {card.name}
+ </Anchor>
+ );
+
+ return (
+ <Flex align="center" gap="sm" c="text-secondary">
+ <Icon name="check" size={14} />
+ <Text c="text-secondary">
+ {target
+ ? jt`Chart ${chartName} saved to ${target}`
+ : jt`Chart ${chartName} saved`}
+ </Text>
+ </Flex>
+ );
+};
+
const formatPartType = (type: string) => type.replace(/^data-/, "");
const DataPartJsonCard = ({
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
index 5a73e425794..cb641122cf1 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
@@ -158,6 +158,7 @@ export const MetabotChat = ({
}
isDoingScience={metabot.isDoingScience}
debug={metabot.debugMode}
+ conversationId={metabot.conversationId}
/>
{/* loading */}
{metabot.isDoingScience && (
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
index 0b054e8823b..f6c257eb0d4 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
@@ -47,6 +47,7 @@ const isUserVisibleDataPart = (part: MetabotDataPart): boolean =>
.with({ type: "data-navigate_to" }, () => true)
.with({ type: "data-code_edit" }, () => true)
.with({ type: "data-generated_entity" }, () => true)
+ .with({ type: "data-entity_saved" }, () => true)
.with({ type: "data-adhoc_viz" }, () => false)
.with({ type: "data-static_viz" }, () => false)
.exhaustive();
@@ -175,6 +176,7 @@ interface AgentMessageProps extends Omit<BaseMessageProps, "message"> {
message: MetabotAgentChatMessage;
debug: boolean;
readonly: boolean;
+ conversationId: string;
onRetry?: (messageId: string) => void;
getCopyText: () => string;
setFeedbackMessage?: (data: { messageId: string; positive: boolean }) => void;
@@ -188,6 +190,7 @@ export const AgentMessage = ({
className,
debug,
readonly,
+ conversationId,
getCopyText,
onRetry,
setFeedbackMessage,
@@ -215,7 +218,12 @@ export const AgentMessage = ({
</AIMarkdown>
))
.with({ type: "data_part" }, (m) => (
- <AgentDataPartMessage message={m} debug={debug} readonly={readonly} />
+ <AgentDataPartMessage
+ message={m}
+ debug={debug}
+ readonly={readonly}
+ conversationId={conversationId}
+ />
))
.with({ type: "tool_call" }, (m) => (
<AgentToolCallMessage message={m} />
@@ -432,6 +440,7 @@ export const Messages = ({
isDoingScience,
debug,
readonly = false,
+ conversationId,
onInternalLinkClick,
getExtraActions,
}: {
@@ -440,6 +449,7 @@ export const Messages = ({
isDoingScience: boolean;
debug: boolean;
readonly?: boolean;
+ conversationId: string;
onInternalLinkClick?: (navigateToPath: string) => void;
getExtraActions?: (messageId: string) => ReactNode;
}) => {
@@ -507,6 +517,7 @@ export const Messages = ({
message={message}
debug={debug}
readonly={readonly}
+ conversationId={conversationId}
onRetry={isLastUserMessage ? onRetryMessage : undefined}
getCopyText={() => getAgentReplyCopyText(message.id)}
setFeedbackMessage={(data) =>
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css
index 7214f0d6a90..363064ad77a 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.module.css
@@ -6,7 +6,7 @@
}
.header {
- padding: 0.5rem 0.5rem 0.5rem 0.75rem;
+ padding: 0.5rem 0.25rem 0.5rem 0.75rem;
}
.title {
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx
index b803526e67a..e073b6310bc 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx
@@ -1,12 +1,38 @@
-import { useMemo } from "react";
+import { useClipboard } from "@mantine/hooks";
+import { useMemo, useState } from "react";
+import { P, match } from "ts-pattern";
+import { t } from "ttag";
import { noop } from "underscore";
-import { useGetAdhocQueryQuery } from "metabase/api";
+import {
+ skipToken,
+ useGetAdhocQueryQuery,
+ useGetCardQuery,
+} from "metabase/api";
import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";
+import { useSaveMetabotEntityMutation } from "metabase/api/metabot";
import { ForwardRefLink } from "metabase/common/components/Link";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { SaveQuestionModal } from "metabase/common/components/SaveQuestionModal";
+import { useSetting } from "metabase/common/hooks";
import { serializeCardForUrl } from "metabase/common/utils/card";
-import { Anchor, Box, Center, Flex } from "metabase/ui";
+import { serializeChartClipboard } from "metabase/common/utils/chart-clipboard";
+import { getSavedChartCardId, markChartSaved } from "metabase/metabot/state";
+import { useDispatch, useSelector } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { push } from "metabase/router";
+import {
+ ActionIcon,
+ Anchor,
+ Box,
+ Button,
+ Center,
+ Flex,
+ Icon,
+ Tooltip,
+} from "metabase/ui";
+import * as Urls from "metabase/urls";
+import { isResourceNotFoundError } from "metabase/utils/errors";
import Visualization from "metabase/visualizations/components/Visualization";
import { ErrorView } from "metabase/visualizations/components/Visualization/ErrorView";
import {
@@ -14,7 +40,7 @@ import {
getGenericErrorMessage,
} from "metabase/visualizations/lib/errors";
import Question from "metabase-lib/v1/Question";
-import type { Card } from "metabase-types/api";
+import type { DashboardTabId } from "metabase-types/api";
import S from "./MetabotInlineChart.module.css";
@@ -24,27 +50,65 @@ import S from "./MetabotInlineChart.module.css";
* result; the title bar links out to the full question.
*/
export function MetabotInlineChart({
- value: { title, display, query },
+ value: { id: chartId, title, description, display, query },
+ readonly = false,
+ conversationId,
}: {
value: GeneratedCard;
+ readonly?: boolean;
+ conversationId: string;
}) {
const datasetQuery = query.query;
+ const clipboard = useClipboard();
+ const recordedCardId = useSelector((state) =>
+ getSavedChartCardId(state, chartId),
+ );
+ const siteUrl = useSetting("site-url");
+
+ const { data: savedCard, error: savedCardError } = useGetCardQuery(
+ recordedCardId != null
+ ? { id: recordedCardId, ignore_error: true }
+ : skipToken,
+ );
+ const isLinkSevered =
+ isResourceNotFoundError(savedCardError) ||
+ (savedCard != null && savedCard.metabot_chart_id !== chartId);
+ const savedCardId = isLinkSevered ? undefined : recordedCardId;
+
+ const question = useMemo(() => {
+ const base = new Question({
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ name: title,
+ description,
+ ...(display != null ? { display, displayIsLocked: true } : {}),
+ });
+ return display != null ? base : base.setDefaultDisplay();
+ }, [datasetQuery, title, description, display]);
- const card: Card = useMemo(
+ const card = useMemo(() => question.card(), [question]);
+
+ const clipboardPayload = useMemo(
() =>
- new Question({
- dataset_query: datasetQuery,
- display: display ?? "table",
- displayIsLocked: display != null,
- visualization_settings: {},
- }).card(),
- [datasetQuery, display],
+ serializeChartClipboard(
+ {
+ name: title,
+ description,
+ display: question.display(),
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ },
+ siteUrl,
+ ),
+ [title, description, question, datasetQuery, siteUrl],
);
const link = useMemo(
() =>
- `/question#${serializeCardForUrl(card, { includeDisplayIsLocked: true })}`,
- [card],
+ savedCardId != null
+ ? Urls.question(question.setId(savedCardId))
+ : `/question#${serializeCardForUrl(card, { includeDisplayIsLocked: true })}`,
+ [card, question, savedCardId],
);
const { data: dataset, error } = useGetAdhocQueryQuery(datasetQuery);
@@ -69,10 +133,28 @@ export function MetabotInlineChart({
to={link}
target="_blank"
fw="bold"
+ flex={1}
+ miw={0}
truncate
>
{title}
</Anchor>
+ <Tooltip label={clipboard.copied ? t`Copied` : t`Copy chart`}>
+ <ActionIcon
+ variant="subtle"
+ aria-label={t`Copy chart`}
+ onClick={() => clipboard.copy(clipboardPayload)}
+ >
+ <Icon name="copy" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ <SaveChartAction
+ conversationId={conversationId}
+ chartId={chartId}
+ savedCardId={savedCardId}
+ question={question}
+ readonly={readonly}
+ />
</Flex>
<Box className={S.viz}>
{chartError ? (
@@ -92,3 +174,89 @@ export function MetabotInlineChart({
</Box>
);
}
+
+function SaveChartAction({
+ conversationId,
+ chartId,
+ savedCardId,
+ question,
+ readonly,
+}: {
+ conversationId: string;
+ chartId: string;
+ savedCardId: number | undefined;
+ question: Question;
+ readonly: boolean;
+}) {
+ const dispatch = useDispatch();
+ const [saveMetabotEntity] = useSaveMetabotEntityMutation();
+ const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
+
+ const handleCreate = async (
+ newQuestion: Question,
+ options?: { dashboardTabId?: DashboardTabId },
+ ) => {
+ const created = await saveMetabotEntity({
+ conversation_id: conversationId,
+ chart_id: chartId,
+ card: {
+ ...newQuestion.card(),
+ dashboard_tab_id: options?.dashboardTabId,
+ },
+ }).unwrap();
+ const savedQuestion = newQuestion.setId(created.id);
+ dispatch(markChartSaved({ entityId: chartId, cardId: created.id }));
+ dispatch(
+ addUndo({
+ icon: "check_filled",
+ message: t`Saved`,
+ extraAction: {
+ label: t`View`,
+ action: () => dispatch(push(Urls.question(savedQuestion))),
+ },
+ }),
+ );
+ return savedQuestion;
+ };
+
+ return (
+ <>
+ {match({ savedCardId, readonly })
+ .with({ savedCardId: P.number }, ({ savedCardId }) => (
+ <Button
+ component={ForwardRefLink}
+ to={Urls.question(question.setId(savedCardId))}
+ target="_blank"
+ variant="subtle"
+ color="text-secondary"
+ size="compact-xs"
+ leftSection={<Icon name="check" size={14} />}
+ >
+ {t`Saved`}
+ </Button>
+ ))
+ .with({ readonly: true }, () => null)
+ .with({ savedCardId: P.nullish, readonly: false }, () => (
+ <Button
+ variant="subtle"
+ size="compact-xs"
+ onClick={() => setIsSaveModalOpen(true)}
+ >
+ {t`Save`}
+ </Button>
+ ))
+ .exhaustive()}
+ {isSaveModalOpen && (
+ <SaveQuestionModal
+ opened
+ question={question}
+ originalQuestion={null}
+ onCreate={handleCreate}
+ onSave={async () => undefined}
+ onClose={() => setIsSaveModalOpen(false)}
+ closeOnSuccess
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx
index e45ee44ae7b..06f5924b473 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.unit.spec.tsx
@@ -1,8 +1,27 @@
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
-import { setupCardDataset } from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
+import {
+ setupCardDataset,
+ setupCardEndpoints,
+ setupCollectionByIdEndpoint,
+ setupCollectionsEndpoints,
+ setupDatabasesEndpoints,
+ setupRecentViewsAndSelectionsEndpoints,
+} from "__support__/server-mocks";
+import {
+ act,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import { parseChartClipboard } from "metabase/common/utils/chart-clipboard";
+import { markChartSaved } from "metabase/metabot/state";
+import { Route } from "metabase/router";
+import { createMockCard, createMockCollection } from "metabase-types/api/mocks";
import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
import { MetabotInlineChart } from "./MetabotInlineChart";
@@ -16,24 +35,70 @@ jest.mock("metabase/visualizations/components/Visualization", () => ({
const datasetQuery = createMockStructuredDatasetQuery();
+const PERSONAL_COLLECTION = createMockCollection({
+ id: 1,
+ name: "My personal collection",
+ can_write: true,
+ personal_owner_id: 1,
+});
+
+const ROOT_TEST_COLLECTION = createMockCollection({
+ ...ROOT_COLLECTION,
+ id: "root",
+ can_write: false,
+});
+
const value: GeneratedCard = {
type: "card",
id: "card-1",
title: "Orders by month",
+ description: "Monthly count of orders.",
query: { id: "q-1", query: datasetQuery },
display: "bar",
};
+function setupSaveModalEndpoints() {
+ setupCollectionByIdEndpoint({ collections: [PERSONAL_COLLECTION] });
+ setupCollectionsEndpoints({
+ collections: [PERSONAL_COLLECTION],
+ rootCollection: ROOT_TEST_COLLECTION,
+ });
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
+ setupRecentViewsAndSelectionsEndpoints(
+ [],
+ ["selections", "views"],
+ {},
+ false,
+ );
+ setupDatabasesEndpoints([]);
+}
+
function setup(
args: Parameters<typeof setupCardDataset>[0] = {},
valueOverrides: Partial<GeneratedCard> = {},
+ { readonly = false }: { readonly?: boolean } = {},
) {
setupCardDataset(args);
return renderWithProviders(
- <MetabotInlineChart value={{ ...value, ...valueOverrides }} />,
+ <MetabotInlineChart
+ value={{ ...value, ...valueOverrides }}
+ readonly={readonly}
+ conversationId="convo-1"
+ />,
);
}
+async function openSaveModal() {
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+ return screen.findByTestId("save-question-modal");
+}
+
+async function submitSaveModal(modal: HTMLElement) {
+ const saveButton = within(modal).getByRole("button", { name: "Save" });
+ await waitFor(() => expect(saveButton).toBeEnabled());
+ await userEvent.click(saveButton);
+}
+
describe("MetabotInlineChart", () => {
beforeEach(() => {
fetchMock.clearHistory();
@@ -100,4 +165,206 @@ describe("MetabotInlineChart", () => {
await screen.findByText("Column FOO does not exist"),
).toBeInTheDocument();
});
+
+ describe("saving", () => {
+ it("opens the save modal when Save is clicked", async () => {
+ setupSaveModalEndpoints();
+ setup();
+
+ expect(
+ screen.queryByTestId("save-question-modal"),
+ ).not.toBeInTheDocument();
+
+ const modal = await openSaveModal();
+ expect(within(modal).getByLabelText("Name")).toHaveValue(
+ "Orders by month",
+ );
+ expect(within(modal).getByLabelText("Description")).toHaveValue(
+ "Monthly count of orders.",
+ );
+ });
+
+ it("does not render the Save button in readonly mode", () => {
+ setup({}, {}, { readonly: true });
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("saves the chart's card through the metabot endpoint", async () => {
+ setupSaveModalEndpoints();
+ fetchMock.post(
+ "express:/api/metabot/conversations/:id/saved-entity",
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ {
+ name: "save-entity",
+ matchPartialBody: true,
+ body: {
+ chart_id: "card-1",
+ card: {
+ display: "bar",
+ name: "Orders by month",
+ description: "Monthly count of orders.",
+ dataset_query: datasetQuery,
+ },
+ },
+ },
+ );
+ setupCardEndpoints(
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ );
+ setup();
+
+ const modal = await openSaveModal();
+ await submitSaveModal(modal);
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("save-entity")).toBe(true);
+ });
+ });
+
+ it("replaces the Save button with a Saved link after saving", async () => {
+ setupSaveModalEndpoints();
+ fetchMock.post(
+ "express:/api/metabot/conversations/:id/saved-entity",
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ );
+ setupCardEndpoints(
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ );
+ setup();
+
+ const modal = await openSaveModal();
+ await submitSaveModal(modal);
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ });
+ expect(await screen.findByText("Saved")).toBeInTheDocument();
+ });
+
+ it("points the title at the saved question instead of the ad-hoc URL after saving", async () => {
+ setupCardDataset();
+ setupCardEndpoints(
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ );
+ const { store } = renderWithProviders(
+ <Route
+ path="/"
+ element={
+ <MetabotInlineChart
+ value={value}
+ readonly={false}
+ conversationId="convo-1"
+ />
+ }
+ />,
+ { withRouter: true },
+ );
+
+ expect(await screen.findByText("Orders by month")).toHaveAttribute(
+ "href",
+ expect.stringContaining("/question#"),
+ );
+
+ act(() => {
+ store.dispatch(markChartSaved({ entityId: "card-1", cardId: 99 }));
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Orders by month")).toHaveAttribute(
+ "href",
+ expect.stringContaining("/question/99"),
+ );
+ });
+ });
+
+ it("flips back to unsaved when the saved card's origin link is severed", async () => {
+ setupCardEndpoints(createMockCard({ id: 99, metabot_chart_id: null }));
+ const { store } = setup();
+
+ act(() => {
+ store.dispatch(markChartSaved({ entityId: "card-1", cardId: 99 }));
+ });
+
+ expect(
+ await screen.findByRole("button", { name: "Save" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Saved")).not.toBeInTheDocument();
+ });
+
+ it("flips back to unsaved when the saved card is gone (404)", async () => {
+ fetchMock.get("path:/api/card/99", { status: 404 });
+ const { store } = setup();
+
+ act(() => {
+ store.dispatch(markChartSaved({ entityId: "card-1", cardId: 99 }));
+ });
+
+ expect(
+ await screen.findByRole("button", { name: "Save" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Saved")).not.toBeInTheDocument();
+ });
+
+ it("stays saved when the card fetch fails transiently", async () => {
+ fetchMock.get(
+ "path:/api/card/99",
+ { status: 500 },
+ { name: "card-error" },
+ );
+ const { store } = setup();
+
+ act(() => {
+ store.dispatch(markChartSaved({ entityId: "card-1", cardId: 99 }));
+ });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("card-error")).toBe(true);
+ });
+
+ expect(await screen.findByText("Saved")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a short 'Saved' link once the chart is marked saved", async () => {
+ setupCardEndpoints(
+ createMockCard({ id: 99, metabot_chart_id: "card-1" }),
+ );
+ const { store } = setup();
+
+ act(() => {
+ store.dispatch(markChartSaved({ entityId: "card-1", cardId: 99 }));
+ });
+
+ expect(await screen.findByText("Saved")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("copying", () => {
+ it("copies the chart payload to the clipboard", async () => {
+ const writeText = jest.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText },
+ configurable: true,
+ });
+ setup();
+
+ await userEvent.click(screen.getByRole("button", { name: "Copy chart" }));
+
+ expect(writeText).toHaveBeenCalledTimes(1);
+ const payload = parseChartClipboard(writeText.mock.calls[0][0]);
+ expect(payload?.display).toBe("bar");
+ expect(payload?.name).toBe("Orders by month");
+ expect(payload?.description).toBe("Monthly count of orders.");
+ expect(payload?.dataset_query).toEqual(datasetQuery);
+ });
+ });
});
diff --git a/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx b/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
index ea62f083c5b..9780850b17e 100644
--- a/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
@@ -14,6 +14,7 @@ export function MetabotDataStudioSidebar() {
<Metabot
hide={disabled}
config={{
+ agentId: "omnibot",
preventRetryMessage: true,
hideSuggestedPrompts: true,
emptyText: t`Let's transform your data together!`,
diff --git a/frontend/src/metabase/metabot/constants.ts b/frontend/src/metabase/metabot/constants.ts
index 3ab1d23acad..15c51c0a2f6 100644
--- a/frontend/src/metabase/metabot/constants.ts
+++ b/frontend/src/metabase/metabot/constants.ts
@@ -110,6 +110,9 @@ export const TOOL_CALL_MESSAGES: Record<string, string | undefined> = {
get analyze_chart() {
return t`Inspecting the visualization`;
},
+ get save_entity() {
+ return t`Saving`;
+ },
get list_available_fields() {
return undefined;
},
diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts b/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
index 96df84e8379..6958c50d77b 100644
--- a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
+++ b/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
@@ -16,6 +16,7 @@ import {
getIsLongMetabotConversation,
getIsProcessing,
getMessages,
+ getMetabotConversation,
getMetabotId,
getMetabotReactionsState,
getMetabotRequestId,
@@ -155,6 +156,9 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
retryMessage,
cancelRequest,
metabotId: useSelector(getMetabotId),
+ conversationId: useSelector(
+ (state) => getMetabotConversation(state, agentId).conversationId,
+ ),
messages: useSelector((state) => getMessages(state, agentId)),
isDoingScience: useSelector((state) => getIsProcessing(state, agentId)),
isLongConversation: useSelector((state) =>
diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.ts
index ca5313d101b..7b3f6eb3439 100644
--- a/frontend/src/metabase/metabot/state/actions.ts
+++ b/frontend/src/metabase/metabot/state/actions.ts
@@ -72,6 +72,7 @@ export const {
destroyAgent,
addSuggestedCodeEdit,
removeSuggestedCodeEdit,
+ markChartSaved,
} = metabot.actions;
type HandledResponseError = {
@@ -477,6 +478,15 @@ export const sendAgentRequest = createAsyncThunk<
metadata: { editorTransform, suggestionId },
});
})
+ .with({ type: "data-entity_saved" }, (part) => {
+ dispatch(
+ markChartSaved({
+ entityId: part.data.chart_id,
+ cardId: part.data.card_id,
+ }),
+ );
+ pushDataPart({ type: "data_part", part });
+ })
.with(
{ type: "data-generated_entity" },
{ type: "data-adhoc_viz" },
diff --git a/frontend/src/metabase/metabot/state/reducer-utils.ts b/frontend/src/metabase/metabot/state/reducer-utils.ts
index e39c14c2bb4..694d5b40ec9 100644
--- a/frontend/src/metabase/metabot/state/reducer-utils.ts
+++ b/frontend/src/metabase/metabot/state/reducer-utils.ts
@@ -204,5 +204,6 @@ export const getMetabotInitialState = (): MetabotState => {
suggestedTransforms: [],
},
debugMode: false,
+ savedChartCardIds: {},
};
};
diff --git a/frontend/src/metabase/metabot/state/reducer.ts b/frontend/src/metabase/metabot/state/reducer.ts
index 5bb246c9d21..405b93bfef1 100644
--- a/frontend/src/metabase/metabot/state/reducer.ts
+++ b/frontend/src/metabase/metabot/state/reducer.ts
@@ -62,6 +62,12 @@ export const metabot = createSlice({
setDebugMode: (state, action: PayloadAction<boolean>) => {
state.debugMode = action.payload;
},
+ markChartSaved: (
+ state,
+ action: PayloadAction<{ entityId: string; cardId: number }>,
+ ) => {
+ state.savedChartCardIds[action.payload.entityId] = action.payload.cardId;
+ },
// CONVERSATION REDUCERS
addDeveloperMessage: convoReducer(
(convo, action: ConvoPayloadAction<{ message: string }>) => {
diff --git a/frontend/src/metabase/metabot/state/selectors.ts b/frontend/src/metabase/metabot/state/selectors.ts
index 26220374694..1cc68f542f2 100644
--- a/frontend/src/metabase/metabot/state/selectors.ts
+++ b/frontend/src/metabase/metabot/state/selectors.ts
@@ -43,6 +43,12 @@ export const getDebugMode = createSelector(
(state) => state.debugMode,
);
+export const getSavedChartCardId = createSelector(
+ [getMetabotState, (_state: State, entityId: string) => entityId],
+ (metabotState, entityId): number | undefined =>
+ metabotState.savedChartCardIds[entityId],
+);
+
export const getMetabotReactionsState = createSelector(
getMetabotState,
(state) => state.reactions,
@@ -199,6 +205,16 @@ export const getMetabotRequestState = createSelector(
(convo) => convo.state,
);
+export const getConversationChart = createSelector(
+ [getMetabotState, (_state: State, chartId: string) => chartId],
+ (metabotState, chartId): Urls.ConversationChart | undefined => {
+ const charts = Object.values(metabotState.conversations)
+ .map((convo) => convo?.state?.charts?.[chartId])
+ .filter((chart) => chart != null);
+ return charts.find(Urls.hasLinkableChartQuery) ?? charts[0];
+ },
+);
+
export const getIsLongMetabotConversation = createSelector(
getMessages,
(messages) => {
diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.ts
index 9860bf96b17..c19c00d0eff 100644
--- a/frontend/src/metabase/metabot/state/types.ts
+++ b/frontend/src/metabase/metabot/state/types.ts
@@ -143,6 +143,7 @@ export interface MetabotState {
conversations: Record<MetabotAgentId, MetabotConverstationState | undefined>;
reactions: MetabotReactionsState;
debugMode: boolean;
+ savedChartCardIds: Record<string, number>;
}
export interface SlashCommand {
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.unit.spec.tsx b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
similarity index 51%
rename from frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.unit.spec.tsx
rename to frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
index 37a9201409b..73e9ec01919 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
@@ -1,18 +1,41 @@
+import fetchMock from "fetch-mock";
+import { assocIn } from "icepick";
+
+import {
+ setupCardEndpoints,
+ setupCollectionByIdEndpoint,
+ setupDocumentEndpoints,
+} from "__support__/server-mocks";
import { renderWithProviders, screen, within } from "__support__/ui";
import type {
MetabotAgentChatMessage,
MetabotChatMessage,
} from "metabase/metabot/state";
+import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
import { thumbsDown, thumbsUp } from "metabase/metabot/tests/utils";
-import { createMockUser } from "metabase-types/api/mocks";
+import { createMockState } from "metabase/redux/store/mocks";
+import { registerVisualizations } from "metabase/visualizations/register";
+import {
+ createMockCard,
+ createMockCollection,
+ createMockDocument,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import {
+ AgentMessage,
+ Messages,
+} from "../components/MetabotChat/MetabotChatMessage";
-import { AgentMessage, Messages } from "./MetabotChatMessage";
+registerVisualizations();
const setup = (message: MetabotAgentChatMessage) =>
renderWithProviders(
<AgentMessage
debug={false}
readonly={false}
+ conversationId="convo-1"
hideActions
setFeedbackMessage={() => {}}
submittedFeedback={undefined}
@@ -36,6 +59,7 @@ describe("AgentMessage", () => {
]}
isDoingScience
debug={false}
+ conversationId="convo-1"
/>,
);
@@ -63,6 +87,7 @@ describe("AgentMessage", () => {
messages={conversation}
isDoingScience={false}
debug={false}
+ conversationId="convo-1"
/>,
);
@@ -78,6 +103,7 @@ describe("AgentMessage", () => {
isDoingScience={false}
debug={false}
readonly
+ conversationId="convo-1"
/>,
);
@@ -90,6 +116,78 @@ describe("AgentMessage", () => {
});
});
+ describe("entity_saved", () => {
+ it("renders a 'Chart X saved to Y' block with the container's current name", async () => {
+ setupCollectionByIdEndpoint({
+ collections: [
+ createMockCollection({ id: 5, name: "Personal Collection" }),
+ ],
+ });
+ setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
+ setup({
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "collection", id: 5 },
+ },
+ },
+ });
+
+ expect(
+ await screen.findByText("Personal Collection"),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Accounts by Day")).toBeInTheDocument();
+ });
+
+ it("renders a plain 'saved' row when the container can't be loaded", async () => {
+ fetchMock.get("path:/api/collection/5", { status: 404 });
+ setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
+ setup({
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "collection", id: 5 },
+ },
+ },
+ });
+
+ expect(await screen.findByText("Accounts by Day")).toBeInTheDocument();
+ expect(screen.getByText(/saved/)).toBeInTheDocument();
+ expect(screen.queryByText(/saved to/)).not.toBeInTheDocument();
+ });
+
+ it("resolves a document destination's current name", async () => {
+ setupDocumentEndpoints(createMockDocument({ id: 7, name: "Q3 report" }));
+ setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
+ setup({
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "document", id: 7 },
+ },
+ },
+ });
+
+ expect(await screen.findByText("Q3 report")).toBeInTheDocument();
+ expect(await screen.findByText("Accounts by Day")).toBeInTheDocument();
+ });
+ });
+
describe("turn_errored", () => {
it("shows locked message for metabase_ai_managed_locked errors", () => {
setup({
@@ -149,6 +247,7 @@ describe("AgentMessage", () => {
<AgentMessage
debug
readonly={false}
+ conversationId="convo-1"
hideActions
setFeedbackMessage={() => {}}
submittedFeedback={undefined}
@@ -170,3 +269,49 @@ describe("AgentMessage", () => {
});
});
});
+
+describe("UserMessage chart mentions", () => {
+ it("renders a chart mention as an icon chip using conversation state", async () => {
+ const datasetQuery = createMockStructuredDatasetQuery();
+ const metabotState = assocIn(
+ getMetabotInitialState(),
+ ["conversations", "omnibot", "state"],
+ {
+ charts: {
+ "chart-1": {
+ queries: [datasetQuery],
+ visualization_settings: { chart_type: "bar" },
+ },
+ },
+ },
+ );
+
+ renderWithProviders(
+ <Messages
+ messages={[
+ {
+ id: "u1",
+ role: "user",
+ type: "text",
+ message:
+ "[Revenue by Product Category](metabase://chart/chart-1) test",
+ },
+ ]}
+ isDoingScience={false}
+ debug={false}
+ conversationId="convo-1"
+ />,
+ {
+ storeInitialState: createMockState({
+ metabot: metabotState,
+ currentUser: createMockUser(),
+ }),
+ },
+ );
+
+ expect(
+ await screen.findByText("Revenue by Product Category"),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("img", { name: "bar icon" })).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/metabot/utils/links.ts b/frontend/src/metabase/metabot/utils/links.ts
index a28ee12ee2c..04ec72a52de 100644
--- a/frontend/src/metabase/metabot/utils/links.ts
+++ b/frontend/src/metabase/metabot/utils/links.ts
@@ -4,6 +4,9 @@ export const METABSE_PROTOCOL_LINK =
export const METABSE_PROTOCOL_MD_LINK =
/\[(?<name>[^\]]+)\]\(metabase:\/\/(?<model>[^\/]+)\/(?<id>\d+)\)/;
+const METABASE_PROTOCOL_CHART_LINK =
+ /metabase:\/\/chart\/(?<id>[A-Za-z0-9_-]+)/;
+
export const METABASE_PROTOCOL_ENTITY_MODELS = [
"question",
"dashboard",
@@ -31,9 +34,18 @@ export interface MetabaseProtocolEntity {
name: string;
}
+export type ParsedMetabaseProtocolLink =
+ | Pick<MetabaseProtocolEntity, "id" | "model">
+ | { id: string; model: "chart" };
+
export const parseMetabaseProtocolLink = (
href: string,
-): Pick<MetabaseProtocolEntity, "id" | "model"> | undefined => {
+): ParsedMetabaseProtocolLink | undefined => {
+ const chartId = href.match(METABASE_PROTOCOL_CHART_LINK)?.groups?.id;
+ if (chartId) {
+ return { id: chartId, model: "chart" };
+ }
+
const match = href.match(METABSE_PROTOCOL_LINK);
if (!match?.groups) {
@@ -71,6 +83,6 @@ export const createMetabaseProtocolLink = ({
id,
name,
model,
-}: MetabaseProtocolEntity): string => {
+}: ParsedMetabaseProtocolLink & { name: string }): string => {
return `[${name}](metabase://${model}/${id})`;
};
diff --git a/frontend/src/metabase/metabot/utils/links.unit.spec.ts b/frontend/src/metabase/metabot/utils/links.unit.spec.ts
index 96239aa3757..ddf93821233 100644
--- a/frontend/src/metabase/metabot/utils/links.unit.spec.ts
+++ b/frontend/src/metabase/metabot/utils/links.unit.spec.ts
@@ -40,6 +40,14 @@ describe("parseMetabaseProtocolLink", () => {
parseMetabaseProtocolLink("metabase://question/abc"),
).toBeUndefined();
});
+
+ it("should parse metabase://chart links with non-numeric ids", () => {
+ expect(
+ parseMetabaseProtocolLink(
+ "metabase://chart/8e5b8bf3-4e6e-4ee7-856a-21d37dd0e6c0",
+ ),
+ ).toEqual({ id: "8e5b8bf3-4e6e-4ee7-856a-21d37dd0e6c0", model: "chart" });
+ });
});
describe("parseMetabaseProtocolMarkdownLink", () => {
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
index db84c341b98..1c4204123cc 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
@@ -22,8 +22,9 @@ import {
import { useDispatch, useSelector } from "metabase/redux";
import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";
import { Box, Button, Flex, Icon, Text, Tooltip } from "metabase/ui";
-import type { Card, MetabotGenerateContentRequest } from "metabase-types/api";
+import type { MetabotGenerateContentRequest } from "metabase-types/api";
+import { buildDraftCard } from "../shared/draft-card";
import { wrapCardEmbed } from "../shared/layout";
import S from "./MetabotEmbed.module.css";
@@ -194,35 +195,14 @@ export const MetabotComponent = memo(
}
const newCardId = host.actions.generateDraftCardId();
- const card: Card = {
- ...data.draft_card,
+ const card = buildDraftCard({
id: newCardId,
- // Unjustified type cast. FIXME
- entity_id: "entity_id" as Card["entity_id"],
- created_at: "",
- updated_at: "",
name: data.draft_card.name || t`Exploration`,
- description: null,
- type: "question",
- public_uuid: null,
- enable_embedding: false,
- embedding_params: null,
- can_write: false,
- can_restore: false,
- can_delete: false,
- can_manage_db: false,
- initially_published_at: null,
- collection_id: null,
- collection_position: null,
- dashboard: null,
- dashboard_id: null,
- dashboard_count: null,
- result_metadata: [],
- last_query_start: null,
- average_query_time: null,
- cache_ttl: null,
- archived: false,
- };
+ display: data.draft_card.display,
+ dataset_query: data.draft_card.dataset_query,
+ visualization_settings: data.draft_card.visualization_settings,
+ database_id: data.draft_card.database_id,
+ });
host.analytics.trackAskMetabot(document);
await dispatch(host.actions.loadMetadataForDocumentCard(card));
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/draft-card.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/draft-card.ts
new file mode 100644
index 00000000000..02161973dad
--- /dev/null
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/draft-card.ts
@@ -0,0 +1,45 @@
+import type {
+ Card,
+ DatabaseId,
+ DatasetQuery,
+ VisualizationDisplay,
+ VisualizationSettings,
+} from "metabase-types/api";
+
+export function buildDraftCard(card: {
+ id: number;
+ name: string;
+ display: VisualizationDisplay;
+ dataset_query: DatasetQuery;
+ visualization_settings: VisualizationSettings;
+ description?: string | null;
+ database_id?: DatabaseId;
+}): Card {
+ return {
+ // BaseEntityId is branded; drafts use a placeholder that never reaches the API
+ entity_id: "" as Card["entity_id"],
+ created_at: "",
+ updated_at: "",
+ type: "question",
+ public_uuid: null,
+ enable_embedding: false,
+ embedding_params: null,
+ can_write: false,
+ can_restore: false,
+ can_delete: false,
+ can_manage_db: false,
+ initially_published_at: null,
+ collection_id: null,
+ collection_position: null,
+ dashboard: null,
+ dashboard_id: null,
+ dashboard_count: null,
+ result_metadata: [],
+ last_query_start: null,
+ average_query_time: null,
+ cache_ttl: null,
+ archived: false,
+ ...card,
+ description: card.description ?? null,
+ };
+}
diff --git a/frontend/src/metabase/urls/metabot.ts b/frontend/src/metabase/urls/metabot.ts
index d01b2e84a07..3b2a6861e4c 100644
--- a/frontend/src/metabase/urls/metabot.ts
+++ b/frontend/src/metabase/urls/metabot.ts
@@ -1,3 +1,35 @@
+import { serializeCardForUrl } from "metabase/common/utils/card";
+import type { CardDisplayType, DatasetQuery } from "metabase-types/api";
+
export function newMetabotConversation({ prompt }: { prompt: string }) {
return `/metabot/new?q=${encodeURIComponent(prompt)}`;
}
+
+export type ConversationChart = {
+ queries?: DatasetQuery[];
+ visualization_settings?: { chart_type?: CardDisplayType };
+};
+
+export const hasLinkableChartQuery = (chart: ConversationChart): boolean => {
+ const query = chart.queries?.[0];
+ return query != null && !("lib/type" in query);
+};
+
+export const conversationChartUrl = (
+ chart: ConversationChart,
+): string | undefined => {
+ const query = chart.queries?.[0];
+ if (query == null || !hasLinkableChartQuery(chart)) {
+ return undefined;
+ }
+ const hash = serializeCardForUrl(
+ {
+ display: chart.visualization_settings?.chart_type ?? "table",
+ dataset_query: query,
+ visualization_settings: {},
+ displayIsLocked: true,
+ },
+ { includeDisplayIsLocked: true },
+ );
+ return `/question#${hash}`;
+};
diff --git a/frontend/src/metabase/urls/metabot.unit.spec.ts b/frontend/src/metabase/urls/metabot.unit.spec.ts
new file mode 100644
index 00000000000..0ad8acb008f
--- /dev/null
+++ b/frontend/src/metabase/urls/metabot.unit.spec.ts
@@ -0,0 +1,44 @@
+import { serializeCardForUrl } from "metabase/common/utils/card";
+import type { DatasetQuery } from "metabase-types/api";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks/query";
+
+import { conversationChartUrl } from "./metabot";
+
+describe("conversationChartUrl", () => {
+ it("builds an ad-hoc question url with a locked display from a conversation chart", () => {
+ const datasetQuery = createMockStructuredDatasetQuery();
+ const url = conversationChartUrl({
+ queries: [datasetQuery],
+ visualization_settings: { chart_type: "bar" },
+ });
+
+ const hash = serializeCardForUrl(
+ {
+ display: "bar",
+ dataset_query: datasetQuery,
+ visualization_settings: {},
+ displayIsLocked: true,
+ },
+ { includeDisplayIsLocked: true },
+ );
+ expect(url).toBe(`/question#${hash}`);
+ });
+
+ it("returns undefined when the chart has no query", () => {
+ expect(conversationChartUrl({ queries: [] })).toBeUndefined();
+ });
+
+ it("returns undefined for a backend pMBQL query that legacy /question# urls cannot represent", () => {
+ // OpaqueDatasetQuery is branded, so the raw pMBQL wire shape needs a cast
+ const pmbqlQuery = {
+ "lib/type": "mbql/query",
+ stages: [{ "lib/type": "mbql.stage/mbql", "source-table": 1 }],
+ } as unknown as DatasetQuery;
+ expect(
+ conversationChartUrl({
+ queries: [pmbqlQuery],
+ visualization_settings: { chart_type: "bar" },
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/resources/metabot/prompts/llm_shape.selmer b/resources/metabot/prompts/llm_shape.selmer
index 4f7ab344198..93d346c4a36 100644
--- a/resources/metabot/prompts/llm_shape.selmer
+++ b/resources/metabot/prompts/llm_shape.selmer
@@ -282,7 +282,7 @@ or jargon that may be relevant to the user's questions.
</user>
{% endif %}
{% if is_search_result %}
-<{{search_tag_name}} id="{{search_id}}"{% if search_uri %} uri="{{search_uri}}"{% endif %} name="{{search_name}}"{% if search_has_curated %} is_curated="{{search_curated}}"{% endif %}{% if search_has_verified %} is_verified="{{search_verified}}"{% endif %}{% if search_has_official %} is_official="{{search_official}}"{% endif %}{% if search_data_layer %} data_layer="{{search_data_layer}}"{% endif %}{% if search_data_authority %} data_authority="{{search_data_authority}}"{% endif %}{% if search_database_id %} database_id="{{search_database_id}}"{% endif %}{% if search_database_name %} database_name="{{search_database_name}}"{% endif %}{% if search_database_engine %} database_engine="{{search_database_engine}}"{% endif %}{% if search_fqn %} fully_qualified_name="{{search_fqn}}"{% endif %}{% if search_base_table_fqn %} base_table_fully_qualified_name="{{search_base_table_fqn}}"{% endif %}{% if search_portable_entity_id %} portable_entity_id="{{search_portable_entity_id}}"{% endif %}>
+<{{search_tag_name}} id="{{search_id}}"{% if search_uri %} uri="{{search_uri}}"{% endif %} name="{{search_name}}"{% if search_has_curated %} is_curated="{{search_curated}}"{% endif %}{% if search_has_verified %} is_verified="{{search_verified}}"{% endif %}{% if search_has_official %} is_official="{{search_official}}"{% endif %}{% if search_has_can_write %} can_write="{{search_can_write}}"{% endif %}{% if search_data_layer %} data_layer="{{search_data_layer}}"{% endif %}{% if search_data_authority %} data_authority="{{search_data_authority}}"{% endif %}{% if search_database_id %} database_id="{{search_database_id}}"{% endif %}{% if search_database_name %} database_name="{{search_database_name}}"{% endif %}{% if search_database_engine %} database_engine="{{search_database_engine}}"{% endif %}{% if search_fqn %} fully_qualified_name="{{search_fqn}}"{% endif %}{% if search_base_table_fqn %} base_table_fully_qualified_name="{{search_base_table_fqn}}"{% endif %}{% if search_portable_entity_id %} portable_entity_id="{{search_portable_entity_id}}"{% endif %}>
{% if search_description %}
{{search_description}}
{% endif %}
diff --git a/resources/metabot/prompts/tools/construct_notebook_query.md b/resources/metabot/prompts/tools/construct_notebook_query.md
index 5e558b7d2a0..05e6b12984b 100644
--- a/resources/metabot/prompts/tools/construct_notebook_query.md
+++ b/resources/metabot/prompts/tools/construct_notebook_query.md
@@ -5,6 +5,7 @@ Construct a Metabase MBQL 5 query as a JSON object describing the query shape. M
Return:
- `query`: a JSON **object** (never a quoted string). The target database is inferred from the first stage's `source-table` (or `source-card`) — use the **exact** database name reported by search / `read_resource` / metadata tools.
- `title`: required short, human-friendly title for the resulting chart, shown above it (e.g. `"Orders by month"`).
+- `description`: required concise one- or two-sentence description of what the chart shows (the metric, the grouping, and any notable filter); it is used as the saved question's description.
- `visualization`: optional `{"chart_type": "bar"}` (sibling of `query`, never embedded inside it).
## Minimal example — count of orders by month
diff --git a/resources/metabot/skills/read-resource.md b/resources/metabot/skills/read-resource.md
index 29944fea8ab..6912cd9b59e 100644
--- a/resources/metabot/skills/read-resource.md
+++ b/resources/metabot/skills/read-resource.md
@@ -62,7 +62,7 @@ You can request multiple resources in one call by providing a list of URIs (max
## Collection resources
- `metabase://collection/{id}` — basic collection info
-- `metabase://collection/{id}/items` — direct children (mix of subcollections, cards, models, metrics, dashboards)
+- `metabase://collection/{id}/items` — direct children (mix of subcollections, cards, models, metrics, dashboards, documents)
- `metabase://collection/{id}/subcollections` — only the subcollections (useful for orientation in deep trees)
**Examples:**
diff --git a/resources/migrations/064/20260706_metabot_card_provenance.yaml b/resources/migrations/064/20260706_metabot_card_provenance.yaml
new file mode 100644
index 00000000000..4ed3cd76fe3
--- /dev/null
+++ b/resources/migrations/064/20260706_metabot_card_provenance.yaml
@@ -0,0 +1,69 @@
+## Metabot provenance columns for saved questions: which conversation a card was
+## saved from and which generated chart it materializes, so a reloaded conversation
+## can mark its inline charts as saved. The conversation FK is SET NULL on delete —
+## trimming conversations must not delete or block the cards saved from them.
+
+databaseChangeLog:
+
+ - changeSet:
+ id: v64.7msecd
+ author: undrfined
+ comment: Add metabot_conversation_id column to report_card
+ changes:
+ - addColumn:
+ tableName: report_card
+ columns:
+ - column:
+ name: metabot_conversation_id
+ type: varchar(36)
+ remarks: The Metabot conversation this card was saved from; NULL when not AI-generated or after the conversation is trimmed
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: report_card
+ columnName: metabot_conversation_id
+
+ - changeSet:
+ id: v64.d47pcb
+ author: undrfined
+ comment: Add metabot_chart_id column to report_card
+ changes:
+ - addColumn:
+ tableName: report_card
+ columns:
+ - column:
+ name: metabot_chart_id
+ type: varchar(36)
+ remarks: The generated chart id within the Metabot conversation this card was saved from; used to match the card back to its inline chart
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: report_card
+ columnName: metabot_chart_id
+
+ - changeSet:
+ id: v64.fzmofw
+ author: undrfined
+ comment: Add index for report_card.metabot_conversation_id
+ changes:
+ - createIndex:
+ tableName: report_card
+ indexName: idx_report_card_metabot_conversation_id
+ columns:
+ - column:
+ name: metabot_conversation_id
+
+ - changeSet:
+ id: v64.h29xu4
+ author: undrfined
+ comment: Add foreign key on report_card(metabot_conversation_id)
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: report_card
+ baseColumnNames: metabot_conversation_id
+ referencedTableName: metabot_conversation
+ referencedColumnNames: id
+ constraintName: fk_report_card_metabot_conversation_id
+ onDelete: SET NULL
diff --git a/src/metabase/documents/api/document.clj b/src/metabase/documents/api/document.clj
index a841db26a50..ab0b6b81eb6 100644
--- a/src/metabase/documents/api/document.clj
+++ b/src/metabase/documents/api/document.clj
@@ -131,14 +131,31 @@
to-clone)))
(defn get-document
- "Get document by id checking if the current user has permission to access and if the document exists."
- [id]
+ "Get document by id checking if the current user has permission to access and if the document exists.
+ Pass `:log-view? false` to skip publishing the `:event/document-read` view event."
+ [id & {:keys [log-view?] :or {log-view? true}}]
(u/prog1 (api/check-404
(api/read-check
(t2/hydrate (t2/select-one :model/Document :id id) :creator :can_write :can_delete :can_restore :is_remote_synced)))
- (events/publish-event! :event/document-read
- {:object-id id
- :user-id api/*current-user-id*})))
+ (when log-view?
+ (events/publish-event! :event/document-read
+ {:object-id id
+ :user-id api/*current-user-id*}))))
+
+(defn add-card-to-document!
+ "Insert an embed for the already-created card with `card-id` into the prose-mirror ast of the
+ document with `document-id` and persist it. `position` is a 0-based index among the document's
+ top-level blocks; `nil` appends the embed at the end and out-of-range indexes are clamped.
+
+ The caller is responsible for write-checking the document first. The document is re-read inside
+ the transaction so a concurrent edit cannot be overwritten. Returns the updated document."
+ [document-id card-id position]
+ (t2/with-transaction [_conn]
+ (let [document (api/check-404 (t2/select-one :model/Document :id document-id))]
+ (t2/update! :model/Document document-id
+ (select-keys (prose-mirror/insert-card-embed document card-id position) [:document]))
+ (collections/check-for-remote-sync-update document)))
+ (get-document document-id :log-view? false))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/documents/core.clj b/src/metabase/documents/core.clj
index bd46bad06f9..609c293bce2 100644
--- a/src/metabase/documents/core.clj
+++ b/src/metabase/documents/core.clj
@@ -10,4 +10,5 @@
(p/import-vars
[metabase.documents.api.document
+ add-card-to-document!
get-document])
diff --git a/src/metabase/documents/prose_mirror.clj b/src/metabase/documents/prose_mirror.clj
index 63f93f979d8..a8d6f6b7c3d 100644
--- a/src/metabase/documents/prose_mirror.clj
+++ b/src/metabase/documents/prose_mirror.clj
@@ -80,3 +80,30 @@
(collect-ast document #(when (and (= card-embed-type (:type %))
(pos-int? (-> % :attrs :id)))
(-> % :attrs :id))))
+
+(defn insert-card-embed
+ "Insert an embed for the card with `card-id` into the document's prose-mirror ast.
+
+ The embed is a `resizeNode`-wrapped `cardEmbed` node, the same shape the document editor
+ produces. `index` is a 0-based position among the ast's top-level blocks (0 inserts at the
+ very top); a `nil` index appends the embed at the end and out-of-range indexes are clamped.
+
+ Args:
+ - doc - a :model/Document, this will check that the content-type is valid for prose mirror
+ - card-id - the id of an existing card to embed
+ - index - 0-based top-level block position, or nil to append
+
+ Returns:
+ - the document with its :document ast updated"
+ [{:keys [document] :as doc} card-id index]
+ (assert-prose-mirror doc)
+ (let [blocks (vec (:content document))
+ at (if (int? index)
+ (-> index (max 0) (min (count blocks)))
+ (count blocks))
+ embed {:type "resizeNode"
+ :content [{:type card-embed-type
+ :attrs {:id card-id}}]}]
+ (assoc doc :document
+ (assoc (or document {:type "doc"})
+ :content (into (conj (subvec blocks 0 at) embed) (subvec blocks at))))))
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.clj
index b49842cbf6e..7342e692eee 100644
--- a/src/metabase/metabot/agent/core.clj
+++ b/src/metabase/metabot/agent/core.clj
@@ -414,7 +414,7 @@
(defn- init-agent
"Initialize agent state."
- [{:keys [messages state metabot-id profile-id context tracking-opts]
+ [{:keys [messages state metabot-id profile-id context tracking-opts conversation-id]
external-memory-atom :memory-atom}]
(let [context (assign-context-ids context)
;; Resolve the profile once (its nlq availability redirect probes the index): reuse it for both the
@@ -427,7 +427,8 @@
(seed-state context)
(seed-chart-configs context)
(seed-charts context))
- memory (memory/initialize messages seeded context)
+ memory (assoc (memory/initialize messages seeded context)
+ :conversation-id conversation-id)
memory-atom (doto (or external-memory-atom (atom nil)) (reset! memory))
tools (tools/wrap-tools-with-state base-tools memory-atom metabot-id profile-id)]
(log/info "Starting agent" {:profile profile-id
@@ -624,6 +625,7 @@
[:messages ::messages]
[:profile-id ::profile-id]
[:metabot-id {:optional true} [:maybe :string]]
+ [:conversation-id {:optional true} [:maybe :string]]
[:state {:optional true} [:maybe ::metabot.schema/state]]
[:context {:optional true} [:maybe ::context]]
[:tracking-opts {:optional true} [:maybe ::tracking-opts]]
diff --git a/src/metabase/metabot/agent/links.clj b/src/metabase/metabot/agent/links.clj
index b7bd748ee01..5b164aaed2c 100644
--- a/src/metabase/metabot/agent/links.clj
+++ b/src/metabase/metabot/agent/links.clj
@@ -23,6 +23,7 @@
{"model" "/model"
"metric" "/metric"
"dashboard" "/dashboard"
+ "document" "/document"
"question" "/question"
"transform" "/data-studio/transforms"})
@@ -30,11 +31,16 @@
(defn ->legacy-mbql
"Normalize a pMBQL query (has `:lib/type`) to legacy MBQL. Frontend /question#
- URLs require legacy MBQL format; non-pMBQL values pass through unchanged."
+ URLs require legacy MBQL format; non-pMBQL values pass through unchanged.
+
+ Agent state is JSON-persisted between turns, which preserves namespaced keys but
+ turns enum values such as `:mbql/query`, `:field`, and `:day` into strings.
+ Normalize before converting so rehydrated queries have their canonical enum
+ values restored."
[query]
#_{:clj-kondo/ignore [:discouraged-var]}
(if (and (map? query) (:lib/type query))
- (lib/->legacy-MBQL query)
+ (lib/->legacy-MBQL (lib/normalize query))
query))
(defn- query->url-hash
@@ -149,6 +155,7 @@
- metabase://model/{id} - Links to models
- 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://transform/{id} - Links to transforms
diff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.clj
index b71d664f07f..06b1601b84d 100644
--- a/src/metabase/metabot/agent/profiles.clj
+++ b/src/metabase/metabot/agent/profiles.clj
@@ -101,7 +101,8 @@
#'tools/construct-notebook-query-tool
#'tools/navigate-user-tool
#'tools/create-chart-tool
- #'tools/edit-chart-tool]})
+ #'tools/edit-chart-tool
+ #'tools/save-entity-tool]})
(register-profile!
{:name :internal
@@ -119,7 +120,8 @@
#'tools/create-chart-tool
#'tools/create-autogenerated-dashboard-tool
#'tools/create-dashboard-subscription-tool
- #'tools/analyze-chart-tool]})
+ #'tools/analyze-chart-tool
+ #'tools/save-entity-tool]})
(register-profile!
{:name :transforms_codegen
@@ -181,7 +183,8 @@
#'tools/construct-notebook-query-tool
#'tools/navigate-user-tool
#'tools/create-chart-tool
- #'tools/edit-chart-tool]})
+ #'tools/edit-chart-tool
+ #'tools/save-entity-tool]})
(register-profile!
{:name :nlq-fallback
@@ -193,7 +196,8 @@
#'tools/construct-notebook-query-tool
#'tools/navigate-user-tool
#'tools/create-chart-tool
- #'tools/edit-chart-tool]})
+ #'tools/edit-chart-tool
+ #'tools/save-entity-tool]})
(register-profile!
{:name :document-generate-content
diff --git a/src/metabase/metabot/agent/streaming.clj b/src/metabase/metabot/agent/streaming.clj
index 185bfe53944..7e19c8a8e3b 100644
--- a/src/metabase/metabot/agent/streaming.clj
+++ b/src/metabase/metabot/agent/streaming.clj
@@ -19,6 +19,7 @@
(def code-edit-type "AI-SDK data type for code edits." "code_edit")
(def transform-suggestion-type "AI-SDK data type for transform suggestions." "transform_suggestion")
(def generated-entity-type "AI-SDK data type for generated entities." "generated_entity")
+(def entity-saved-type "AI-SDK data type for saved-entity annotations." "entity_saved")
(def adhoc-viz-type "AI-SDK data type for ad-hoc visualizations." "adhoc_viz")
(def static-viz-type "AI-SDK data type for static visualizations." "static_viz")
@@ -27,7 +28,8 @@
skipped because their value is diffed separately into MetabotMessage.state;
duplicating the full blob in the message data would bloat storage. Non-data
parts are always persistable here; the caller is responsible for filtering
- stream-level metadata (`:start`, `:usage`, `:finish`) separately."
+ stream-level metadata
+ (`:start`, `:usage`, `:finish`) separately."
[part]
(not (and (= :data (:type part))
(= state-type (:data-type part)))))
@@ -141,6 +143,16 @@
:data-type generated-entity-type
:data entity})
+(defn entity-saved-part
+ "Create an ENTITY_SAVED data part for streaming. `value` is a map describing where a
+ previously-generated inline chart was persisted: `{:chart_id <generated chart id>,
+ :card_id <saved card id>, :destination {:type :id}}`. The FE resolves the card's
+ and the destination's display names at render time."
+ [value]
+ {:type :data
+ :data-type entity-saved-type
+ :data value})
+
(defn viz-part
"Return the data part used to surface a query/chart result to the frontend.
@@ -150,15 +162,16 @@
returns a `navigate_to` part that sends the user to the question. Pure: the
caller passes `inline?` (typically `(shared/inline-viz-capable?)`) and a legacy
`query`. The caller must supply a distinct `entity-id` (card id), `query-id`,
- and `title`; `display` is included when present."
- [{:keys [inline? entity-id query-id query display title link]}]
+ and `title`; `display` and `description` are included when present."
+ [{:keys [inline? entity-id query-id query display title description link]}]
(if inline?
(generated-entity-part
(cond-> {:type "card"
:id entity-id
:title title
:query {:id query-id :query query}}
- display (assoc :display (some-> display name))))
+ display (assoc :display (some-> display name))
+ description (assoc :description description)))
(navigate-to-part link)))
;;; Reaction Conversion
diff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.clj
index 4b8828192c0..832cd3309eb 100644
--- a/src/metabase/metabot/agent/user_context.clj
+++ b/src/metabase/metabot/agent/user_context.clj
@@ -5,16 +5,14 @@
recent views, user time formatting, and SQL dialect extraction from context."
(:require
[clojure.string :as str]
- [metabase.agent-lib.representations.resolve :as repr.resolve]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.entity-details :as entity-details]
- [metabase.metabot.tools.shared.content-store :as shared.content-store]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.metabot.util :as metabot.u]
+ [metabase.models.interface :as mi]
[metabase.util :as u]
- [metabase.util.json :as json]
[metabase.util.log :as log])
(:import
(java.time OffsetDateTime)
@@ -225,6 +223,17 @@
;;; Viewing Context Formatting
+(defn- query-if-database-readable
+ "The client-supplied adhoc query, only when the current user can read its database.
+ Exporting resolves table/field ids to names through an unfiltered metadata provider,
+ so gate it like the metabase://chart|query resources do. Queries with no :database
+ only ever pprint (no name resolution), so they pass through."
+ [query]
+ (let [database-id (and (map? query) (:database query))]
+ (when (or (not database-id)
+ (mi/can-read? :model/Database database-id))
+ query)))
+
;; Format adhoc query (notebook editor) viewing context.
(defmethod format-entity "adhoc"
[item]
@@ -233,6 +242,7 @@
(te/lines "The user is currently in the notebook editor viewing a query."
(te/field "Query ID" (:id item))
(te/field "Database ID" (get-in item [:query :database]))
+ (te/field "Query" (some-> (:query item) query-if-database-readable llm-shape/export-query-for-llm))
(when-let [config-ids (format-chart-config-ids item)]
(te/field "Chart Config IDs (for analyze_chart tool)" config-ids))
(te/field "Tables used" (some->> (:used_tables item)
@@ -257,27 +267,7 @@
Falls back to a `pprint`'d query map only as a last resort, when repr export is
unavailable (e.g. a partially-broken `dataset_query`)."
[source]
- (let [query (:query source)]
- (cond
- (string? query) query
- (string? (:query-content query)) (:query-content query)
- (and (map? query) (:database query))
- (try
- (let [normalized (lib-be/normalize-query query)
- database-id (:database normalized)
- mp (when database-id
- (lib-be/application-database-metadata-provider database-id))
- exported (some->> mp (#(repr.resolve/try-export-query % normalized shared.content-store/default-store)))]
- (if exported
- (str "```json\n" (json/encode exported {:pretty true}) "\n```")
- (u/pprint-to-str normalized)))
- (catch Exception _
- (u/pprint-to-str query)))
- ;; Legacy native shape with no :database (rare). Surface the raw SQL so the LLM at
- ;; least sees the query body; if there's no :database we can't normalise / build a MP.
- (string? (get-in query [:native :query])) (get-in query [:native :query])
- (map? query) (u/pprint-to-str query)
- :else (some-> query str))))
+ (llm-shape/export-query-for-llm (:query source)))
(defn- transform-source-type
[source]
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index 830c6423f35..d87df6ea039 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -212,6 +212,7 @@
(cond-> {:messages messages
:state state
:metabot-id metabot-id
+ :conversation-id conversation-id
:profile-id (keyword profile-id)
:context enriched-context
:eval-session-id eval-session-id
diff --git a/src/metabase/metabot/api/conversations.clj b/src/metabase/metabot/api/conversations.clj
index 436ccb35db1..7cb2d01ea6b 100644
--- a/src/metabase/metabot/api/conversations.clj
+++ b/src/metabase/metabot/api/conversations.clj
@@ -10,9 +10,14 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
+ [metabase.events.core :as events]
[metabase.metabot.persistence :as metabot.persistence]
[metabase.metabot.schema :as metabot.schema]
+ [metabase.queries.core :as queries]
+ [metabase.query-permissions.core :as query-perms]
[metabase.request.core :as request]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -45,11 +50,46 @@
[:summary [:maybe :string]]
[:user_id [:maybe ms/PositiveInt]]
[:state {:optional true} [:maybe ::metabot.schema/state]]
+ [:saved_entities [:sequential
+ [:map
+ [:card_id ms/PositiveInt]
+ [:chart_id [:maybe :string]]]]]
[:chat_messages [:sequential :map]]])
(def ^:private ConversationIdParams
[:map [:id ms/UUIDString]])
+(def ^:private SaveEntityCard
+ [:map
+ [:name ms/NonBlankString]
+ [:description {:optional true} [:maybe :string]]
+ [:dataset_query :map]
+ [:display ms/NonBlankString]
+ [:visualization_settings {:optional true} [:maybe :map]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]])
+
+(def ^:private SaveEntityBody
+ [:map
+ ;; stamped onto report_card.metabot_chart_id, a varchar(36) — clamp to fit
+ [:chart_id [:and ms/NonBlankString [:string {:max 36}]]]
+ [:card SaveEntityCard]])
+
+(def ^:private SaveEntityResponse
+ [:map
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]
+ [:description {:optional true} [:maybe :string]]
+ [:dataset_query :map]
+ [:display :keyword]
+ [:visualization_settings {:optional true} [:maybe :map]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]
+ [:metabot_conversation_id ms/UUIDString]
+ [:metabot_chart_id ms/NonBlankString]])
+
;;; ---------------------------------------- Queries ----------------------------------------
(def ^:private default-limit 50)
@@ -122,6 +162,54 @@
(api/read-check :model/MetabotConversation id)
(metabot.persistence/conversation-detail id))
+(api.macros/defendpoint :post "/:id/saved-entity" :- SaveEntityResponse
+ "Save a Metabot-generated chart from this conversation as a card, stamping the
+ card's origin columns in the same request — used by the inline chart's
+ manual Save button, which runs outside any agent turn. Creating and stamping
+ together (rather than stamping after a separate `POST /api/card`) means the
+ card and its origin cannot desync when the follow-up request is lost.
+
+ Accessible to any participant in the conversation or to any superuser."
+ [{:keys [id]} :- ConversationIdParams
+ _query-params
+ {:keys [chart_id card]} :- SaveEntityBody]
+ (api/read-check :model/MetabotConversation id)
+ ;; Mirror the POST /api/card pre-checks: `create-card!` itself does not check
+ ;; permissions on the query's data or the target container. Like the card API's
+ ;; `actual-collection-id`, an explicit `collection_id` on a dashboard save must
+ ;; match the dashboard's own collection.
+ (query-perms/check-run-permissions-for-query (:dataset_query card))
+ (if-let [dashboard-id (:dashboard_id card)]
+ (let [dashboard-collection-id (:collection_id (api/write-check :model/Dashboard dashboard-id))
+ [_ specified-collection-id :as specified?] (find card :collection_id)]
+ (when specified?
+ (api/check-400 (= specified-collection-id dashboard-collection-id)
+ (tru "Mismatch detected between Dashboard''s `collection_id` ({0}) and `collection_id` ({1})"
+ dashboard-collection-id specified-collection-id))))
+ (api/create-check :model/Card {:collection_id (:collection_id card)}))
+ ;; Create the card and stamp its origin in ONE transaction so they cannot desync.
+ ;; The stamp is a raw table update — it should not run the Card model's heavy
+ ;; before-update pipeline (query normalization, metadata population). The
+ ;; `:card-create` event is delayed until after the transaction commits so
+ ;; subscribers see the card.
+ (let [created (t2/with-transaction [_conn]
+ (u/prog1 (queries/create-card!
+ (-> (select-keys card [:name :description :dataset_query :display
+ :visualization_settings :collection_id
+ :dashboard_id :dashboard_tab_id])
+ (update :display keyword)
+ (update :visualization_settings #(or % {})))
+ {:id api/*current-user-id*}
+ :delay-event)
+ (t2/update! (t2/table-name :model/Card) (:id <>)
+ {:metabot_conversation_id id
+ :metabot_chart_id chart_id})))]
+ (events/publish-event! :event/card-create
+ {:object created :user-id api/*current-user-id*})
+ (assoc created
+ :metabot_conversation_id id
+ :metabot_chart_id chart_id)))
+
(def ^{:arglists '([request respond raise])} routes
"`/api/metabot/conversations` routes."
(api.macros/ns-handler *ns* +auth))
diff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.clj
index a6e2a0786d9..96e0d35637e 100644
--- a/src/metabase/metabot/persistence.clj
+++ b/src/metabase/metabot/persistence.clj
@@ -728,7 +728,14 @@
flat-messages))))
(defn conversation-detail
- "Conversation-with-chat-messages snapshot. Nil if not found."
+ "Conversation-with-chat-messages snapshot. Nil if not found.
+
+ `:saved_entities` lists the live (non-archived) cards saved out of this
+ conversation (origin columns on `report_card`), keyed by the generated chart id
+ so a reloaded conversation can mark its inline charts as saved. Deliberately ids
+ only — including display fields like the card name would leak content that other
+ conversation participants may not be able to read; readers resolve names through
+ the permission-checked card API."
[conversation-id]
(when-let [conv (t2/select-one :model/MetabotConversation :id conversation-id)]
(let [messages (live-messages conversation-id)]
@@ -737,4 +744,11 @@
:summary (:summary conv)
:user_id (:user_id conv)
:state (conversation-state messages)
+ :saved_entities (mapv (fn [{:keys [id metabot_chart_id]}]
+ {:card_id id
+ :chart_id metabot_chart_id})
+ (t2/select [:model/Card :id :metabot_chart_id]
+ :metabot_conversation_id conversation-id
+ :archived false
+ {:order-by [[:id :asc]]}))
:chat_messages (messages->chat-messages messages)})))
diff --git a/src/metabase/metabot/tools.clj b/src/metabase/metabot/tools.clj
index b5e445e4f29..778f25eac47 100644
--- a/src/metabase/metabot/tools.clj
+++ b/src/metabase/metabot/tools.clj
@@ -20,6 +20,7 @@
[metabase.metabot.tools.metadata :as tools.metadata]
[metabase.metabot.tools.navigation :as tools.navigation]
[metabase.metabot.tools.resources :as tools.resources]
+ [metabase.metabot.tools.save-entity :as tools.save-entity]
[metabase.metabot.tools.search :as tools.search]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.skills :as tools.skills]
@@ -67,6 +68,8 @@
[tools.charts
create-chart-tool
edit-chart-tool]
+ [tools.save-entity
+ save-entity-tool]
[tools.resources
read-resource-tool]
[tools.todo
@@ -106,11 +109,12 @@
(def ^:private state-dependent-tools
"Set of tool names that require access to agent state."
#{"analyze_chart"
- "create_chart" "edit_chart" "todo_write" "todo_read" "navigate_user"
+ "create_chart" "edit_chart" "save_entity" "todo_write" "todo_read" "navigate_user"
"write_transform_sql" "write_transform_python" "create_autogenerated_dashboard"
"create_sql_query" "edit_sql_query" "replace_sql_query" "construct_notebook_query"
"document_schema_collect" "document_construct_sql_chart" "document_construct_model_chart"
- "create_alert" "create_dashboard_subscription" "static_viz"})
+ "create_alert" "create_dashboard_subscription" "static_viz"
+ "read_resource"})
(defn- wrap-with-scope-check
"Wrap a tool function with a scope check. Returns a function that checks
diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.clj
index 4172a72835e..ea863d7b12a 100644
--- a/src/metabase/metabot/tools/charts.clj
+++ b/src/metabase/metabot/tools/charts.clj
@@ -32,7 +32,8 @@
[:query_id :string]]]
[:viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]
- [:title :string]])
+ [:title :string]
+ [:description :string]])
(mu/defn ^{:tool-name "create_chart"
:scope scope/agent-viz-create}
@@ -40,8 +41,11 @@
"Create a chart from a query.
Provide a query_id in data_source, a chart_type in viz_settings, and a short,
- human-friendly `title` shown above the chart."
- [{:keys [data_source viz_settings title]} :- create-chart-schema]
+ human-friendly `title` shown above the chart. Also provide a concise one- or
+ two-sentence `description` explaining what the chart shows (the metric, the
+ grouping, and any notable filter); it is used as the saved question's
+ description."
+ [{:keys [data_source viz_settings title description]} :- create-chart-schema]
(try
(let [result (create-chart-tools/create-chart
{:query-id (get data_source :query_id)
@@ -51,13 +55,14 @@
{:output (format-chart-output structured)
:structured-output structured
:data-parts [(streaming/viz-part
- {:inline? (shared/inline-viz-capable?)
- :entity-id (:chart-id result)
- :query-id (:query-id result)
- :query (links/->legacy-mbql (:query result))
- :display (:chart-type result)
- :title title
- :link (:results-url result)})]})
+ {:inline? (shared/inline-viz-capable?)
+ :entity-id (:chart-id result)
+ :query-id (:query-id result)
+ :query (links/->legacy-mbql (:query result))
+ :display (:chart-type result)
+ :title title
+ :description description
+ :link (:results-url result)})]})
(catch Exception e
(log/error e "Error creating chart")
(if (:agent-error? (ex-data e))
@@ -69,7 +74,8 @@
[:chart_id :string]
[:new_viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]
- [:title :string]])
+ [:title :string]
+ [:description :string]])
(mu/defn ^{:tool-name "edit_chart"
:scope scope/agent-viz-edit}
@@ -77,8 +83,9 @@
"Edit an existing chart's visualization type.
Provide a new chart_type in new_viz_settings and a short, human-friendly `title`
- shown above the chart."
- [{:keys [chart_id new_viz_settings title]} :- edit-chart-schema]
+ shown above the chart. Also provide a concise `description` of what the chart
+ shows; it is used as the saved question's description."
+ [{:keys [chart_id new_viz_settings title description]} :- edit-chart-schema]
(try
(let [new-viz (keyword (get new_viz_settings :chart_type))
chart (get (shared/current-charts-state) chart_id)
@@ -98,16 +105,17 @@
{:output (format-chart-output structured)
:structured-output structured
:data-parts [(streaming/viz-part
- {:inline? (shared/inline-viz-capable?)
- :entity-id (or (:chart_id new-chart-data) chart_id)
- :query-id (or (:query_id chart) (str (random-uuid)))
- :query (links/->legacy-mbql query)
- :display new-viz
- :title title
- :link (links/pseudo-card->link
- {:dataset_query query
- :display new-viz
- :displayIsLocked true})})]})
+ {:inline? (shared/inline-viz-capable?)
+ :entity-id (or (:chart_id new-chart-data) chart_id)
+ :query-id (or (:query_id chart) (str (random-uuid)))
+ :query (links/->legacy-mbql query)
+ :display new-viz
+ :title title
+ :description description
+ :link (links/pseudo-card->link
+ {:dataset_query query
+ :display new-viz
+ :displayIsLocked true})})]})
(catch Exception e
(log/error e "Error editing chart")
(if (:agent-error? (ex-data e))
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index 3c73866d777..ebcee0753fd 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -109,7 +109,8 @@
;; `:json-schema` override only changes what the LLM sees. See [[construct-notebook-query-json-schema]].
[:query [:map {:json-schema construct-notebook-query-json-schema}]]
[:visualization {:optional true} construct-visualization-schema]
- [:title :string]])
+ [:title :string]
+ [:description :string]])
;;; ---------------------------------------- Source resolution ----------------------------------------
@@ -445,9 +446,11 @@
"Construct and visualize a notebook query from a metric, model, or table.
Accepts an MBQL 5 query as a JSON object matching `::lib.schema/external-query`, plus a
- short, human-friendly `title` shown above the resulting chart. See
+ short, human-friendly `title` shown above the resulting chart. Also provide a concise
+ one- or two-sentence `description` of what the chart shows (the metric, the grouping, and
+ any notable filter); it is used as the saved question's description. See
`resources/metabot/prompts/tools/construct_notebook_query.md` for the prompt contract."
- [{:keys [_reasoning query visualization title]} :- construct-notebook-query-args-schema]
+ [{:keys [_reasoning query visualization title description]} :- construct-notebook-query-args-schema]
(try
(let [normalized-visualization (some-> visualization (update-keys (comp keyword u/->kebab-case-en name)))
chart-type (or (chart-type->keyword (:chart-type normalized-visualization))
@@ -479,13 +482,14 @@
"<instructions>\n" instruction-text "\n</instructions>")
:data-parts (when results-url
[(streaming/viz-part
- {:inline? (shared/inline-viz-capable?)
- :entity-id (:chart-id chart-result)
- :query-id (:query-id structured)
- :query (links/->legacy-mbql (:query structured))
- :display chart-type
- :title title
- :link results-url})])
+ {:inline? (shared/inline-viz-capable?)
+ :entity-id (:chart-id chart-result)
+ :query-id (:query-id structured)
+ :query (links/->legacy-mbql (:query structured))
+ :display chart-type
+ :title title
+ :description description
+ :link results-url})])
:structured-output full-structured
:instructions instruction-text})
;; query-result may already have :output (error) or only :structured-output
diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.clj
index 64fcabc79a6..e5d5865b346 100644
--- a/src/metabase/metabot/tools/resources.clj
+++ b/src/metabase/metabot/tools/resources.clj
@@ -56,18 +56,27 @@
- metabase://transform/{id}/sources - tables/databases this transform reads from
- metabase://transform/{id}/target - table this transform writes to
- metabase://dashboard/{id} - dashboard details
- - metabase://dashboard/{id}/items - cards on the dashboard"
+ - metabase://dashboard/{id}/items - cards on the dashboard
+ - metabase://document/{id} - document name + indexed outline of its top-level blocks
+
+ Conversation state (agent-memory charts/queries, e.g. pasted chart mentions):
+ - metabase://chart/{chart_id} - chart type + query of a conversation chart
+ - metabase://query/{query_id} - a query from this conversation's state"
(:require
[clojure.string :as str]
[metabase.activity-feed.core :as activity-feed]
[metabase.api.common :as api]
+ [metabase.documents.core :as documents]
+ [metabase.documents.prose-mirror :as prose-mirror]
[metabase.metabot.scope :as scope]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.field-stats :as field-stats]
+ [metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.models.interface :as mi]
[metabase.transforms.core :as transforms]
+ [metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.match :as match]
@@ -176,7 +185,7 @@
(defn- present-collection
"Trim a collection row to an item map. `path-name` may be supplied if the caller pre-computed it."
([coll] (present-collection coll nil))
- ([{:keys [id name location authority_level description personal_owner_id]} path-name]
+ ([{:keys [id name location authority_level description personal_owner_id] :as coll} path-name]
{:type "collection"
:id id
:name name
@@ -184,6 +193,7 @@
:location location
:authority_level authority_level
:is_personal (boolean personal_owner_id)
+ :can_write (boolean (mi/can-write? coll))
:description description
:uri (llm-shape/metabase-uri :collection id)}))
@@ -216,14 +226,24 @@
:uri (llm-shape/metabase-uri (keyword model-type) id)}))
(defn- present-dashboard
- [{:keys [id name collection_id description]}]
+ [{:keys [id name collection_id description] :as dashboard}]
{:type "dashboard"
:id id
:name name
:collection_id collection_id
+ :can_write (boolean (mi/can-write? dashboard))
:description description
:uri (llm-shape/metabase-uri :dashboard id)})
+(defn- present-document
+ [{:keys [id name collection_id] :as document}]
+ {:type "document"
+ :id id
+ :name name
+ :collection_id collection_id
+ :can_write (boolean (mi/can-write? document))
+ :uri (llm-shape/metabase-uri :document id)})
+
(defn- present-transform
[{:keys [id name description source_database_id]}]
{:type "transform"
@@ -405,6 +425,11 @@
:archived false
{:order-by [[:%lower.name :asc]]})
(filter mi/can-read?))
+ documents (->> (t2/select [:model/Document :id :name :collection_id]
+ :collection_id coll-id
+ :archived false
+ {:order-by [[:%lower.name :asc]]})
+ (filter mi/can-read?))
subcollections (->> (t2/select [:model/Collection :id :name :location :authority_level
:description :personal_owner_id]
:location (str (:location coll) coll-id "/")
@@ -413,7 +438,8 @@
(filter mi/can-read?))
items (concat (map present-collection subcollections)
(map present-card cards)
- (map present-dashboard dashboards))]
+ (map present-dashboard dashboards)
+ (map present-document documents))]
(list-result :collection-items items query-params)))
(defn- fetch-collection-subcollections [id-str query-params]
@@ -605,9 +631,12 @@
;; ----- Dashboard -----
(defn- fetch-dashboard [id-str]
- (let [result (entity-details/get-dashboard-details {:dashboard-id (parse-long id-str)})]
+ (let [dashboard-id (parse-long id-str)
+ result (entity-details/get-dashboard-details {:dashboard-id dashboard-id})]
(if-let [dashboard (:structured-output result)]
- {:structured-output (assoc dashboard :result-type :entity)}
+ {:structured-output (assoc dashboard
+ :result-type :entity
+ :can_write (boolean (mi/can-write? :model/Dashboard dashboard-id)))}
{:status-code 404 :output (:output result)})))
(defn- present-non-question-dashcard
@@ -682,6 +711,75 @@
(cond-> (list-result :dashboard-items items query-params)
(seq tabs) (update :structured-output assoc :tabs (mapv #(select-keys % [:id :name]) tabs)))))
+;; ----- Document -----
+
+(defn- document-block-line
+ "One outline line for a top-level document block: `[index] type`, plus the ids of any
+ embedded cards and a truncated text preview when the block has either."
+ [index block]
+ (let [card-ids (->> (tree-seq :content :content block)
+ (keep #(when (= (:type %) prose-mirror/card-embed-type)
+ (-> % :attrs :id))))
+ text (prose-mirror/ast->text block)]
+ (str "[" index "] " (:type block)
+ (when (seq card-ids)
+ (str " (embeds card " (str/join ", " card-ids) ")"))
+ (when-not (str/blank? text)
+ (str ": " (u/truncate text 200))))))
+
+(defn- fetch-document
+ "Present a document as an indexed outline of its top-level blocks. The indices are the
+ `position` values the `save_entity` tool accepts when inserting a chart into the document."
+ [id-str]
+ (let [document (documents/get-document (parse-long id-str))
+ blocks (get-in document [:document :content])]
+ (entity-result
+ {:type "document"
+ :id (:id document)
+ :name (:name document)
+ :can_write (boolean (:can_write document))
+ :description (if (seq blocks)
+ (str "Top-level blocks, listed as `[index] type`. Inserting at `position` i "
+ "places new content before the block currently at index i:\n"
+ (str/join "\n" (map-indexed document-block-line blocks)))
+ "The document is empty.")})))
+
+(defn- fetch-conversation-query
+ "Present a query stored in this conversation's agent state (created by tools or pasted
+ as a chart mention). Read-checks the query's database before exporting it with resolved
+ table/field names."
+ [query-id]
+ (if-let [query (get (shared/current-queries-state) query-id)]
+ (do
+ (when-let [database-id (and (map? query) (:database query))]
+ (api/read-check :model/Database database-id))
+ (entity-result
+ {:type "conversation-query"
+ :id query-id
+ :description (llm-shape/export-query-for-llm query)}))
+ {:status-code 404
+ :output (str "No chart or query with id '" query-id "' exists in this conversation. "
+ "It may belong to another conversation; ask the user to paste or recreate it here.")}))
+
+(defn- fetch-conversation-chart
+ "Present a chart stored in this conversation's agent state (created by chart tools or
+ pasted as a mention). Falls back to the queries state when the id is actually a query id."
+ [chart-id]
+ (if-let [chart (get (shared/current-charts-state) chart-id)]
+ (let [query (or (first (:queries chart))
+ (get (shared/current-queries-state) (:query_id chart)))]
+ (when-let [database-id (and (map? query) (:database query))]
+ (api/read-check :model/Database database-id))
+ (entity-result
+ {:type "conversation-chart"
+ :id chart-id
+ :description (str "Chart type: "
+ (or (some-> (get-in chart [:visualization_settings :chart_type]) name)
+ "table")
+ "\nQuery:\n"
+ (llm-shape/export-query-for-llm query))}))
+ (fetch-conversation-query chart-id)))
+
;; ----- Dispatch -----
(def ^:private numeric-id-uri-types
@@ -764,6 +862,13 @@
["dashboard" id] (fetch-dashboard id)
["dashboard" id "items"] (fetch-dashboard-items id query-params)
+ ;; Document
+ ["document" id] (fetch-document id)
+
+ ;; Conversation state
+ ["chart" id] (fetch-conversation-chart id)
+ ["query" id] (fetch-conversation-query id)
+
;; Default — required to make match non-recursive
_ (throw (ex-info (str "Unsupported URI: " uri)
{:uri uri :segments segments})))))
@@ -888,7 +993,14 @@
- metabase://measure/{id}
- metabase://segment/{id}
- metabase://transform/{id}[/sources|/target]
- - metabase://dashboard/{id}[/items]"
+ - metabase://dashboard/{id}[/items]
+ - metabase://document/{id} - name + indexed outline of the document's top-level blocks
+ (the indices are valid `position` values for `save_entity` document destinations)
+
+ CONVERSATION STATE (charts and queries generated in or pasted into this conversation,
+ e.g. referenced in a user message as [name](metabase://chart/{id})):
+ - metabase://chart/{chart_id} - the chart's type and its query
+ - metabase://query/{query_id} - the query definition"
[{:keys [uris]} :- [:map {:closed true}
[:uris [:sequential [:string {:description "Metabase resource URIs to fetch"}]]]]]
(try
diff --git a/src/metabase/metabot/tools/save_entity.clj b/src/metabase/metabot/tools/save_entity.clj
new file mode 100644
index 00000000000..e03d47aa611
--- /dev/null
+++ b/src/metabase/metabot/tools/save_entity.clj
@@ -0,0 +1,239 @@
+(ns metabase.metabot.tools.save-entity
+ "Tool that persists a previously-generated chart into a collection, dashboard, or document.
+
+ The model creates ad-hoc charts with `construct_notebook_query` / `create_chart`;
+ those live only in agent memory (`shared/current-charts-state`). This tool turns
+ one of them into a real saved question — in a collection, as a question on a
+ dashboard, or embedded in a document at a chosen position — and emits an
+ `entity_saved` data part so the inline chart can show where it landed. It should
+ only be called when the user asks to save the chart."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.collections.models.collection :as collection]
+ [metabase.documents.core :as documents]
+ [metabase.events.core :as events]
+ [metabase.metabot.agent.links :as links]
+ [metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
+ [metabase.metabot.tmpl :as te]
+ [metabase.metabot.tools.shared :as shared]
+ [metabase.queries.core :as queries]
+ [metabase.query-permissions.core :as query-perms]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private save-entity-schema
+ [:map {:closed true}
+ ;; stamped onto report_card.metabot_chart_id, a varchar(36) — clamp to fit
+ [:chart_id [:string {:min 1 :max 36}]]
+ [:name :string]
+ [:description :string]
+ [:destination
+ [:multi {:dispatch :target_type}
+ ["collection"
+ [:map {:closed true}
+ [:target_type [:= "collection"]]
+ ;; omit for the user's personal collection; explicit null for the root collection
+ [:collection_id {:optional true} [:maybe :int]]]]
+ ["dashboard"
+ [:map {:closed true}
+ [:target_type [:= "dashboard"]]
+ [:dashboard_id :int]]]
+ ["document"
+ [:map {:closed true}
+ [:target_type [:= "document"]]
+ [:document_id :int]
+ [:position {:optional true} [:maybe :int]]]]]]])
+
+(defn- agent-error! [msg]
+ (throw (ex-info msg {:agent-error? true :status-code 400})))
+
+(defn- resolve-chart
+ "Look up the generated chart from agent memory and return the pieces needed to
+ build a card: a legacy `dataset_query` and a `display` keyword. Mirrors the
+ lookup in `edit_chart` / `links/resolve-chart-link`."
+ [chart-id]
+ (let [chart (get (shared/current-charts-state) chart-id)
+ query (or (first (:queries chart))
+ (get (shared/current-queries-state) (:query_id chart)))]
+ (when-not query
+ (agent-error!
+ (tru (str "No generated chart found with id `{0}`. Create a chart with "
+ "`construct_notebook_query` first, then save it using the id it returns.")
+ chart-id)))
+ ;; agent-created charts carry the display in `:visualization_settings :chart_type`;
+ ;; charts seeded from the frontend viewing context (`seed-charts`) leave that nil
+ ;; and keep the raw config under `:chart_config` instead
+ {:dataset_query (links/->legacy-mbql query)
+ :display (or (some-> (get-in chart [:visualization_settings :chart_type]) keyword)
+ (some-> (get-in chart [:chart_config :display_type]) keyword)
+ :table)}))
+
+(defn- personal-collection-id []
+ (or (:id (collection/user->personal-collection api/*current-user-id*))
+ ;; API-key users have no personal collection; without this check the nil would
+ ;; silently save into the root collection instead
+ (agent-error!
+ (tru (str "The current user has no personal collection. Pass an explicit "
+ "`collection_id` (or `null` for the root collection) instead.")))))
+
+(defn- collection-name
+ "Current display name of a collection target, for the LLM-facing save summary.
+ A `nil` id is the root (\"Our analytics\") collection."
+ [collection-id]
+ (if (nil? collection-id)
+ (:name (collection/root-collection-with-ui-details nil))
+ (t2/select-one-fn :name :model/Collection :id collection-id)))
+
+(defn- save-to-collection!
+ [{:keys [name description dataset_query display destination]}]
+ (let [collection-id (if (contains? destination :collection_id)
+ (:collection_id destination)
+ (personal-collection-id))]
+ (query-perms/check-run-permissions-for-query dataset_query)
+ (api/create-check :model/Card {:collection_id collection-id})
+ (let [card (queries/create-card!
+ {:name name
+ :description description
+ :dataset_query dataset_query
+ :display display
+ :visualization_settings {}
+ :collection_id collection-id}
+ {:id api/*current-user-id*}
+ :delay-event)]
+ {:card card
+ :destination {:type "collection" :id collection-id}
+ :destination-name (collection-name collection-id)
+ :link (str "metabase://question/" (:id card))})))
+
+(defn- save-to-dashboard!
+ [{:keys [name description dataset_query display destination]}]
+ (let [dashboard-id (:dashboard_id destination)]
+ (when-not dashboard-id
+ (agent-error! (tru "A `dashboard_id` is required when saving to a dashboard.")))
+ (query-perms/check-run-permissions-for-query dataset_query)
+ (api/write-check :model/Dashboard dashboard-id)
+ (let [card (queries/create-card!
+ {:name name
+ :description description
+ :dataset_query dataset_query
+ :display display
+ :visualization_settings {}
+ :dashboard_id dashboard-id}
+ {:id api/*current-user-id*}
+ :delay-event)]
+ {:card card
+ :destination {:type "dashboard" :id dashboard-id}
+ :destination-name (t2/select-one-fn :name :model/Dashboard :id dashboard-id)
+ :link (str "metabase://dashboard/" dashboard-id)})))
+
+(defn- save-to-document!
+ [{:keys [name description dataset_query display destination]}]
+ (let [document-id (:document_id destination)]
+ (when-not document-id
+ (agent-error! (tru "A `document_id` is required when saving to a document.")))
+ (query-perms/check-run-permissions-for-query dataset_query)
+ (let [document (api/write-check (documents/get-document document-id :log-view? false))
+ _ (api/check-not-archived document)
+ card (queries/create-card!
+ {:name name
+ :description description
+ :dataset_query dataset_query
+ :display display
+ :visualization_settings {}
+ :collection_id (:collection_id document)
+ :document_id document-id}
+ {:id api/*current-user-id*}
+ :delay-event)]
+ (documents/add-card-to-document! document-id (:id card) (:position destination))
+ {:card card
+ :destination {:type "document" :id document-id}
+ :destination-name (:name document)
+ :link (str "metabase://document/" document-id)})))
+
+(mu/defn ^{:tool-name "save_entity"
+ :scope scope/agent-question-create}
+ save-entity-tool
+ "Save a chart you previously created into a collection, a dashboard, or a document.
+
+ ONLY call this when the user explicitly asks to save, keep, or add the chart
+ somewhere. Reference the chart by the `chart_id` you were given when it was
+ created. Provide a `name` and a concise `description` for the saved question
+ (reuse the chart's description).
+
+ Choose a `destination`:
+ - To save into a collection, set `target_type` to `collection` and pass a
+ `collection_id`. Inspect available collections first with
+ `read_resource` on `metabase://collections?tree=true`. Omit `collection_id`
+ to use the user's personal collection; pass `null` for the root collection.
+ - To add it to a dashboard, set `target_type` to `dashboard` and pass a
+ `dashboard_id`. Find dashboards with `search`, restricting `entity_types` to
+ the `dashboard` type. Only offer or use results with `can_write=true`; results
+ with `can_write=false` are visible but read-only and cannot be save destinations.
+ - To embed it in a document, set `target_type` to `document` and pass a
+ `document_id`. Find documents with `search`, restricting `entity_types` to
+ the `document` type, just as you would use the `dashboard` type to find dashboards. Search
+ using any name or topic the user provided. Before calling `save_entity`, you MUST call
+ `read_resource` on `metabase://document/{id}` for the selected result and inspect its
+ contents. Only save after that read succeeds and reports `can_write=true`. If it returns
+ `can_write=false`, an error, or Not found,
+ discard that search result and do not call `save_entity` with its id. If there are
+ multiple plausible targets, ask the user which one they mean. Optionally pass `position` — the 0-based index among the
+ document's top-level blocks where the chart is inserted (`0` puts it at the
+ very top). Omit `position` to append the chart at the end. To pick a
+ meaningful position, first inspect the document's blocks with
+ `read_resource` on `metabase://document/{id}`.
+
+ After saving, tell the user where it went and share the returned link."
+ [{:keys [chart_id destination description] question-name :name} :- save-entity-schema]
+ (try
+ (let [{:keys [dataset_query display]} (resolve-chart chart_id)
+ args {:name question-name
+ :description description
+ :dataset_query dataset_query
+ :display display
+ :destination destination}
+ ;; Create the card and stamp which conversation + generated chart it came
+ ;; from in ONE transaction, so a reloaded conversation can't observe the
+ ;; card without its origin. The stamp is a raw table update — it should not
+ ;; run the Card model's heavy before-update pipeline. The `:card-create`
+ ;; event is delayed until after the transaction commits so subscribers see
+ ;; the card.
+ {:keys [card link destination-name] saved-destination :destination}
+ (t2/with-transaction [_conn]
+ (let [saved (case (:target_type destination)
+ "collection" (save-to-collection! args)
+ "dashboard" (save-to-dashboard! args)
+ "document" (save-to-document! args))]
+ (when-let [conversation-id (shared/current-conversation-id)]
+ (t2/update! (t2/table-name :model/Card) (:id (:card saved))
+ {:metabot_conversation_id conversation-id
+ :metabot_chart_id chart_id}))
+ saved))
+ _ (events/publish-event! :event/card-create
+ {:object card :user-id api/*current-user-id*})
+ instruction-text (te/lines
+ (str "Saved \"" question-name "\" to " destination-name ".")
+ ""
+ (str "Tell the user it was saved and share this link: "
+ (te/link question-name link)))]
+ {:output (str "<result>\nSaved as card " (:id card)
+ " in " destination-name ".\n</result>\n"
+ "<instructions>\n" instruction-text "\n</instructions>")
+ :structured-output {:result-type :saved-entity
+ :card-id (:id card)
+ :collection-id (:collection_id card)
+ :destination saved-destination}
+ :data-parts [(streaming/entity-saved-part
+ {:chart_id chart_id
+ :card_id (:id card)
+ :destination saved-destination})]})
+ (catch Exception e
+ (log/error e "Error saving entity")
+ (if (:agent-error? (ex-data e))
+ {:output (ex-message e)}
+ {:output (str "Failed to save: " (or (ex-message e) "Unknown error"))}))))
diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.clj
index af2a106f2ce..ed4299fa933 100644
--- a/src/metabase/metabot/tools/search.clj
+++ b/src/metabase/metabot/tools/search.clj
@@ -24,11 +24,11 @@
(set! *warn-on-reflection* true)
(def ^:private metabot-search-models
- (sorted-set "card" "dashboard" "database" "dataset" "metric" "table" "transform"))
+ (sorted-set "card" "dashboard" "database" "dataset" "document" "metric" "table" "transform"))
(defn- postprocess-search-result
"Transform a single search result to match the appropriate entity-specific schema."
- [{:keys [verified moderated_status collection data_authority curated data_layer] :as result}]
+ [{:keys [verified moderated_status collection data_authority curated data_layer can_write] :as result}]
(let [model (:model result)
verified? (or (boolean verified) (= moderated_status "verified"))
collection-info (select-keys collection [:id :name :authority_level])
@@ -67,7 +67,15 @@
(merge {:verified verified?
:official official?
:collection collection-info})
- (m/assoc-some :curated curated))
+ (m/assoc-some :curated curated
+ :can_write can_write))
+
+ "document"
+ (-> common-fields
+ (merge {:official official?
+ :collection collection-info})
+ (m/assoc-some :curated curated
+ :can_write can_write))
"transform"
(merge common-fields
@@ -182,6 +190,31 @@
(or (not= "transform" (:type result))
(contains? readable-ids (:id result))))))))
+(defn- validate-and-enrich-documents
+ "Remove stale or unreadable document hits and attach live write permission.
+
+ Search indexes are updated asynchronously, so a deleted document can briefly remain
+ searchable. Destination discovery must validate hits against the live model before the
+ agent attempts to save into them."
+ [results]
+ (let [document-ids (->> results (filter #(= "document" (:type %))) (map :id) set)
+ id->document (when (seq document-ids)
+ (->> (t2/select :model/Document
+ :id [:in document-ids]
+ :archived false)
+ (filter mi/can-read?)
+ (map (juxt :id identity))
+ (into {})))]
+ (if (seq document-ids)
+ (into []
+ (keep (fn [result]
+ (if (= "document" (:type result))
+ (when-let [document (get id->document (:id result))]
+ (assoc result :can_write (boolean (mi/can-write? document))))
+ result)))
+ results)
+ results)))
+
(defn- search-result-id
"Generate a unique identifier for a search result based on its id and model."
[search-result]
@@ -323,6 +356,7 @@
enrich-with-database-engines
enrich-with-portable-entity-ids
enrich-with-metric-base-tables
+ validate-and-enrich-documents
remove-unreadable-transforms)))
(defn- table-refs->results
@@ -514,15 +548,15 @@
[:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
[:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
[:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model" "metric" "dashboard" "question"]]]]
+ [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model" "metric" "dashboard" "document" "question"]]]]
[:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
(mu/defn ^{:tool-name "search"
:scope scope/agent-search}
search-tool
- "Find tables, models, metrics, dashboards, and saved questions by topic across the instance. Use it when you don't know where something lives; once you have a hit, drill into it with read_resource rather than searching the same concept again."
+ "Find tables, models, metrics, dashboards, documents, and saved questions by topic across the instance. Use it when you don't know where something lives; once you have a hit, drill into it with read_resource rather than searching the same concept again."
[args :- search-schema]
- (do-search "search" (sorted-set "dashboard" "metric" "model" "question" "table") {} args))
+ (do-search "search" (sorted-set "dashboard" "document" "metric" "model" "question" "table") {} args))
(def ^:private sql-search-schema
[:map {:closed true}
@@ -545,15 +579,20 @@
[:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
[:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
[:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model" "metric" "question"]]]]
+ [:maybe [:sequential [:enum {:description entity-types-desc}
+ "table" "model" "metric" "question" "dashboard" "document"]]]]
[:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
(mu/defn ^{:tool-name "search"
:scope scope/agent-search}
nlq-search-tool
- "Find NLQ-queryable data sources (tables, models, metrics, saved questions) by topic, to build a visualization from."
- [args :- nlq-search-schema]
- (do-search "NLQ search" (sorted-set "metric" "model" "question" "table") {:profile-id "nlq"} args))
+ "Find NLQ-queryable data sources by topic, or find dashboards and documents as save destinations."
+ [{:keys [entity_types] :as args} :- nlq-search-schema]
+ (let [allowed-types (sorted-set "dashboard" "document" "metric" "model" "question" "table")
+ args (cond-> args
+ (not (seq entity_types))
+ (assoc :entity_types ["metric" "model" "question" "table"]))]
+ (do-search "NLQ search" allowed-types {:profile-id "nlq"} args)))
(def ^:private transform-search-schema
[:map {:closed true}
diff --git a/src/metabase/metabot/tools/shared.clj b/src/metabase/metabot/tools/shared.clj
index 15e39021ea2..7a96ac549e1 100644
--- a/src/metabase/metabot/tools/shared.clj
+++ b/src/metabase/metabot/tools/shared.clj
@@ -25,6 +25,13 @@
(when *memory-atom*
@*memory-atom*))
+(defn current-conversation-id
+ "The current conversation's id (a UUID string) from agent memory, or nil outside a
+ conversation-backed run. Tools use it to record which conversation an entity they
+ create came from (e.g. `save_entity` stamps it onto the saved card)."
+ []
+ (:conversation-id (current-memory)))
+
(defn current-queries-state
"Returns the current queries state map from agent memory."
[]
diff --git a/src/metabase/metabot/tools/shared/instructions.clj b/src/metabase/metabot/tools/shared/instructions.clj
index 49c62d12ab4..fff3bc5dd81 100644
--- a/src/metabase/metabot/tools/shared/instructions.clj
+++ b/src/metabase/metabot/tools/shared/instructions.clj
@@ -12,6 +12,7 @@ When using results:
- Check available fields or metadata of promising results before recommending them to ensure they contain needed data
- **Be proactive with clear matches**: When the top result(s) have names or descriptions that clearly match the user's request, use them to achieve the users goal first, then list alternatives at the end. Don't ask for confirmation when there's an obvious best choice.
- **Collection metadata**: Results may include collection information (name, description, authority level) that can help you determine whether the result is relevant to the user's query. Use this context to assess relevance.
+- **Save destinations**: Dashboard and document results include `can_write`. Only offer or use destinations where `can_write=true`; `can_write=false` means the user can view but cannot save there.
- **Present options for ambiguous results**: When search returns multiple plausible options without a clear best match, present them and ask the user to choose
- **Drill in via the `uri` attribute**: To inspect a result's details, pass its `uri` attribute to `read_resource` (append `/fields` for a table/model/question's columns). URIs always use the numeric `id` — never put a `portable_entity_id` in a URI; that value belongs only in `construct_notebook_query` query text (`source-card:` and metric/measure/segment references)
- Reference results using the metabase protocol link format: [display name](metabase://type/id)
diff --git a/src/metabase/metabot/tools/shared/llm_shape.clj b/src/metabase/metabot/tools/shared/llm_shape.clj
index 992a3a495f1..511a5853198 100644
--- a/src/metabase/metabot/tools/shared/llm_shape.clj
+++ b/src/metabase/metabot/tools/shared/llm_shape.clj
@@ -12,9 +12,12 @@
Matches Python AI Service patterns exactly for consistency."
(:require
[clojure.string :as str]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.schema :as lib.schema]
[metabase.metabot.agent.prompts :as prompts]
[metabase.metabot.tmpl :as te]
+ [metabase.metabot.tools.shared.content-store :as shared.content-store]
[metabase.util :as u]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -721,7 +724,7 @@
gives the LLM the full portable FK `[database_name, schema, table]` it must put in
`source-table:` when using `[metric, {}, <portable_entity_id>]` as an aggregation —
without a separate `read_resource` round-trip."
- [{:keys [id type name description verified official curated data_authority data_layer collection
+ [{:keys [id type name description verified official curated can_write data_authority data_layer collection
database_id database_name database_engine database_schema portable_entity_id
base_table_portable_fk]}]
(let [fqn (cond
@@ -751,6 +754,8 @@
:search_official official
:search_has_curated (some? curated)
:search_curated curated
+ :search_has_can_write (some? can_write)
+ :search_can_write can_write
:search_data_layer (some-> data_layer clojure.core/name)
:search_data_authority (when (and data_authority (not= "unconfigured" (clojure.core/name data_authority)))
(clojure.core/name data_authority))
@@ -879,7 +884,7 @@
(def ^:private item-attr-keys
"Attributes rendered as XML attrs on each <item> element. Order matters for stable output."
- [:type :id :dashcard_id :tab_id :name :uri :database_id :collection_id :table_id
+ [:type :id :dashcard_id :tab_id :name :uri :database_id :collection_id :table_id :can_write
:schema :display_name :authority_level :is_personal :path :location
:engine :timestamp])
@@ -887,8 +892,9 @@
[item]
(->> item-attr-keys
(keep (fn [k]
- (when-let [v (get item k)]
- (str (clojure.core/name k) "=\"" (escape-xml v) "\""))))
+ (let [v (get item k)]
+ (when (if (= k :can_write) (contains? item k) v)
+ (str (clojure.core/name k) "=\"" (escape-xml (str v)) "\"")))))
(str/join " ")))
(defn- list-item->xml
@@ -950,3 +956,28 @@
(str "<" tag (when-not (str/blank? attrs) (str " " attrs)) ">"
(escape-xml description) "</" tag ">")
(str "<" tag (when-not (str/blank? attrs) (str " " attrs)) "/>"))))
+
+(defn export-query-for-llm
+ "Render a `query` (legacy or pMBQL map, or a pre-resolved string) for the LLM. A query
+ map with a `:database` is normalized and exported to the portable representations form
+ the `construct_notebook_query` tool consumes (a JSON code block); pre-resolved string
+ sources pass through; a `pprint`'d map is the last-resort fallback."
+ [query]
+ (cond
+ (string? query) query
+ (string? (:query-content query)) (:query-content query)
+ (and (map? query) (:database query))
+ (try
+ (let [normalized (lib-be/normalize-query query)
+ database-id (:database normalized)
+ mp (when database-id
+ (lib-be/application-database-metadata-provider database-id))
+ exported (some->> mp (#(repr.resolve/try-export-query % normalized shared.content-store/default-store)))]
+ (if exported
+ (str "```json\n" (json/encode exported {:pretty true}) "\n```")
+ (u/pprint-to-str normalized)))
+ (catch Exception _
+ (u/pprint-to-str query)))
+ (string? (get-in query [:native :query])) (get-in query [:native :query])
+ (map? query) (u/pprint-to-str query)
+ :else (some-> query str)))
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 5294810344c..4579a2feb4e 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -852,6 +852,19 @@
(card.metadata/populate-result-metadata changes))
(m/update-existing :result_metadata #(some->> % (lib/normalize [:sequential ::lib.schema.metadata/lib-or-legacy-column])))))
+(defn- clear-metabot-origin
+ "A card edited after being saved from a Metabot conversation no longer materializes
+ the chart it was saved from, so sever the link back to its origin — the conversation
+ then stops showing that chart as saved. Only content edits count (query, display, viz
+ settings); renames, moves, and archiving keep the link. The Metabot save paths stamp
+ these columns with raw table updates, so stamping never re-enters this hook."
+ [card changes]
+ (if (and (some (partial contains? changes)
+ [:dataset_query :display :visualization_settings])
+ (or (:metabot_conversation_id card) (:metabot_chart_id card)))
+ (assoc card :metabot_conversation_id nil :metabot_chart_id nil)
+ card))
+
(t2/define-before-update :model/Card
[{:keys [verified-result-metadata?] :as card}]
(let [changes (some-> card t2/changes queries.schema/normalize-card)
@@ -866,6 +879,7 @@
;; populate-query-fields must run before pre-update in case source_card_id should be nilled.
;; Only allow it to nil out a stale table_id when the query itself is changing.
(populate-query-fields (contains? changes :dataset_query))
+ (clear-metabot-origin changes)
(pre-update changes)
maybe-populate-initially-published-at)))
@@ -1409,7 +1423,9 @@
;; always derivable from dataset_query by populate-query-fields; nil when not derivable
:query_type
;; always re-derived from dataset_query by populate-query-fields on import
- :table_id :source_card_id]
+ :table_id :source_card_id
+ ;; instance-specific Metabot origin (which conversation/chart the card was saved from)
+ :metabot_conversation_id :metabot_chart_id]
:transform
{:created_at (serdes/date)
;; database_id is usually derivable from dataset_query, but must be kept when the query
diff --git a/src/metabase/revisions/impl/card.clj b/src/metabase/revisions/impl/card.clj
index 71abd96c737..0ad5a76644c 100644
--- a/src/metabase/revisions/impl/card.clj
+++ b/src/metabase/revisions/impl/card.clj
@@ -17,6 +17,11 @@
:legacy_query
:made_public_by_id
:metabase_version
+ ;; internal Metabot bookkeeping (which conversation/chart the card was saved from);
+ ;; excluding them also keeps a revert from writing back a stale conversation id
+ ;; after the conversation is deleted (the FK would reject it)
+ :metabot_chart_id
+ :metabot_conversation_id
:public_uuid
:updated_at
:view_count})
diff --git a/src/metabase/slackbot/streaming.clj b/src/metabase/slackbot/streaming.clj
index 1343788277d..e5c30d9716e 100644
--- a/src/metabase/slackbot/streaming.clj
+++ b/src/metabase/slackbot/streaming.clj
@@ -245,13 +245,14 @@
(try
(transduce dispatch-xf (constantly nil) nil
(agent/run-agent-loop
- {:messages messages
- :state {}
- :profile-id :slackbot
- :context context
- :memory-atom memory-atom
- :tracking-opts {:source "slackbot"
- :session-id conversation-id}}))
+ {:messages messages
+ :state {}
+ :profile-id :slackbot
+ :conversation-id conversation-id
+ :context context
+ :memory-atom memory-atom
+ :tracking-opts {:source "slackbot"
+ :session-id conversation-id}}))
(catch Throwable t
;; Capture for the finally's `:error` payload, then re-throw so the
;; existing slack error-handling path (DM/channel) still surfaces a
diff --git a/test/metabase/documents/prose_mirror_test.clj b/test/metabase/documents/prose_mirror_test.clj
index 514c0f3dd10..665cb00b995 100644
--- a/test/metabase/documents/prose_mirror_test.clj
+++ b/test/metabase/documents/prose_mirror_test.clj
@@ -344,3 +344,47 @@
(testing "returns an empty string for an empty document"
(is (= "" (prose-mirror/ast->text {:type "doc" :content []})))
(is (= "" (prose-mirror/ast->text nil)))))
+
+(deftest ^:parallel insert-card-embed-test
+ (let [doc {:document {:type "doc"
+ :content [{:type "paragraph" :content [{:type "text" :text "one"}]}
+ {:type "paragraph" :content [{:type "text" :text "two"}]}]}
+ :content_type prose-mirror/prose-mirror-content-type}
+ embed {:type "resizeNode"
+ :content [{:type prose-mirror/card-embed-type :attrs {:id 42}}]}]
+ (testing "a nil index appends the embed at the end"
+ (let [result (prose-mirror/insert-card-embed doc 42 nil)]
+ (is (= 3 (count (get-in result [:document :content]))))
+ (is (= embed (get-in result [:document :content 2])))))
+ (testing "an index inserts before the block currently at that index"
+ (let [result (prose-mirror/insert-card-embed doc 42 1)]
+ (is (= embed (get-in result [:document :content 1])))
+ (is (= "two" (get-in result [:document :content 2 :content 0 :text])))))
+ (testing "index 0 inserts at the very top"
+ (is (= embed (-> (prose-mirror/insert-card-embed doc 42 0)
+ (get-in [:document :content 0])))))
+ (testing "out-of-range indexes are clamped"
+ (is (= embed (-> (prose-mirror/insert-card-embed doc 42 99)
+ (get-in [:document :content 2]))))
+ (is (= embed (-> (prose-mirror/insert-card-embed doc 42 -5)
+ (get-in [:document :content 0])))))))
+
+(deftest ^:parallel insert-card-embed-empty-document-test
+ (testing "inserting into an empty or nil ast produces a doc with just the embed"
+ (doseq [document [{:type "doc" :content []} nil]]
+ (let [result (prose-mirror/insert-card-embed
+ {:document document
+ :content_type prose-mirror/prose-mirror-content-type}
+ 7 nil)]
+ (is (= {:type "doc"
+ :content [{:type "resizeNode"
+ :content [{:type prose-mirror/card-embed-type :attrs {:id 7}}]}]}
+ (:document result)))))))
+
+(deftest ^:parallel insert-card-embed-invalid-content-type-test
+ (testing "throws for non-prose-mirror documents"
+ (is (thrown-with-msg?
+ Exception #"Document does not have the prose mirror content-type"
+ (prose-mirror/insert-card-embed {:document {:type "doc" :content []}
+ :content_type "text/plain"}
+ 7 nil)))))
diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.clj
index 79999d8ca3a..511c92149ab 100644
--- a/test/metabase/metabot/agent/core_test.clj
+++ b/test/metabase/metabot/agent/core_test.clj
@@ -326,6 +326,7 @@
:arguments {:reasoning "User wants to see orders"
:query external-query
:title "First 10 orders"
+ :description "The first 10 orders."
:visualization {:chart_type "table"}}}
{:type :usage :usage {:promptTokens 200 :completionTokens 30} :model "test" :id "msg-2"}]
;; Iteration 3: Final text response
diff --git a/test/metabase/metabot/agent/links_test.clj b/test/metabase/metabot/agent/links_test.clj
index d79bc691bc6..a17cdce04c9 100644
--- a/test/metabase/metabot/agent/links_test.clj
+++ b/test/metabase/metabot/agent/links_test.clj
@@ -18,6 +18,26 @@
u/decode-base64
(json/decode+kw)))
+(deftest ^:parallel ->legacy-mbql-rehydrated-query-test
+ (testing "normalizes enum values stringified by JSON persistence before conversion"
+ (let [query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 6
+ :aggregation [[:count {}]]
+ :breakout [[:field
+ {:temporal-unit :day
+ :base-type :type/DateTime}
+ 31]]}]}
+ rehydrated (json/decode+kw (json/encode query))]
+ (is (= {:database 1
+ :type :query
+ :query {:source-table 6
+ :aggregation [[:count]]
+ :breakout [[:field 31 {:temporal-unit :day
+ :base-type :type/DateTime}]]}}
+ (links/->legacy-mbql rehydrated))))))
+
;;; resolve-metabase-uri tests
(deftest ^:parallel resolve-metabase-uri-query-links-test
@@ -53,6 +73,7 @@
(is (= "/model/123" (links/resolve-metabase-uri "metabase://model/123" {} {})))
(is (= "/metric/456" (links/resolve-metabase-uri "metabase://metric/456" {} {})))
(is (= "/dashboard/789" (links/resolve-metabase-uri "metabase://dashboard/789" {} {})))
+ (is (= "/document/303" (links/resolve-metabase-uri "metabase://document/303" {} {})))
(is (= "/question/101" (links/resolve-metabase-uri "metabase://question/101" {} {})))
(is (= "/data-studio/transforms/202" (links/resolve-metabase-uri "metabase://transform/202" {} {})))))
diff --git a/test/metabase/metabot/agent/user_context_test.clj b/test/metabase/metabot/agent/user_context_test.clj
index 9ef7bc6adfa..acb19b9ffb9 100644
--- a/test/metabase/metabot/agent/user_context_test.clj
+++ b/test/metabase/metabot/agent/user_context_test.clj
@@ -64,12 +64,13 @@
(deftest ^:parallel format-viewing-context-test
(let [mp meta/metadata-provider]
(testing "formats adhoc notebook (MBQL) query context"
- (is (=? (re-pattern
- (format "(?s).*notebook editor.*Database ID: %d.*"
- (meta/id)))
- (user-context/format-viewing-context
- {:user_is_viewing [{:type "adhoc"
- :query (lib/query mp (lib.metadata/table mp (meta/id :venues)))}]}))))
+ (mt/with-test-user :crowberto
+ (is (=? (re-pattern
+ (format "(?s).*notebook editor.*Database ID: %d.*"
+ (meta/id)))
+ (user-context/format-viewing-context
+ {:user_is_viewing [{:type "adhoc"
+ :query (lib/query mp (lib.metadata/table mp (meta/id :venues)))}]})))))
(testing "formats adhoc native SQL query from frontend (type: adhoc, query.type: native)"
(let [result (user-context/format-viewing-context
{:user_is_viewing [{:type "adhoc"
@@ -472,3 +473,31 @@
(is (string? text))
(is (re-find #"\"mbql.stage/native\"" text))
(is (re-find #"SELECT \* FROM VENUES" text)))))))
+
+(deftest ^:parallel adhoc-viewing-context-includes-query-test
+ (testing "adhoc viewing context renders the query so the model can see the chart"
+ (let [out (user-context/format-viewing-context
+ {:user_is_viewing
+ [{:type "adhoc"
+ :query {:type "query" :query {:source-table 1}}}]})]
+ (is (str/includes? out "notebook editor"))
+ (is (str/includes? out "source-table")))))
+
+(deftest adhoc-viewing-context-read-checks-database-test
+ (let [viewing (fn [db-id]
+ {:user_is_viewing [{:type "adhoc"
+ :query {:database db-id
+ :type "query"
+ :query {:source-table (mt/id :venues)}}}]})]
+ (testing "renders the query when the user can read its database"
+ (mt/with-test-user :crowberto
+ (let [out (user-context/format-viewing-context (viewing (mt/id)))]
+ (is (str/includes? out "notebook editor"))
+ (is (str/includes? out "source-table")))))
+ (testing "omits the query when the user cannot read its database"
+ (mt/with-temp [:model/Database {db-id :id} {}]
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-test-user :rasta
+ (let [out (user-context/format-viewing-context (viewing db-id))]
+ (is (str/includes? out "notebook editor"))
+ (is (not (str/includes? out "source-table"))))))))))
diff --git a/test/metabase/metabot/api/conversations_test.clj b/test/metabase/metabot/api/conversations_test.clj
index d5600348dca..258aebd3eff 100644
--- a/test/metabase/metabot/api/conversations_test.clj
+++ b/test/metabase/metabot/api/conversations_test.clj
@@ -3,6 +3,8 @@
[clojure.test :refer [deftest is testing]]
[java-time.api :as t]
[metabase.api.common :as api]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.metabot.api :as metabot.api]
[metabase.metabot.persistence :as metabot.persistence]
[metabase.test :as mt]
@@ -13,6 +15,10 @@
(defn- seconds-ago [n]
(t/minus (t/offset-date-time) (t/seconds n)))
+(defn- venues-query []
+ (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues))))
+
(deftest list-conversations-authentication-test
(testing "GET /api/metabot/conversations requires auth"
(is (= "Unauthenticated"
@@ -347,3 +353,70 @@
(finally
(t2/delete! :model/MetabotMessage :conversation_id convo-id)
(t2/delete! :model/MetabotConversation :id convo-id))))))
+
+(deftest record-saved-entity-test
+ (testing "POST /api/metabot/conversations/:id/saved-entity creates the card with its origin stamped"
+ (let [user-id (mt/user->id :crowberto)]
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id}
+ :model/MetabotMessage _ {:conversation_id convo-id :user_id user-id :role "user"}]
+ (let [created (mt/user-http-request :crowberto :post 200
+ (str "metabot/conversations/" convo-id "/saved-entity")
+ {:chart_id "chart-1"
+ :card {:name "Venues by price"
+ :dataset_query (venues-query)
+ :display "bar"}})]
+ (is (= "Venues by price" (:name created)))
+ (is (= {:metabot_conversation_id convo-id
+ :metabot_chart_id "chart-1"
+ :display :bar}
+ (t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id :display]
+ :id (:id created))))
+ (testing "the conversation detail lists the saved entity"
+ (is (= [{:card_id (:id created) :chart_id "chart-1"}]
+ (:saved_entities
+ (mt/user-http-request :crowberto :get 200
+ (str "metabot/conversations/" convo-id))))))
+ (testing "archived cards drop out of saved_entities"
+ (t2/update! :model/Card (:id created) {:archived true})
+ (is (= []
+ (:saved_entities
+ (mt/user-http-request :crowberto :get 200
+ (str "metabot/conversations/" convo-id))))))))))))
+
+(deftest record-saved-entity-collection-mismatch-test
+ (testing "an explicit collection_id that doesn't match the dashboard's own collection 400s"
+ (let [user-id (mt/user->id :crowberto)]
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id}
+ :model/MetabotMessage _ {:conversation_id convo-id :user_id user-id :role "user"}
+ :model/Collection {coll-id :id} {}
+ :model/Dashboard {dash-id :id} {}]
+ (mt/user-http-request :crowberto :post 400
+ (str "metabot/conversations/" convo-id "/saved-entity")
+ {:chart_id "chart-1"
+ :card {:name "x"
+ :dataset_query (venues-query)
+ :display "bar"
+ :dashboard_id dash-id
+ :collection_id coll-id}})
+ (is (zero? (t2/count :model/Card :metabot_conversation_id convo-id))))))))
+
+(deftest record-saved-entity-permissions-test
+ (let [user-id (mt/user->id :crowberto)
+ body {:chart_id "chart-1"
+ :card {:name "x"
+ :dataset_query (venues-query)
+ :display "bar"}}]
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id}
+ :model/MetabotMessage _ {:conversation_id convo-id :user_id user-id :role "user"}]
+ (testing "a non-participant cannot save into the conversation, and no card is created"
+ (mt/user-http-request :lucky :post 403
+ (str "metabot/conversations/" convo-id "/saved-entity")
+ body)
+ (is (zero? (t2/count :model/Card :metabot_conversation_id convo-id))))
+ (testing "a nonexistent conversation 404s"
+ (mt/user-http-request :crowberto :post 404
+ (str "metabot/conversations/" (random-uuid) "/saved-entity")
+ body))))))
diff --git a/test/metabase/metabot/tools/charts/edit_test.clj b/test/metabase/metabot/tools/charts/edit_test.clj
index e770dbfa161..cfbbc678fa7 100644
--- a/test/metabase/metabot/tools/charts/edit_test.clj
+++ b/test/metabase/metabot/tools/charts/edit_test.clj
@@ -92,6 +92,7 @@
construct-result (tools.construct/construct-notebook-query-tool
{:query external-query
:title "Counts by category"
+ :description "Counts by category."
:visualization {:chart_type "bar"}})
query-id (get-in construct-result [:structured-output :query-id])
query (get-in construct-result [:structured-output :query])
@@ -106,7 +107,8 @@
;; (3) call the edit-chart-tool which uses the shared memory
(let [edit-result (tools.charts/edit-chart-tool {:chart_id chart-id
:new_viz_settings {:chart_type "pie"}
- :title "Counts by category"})
+ :title "Counts by category"
+ :description "Counts by category."})
new-chart-id (get-in edit-result [:structured-output :chart-id])
new-chart-in-memory (get (tools.shared/current-charts-state) new-chart-id)]
(is (= :pie
@@ -141,6 +143,7 @@
result (tools.construct/construct-notebook-query-tool
{:query external-query
:title "Test chart"
+ :description "Test chart description."
:visualization {:chart_type "bar"}})
query (get-in result [:structured-output :query])]
(testing "order-by inner clause is now an aggregation reference, not :sum"
@@ -185,6 +188,7 @@
result (tools.construct/construct-notebook-query-tool
{:query external-query
:title "Test chart"
+ :description "Test chart description."
:visualization {:chart_type "bar"}})]
(testing "tool returns a clear, agent-targeted error rather than producing a chart"
;; The outer `construct-notebook-query-tool` catches the ex-info and returns
@@ -218,6 +222,7 @@
result (tools.construct/construct-notebook-query-tool
{:query external-query
:title "Test chart"
+ :description "Test chart description."
:visualization {:chart_type "bar"}})
query (get-in result [:structured-output :query])
breakout-field (get-in query [:stages 0 :breakout 0])]
@@ -273,6 +278,7 @@
construct-result (tools.construct/construct-notebook-query-tool
{:query external-query
:title "Test chart"
+ :description "Test chart description."
:visualization {:chart_type "bar"}})
query (get-in construct-result [:structured-output :query])
breakout-field (get-in query [:stages 0 :breakout 0])
diff --git a/test/metabase/metabot/tools/charts_test.clj b/test/metabase/metabot/tools/charts_test.clj
index f80499fe4c1..fec0b3b3961 100644
--- a/test/metabase/metabot/tools/charts_test.clj
+++ b/test/metabase/metabot/tools/charts_test.clj
@@ -22,7 +22,8 @@
shared/*profile-id* profile-id]
(charts/create-chart-tool {:data_source {:query_id "q-1"}
:viz_settings {:chart_type chart-type}
- :title "Orders by month"})))))
+ :title "Orders by month"
+ :description "Monthly count of orders."})))))
(deftest create-chart-inline-viz-test
(testing "emits a single generated_entity card part in the NLQ profile"
@@ -34,6 +35,7 @@
(is (= "card" (:type entity)))
(is (string? (:id entity)))
(is (= "Orders by month" (:title entity)))
+ (is (= "Monthly count of orders." (:description entity)))
(is (= "bar" (:display entity)))
(testing "embeds the query so the FE can run it"
(is (= "q-1" (get-in entity [:query :id])))
@@ -66,7 +68,8 @@
shared/*profile-id* :nlq]
(charts/edit-chart-tool {:chart_id "c-1"
:new_viz_settings {:chart_type "pie"}
- :title "Orders by month"}))
+ :title "Orders by month"
+ :description "Monthly count of orders."}))
parts (:data-parts result)
entity (:data (first parts))]
(is (= 1 (count parts)))
diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.clj
index 0f5d1cf8704..1c6c5341bc6 100644
--- a/test/metabase/metabot/tools/resources_test.clj
+++ b/test/metabase/metabot/tools/resources_test.clj
@@ -7,6 +7,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.metabot.tools.resources :as read-resource]
+ [metabase.metabot.tools.shared :as tools.shared]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.models.interface :as mi]
[metabase.query-processor :as qp]
@@ -129,7 +130,10 @@
;; ----- Dashboard -----
["metabase://dashboard/8" :dashboard ["8"]]
["metabase://dashboard/8/items" :dashboard-items ["8" nil]]
- ["metabase://dashboard/8/items?page=2" :dashboard-items ["8" {:page "2"}]]])
+ ["metabase://dashboard/8/items?page=2" :dashboard-items ["8" {:page "2"}]]
+ ;; ----- Conversation state -----
+ ["metabase://chart/7f018c82-4381-4264" :conversation-chart ["7f018c82-4381-4264"]]
+ ["metabase://query/NXRVLzEMoMpfNJpqPshQR" :conversation-query ["NXRVLzEMoMpfNJpqPshQR"]]])
(deftest dispatch-routing-test
(testing "every supported URI pattern routes to the expected handler with the expected args"
@@ -163,7 +167,9 @@
read-resource/fetch-transform-sources (spy :transform-sources)
read-resource/fetch-transform-target (spy :transform-target)
read-resource/fetch-dashboard (spy :dashboard)
- read-resource/fetch-dashboard-items (spy :dashboard-items)]
+ read-resource/fetch-dashboard-items (spy :dashboard-items)
+ read-resource/fetch-conversation-chart (spy :conversation-chart)
+ read-resource/fetch-conversation-query (spy :conversation-query)]
(doseq [[uri expected-handler expected-args] dispatch-cases]
(testing uri
(reset! calls nil)
@@ -262,6 +268,61 @@
(is (=? {:resources [{:error string?}]}
(read-resource/read-resource {:uris ["metabase://dashboard/99999"]})))))))
+(deftest read-document-resource-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id} {:name "Embedded chart"}
+ :model/Document {document-id :id}
+ {:name "Q3 report"
+ :document {:type "doc"
+ :content [{:type "heading"
+ :content [{:type "text" :text "Revenue"}]}
+ {:type "resizeNode"
+ :content [{:type "cardEmbed" :attrs {:id card-id}}]}
+ {:type "paragraph"
+ :content [{:type "text" :text "Detailed analysis"}]}]}}]
+ (testing "fetches an indexed outline of the document's top-level blocks"
+ (let [{:keys [output] :as result} (read-resource/read-resource
+ {:uris [(str "metabase://document/" document-id)]})]
+ (is (=? {:resources [{:content {:structured-output map?}}]}
+ result))
+ (is (str/includes? output "Q3 report"))
+ (is (str/includes? output "[0] heading: Revenue"))
+ (is (str/includes? output (str "[1] resizeNode (embeds card " card-id ")")))
+ (is (str/includes? output "[2] paragraph: Detailed analysis"))))
+ (testing "returns error for unknown document"
+ (is (=? {:resources [{:error string?}]}
+ (read-resource/read-resource {:uris ["metabase://document/99999"]})))))))
+
+(deftest read-conversation-chart-resource-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [query {:database (mt/id)
+ :type "query"
+ :query {:source-table (mt/id :orders)
+ :aggregation [["count"]]}}]
+ (binding [tools.shared/*memory-atom*
+ (atom {:state {:queries {"q-1" query}
+ :charts {"chart-1" {:chart_id "chart-1"
+ :query_id "q-1"
+ :queries [query]
+ :visualization_settings {:chart_type "line"}}}}})]
+ (testing "resolves a conversation chart to its chart type and exported query"
+ (let [result (read-resource/read-resource {:uris ["metabase://chart/chart-1"]})]
+ (is (=? {:resources [{:content {:structured-output map?}}]}
+ result))
+ (is (str/includes? (:output result) "conversation-chart"))
+ (is (str/includes? (:output result) "Chart type: line"))
+ (is (str/includes? (:output result) "ORDERS"))))
+ (testing "falls back to the queries state when the id is a query id"
+ (let [result (read-resource/read-resource {:uris ["metabase://chart/q-1"]})]
+ (is (str/includes? (:output result) "conversation-query"))))
+ (testing "resolves a conversation query"
+ (let [result (read-resource/read-resource {:uris ["metabase://query/q-1"]})]
+ (is (str/includes? (:output result) "conversation-query"))
+ (is (str/includes? (:output result) "ORDERS"))))
+ (testing "errors clearly for ids that are in neither charts nor queries state"
+ (is (=? {:resources [{:error #"No chart or query with id 'nope'.*"}]}
+ (read-resource/read-resource {:uris ["metabase://chart/nope"]}))))))))
+
(deftest read-transform-resource-test
(mt/with-premium-features #{:transforms-basic :hosting}
(mt/with-current-user (mt/user->id :crowberto)
@@ -528,14 +589,18 @@
(deftest read-collections-and-collection-items-test
(mt/with-current-user (mt/user->id :crowberto)
(mt/with-temp [:model/Collection {coll-id :id} {:name "Marketing" :location "/"}
- :model/Card {card-id :id} {:name "Sales report" :collection_id coll-id}]
+ :model/Card {card-id :id} {:name "Sales report" :collection_id coll-id}
+ :model/Document {doc-id :id} {:name "Campaign plan" :collection_id coll-id}]
(testing "metabase://collections lists root collections (excluding trash)"
(let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://collections"]})]
(is (str/includes? output "Marketing"))))
(testing "metabase://collection/{id}/items lists members with drill-in URIs"
(let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://collection/" coll-id "/items")]})]
(is (str/includes? output "Sales report"))
- (is (str/includes? output (str "uri=\"metabase://question/" card-id "\""))))))))
+ (is (str/includes? output (str "uri=\"metabase://question/" card-id "\"")))
+ (is (str/includes? output "Campaign plan"))
+ (is (str/includes? output (str "uri=\"metabase://document/" doc-id "\"")))
+ (is (str/includes? output "can_write=\"true\"")))))))
(deftest read-table-derived-test
(mt/with-current-user (mt/user->id :crowberto)
diff --git a/test/metabase/metabot/tools/save_entity_test.clj b/test/metabase/metabot/tools/save_entity_test.clj
new file mode 100644
index 00000000000..3eb54b1a688
--- /dev/null
+++ b/test/metabase/metabot/tools/save_entity_test.clj
@@ -0,0 +1,220 @@
+(ns metabase.metabot.tools.save-entity-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.metabot.tools.save-entity :as save-entity]
+ [metabase.metabot.tools.shared :as shared]
+ [metabase.test :as mt]
+ [metabase.util.json :as json]
+ [toucan2.core :as t2]))
+
+(defn- venues-query []
+ (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues))))
+
+(defn- chart-memory
+ "A memory atom holding one generated chart `c-1` over a real query."
+ []
+ (let [query (venues-query)]
+ (atom {:state {:queries {"q-1" query}
+ :charts {"c-1" {:chart_id "c-1"
+ :query_id "q-1"
+ :queries [query]
+ :visualization_settings {:chart_type :bar}}}}
+ :context {}})))
+
+(defn- rehydrated-chart-memory
+ "A chart memory whose query has crossed the JSON persistence boundary between turns."
+ []
+ (let [query (-> (venues-query)
+ (dissoc :lib/metadata)
+ json/encode
+ json/decode+kw)]
+ (atom {:state {:queries {"q-1" query}
+ :charts {"c-1" {:chart_id "c-1"
+ :query_id "q-1"
+ :queries [query]
+ :visualization_settings {:chart_type "bar"}}}}
+ :context {}})))
+
+(defn- save! [destination]
+ (binding [shared/*memory-atom* (chart-memory)]
+ (save-entity/save-entity-tool
+ {:chart_id "c-1"
+ :name "Venues by price"
+ :description "Count of venues grouped by price."
+ :destination destination})))
+
+(deftest save-to-collection-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {:name "Sales analytics"}]
+ (let [result (save! {:target_type "collection" :collection_id (:id coll)})
+ part (first (:data-parts result))
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (testing "creates a saved question in the target collection"
+ (is (some? card))
+ (is (= "Venues by price" (:name card)))
+ (is (= :bar (:display card)))
+ (is (= (:id coll) (:collection_id card))))
+ (testing "emits an entity_saved data part pointing at the chart and destination"
+ (is (= "entity_saved" (:data-type part)))
+ (is (= "c-1" (get-in part [:data :chart_id])))
+ (is (= (:id card) (get-in part [:data :card_id])))
+ (is (= {:type "collection" :id (:id coll)}
+ (get-in part [:data :destination])))))))))
+
+(deftest save-rehydrated-chart-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {:name "Persisted charts"}]
+ (let [result (binding [shared/*memory-atom* (rehydrated-chart-memory)]
+ (save-entity/save-entity-tool
+ {:chart_id "c-1"
+ :name "Venues by price"
+ :description "Count of venues grouped by price."
+ :destination {:target_type "collection" :collection_id (:id coll)}}))]
+ (testing "saves a generated query after its enum values were stringified between turns"
+ (is (integer? (get-in result [:structured-output :card-id])))))))))
+
+(deftest save-stamps-card-origin-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}
+ :model/MetabotConversation {convo-id :id} {:user_id (mt/user->id :crowberto)}]
+ (let [memory (doto (chart-memory) (swap! assoc :conversation-id convo-id))
+ result (binding [shared/*memory-atom* memory]
+ (save-entity/save-entity-tool
+ {:chart_id "c-1"
+ :name "Venues by price"
+ :description "Count of venues grouped by price."
+ :destination {:target_type "collection" :collection_id (:id coll)}}))
+ card-id (get-in result [:structured-output :card-id])]
+ (testing "the card records which conversation + chart it was saved from"
+ (is (= {:metabot_conversation_id convo-id
+ :metabot_chart_id "c-1"}
+ (t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id]
+ :id card-id)))))))))
+
+(deftest save-without-conversation-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (testing "saving outside a conversation-backed run leaves the origin columns nil"
+ (let [result (save! {:target_type "collection" :collection_id nil})
+ card-id (get-in result [:structured-output :card-id])]
+ (is (= {:metabot_conversation_id nil :metabot_chart_id nil}
+ (t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id]
+ :id card-id))))))))
+
+(deftest save-to-root-collection-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (let [result (save! {:target_type "collection" :collection_id nil})
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (testing "an explicit null collection_id saves to the root collection"
+ (is (nil? (:collection_id card)))
+ (is (nil? (get-in result [:data-parts 0 :data :destination :id]))))))))
+
+(deftest save-to-personal-collection-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (let [result (save! {:target_type "collection"})
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (testing "omitting collection_id defaults to the user's personal collection"
+ (is (= (t2/select-one-fn :id :model/Collection :personal_owner_id (mt/user->id :crowberto))
+ (:collection_id card))))))))
+
+(deftest save-to-dashboard-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}
+ :model/Dashboard dash {:name "Ops" :collection_id (:id coll)}]
+ (let [result (save! {:target_type "dashboard" :dashboard_id (:id dash)})
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (testing "creates a dashboard question and places it on the dashboard"
+ (is (= (:id dash) (:dashboard_id card)))
+ (is (t2/exists? :model/DashboardCard :dashboard_id (:id dash) :card_id (:id card))))
+ (testing "the destination points at the dashboard"
+ (is (= {:type "dashboard" :id (:id dash)}
+ (get-in result [:data-parts 0 :data :destination])))))))))
+
+(deftest save-seeded-chart-display-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (testing "charts seeded from the viewing context carry no :visualization_settings, so the display falls back to :chart_config :display_type"
+ (let [query (venues-query)
+ memory (atom {:state {:queries {}
+ :charts {"c-2" {:chart_id "c-2"
+ :queries [query]
+ :visualization_settings nil
+ :chart_config {:display_type "line"}}}}
+ :context {}})
+ result (binding [shared/*memory-atom* memory]
+ (save-entity/save-entity-tool
+ {:chart_id "c-2"
+ :name "Seeded chart"
+ :description "Seeded from the viewing context."
+ :destination {:target_type "collection" :collection_id nil}}))
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (is (= :line (:display card))))))))
+
+(def ^:private document-ast
+ {:type "doc"
+ :content [{:type "paragraph" :content [{:type "text" :text "Intro"}]}
+ {:type "paragraph" :content [{:type "text" :text "Outro"}]}]})
+
+(defn- card-embed [card-id]
+ {:type "resizeNode"
+ :content [{:type "cardEmbed" :attrs {:id card-id}}]})
+
+(deftest save-to-document-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}
+ :model/Document doc {:name "Q3 report"
+ :collection_id (:id coll)
+ :document document-ast}]
+ (let [result (save! {:target_type "document" :document_id (:id doc)})
+ card (t2/select-one :model/Card :id (get-in result [:structured-output :card-id]))]
+ (testing "creates a document question inheriting the document's collection"
+ (is (= (:id doc) (:document_id card)))
+ (is (= (:id coll) (:collection_id card)))
+ (is (= "Venues by price" (:name card))))
+ (testing "omitting position appends a card embed at the end of the document"
+ (is (= (conj (:content document-ast) (card-embed (:id card)))
+ (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content]))))
+ (testing "the destination points at the document"
+ (is (= {:type "document" :id (:id doc)}
+ (get-in result [:data-parts 0 :data :destination])))))))))
+
+(deftest save-to-document-position-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Document doc {:name "Q3 report" :document document-ast}]
+ (let [result (save! {:target_type "document" :document_id (:id doc) :position 1})
+ card-id (get-in result [:structured-output :card-id])]
+ (testing "an explicit position inserts before the block at that index"
+ (is (= [(first (:content document-ast))
+ (card-embed card-id)
+ (second (:content document-ast))]
+ (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content])))))))))
+
+(deftest save-to-document-requires-id-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (testing "a missing document_id fails destination schema validation"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"document_id"
+ (save! {:target_type "document"}))))))
+
+(deftest unknown-chart-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (testing "a missing chart id returns an agent-facing error and creates nothing"
+ (let [result (binding [shared/*memory-atom* (chart-memory)]
+ (save-entity/save-entity-tool
+ {:chart_id "does-not-exist"
+ :name "x"
+ :description "y"
+ :destination {:target_type "collection" :collection_id nil}}))]
+ (is (nil? (:data-parts result)))
+ (is (re-find #"No generated chart found" (:output result)))))))
diff --git a/test/metabase/metabot/tools/search_test.clj b/test/metabase/metabot/tools/search_test.clj
index 7d5d2a800cb..55d301bf487 100644
--- a/test/metabase/metabot/tools/search_test.clj
+++ b/test/metabase/metabot/tools/search_test.clj
@@ -230,6 +230,7 @@
:name "Main Dashboard"
:description "Dashboard desc"
:verified false
+ :can_write false
:collection {:id 10 :name "Finance" :authority_level "official"}
:updated_at "2024-01-03"
:created_at "2024-01-03"}
@@ -238,12 +239,33 @@
:name "Main Dashboard"
:description "Dashboard desc"
:verified false
+ :can_write false
:official true
:collection {:id 10 :name "Finance" :authority_level "official"}
:updated_at "2024-01-03"
:created_at "2024-01-03"}]
(is (= expected (#'search/postprocess-search-result result))))))
+(deftest ^:parallel postprocess-document-search-result-test
+ (testing "document result postprocessing"
+ (let [result {:model "document"
+ :id 8
+ :name "Quarterly plan"
+ :can_write false
+ :collection {:id 10 :name "Finance" :authority_level "official"}
+ :updated_at "2024-01-03"
+ :created_at "2024-01-02"}
+ expected {:id 8
+ :type "document"
+ :name "Quarterly plan"
+ :description nil
+ :can_write false
+ :official true
+ :collection {:id 10 :name "Finance" :authority_level "official"}
+ :updated_at "2024-01-03"
+ :created_at "2024-01-02"}]
+ (is (= expected (#'search/postprocess-search-result result))))))
+
(deftest ^:parallel postprocess-search-result-test-5
(testing "question (card) result postprocessing with moderated_status"
(let [result {:model "card"
@@ -349,13 +371,28 @@
{:data []})]
(search/sql-search-tool {:keyword_queries ["x"] :database_id 1}))
(is (= #{"table" "dataset"} @captured))))
+ (testing "general search includes documents in its default entity types"
+ (let [captured (atom nil)]
+ (mt/with-dynamic-fn-redefs [search-core/search (fn [context]
+ (reset! captured (:models context))
+ {:data []})]
+ (search/search-tool {:keyword_queries ["x"]}))
+ (is (contains? @captured "document"))))
(testing "agent-supplied entity_types narrow the default allowed set"
(let [captured (atom nil)]
(mt/with-dynamic-fn-redefs [search-core/search (fn [context]
(reset! captured (:models context))
{:data []})]
(search/nlq-search-tool {:keyword_queries ["x"] :entity_types ["metric"]}))
- (is (= #{"metric"} @captured))))))))
+ (is (= #{"metric"} @captured))))
+ (testing "NLQ search accepts document and dashboard destination types"
+ (let [captured (atom nil)]
+ (mt/with-dynamic-fn-redefs [search-core/search (fn [context]
+ (reset! captured (:models context))
+ {:data []})]
+ (search/nlq-search-tool {:keyword_queries ["plan"]
+ :entity_types ["document" "dashboard"]}))
+ (is (= #{"document" "dashboard"} @captured))))))))
(deftest tool-limit-test
(testing "tool variants apply the :limit arg with default 10 and cap 50"
@@ -401,6 +438,30 @@
(map :name)
(set)))))))))))
+(deftest document-search-test
+ (testing "search can discover documents by name"
+ (mt/with-test-user :crowberto
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Document {document-id :id}
+ {:name "Quarterly planning sh1b0le#doc"}]
+ (let [result (->> (search/search {:term-queries ["sh1b0le#doc"]
+ :entity-types ["document"]})
+ (filter #(= document-id (:id %)))
+ first)]
+ (is (= "document" (:type result)))
+ (is (= "Quarterly planning sh1b0le#doc" (:name result)))))))))
+
+(deftest validate-and-enrich-documents-test
+ (testing "stale document search hits are removed using the live model"
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Document {document-id :id} {:name "Existing document"}]
+ (let [results [{:id document-id :type "document" :name "Existing document"}
+ {:id Integer/MAX_VALUE :type "document" :name "Deleted document"}
+ {:id 1 :type "dashboard" :name "Unrelated dashboard"}]]
+ (is (= [{:id document-id :type "document" :name "Existing document" :can_write true}
+ {:id 1 :type "dashboard" :name "Unrelated dashboard"}]
+ (#'search/validate-and-enrich-documents results))))))))
+
(deftest enrich-with-collection-descriptions-test
(mt/with-premium-features #{:content-verification}
(mt/with-test-user :crowberto
diff --git a/test/metabase/metabot/tools/shared/llm_shape_test.clj b/test/metabase/metabot/tools/shared/llm_shape_test.clj
index 087b1448191..40cd3efd4a8 100644
--- a/test/metabase/metabot/tools/shared/llm_shape_test.clj
+++ b/test/metabase/metabot/tools/shared/llm_shape_test.clj
@@ -672,6 +672,25 @@
(is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :card :name "c"}) "<metabase_question"))
(is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :dataset :name "d"}) "<metabase-model"))))
+(deftest ^:parallel search-result-write-permission-test
+ (testing "renders false as an explicit destination permission"
+ (is (str/includes? (llm-shape/search-result->xml
+ {:id 5 :type :dashboard :name "Read only" :can_write false})
+ "can_write=\"false\"")))
+ (testing "omits write permission for search entities where it is not supplied"
+ (is (not (str/includes? (llm-shape/search-result->xml
+ {:id 1 :type :table :name "Orders"})
+ "can_write=")))))
+
+(deftest ^:parallel list-item-write-permission-test
+ (is (str/includes? (llm-shape/metabot-list->xml
+ {:list-type :dashboards
+ :items [{:type "dashboard" :id 5 :name "Read only" :can_write false}]
+ :total 1
+ :page 1
+ :pages 1})
+ "can_write=\"false\"")))
+
(deftest ^:parallel search-results->xml-test
(testing "formats multiple search results"
(let [results [{:id 1 :type :metric :name "Metric 1"}
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index 0ca3b94e910..b159ae17736 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -149,16 +149,20 @@
:stages [{:lib/type "mbql.stage/mbql"
:source-table ["Sample" "PUBLIC" "ORDERS"]
:aggregation [["count" {}]]}]}
- result (agent-tools/construct-notebook-query-tool
- {:reasoning "check seats"
- :query query-input
- :title "Seat check"
- :visualization {:chart_type "table"}})]
+ result (binding [shared/*profile-id* :nlq]
+ (agent-tools/construct-notebook-query-tool
+ {:reasoning "check seats"
+ :query query-input
+ :title "Seat check"
+ :description "Total order count."
+ :visualization {:chart_type "table"}}))]
(is (= query-input @query-captured))
(is (= "c-1" (get-in result [:structured-output :chart-id])))
(is (= "q-1" (get-in result [:structured-output :query-id])))
(is (= :table (get @chart-called :chart-type)))
- (is (seq (:data-parts result))))))))
+ (is (seq (:data-parts result)))
+ (is (= "Total order count."
+ (get-in result [:data-parts 0 :data :description]))))))))
(deftest state-dependent-tools-test
(testing "state-dependent-tools set contains expected tools"
@@ -179,7 +183,8 @@
(is (contains? @#'agent-tools/state-dependent-tools "document_construct_model_chart"))
(is (contains? @#'agent-tools/state-dependent-tools "create_alert"))
(is (contains? @#'agent-tools/state-dependent-tools "create_dashboard_subscription"))
- (is (contains? @#'agent-tools/state-dependent-tools "static_viz"))))
+ (is (contains? @#'agent-tools/state-dependent-tools "static_viz"))
+ (is (contains? @#'agent-tools/state-dependent-tools "read_resource"))))
(deftest wrap-tools-with-state-test
(testing "wraps state-dependent tools with state injection"
diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.clj
index 8a48761a20c..ab54ee7d91b 100644
--- a/test/metabase/queries/models/card_test.clj
+++ b/test/metabase/queries/models/card_test.clj
@@ -1761,3 +1761,27 @@
(is (contains? (stale-ids) public-id)))
(tu/with-temporary-setting-values [enable-public-sharing true]
(is (not (contains? (stale-ids) public-id))))))))))
+(deftest editing-clears-metabot-origin-test
+ (testing "editing a card's content severs its link back to the Metabot chart it came from"
+ (doseq [[change-desc changes] {"query" {:dataset_query (mt/mbql-query checkins)}
+ "display" {:display :line}
+ "viz settings" {:visualization_settings {"graph.goal_value" 10}}}]
+ (testing (str "changing the " change-desc " clears the link")
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id (mt/user->id :rasta)}
+ :model/Card {card-id :id} {:dataset_query (mt/mbql-query venues)
+ :metabot_conversation_id convo-id
+ :metabot_chart_id "chart-1"}]
+ (t2/update! :model/Card card-id changes)
+ (is (= {:metabot_conversation_id nil :metabot_chart_id nil}
+ (t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id]
+ :id card-id)))))))
+ (testing "renaming or moving a card keeps the link"
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id (mt/user->id :rasta)}
+ :model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:dataset_query (mt/mbql-query venues)
+ :metabot_conversation_id convo-id
+ :metabot_chart_id "chart-1"}]
+ (t2/update! :model/Card card-id {:name "Renamed" :collection_id coll-id})
+ (is (= {:metabot_conversation_id convo-id :metabot_chart_id "chart-1"}
+ (t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id]
+ :id card-id))))))
diff --git a/test/metabase/revisions/impl/card_test.clj b/test/metabase/revisions/impl/card_test.clj
index 012f2670cc2..5673bad2d05 100644
--- a/test/metabase/revisions/impl/card_test.clj
+++ b/test/metabase/revisions/impl/card_test.clj
@@ -188,6 +188,13 @@
before
changes)))))))))
+(deftest card-revision-excludes-metabot-origin-test
+ (testing "the Metabot origin columns are not captured in revisions, so reverting can never write back a stale conversation id"
+ (mt/with-temp [:model/Card card {:metabot_chart_id "chart-1"}]
+ (let [serialized (revision/serialize-instance :model/Card (:id card) card)]
+ (is (not (contains? serialized :metabot_chart_id)))
+ (is (not (contains? serialized :metabot_conversation_id)))))))
+
(deftest load-old-revision-without-card-schema-test
(testing "Old revisions without :card_schema should be loadable (regression test for #61555)"
(mt/with-temp [:model/Card {card-id :id} {:name "Test Card"