The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: remove navigate_to (#75646)
Maksym Yakubych8ff4bd113d08
diff --git a/e2e/support/helpers/e2e-metabot-helpers.ts b/e2e/support/helpers/e2e-metabot-helpers.tsindex cc926fe84b3..3fd5976c521 100644--- a/e2e/support/helpers/e2e-metabot-helpers.ts+++ b/e2e/support/helpers/e2e-metabot-helpers.ts@@ -111,7 +111,7 @@ const lifecycleFinishFor = (events: SSEEvent[]): (SSEEvent | "[DONE]")[] => {* Arguments are flattened one level, so parts compose without spreading:* createMetabotSSEBody(* metabotTextPart("Here is the link"),- * metabotDataPart("navigate_to", path),+ * metabotDataPart("generated_entity", card),* )** Each event is emitted as a `data: {JSON}\n\n` chunk, wrapped in the backenddiff --git a/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsxindex 74a2689e7b3..13488d32279 100644--- a/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx@@ -20,10 +20,17 @@ const query = {breakout: [["field", ORDERS.PRODUCT_ID, null]],limit: 2,};+const generatedCard = {+ type: "card",+ id: "card-1",+ title: "Question",+ query: { id: "query-1", query: { database: 1, type: "query", query } },+ display: "table",+};const adHocQuestionPath = `/question#${btoa(JSON.stringify({- dataset_query: { database: 1, type: "query", query },- display: "table",+ dataset_query: generatedCard.query.query,+ display: generatedCard.display,displayIsLocked: true,visualization_settings: {},}),@@ -32,25 +39,29 @@ const adHocQuestionPath = `/question#${btoa(const metabotResponse = H.createMetabotSSEBody(H.metabotTextPart(`Here is the [question link](${adHocQuestionPath})`),);-const metabotResponseWithNavigateTo = H.createMetabotSSEBody(+// Metabot surfaces a chart to the SDK via a `generated_entity` card data part.+const metabotResponseWithChart = H.createMetabotSSEBody(H.metabotTextPart(`Here is the [question link](${adHocQuestionPath})`),- H.metabotDataPart("navigate_to", adHocQuestionPath),-);--const metabotRetryResponse = H.createMetabotSSEBody(- H.metabotTextPart(`Retry: Here is the [question link](${adHocQuestionPath})`),+ H.metabotDataPart("generated_entity", generatedCard),);-// navigate_to response captured from a real embedding Metabot session-// (database id swapped from 2 to 1 to match this env's Sample Database).const metabotResponseWithSqlEditor = H.createMetabotSSEBody(H.metabotTextPart(- "I'll direct you to the SQL editor for the Sample Database so you can write a query for the most popular products!",- ),- H.metabotDataPart(- "navigate_to",- "/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJ0eXBlIjoibmF0aXZlIiwibmF0aXZlIjp7InF1ZXJ5IjoiIn19fQ==",+ "I'll write a SQL query for the most popular products so you can tweak it in the SQL editor!",),+ H.metabotDataPart("generated_entity", {+ type: "card",+ id: "card-sql",+ title: "SQL query",+ query: {+ id: "query-sql",+ query: { database: 1, type: "native", native: { query: "" } },+ },+ }),+);++const metabotRetryResponse = H.createMetabotSSEBody(+ H.metabotTextPart(`Retry: Here is the [question link](${adHocQuestionPath})`),);describe("scenarios > embedding-sdk > metabot-question", () => {@@ -89,7 +100,7 @@ describe("scenarios > embedding-sdk > metabot-question", () => {mockAuthProviderAndJwtSignIn();};- it("should show the SQL editor when Metabot navigates to the SQL editor page", () => {+ it("should show the SQL editor when Metabot generates a native query", () => {setup(metabotResponseWithSqlEditor);mountSdkContent(<MetabotQuestion />);@@ -101,7 +112,7 @@ describe("scenarios > embedding-sdk > metabot-question", () => {});it("should show drill-through results after drilling from a metabot question", () => {- setup(metabotResponseWithNavigateTo);+ setup(metabotResponseWithChart);mountSdkContent(<MetabotQuestion />);@@ -125,7 +136,7 @@ describe("scenarios > embedding-sdk > metabot-question", () => {});it("should automatically show the ad-hoc question for the last agent message containing ad-hoc question link", () => {- setup(metabotResponseWithNavigateTo);+ setup(metabotResponseWithChart);mountSdkContent(<MetabotQuestion />);@@ -139,7 +150,7 @@ describe("scenarios > embedding-sdk > metabot-question", () => {it("should allow saving a question", () => {cy.intercept("POST", "/api/card").as("postCard");- setup(metabotResponseWithNavigateTo);+ setup(metabotResponseWithChart);cy.get("@collectionId").then((collectionId) => {mountSdkContent(diff --git a/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsxindex c1082932ee7..f65a7734922 100644--- a/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/use-metabot.cy.spec.tsx@@ -11,50 +11,57 @@ import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;-const buildAdHocPath = (query: Record<string, unknown>) =>- `/question#${btoa(- JSON.stringify({- dataset_query: { database: SAMPLE_DB_ID, type: "query", query },- display: "table",- displayIsLocked: true,- visualization_settings: {},- }),- )}`;--const adHocQuestionPathOrders = buildAdHocPath({+const ordersQuery = {"source-table": ORDERS_ID,aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],breakout: [["field", ORDERS.PRODUCT_ID, null]],limit: 2,-});+};-const adHocQuestionPathProducts = buildAdHocPath({+const productsQuery = {"source-table": PRODUCTS_ID,aggregation: [["count"]],breakout: [["field", PRODUCTS.CATEGORY, null]],limit: 2,-});+};-// A native card with no numeric slug — the shape Metabot emits when it opens-// the SQL editor. `CurrentChart drills` must render the editor, not just the-// result window. Regression coverage for EMB-2042.-const nativeQuestionPath = `/question#${btoa(- JSON.stringify({- dataset_query: {- database: SAMPLE_DB_ID,- type: "native",- native: { query: "" },- },- display: "table",- visualization_settings: {},- }),-)}`;--const buildNavigateToResponse = (path: string) =>- H.createMetabotSSEBody(- H.metabotTextPart(`Here is the [question link](${path})`),- H.metabotDataPart("navigate_to", path),- );+// Metabot surfaces a chart to the SDK via a `generated_entity` card data part.+const buildGeneratedCardResponse = (query: Record<string, unknown>) =>+ H.createMetabotSSEBody([+ ...H.metabotTextPart("Here are the results"),+ H.metabotDataPart("generated_entity", {+ type: "card",+ id: "card-1",+ title: "Question",+ query: {+ id: "query-1",+ query: { database: SAMPLE_DB_ID, type: "query", query },+ },+ display: "table",+ }),+ ]);++// A native card produces a path with no numeric slug — the shape Metabot emits+// when it opens the SQL editor. `CurrentChart drills` must render the editor,+// not just the result window. Regression coverage for EMB-2042.+const buildNativeCardResponse = () =>+ H.createMetabotSSEBody([+ ...H.metabotTextPart("Opening the SQL editor"),+ H.metabotDataPart("generated_entity", {+ type: "card",+ id: "card-native",+ title: "Native question",+ query: {+ id: "query-native",+ query: {+ database: SAMPLE_DB_ID,+ type: "native",+ native: { query: "" },+ },+ },+ display: "table",+ }),+ ]);type MetabotConsumerProps = {prompts: string[];@@ -111,10 +118,10 @@ describe("scenarios > embedding-sdk > use-metabot hook", () => {mockAuthProviderAndJwtSignIn();});- it("exposes Metabot and renders CurrentChart after navigate_to", () => {+ it("exposes Metabot and renders CurrentChart after a chart is generated", () => {H.mockMetabotResponse({statusCode: 200,- body: buildNavigateToResponse(adHocQuestionPathOrders),+ body: buildGeneratedCardResponse(ordersQuery),});mountSdkContent(<MetabotConsumer prompts={["Show me orders"]} />);@@ -136,10 +143,10 @@ describe("scenarios > embedding-sdk > use-metabot hook", () => {});});- it("opens the SQL editor when Metabot navigates to a native question (EMB-2042)", () => {+ it("opens the SQL editor when Metabot generates a native question (EMB-2042)", () => {H.mockMetabotResponse({statusCode: 200,- body: buildNavigateToResponse(nativeQuestionPath),+ body: buildNativeCardResponse(),});mountSdkContent(@@ -163,15 +170,15 @@ describe("scenarios > embedding-sdk > use-metabot hook", () => {});});- it("swaps CurrentChart when a second navigate_to reaction arrives with a new path", () => {+ it("swaps CurrentChart when a second chart arrives with a new query", () => {cy.intercept("POST", "/api/metabot/agent-streaming", (request) => {- const path =+ const query =request.body.message === "Show me products"- ? adHocQuestionPathProducts- : adHocQuestionPathOrders;+ ? productsQuery+ : ordersQuery;request.reply({statusCode: 200,- body: buildNavigateToResponse(path),+ body: buildGeneratedCardResponse(query),headers: { "content-type": "text/event-stream; charset=utf-8" },});}).as("metabotAgent");diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.tsindex b83ab193d49..78bfaeb2d6b 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts@@ -528,15 +528,14 @@ describe("scenarios > embedding > sdk iframe embedding > custom elements api", (}),)}`;- const metabotResponseWithNavigateTo = H.createMetabotSSEBody(+ const metabotResponse = H.createMetabotSSEBody(H.metabotTextPart(`Here is the [question link](${adHocQuestionPath})`),- H.metabotDataPart("navigate_to", adHocQuestionPath),);it("should allow to save a new question", () => {H.mockMetabotResponse({statusCode: 200,- body: metabotResponseWithNavigateTo,+ body: metabotResponse,});cy.intercept("POST", "http://localhost:4000/api/card").as("postCard");diff --git a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.tsindex 462cff0a7bd..3f24a2488ec 100644--- a/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts+++ b/e2e/test/scenarios/metabot/metabot-query-builder.cy.spec.ts@@ -91,26 +91,6 @@ describe("Metabot Query Builder", () => {cy.url().should("include", "/metabot/conversation/");});- it("should navigate to a question when the agent returns a navigate_to", () => {- cy.visit("/");-- // go to new button and click "AI exploration"- H.newButton("AI exploration").click();- cy.url().should("include", "/question/ask");- cy.findByTestId("metabot-chat").should("not.exist");-- const questionHash = H.adhocQuestionHash(allOrdersQuestion);- H.mockMetabotResponse({- body: mockNavigateToResponse(`/question#${questionHash}`),- delay: 100,- });- H.sendMetabotMessage("Show me all orders");-- // when we receive a navigate_to, we should be taken to a question- cy.url().should("include", "/question#");- cy.findByTestId("qb-header").should("contain", "Orders");- });-it("should support clicking suggested prompts", () => {// mock suggested promptscy.intercept("GET", "/api/metabot/metabot/*/prompt-suggestions*", {@@ -122,16 +102,15 @@ describe("Metabot Query Builder", () => {H.metabotChatInput().should("be.visible");// click suggested prompt- const questionHash = H.adhocQuestionHash(allOrdersQuestion);H.mockMetabotResponse({- body: mockNavigateToResponse(`/question#${questionHash}`),+ body: mockGeneratedEntityResponse(allOrdersQuestion.dataset_query),});cy.get("main").findByText("Show me all orders").click();- // should be taken to a question+ // the chart renders inline rather than in the query buildercy.wait("@metabotAgent");- cy.url().should("include", "/question#");- cy.findByTestId("qb-header").should("contain", "Orders");+ cy.findByTestId("metabot-inline-chart").should("be.visible");+ cy.url().should("include", "/metabot/conversation/");});it("should handle errors", () => {@@ -151,9 +130,6 @@ describe("Metabot Query Builder", () => {});// Response helpers-const mockNavigateToResponse = (path: string) =>- H.createMetabotSSEBody(H.metabotDataPart("navigate_to", path));-const mockTextOnlyResponse = (text: string) =>H.createMetabotSSEBody(H.metabotTextPart(text));diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsxindex 04e01db466d..c1f9f2b59e8 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx@@ -10,7 +10,9 @@ import { Stack } from "metabase/ui";import S from "./MetabotQuestion.module.css";const isQuestionNavigationMessage = (message: MetabotChatMessage) =>- message.type === "data_part" && message.part.type === "data-navigate_to";+ message.type === "data_part" &&+ message.part.type === "data-generated_entity" &&+ message.part.data.type === "card";const AGENT_ID = "omnibot";diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsxindex f7750eb05a2..f871910b182 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx@@ -19,7 +19,7 @@ const makeVisibleState = (messages: MetabotChatMessage[]) =>);describe("MetabotChatHistory", () => {- it("should not render navigate_to data_part messages in the message list", () => {+ it("should not render generated_entity card data_part messages in the message list", () => {setup({ui: <MetabotChatHistory />,metabotInitialState: makeVisibleState([@@ -27,7 +27,23 @@ describe("MetabotChatHistory", () => {id: "1",role: "agent",type: "data_part",- part: { type: "data-navigate_to", data: "/question#abc" },+ part: {+ type: "data-generated_entity",+ data: {+ type: "card",+ id: "card-1",+ title: "Orders",+ query: {+ id: "q-1",+ query: {+ database: 1,+ type: "query",+ query: { "source-table": 1 },+ },+ },+ display: "table",+ },+ },},]),});diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.stories.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.stories.tsxindex 70fdeb83493..99d549aacd6 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.stories.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.stories.tsx@@ -8,6 +8,7 @@ import { MetabaseProvider } from "embedding-sdk-package/components/public/Metabaimport { getHostedBundleStoryDecorator } from "embedding-sdk-package/test/getHostedBundleStoryDecorator";import {MOCK_AD_HOC_QUESTION_ID,+ mockGeneratedCardChunk,mockStreamResponse,} from "embedding-sdk-shared/test/mocks/mock-metabot-response";import { Flex, Stack } from "metabase/ui";@@ -53,7 +54,7 @@ export const Centered = {},};-export const RedirectReaction = {+export const GeneratedChart = {render: Template,parameters: {msw: {@@ -66,7 +67,7 @@ export const RedirectReaction = {delta: `Here is the [question link](${MOCK_AD_HOC_QUESTION_ID})`,},{ type: "text-end", id: "t1" },- { type: "data-navigate_to", data: MOCK_AD_HOC_QUESTION_ID },+ mockGeneratedCardChunk(),{ type: "finish", finishReason: "stop" },]),],diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsxindex 7b1835d5711..0ffbf9903ad 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx@@ -16,9 +16,10 @@ import type {import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";import { useMetabotAgent } from "metabase/metabot/hooks";import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";-import { getFinalNavigateToMessageIdsPerTurn } from "metabase/metabot/state";+import { getFinalChartMessageIdsPerTurn } from "metabase/metabot/state";import type { MetabotChatMessage } from "metabase/metabot/state/types";import { useSelector } from "metabase/redux";+import * as Urls from "metabase/urls";/*** Public-facing hook for interacting with Metabot in the SDK.@@ -80,18 +81,18 @@ export const useMetabot = (): UseMetabotResult => {agentCreateNewConversation();}, [agentCreateNewConversation]);- // keep only the last navigate_to per turn — agent may emit several mid-stream- const finalNavigateToIds = useSelector((state) =>- getFinalNavigateToMessageIdsPerTurn(state, "omnibot"),+ // keep only the last chart per turn — agent may emit several mid-stream+ const finalChartIds = useSelector((state) =>+ getFinalChartMessageIdsPerTurn(state, "omnibot"),);const messages = useMemo<MetabotMessage[]>(() =>agent.messages- .filter((message) => isPublicMessage(message, finalNavigateToIds))+ .filter((message) => isPublicMessage(message, finalChartIds)).map((message) =>mapMessage(message, chartComponentsCache.current, authConfig),),- [agent.messages, finalNavigateToIds, authConfig],+ [agent.messages, finalChartIds, authConfig],);const errorMessages = useMemo<SdkMetabotErrorMessage[]>(@@ -160,17 +161,18 @@ function getCachedChartComponent(type PublicChatMessage =| Extract<MetabotChatMessage, { type: "text" }>| (Extract<MetabotChatMessage, { type: "data_part" }> & {- part: { type: "data-navigate_to" };+ part: { type: "data-generated_entity"; data: { type: "card" } };});const isPublicMessage = (message: MetabotChatMessage,- finalNavigateToIds: Set<string>,+ finalChartIds: Set<string>,): message is PublicChatMessage =>message.type === "text" ||(message.type === "data_part" &&- message.part.type === "data-navigate_to" &&- finalNavigateToIds.has(message.id));+ message.part.type === "data-generated_entity" &&+ message.part.data.type === "card" &&+ finalChartIds.has(message.id));const mapMessage = (message: PublicChatMessage,@@ -189,9 +191,13 @@ const mapMessage = (({ id, role: "agent", type: "text", message }) as const,).with(- { role: "agent", type: "data_part", part: { type: "data-navigate_to" } },+ {+ role: "agent",+ type: "data_part",+ part: { type: "data-generated_entity", data: { type: "card" } },+ },({ id, part }) => {- const questionPath = part.data;+ const questionPath = Urls.generatedCard(part.data);const Chart = authConfig? getCachedChartComponent(questionPath, cache, authConfig): FallbackChartComponent;diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsxindex 3ffdf818be7..4382c874f19 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx@@ -4,6 +4,7 @@ import { useState } from "react";import { act, screen, waitFor } from "__support__/ui";import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";+import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";import { metabotActions } from "metabase/metabot/state";import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";import {@@ -12,9 +13,42 @@ import {setup,whoIsYourFavoriteResponse,} from "metabase/metabot/tests/utils";+import * as Urls from "metabase/urls";import { useMetabot } from "./use-metabot";+const makeCard = (id: string, sourceTable = 1): GeneratedCard => ({+ type: "card",+ id,+ title: "Chart",+ query: {+ id: `q-${id}`,+ query: {+ database: 1,+ type: "query",+ query: { "source-table": sourceTable },+ },+ },+ display: "table",+});++const cardMessage = (id: string, sourceTable = 1) =>+ // `addAgentMessage` types its payload with a non-distributive `Omit` that+ // collapses the message union to common keys, so the branch-specific `part`+ // field fails excess-property checks (see the fuller note in the+ // "maps agent.text passthrough" test below).+ ({+ agentId: "omnibot",+ type: "data_part",+ part: {+ type: "data-generated_entity",+ data: makeCard(id, sourceTable),+ },+ }) as any;++const cardPath = (id: string, sourceTable = 1) =>+ Urls.generatedCard(makeCard(id, sourceTable));+/*** Covers `useMetabot()` non-passthrough wiring: `CurrentChart`,* `messages[n].Chart`, `submitMessage`, `messages` mapping. Chart mocks@@ -59,7 +93,7 @@ describe("useMetabot", () => {return CurrentChart ? <CurrentChart drills={drills} /> : null;};- it("renders nothing before navigate_to fires", () => {+ it("renders nothing before a chart path is set", () => {setup({ ui: <TestCurrentChart /> });expect(@@ -67,7 +101,7 @@ describe("useMetabot", () => {).not.toBeInTheDocument();});- it("renders a chart after navigate_to fires", async () => {+ it("renders a chart after a chart path is set", async () => {const { store } = setup({ ui: <TestCurrentChart /> });expect(@@ -151,7 +185,7 @@ describe("useMetabot", () => {expect(identityChanges).toBe(0);});- it("updates when a second navigate_to fires", async () => {+ it("updates when a second chart path is set", async () => {const { store } = setup({ ui: <TestCurrentChart /> });act(() => {@@ -242,21 +276,11 @@ describe("useMetabot", () => {});});- it("projects a navigate_to data_part into a chart message with questionPath", async () => {+ it("projects a generated_entity card data_part into a chart message with questionPath", async () => {const { store } = setup({ ui: <TestMessages /> });act(() => {- store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: {- type: "data-navigate_to",- data: "/question#base64",- },- } as any),- );+ store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));});const [message] = await readMessages();@@ -268,7 +292,7 @@ describe("useMetabot", () => {id: expect.any(String),role: "agent",type: "chart",- questionPath: "/question#base64",+ questionPath: cardPath("card-1"),});});@@ -340,7 +364,7 @@ describe("useMetabot", () => {});});- it("keeps only the last navigate_to per turn, across multiple turns", async () => {+ it("keeps only the last chart per turn, across multiple turns", async () => {const { store } = setup({ ui: <TestMessages /> });act(() => {@@ -353,20 +377,10 @@ describe("useMetabot", () => {}),);store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: { type: "data-navigate_to", data: "/question#1a" },- } as any),+ metabotActions.addAgentMessage(cardMessage("card-1A", 1)),);store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: { type: "data-navigate_to", data: "/question#1b" },- } as any),+ metabotActions.addAgentMessage(cardMessage("card-1B", 2)),);store.dispatch(metabotActions.addUserMessage({@@ -377,20 +391,15 @@ describe("useMetabot", () => {}),);store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: { type: "data-navigate_to", data: "/question#2" },- } as any),+ metabotActions.addAgentMessage(cardMessage("card-2", 3)),);});const messages = await readMessages();const charts = messages.filter((m) => m.type === "chart");expect(charts).toHaveLength(2);- expect(charts[0].questionPath).toBe("/question#1b");- expect(charts[1].questionPath).toBe("/question#2");+ expect(charts[0].questionPath).toBe(cardPath("card-1B", 2));+ expect(charts[1].questionPath).toBe(cardPath("card-2", 3));});});@@ -480,17 +489,7 @@ describe("useMetabot", () => {const { store } = setup({ ui: <TestChart /> });act(() => {- store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: {- type: "data-navigate_to",- data: "/question#base64",- },- } as any),- );+ store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));});expect(await screen.findByTestId("mock-static-question")).toBeVisible();@@ -500,17 +499,7 @@ describe("useMetabot", () => {const { store } = setup({ ui: <TestChart drills /> });act(() => {- store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: {- type: "data-navigate_to",- data: "/question#base64",- },- } as any),- );+ store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));});expect(@@ -544,12 +533,7 @@ describe("useMetabot", () => {}),);store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: { type: "data-navigate_to", data: "/question#abc" },- } as any),+ metabotActions.addAgentMessage(cardMessage("card-abc", 1)),);});@@ -559,7 +543,7 @@ describe("useMetabot", () => {const capturedChart = firstChart;expect(capturedChart).not.toBeNull();- // Open a second turn so both navigate_tos survive the per-turn filter.+ // Open a second turn so both charts survive the per-turn filter.act(() => {store.dispatch(metabotActions.addUserMessage({@@ -570,12 +554,7 @@ describe("useMetabot", () => {}),);store.dispatch(- // Unjustified type cast. FIXME- metabotActions.addAgentMessage({- agentId: "omnibot",- type: "data_part",- part: { type: "data-navigate_to", data: "/question#xyz" },- } as any),+ metabotActions.addAgentMessage(cardMessage("card-xyz", 2)),);});diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsxindex 3a2fd770bba..dfbbd1bb2e9 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabotQuestion/MetabotQuestion.stories.tsx@@ -2,6 +2,7 @@ import { getStorybookSdkAuthConfigForUser } from "embedding-sdk-bundle/test/Commimport { getHostedBundleStoryDecorator } from "embedding-sdk-package/test/getHostedBundleStoryDecorator";import {MOCK_AD_HOC_QUESTION_ID,+ mockGeneratedCardChunk,mockStreamResponse,} from "embedding-sdk-shared/test/mocks/mock-metabot-response";@@ -25,7 +26,7 @@ export default {delta: `Here is the [question link](${MOCK_AD_HOC_QUESTION_ID})`,},{ type: "text-end", id: "t1" },- { type: "data-navigate_to", data: MOCK_AD_HOC_QUESTION_ID },+ mockGeneratedCardChunk(),{ type: "finish", finishReason: "stop" },]),],diff --git a/frontend/src/embedding-sdk-bundle/types/metabot.ts b/frontend/src/embedding-sdk-bundle/types/metabot.tsindex b05a092b35b..e611c168299 100644--- a/frontend/src/embedding-sdk-bundle/types/metabot.ts+++ b/frontend/src/embedding-sdk-bundle/types/metabot.ts@@ -32,13 +32,13 @@ export type MetabotAgentChartMessage = {};// Internal variants intentionally omitted. `use-metabot.tsx` only exposes-// `type === "text"` messages `:+// `type === "text"` messages and `generated_entity` chart cards:// - `tool_call` messages: debug-only, gated on metabot's `debugMode`.// - `action` user messages: produced only when replaying historical audit conversations,// never via the SDK input path.-// - `data_part` messages other than `navigate_to` (`code_edit`, `transform_suggestion`,-// `todo_list`, `adhoc_viz`, `static_viz`, `state`): in-app surfaces (Transform editor,-// codegen profiles) the SDK does not render.+// - `data_part` messages other than `generated_entity` cards (`code_edit`,+// `transform_suggestion`, `todo_list`, `adhoc_viz`, `static_viz`, `state`): in-app+// surfaces (Transform editor, codegen profiles) the SDK does not render.export type MetabotAgentMessage =| MetabotAgentTextMessage| MetabotAgentChartMessage;@@ -90,7 +90,7 @@ export type UseMetabotResult = {isProcessing: boolean;/**- * A pre-wired component bound to the latest `navigate_to` path.+ * A pre-wired component bound to the latest chart the agent produced.* `null` until the agent sends a chart — lets consumers detect presence* and render a placeholder or swap panel content only when set.*diff --git a/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.ts b/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.tsindex 784fc4bc96c..d5585f1fe58 100644--- a/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.ts+++ b/frontend/src/embedding-sdk-shared/test/mocks/mock-metabot-response.ts@@ -3,6 +3,29 @@ import { http } from "msw";export const MOCK_AD_HOC_QUESTION_ID ="/question#eyJkYXRhc2V0X3F1ZXJ5IjogeyJkYXRhYmFzZSI6IDEsICJ0eXBlIjogInF1ZXJ5IiwgInF1ZXJ5IjogeyJzb3VyY2UtdGFibGUiOiAiY2FyZF9fMSJ9fSwgImRpc3BsYXkiOiAidGFibGUiLCAiZGlzcGxheUlzTG9ja2VkIjogdHJ1ZSwgInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOiB7fX0=";+export const MOCK_AD_HOC_DATASET_QUERY = {+ database: 1,+ type: "query",+ query: { "source-table": "card__1" },+};++export const mockGeneratedCardChunk = (+ datasetQuery: unknown = MOCK_AD_HOC_DATASET_QUERY,+ {+ title = "Question",+ display = "table",+ }: { title?: string; display?: string } = {},+) => ({+ type: "data-generated_entity",+ data: {+ type: "card",+ id: "card-1",+ title,+ query: { id: "query-1", query: datasetQuery },+ display,+ },+});+export const mockStreamResponse = (events: object[]) => {return http.post("*/api/metabot/agent-streaming", () => {const encoder = new TextEncoder();diff --git a/frontend/src/metabase/api/ai-streaming/schemas.ts b/frontend/src/metabase/api/ai-streaming/schemas.tsindex 3390277af94..a6f3867607e 100644--- a/frontend/src/metabase/api/ai-streaming/schemas.ts+++ b/frontend/src/metabase/api/ai-streaming/schemas.ts@@ -71,7 +71,14 @@ export type GeneratedCard = {display?: CardDisplayType;};-export type GeneratedEntity = GeneratedCard;+export type GeneratedDashboard = {+ type: "dashboard";+ id?: number;+ title: string;+ url: string;+};++export type GeneratedEntity = GeneratedCard | GeneratedDashboard;export type SavedEntityDestination =| { type: "collection"; id: number | null }diff --git a/frontend/src/metabase/common/utils/card.ts b/frontend/src/metabase/common/utils/card.tsindex 136e3d7c01b..17c70d23971 100644--- a/frontend/src/metabase/common/utils/card.ts+++ b/frontend/src/metabase/common/utils/card.ts@@ -109,11 +109,11 @@ export function deserializeCardFromUrl(serialized: string): Card {}/**- * Converts a Metabot `navigate_to` path like `/question#<base64>` into a+ * Converts a Metabot question path like `/question#<base64>` into a* Card suitable for `deserializedCard`.*- * Sole producer is Metabot's `navigate_to` stream part, which always emits- * `/question#<base64>`. Intentionally not guarded against other shapes.+ * Sole producer is Metabot's `generated_entity` card stream part, whose path+ * is always `/question#<base64>`. Intentionally not guarded against other shapes.*/export function deserializeCardFromQuery(query: string): Card {const base64 = query.replace(/^\/question#/, "");diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsxindex 1492eed5998..b900d866681 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx@@ -31,12 +31,14 @@ import type { MetabotCodeEdit } from "metabase-types/api";import {CodeEditTablePills,+ GeneratedCardTablePills,NavigateToTablePills,} from "./MetabotAgentDataSourcePills";import { AgentSuggestionMessage } from "./MetabotAgentSuggestionMessage";import { AgentTodoListMessage } from "./MetabotAgentTodoMessage";import Styles from "./MetabotChat.module.css";import { MetabotInlineChart } from "./MetabotInlineChart";+import { MetabotInlineDashboardLink } from "./MetabotInlineDashboardLink";type AgentDataPartMessageProps = {message: MetabotAgentDataPartMessage;@@ -99,6 +101,19 @@ export const AgentDataPartMessage = ({readonly={readonly}conversationId={conversationId}/>+ <GeneratedCardTablePills+ value={part.data}+ messageId={readonly ? undefined : message.externalId}+ />+ </Stack>+ ),+ )+ .with(+ { part: { type: "data-generated_entity", data: { type: "dashboard" } } },+ ({ part }) => (+ <Stack gap="md">+ {debug && <DataPartJsonCard type={part.type} value={part.data} />}+ <MetabotInlineDashboardLink value={part.data} /></Stack>),)@@ -207,6 +222,34 @@ const EntitySavedMessage = ({ value }: { value: EntitySavedValue }) => {const formatPartType = (type: string) => type.replace(/^data-/, "");+const NavigateToDataPart = ({ type, path }: { type: string; path: string }) => (+ <Flex+ direction="row"+ align="center"+ justify="space-between"+ bd="1px solid var(--mb-color-border-neutral)"+ bdrs="sm"+ className={Styles.agentPartCard}+ p="sm"+ pl="md"+ >+ <Flex align="center">+ <Icon name="document" c="text-secondary" mr="sm" />+ <Text fw="bold">{formatPartType(type)}</Text>+ </Flex>+ <ActionIcon+ component={ForwardRefLink}+ to={path}+ target="_blank"+ h="sm"+ aria-label={t`Visit`}+ className={cx(Styles.agentPartActions, Styles.agentPartActionIcon)}+ >+ <Icon name="external" size="1rem" />+ </ActionIcon>+ </Flex>+);+const DataPartJsonCard = ({type,value,@@ -275,34 +318,6 @@ const DataPartJsonCard = ({);};-const NavigateToDataPart = ({ type, path }: { type: string; path: string }) => (- <Flex- direction="row"- align="center"- justify="space-between"- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- className={Styles.agentPartCard}- p="sm"- pl="md"- >- <Flex align="center">- <Icon name="document" c="text-secondary" mr="sm" />- <Text fw="bold">{formatPartType(type)}</Text>- </Flex>- <ActionIcon- component={ForwardRefLink}- to={path}- target="_blank"- h="sm"- aria-label={t`Visit`}- className={cx(Styles.agentPartActions, Styles.agentPartActionIcon)}- >- <Icon name="external" size="1rem" />- </ActionIcon>- </Flex>-);-const CodeEditDataPart = ({type,value,diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsxindex 2868b47b894..420c3644bcd 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx@@ -10,6 +10,7 @@ import {useGetTableQuery,useSubmitMetabotSourceFeedbackMutation,} from "metabase/api";+import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";import { ForwardRefLink } from "metabase/common/components/Link";import { useToast } from "metabase/common/hooks";import { deserializeCardFromQuery } from "metabase/common/utils/card";@@ -73,9 +74,8 @@ const isNativeDatasetQuery = (): datasetQuery is NativeDatasetQuery =>"type" in datasetQuery && datasetQuery.type === "native";-const decodeQueryFromPath = (path: string): DecodedQuery => {+const decodeQuery = (datasetQuery: DatasetQuery | undefined): DecodedQuery => {try {- const datasetQuery = deserializeCardFromQuery(path).dataset_query;if (!datasetQuery) {return { kind: "none" };}@@ -606,14 +606,14 @@ const NativeSourcesRow = ({);};-export const NavigateToTablePills = ({+const DatasetQueryTablePills = ({messageId,- path,+ datasetQuery,}: {messageId?: string;- path: string;+ datasetQuery: DatasetQuery | undefined;}) => {- const decoded = useMemo(() => decodeQueryFromPath(path), [path]);+ const decoded = useMemo(() => decodeQuery(datasetQuery), [datasetQuery]);if (decoded.kind === "none") {return null;@@ -648,6 +648,39 @@ export const NavigateToTablePills = ({);};+export const GeneratedCardTablePills = ({+ messageId,+ value,+}: {+ messageId?: string;+ value: GeneratedCard;+}) => (+ <DatasetQueryTablePills+ messageId={messageId}+ datasetQuery={value.query.query}+ />+);++export const NavigateToTablePills = ({+ messageId,+ path,+}: {+ messageId?: string;+ path: string;+}) => {+ const datasetQuery = useMemo(() => {+ try {+ return deserializeCardFromQuery(path).dataset_query;+ } catch {+ return undefined;+ }+ }, [path]);++ return (+ <DatasetQueryTablePills messageId={messageId} datasetQuery={datasetQuery} />+ );+};+export const CodeEditTablePills = ({buffer,messageId,diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsxindex 88dde596c41..72a9037b40c 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx@@ -2,10 +2,13 @@ import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";import { FIXED_METABOT_IDS } from "metabase/metabot/constants";import type {+ DatasetQuery,MetabotCodeEdit,MetabotCodeEditorBufferContext,+ StructuredQuery,TemplateTags,} from "metabase-types/api";import {@@ -17,7 +20,7 @@ import {import {CodeEditTablePills,- NavigateToTablePills,+ GeneratedCardTablePills,} from "./MetabotAgentDataSourcePills";const SOURCE_FEEDBACK_ENDPOINT = "path:/api/metabot/source-feedback";@@ -52,22 +55,26 @@ const CODE_EDIT_BUFFER: MetabotCodeEditorBufferContext = {cursor: { line: 1, column: 1 },};-const createQuestionPath = (datasetQuery: Record<string, unknown>) =>- `/question#${btoa(JSON.stringify({ dataset_query: datasetQuery }))}`;+const createGeneratedCard = (datasetQuery: DatasetQuery): GeneratedCard => ({+ type: "card",+ id: "card-1",+ title: "Generated",+ query: { id: "query-1", query: datasetQuery },+});-const createMbqlPath = (query: Record<string, unknown>, database = 1) =>- createQuestionPath({+const createMbqlCard = (query: StructuredQuery, database = 1) =>+ createGeneratedCard({type: "query",database,query,});-const createNativePath = (+const createNativeCard = (sql = "SELECT * FROM ORDERS",database = 1,templateTags?: TemplateTags,) =>- createQuestionPath({+ createGeneratedCard({type: "native",database,native: {@@ -121,10 +128,13 @@ const renderMbqlPills = ({query,}: {messageId?: string;- query: Record<string, unknown>;+ query: StructuredQuery;}) =>renderWithProviders(- <NavigateToTablePills messageId={messageId} path={createMbqlPath(query)} />,+ <GeneratedCardTablePills+ messageId={messageId}+ value={createMbqlCard(query)}+ />,);describe("MetabotAgentDataSourcePills", () => {@@ -252,9 +262,9 @@ describe("MetabotAgentDataSourcePills", () => {setupNativeEndpoints();renderWithProviders(- <NavigateToTablePills+ <GeneratedCardTablePillsmessageId="message-5"- path={createNativePath(sql)}+ value={createNativeCard(sql)}/>,);@@ -294,9 +304,9 @@ describe("MetabotAgentDataSourcePills", () => {fetchMock.post(SOURCE_FEEDBACK_ENDPOINT, 204);renderWithProviders(- <NavigateToTablePills+ <GeneratedCardTablePillsmessageId="message-5-model"- path={createNativePath(sql, 1, templateTags)}+ value={createNativeCard(sql, 1, templateTags)}/>,);@@ -361,7 +371,9 @@ describe("MetabotAgentDataSourcePills", () => {fetchMock.get("path:/api/database/1", DATABASE);renderWithProviders(- <NavigateToTablePills path={createNativePath(sql, 1, templateTags)} />,+ <GeneratedCardTablePills+ value={createNativeCard(sql, 1, templateTags)}+ />,);expect(@@ -375,7 +387,9 @@ describe("MetabotAgentDataSourcePills", () => {setupNativeEndpoints();renderWithProviders(- <NavigateToTablePills path={createNativePath("SELECT * FROM ORDERS")} />,+ <GeneratedCardTablePills+ value={createNativeCard("SELECT * FROM ORDERS")}+ />,);const sourceLink = await screen.findByRole("link", { name: "Orders" });@@ -451,9 +465,9 @@ describe("MetabotAgentDataSourcePills", () => {setupNativeEndpoints({ delay: 50 });renderWithProviders(- <NavigateToTablePills+ <GeneratedCardTablePillsmessageId="message-9"- path={createNativePath("SELECT * FROM ORDERS")}+ value={createNativeCard("SELECT * FROM ORDERS")}/>,);diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsxindex e073b6310bc..b678aad7a7e 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineChart.tsx@@ -15,7 +15,6 @@ 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 { serializeChartClipboard } from "metabase/common/utils/chart-clipboard";import { getSavedChartCardId, markChartSaved } from "metabase/metabot/state";import { useDispatch, useSelector } from "metabase/redux";@@ -50,7 +49,7 @@ import S from "./MetabotInlineChart.module.css";* result; the title bar links out to the full question.*/export function MetabotInlineChart({- value: { id: chartId, title, description, display, query },+ value,readonly = false,conversationId,}: {@@ -58,6 +57,7 @@ export function MetabotInlineChart({readonly?: boolean;conversationId: string;}) {+ const { id: chartId, title, description, display, query } = value;const datasetQuery = query.query;const clipboard = useClipboard();const recordedCardId = useSelector((state) =>@@ -107,8 +107,8 @@ export function MetabotInlineChart({() =>savedCardId != null? Urls.question(question.setId(savedCardId))- : `/question#${serializeCardForUrl(card, { includeDisplayIsLocked: true })}`,- [card, question, savedCardId],+ : Urls.generatedCard(value),+ [question, savedCardId, value],);const { data: dataset, error } = useGetAdhocQueryQuery(datasetQuery);diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineDashboardLink.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineDashboardLink.tsxnew file mode 100644index 00000000000..ae376ad1c23--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotInlineDashboardLink.tsx@@ -0,0 +1,33 @@+import { t } from "ttag";++import type { GeneratedDashboard } from "metabase/api/ai-streaming/schemas";+import { ForwardRefLink } from "metabase/common/components/Link";+import { Anchor, Flex, Icon } from "metabase/ui";++export function MetabotInlineDashboardLink({+ value: { title, url },+}: {+ value: GeneratedDashboard;+}) {+ return (+ <Flex+ align="center"+ gap="sm"+ bd="1px solid var(--mb-color-border)"+ bdrs="md"+ p="md"+ data-testid="metabot-inline-dashboard-link"+ >+ <Icon name="dashboard" c="brand" />+ <Anchor+ component={ForwardRefLink}+ to={url}+ fw="bold"+ truncate+ aria-label={t`Open dashboard`}+ >+ {title}+ </Anchor>+ </Flex>+ );+}diff --git a/frontend/src/metabase/metabot/context.tsx b/frontend/src/metabase/metabot/context.tsxindex 9891a9f003a..99892630107 100644--- a/frontend/src/metabase/metabot/context.tsx+++ b/frontend/src/metabase/metabot/context.tsx@@ -168,7 +168,6 @@ export const MetabotProvider = ({current_time_with_timezone: dayjs.tz(dayjs()).format(),// Unjustified type cast. FIXMEcapabilities: _.compact([- "frontend:navigate_user_v1",hasDataAccess && "permission:save_questions",hasNativeWrite && "permission:write_sql_queries",isAdmin && "permission:write_transforms",diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.tsindex 350e09e8ab5..9c723745041 100644--- a/frontend/src/metabase/metabot/state/actions.ts+++ b/frontend/src/metabase/metabot/state/actions.ts@@ -24,6 +24,7 @@ import { createAsyncThunk } from "metabase/redux/utils";import { push } from "metabase/router";import { getSetting } from "metabase/selectors/settings";import { getUser } from "metabase/selectors/user";+import * as Urls from "metabase/urls";import { retry } from "metabase/utils/retry";import { uuid } from "metabase/utils/uuid";import type {@@ -554,15 +555,6 @@ export const sendAgentRequest = createAsyncThunk<},});})- .with({ type: "data-navigate_to" }, (part) => {- dispatchToConvo(setNavigateToPath(part.data));-- if (!isEmbeddingSdk()) {- // Unjustified type cast. FIXME- dispatchToConvo(push(part.data) as UnknownAction);- }- pushDataPart({ type: "data_part", part });- }).with({ type: "data-transform_suggestion" }, (part) => {const suggestionId = nanoid();const suggestedTransform = {@@ -584,6 +576,25 @@ export const sendAgentRequest = createAsyncThunk<metadata: { editorTransform, suggestionId },});})+ .with({ type: "data-generated_entity" }, (part) => {+ if (agentId === "ask") {+ pushDataPart({ type: "data_part", part });+ return;+ }++ const path = Urls.generatedEntity(part.data);++ if (isEmbeddingSdk()) {+ if (part.data.type === "card") {+ dispatchToConvo(setNavigateToPath(path));+ }+ pushDataPart({ type: "data_part", part });+ return;+ }++ // Unjustified type cast. FIXME+ dispatchToConvo(push(path) as UnknownAction);+ }).with({ type: "data-entity_saved" }, (part) => {dispatch(markChartSaved({@@ -594,12 +605,10 @@ export const sendAgentRequest = createAsyncThunk<pushDataPart({ type: "data_part", part });}).with(- { type: "data-generated_entity" },+ { type: "data-navigate_to" },{ type: "data-adhoc_viz" },{ type: "data-static_viz" },- (part) => {- pushDataPart({ type: "data_part", part });- },+ () => {},).exhaustive();},diff --git a/frontend/src/metabase/metabot/state/selectors.ts b/frontend/src/metabase/metabot/state/selectors.tsindex 42ab4fce974..763283d2e26 100644--- a/frontend/src/metabase/metabot/state/selectors.ts+++ b/frontend/src/metabase/metabot/state/selectors.ts@@ -178,15 +178,18 @@ const splitByTurn = (messages: MetabotChatMessage[]): MetabotChatMessage[][] =>return turns;}, []);-export const getFinalNavigateToMessageIdsPerTurn = createSelector(+export const getFinalChartMessageIdsPerTurn = createSelector(getMessages,(messages) =>new Set(splitByTurn(messages).flatMap((turn) => {- const lastNav = turn.findLast(- (m) => m.type === "data_part" && m.part.type === "data-navigate_to",+ const lastChart = turn.findLast(+ (m) =>+ m.type === "data_part" &&+ m.part.type === "data-generated_entity" &&+ m.part.data.type === "card",);- return lastNav ? [lastNav.id] : [];+ return lastChart ? [lastChart.id] : [];}),),);diff --git a/frontend/src/metabase/metabot/tests/context.unit.spec.tsx b/frontend/src/metabase/metabot/tests/context.unit.spec.tsxindex 905a08ffc23..aac54e4550e 100644--- a/frontend/src/metabase/metabot/tests/context.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/context.unit.spec.tsx@@ -87,7 +87,7 @@ describe("metabot > context", () => {expect(_.pick((await lastReqBody(agentSpy))?.context, "capabilities"),).toEqual({- capabilities: ["frontend:navigate_user_v1", "permission:save_questions"],+ capabilities: ["permission:save_questions"],});});diff --git a/frontend/src/metabase/urls/metabot.ts b/frontend/src/metabase/urls/metabot.tsindex a899e8a7c9d..eb85f03f46e 100644--- a/frontend/src/metabase/urls/metabot.ts+++ b/frontend/src/metabase/urls/metabot.ts@@ -1,10 +1,39 @@+import type {+ GeneratedCard,+ GeneratedEntity,+} from "metabase/api/ai-streaming/schemas";import { serializeCardForUrl } from "metabase/common/utils/card";-import type { CardDisplayType, DatasetQuery } from "metabase-types/api";+import type {+ CardDisplayType,+ DatasetQuery,+ UnsavedCard,+} from "metabase-types/api";++import { serializedQuestion } from "./questions";export function newMetabotConversation({ prompt }: { prompt: string }) {return `/metabot/new?q=${encodeURIComponent(prompt)}`;}+export function generatedCard(card: GeneratedCard) {+ const unsavedCard: UnsavedCard = {+ dataset_query: card.query.query,+ display: card.display ?? "table",+ visualization_settings: {},+ displayIsLocked: card.display != null,+ };+ return serializedQuestion(unsavedCard, { includeDisplayIsLocked: true });+}++export function generatedEntity(entity: GeneratedEntity) {+ switch (entity.type) {+ case "card":+ return generatedCard(entity);+ case "dashboard":+ return entity.url;+ }+}+export function metabotConversation(conversationId: string) {return `/metabot/conversation/${conversationId}`;}diff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.cljindex 06b1601b84d..86171205168 100644--- a/src/metabase/metabot/agent/profiles.clj+++ b/src/metabase/metabot/agent/profiles.clj@@ -99,7 +99,6 @@:tools [#'tools/nlq-search-tool#'tools/read-resource-tool#'tools/construct-notebook-query-tool- #'tools/navigate-user-tool#'tools/create-chart-tool#'tools/edit-chart-tool#'tools/save-entity-tool]})@@ -116,7 +115,6 @@#'tools/edit-sql-query-tool#'tools/replace-sql-query-tool#'tools/edit-chart-tool- #'tools/navigate-user-tool#'tools/create-chart-tool#'tools/create-autogenerated-dashboard-tool#'tools/create-dashboard-subscription-tool@@ -181,7 +179,6 @@:tools [#'tools/retrieve-library-entities-tool#'tools/read-resource-tool#'tools/construct-notebook-query-tool- #'tools/navigate-user-tool#'tools/create-chart-tool#'tools/edit-chart-tool#'tools/save-entity-tool]})@@ -194,7 +191,6 @@:tools [#'tools/nlq-search-tool#'tools/read-resource-tool#'tools/construct-notebook-query-tool- #'tools/navigate-user-tool#'tools/create-chart-tool#'tools/edit-chart-tool#'tools/save-entity-tool]})@@ -231,8 +227,8 @@(defn- filter-by-capabilities"Filter tool vars by user capabilities.Removes tools that require capabilities the user doesn't have.- Capabilities from the API arrive as strings (e.g. \"frontend:navigate_user_v1\")- while tool metadata uses keywords (e.g. :frontend-navigate-user-v1), so we+ Capabilities from the API arrive as strings (e.g. \"permission:write_sql_queries\")+ while tool metadata uses keywords (e.g. :permission-write-sql-queries), so wenormalize to keywords before comparing."[tool-vars capabilities](let [capabilities-set (capabilities/capability-set capabilities)]diff --git a/src/metabase/metabot/agent/streaming.clj b/src/metabase/metabot/agent/streaming.cljindex 7e19c8a8e3b..1f83c244d83 100644--- a/src/metabase/metabot/agent/streaming.clj+++ b/src/metabase/metabot/agent/streaming.clj@@ -1,7 +1,7 @@(ns metabase.metabot.agent.streaming"Streaming helpers for the agent loop.- Provides utilities for creating AI-SDK data parts, including navigation,- and transducers for stream processing."+ Provides utilities for creating AI-SDK data parts and transducers for stream+ processing."(:require[buddy.core.codecs :as codecs][metabase.metabot.agent.markdown-link-buffer :as markdown-link-buffer]@@ -13,7 +13,6 @@;;;; These match the Python AI Service's AISDKDataTypes enum-(def navigate-to-type "AI-SDK data type for navigation links." "navigate_to")(def state-type "AI-SDK data type for state updates." "state")(def todo-list-type "AI-SDK data type for todo lists." "todo_list")(def code-edit-type "AI-SDK data type for code edits." "code_edit")@@ -60,17 +59,6 @@;;; Data Part Constructors-(defn navigate-to-part- "Create a NAVIGATE_TO data part for streaming.- The URL should be a path like '/question#...' or '/model/123'.-- This matches Python AI Service's:- ai_sdk.create_data_part(data_type=AISDKDataTypes.NAVIGATE_TO, version=1, value=path)"- [url]- {:type :data- :data-type navigate-to-type- :data url})-(defn state-part"Create a STATE data part for streaming."[state-map]@@ -154,53 +142,30 @@:data value})(defn viz-part- "Return the data part used to surface a query/chart result to the frontend.-- When `inline?` is true (the surface declared it can render visualizations- inline) returns a `generated_entity` card part that embeds the (legacy)- dataset_query so the FE runs and renders it in the conversation; otherwise- 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` 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))- description (assoc :description description)))- (navigate-to-part link)))--;;; Reaction Conversion--(defn reactions->data-parts- "Convert tool reactions to AI-SDK data parts for streaming.-- Reactions are metadata returned by tools that trigger side effects:- - :metabot.reaction/redirect -> navigate_to data part-- Returns a vector of data parts (may be empty if no relevant reactions)."- [reactions]- (into []- (keep (fn [{:keys [type url]}]- (case type- :metabot.reaction/redirect (navigate-to-part url)- nil)))- reactions))+ "Return the `generated_entity` card data part that surfaces a query/chart result+ to the frontend. Embeds the (legacy) `query` so the FE runs and renders the card+ in the conversation. The caller must supply a distinct `entity-id` (card id) and+ `query-id`, plus a `title`; `display` and `description` are included when present."+ [{:keys [entity-id query-id query display title description]}]+ (generated-entity-part+ (cond-> {:type "card"+ :id entity-id+ :title title+ :query {:id query-id :query query}}+ display (assoc :display (some-> display name))+ description (assoc :description description))))++(defn dashboard-entity-part+ "Return a `generated_entity` dashboard data part. `url` is the navigation path the+ FE will route to (e.g. `/auto/dashboard/table/123`), `title` is a short human label+ for the inline link card, and `id` is an optional entity id."+ [{:keys [id title url]}]+ (generated-entity-part+ (cond-> {:type "dashboard" :url url :title title}+ id (assoc :id id))));;; Stream Processing Transducers-(def expand-reactions-xf- "Stateless transducer that expands :reactions from tool-output parts into data parts.- Passes through all parts unchanged, then appends any reaction data parts after tool-output parts."- (mapcat (fn [part]- (if (= (:type part) :tool-output)- (cons part (reactions->data-parts (get-in part [:result :reactions])))- [part]))))-(def expand-data-parts-xf"Stateless transducer that expands :data-parts from tool-output results.Passes through all parts unchanged, then appends any data parts after tool-output parts."@@ -214,11 +179,7 @@Applies in order:1. expand-data-parts-xf - Extract data-parts from tool outputs- 2. expand-reactions-xf - Extract reactions from tool outputs as data parts- 3. resolve-links-xf - Resolve metabase:// links in text parts-- Note: expand-data-parts-xf comes first so its output appears before reactions,- matching the original stream-parts-to-output! behavior.+ 2. resolve-links-xf - Resolve metabase:// links in text partsParameters:- initial-queries: Initial map of query-id to query data@@ -227,5 +188,4 @@[initial-queries initial-charts link-registry-atom](compexpand-data-parts-xf- expand-reactions-xf(markdown-link-buffer/resolve-xf initial-queries initial-charts link-registry-atom)))diff --git a/src/metabase/metabot/tools.clj b/src/metabase/metabot/tools.cljindex 778f25eac47..9c17585fa3d 100644--- a/src/metabase/metabot/tools.clj+++ b/src/metabase/metabot/tools.clj@@ -18,7 +18,6 @@[metabase.metabot.tools.document :as tools.document][metabase.metabot.tools.entity-retrieval :as tools.entity-retrieval][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]@@ -75,8 +74,6 @@[tools.todotodo-write-tooltodo-read-tool]- [tools.navigation- navigate-user-tool][tools.snippetslist-snippets-toolget-snippet-details-tool]@@ -109,7 +106,7 @@(def ^:private state-dependent-tools"Set of tool names that require access to agent state."#{"analyze_chart"- "create_chart" "edit_chart" "save_entity" "todo_write" "todo_read" "navigate_user"+ "create_chart" "edit_chart" "save_entity" "todo_write" "todo_read""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"diff --git a/src/metabase/metabot/tools/autogen_dashboard.clj b/src/metabase/metabot/tools/autogen_dashboard.cljindex b5402fa42bb..38cb7ca9489 100644--- a/src/metabase/metabot/tools/autogen_dashboard.clj+++ b/src/metabase/metabot/tools/autogen_dashboard.clj@@ -2,6 +2,7 @@"Autogenerated dashboard tool wrappers."(:require[clojure.string :as str]+ [metabase.metabot.agent.streaming :as streaming][metabase.metabot.scope :as scope][metabase.metabot.tools.shared :as shared][metabase.util.log :as log]@@ -98,21 +99,22 @@Returns map with:- :structured-output - Message and dashboard info- - :reactions - Navigation action to show the dashboard+ - :data-parts - Dashboard `generated_entity` part for the frontend- :instructions - Guidance for the LLM on how to respond"[{:keys [source memory-atom]}](log/info "Creating autogenerated dashboard" {:source source})- (let [memory (when memory-atom @memory-atom)- {:keys [path]} (resolve-source source memory)- response-message (str (random-response-message) "\n\nLet me know if you need anything else.")]+ (let [memory (when memory-atom @memory-atom)+ {:keys [entity path]} (resolve-source source memory)+ title (or (:display_name entity) (:name entity) "Dashboard")+ response-message (str (random-response-message) "\n\nLet me know if you need anything else.")];; Note: The actual automagic analysis happens on navigation to the /auto/dashboard/... URL;; The frontend handles rendering the X-ray dashboard(log/info "Autogenerated dashboard created" {:path path}){:structured-output {:message response-message:path path}- :reactions [{:type :metabot.reaction/redirect :url path}]+ :data-parts [(streaming/dashboard-entity-part {:title title :url path})]:instructions "The dashboard has been created and the user has been navigated to view it. Briefly acknowledge this (1 sentence) and stop. Do not describe the dashboard contents."}))(def ^:private autogen-dashboard-schema@@ -145,11 +147,11 @@{:source source:memory-atom shared/*memory-atom*})structured (:structured-output result)- reactions (:reactions result)]+ data-parts (:data-parts result)](cond-> {:output (:message structured):structured-output structured:instructions (:instructions result)}- (seq reactions) (assoc :reactions reactions)))+ (seq data-parts) (assoc :data-parts data-parts)))(catch Exception e(log/error e "Error creating autogenerated dashboard")(if (:agent-error? (ex-data e))diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.cljindex ea863d7b12a..e1e71e5a7f3 100644--- a/src/metabase/metabot/tools/charts.clj+++ b/src/metabase/metabot/tools/charts.clj@@ -55,14 +55,12 @@{:output (format-chart-output structured):structured-output structured:data-parts [(streaming/viz-part- {:inline? (shared/inline-viz-capable?)- :entity-id (:chart-id result)+ {: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)})]})+ :description description})]})(catch Exception e(log/error e "Error creating chart")(if (:agent-error? (ex-data e))@@ -104,18 +102,13 @@(swap! shared/*memory-atom* memory/set-chart (:chart_id new-chart-data) new-chart-data)){: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- :description description- :link (links/pseudo-card->link- {:dataset_query query- :display new-viz- :displayIsLocked true})})]})+ :data-parts [(streaming/viz-part+ {:entity-id (or (:chart_id new-chart-data) chart_id)+ :query-id (or (:query_id new-chart-data) (str (random-uuid)))+ :query (links/->legacy-mbql query)+ :display new-viz+ :title title+ :description description})]})(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.cljindex ebcee0753fd..5cf4c552b32 100644--- a/src/metabase/metabot/tools/construct.clj+++ b/src/metabase/metabot/tools/construct.clj@@ -15,7 +15,6 @@[metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te][metabase.metabot.tools.charts.create :as create-chart-tools]- [metabase.metabot.tools.shared :as shared][metabase.metabot.tools.shared.content-store :as shared.content-store][metabase.metabot.tools.shared.instructions :as instructions][metabase.metabot.tools.shared.llm-shape :as llm-shape]@@ -482,14 +481,12 @@"<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)+ {: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})])+ :description description})]):structured-output full-structured:instructions instruction-text});; query-result may already have :output (error) or only :structured-outputdiff --git a/src/metabase/metabot/tools/generate_insights.clj b/src/metabase/metabot/tools/generate_insights.cljindex a4d6f8a05d5..5fcd2a6c330 100644--- a/src/metabase/metabot/tools/generate_insights.clj+++ b/src/metabase/metabot/tools/generate_insights.clj@@ -2,6 +2,7 @@(:require[buddy.core.codecs :as codecs][metabase.lib.util :as lib.util]+ [metabase.metabot.agent.streaming :as streaming][metabase.metabot.tools.util :as metabot.tools.u][metabase.util.json :as json]))@@ -31,6 +32,6 @@(throw (ex-info "Invalid table_id" {:agent-error? true:table_id id}))){:output results-url- :reactions [{:type :metabot.reaction/redirect :url results-url}]})+ :data-parts [(streaming/dashboard-entity-part {:url results-url})]})(catch Exception e(metabot.tools.u/handle-agent-error e))))diff --git a/src/metabase/metabot/tools/navigation.clj b/src/metabase/metabot/tools/navigation.cljdeleted file mode 100644index b619426a6fd..00000000000--- a/src/metabase/metabot/tools/navigation.clj+++ /dev/null@@ -1,172 +0,0 @@-(ns metabase.metabot.tools.navigation- "Navigation tool wrappers."- (:require- [buddy.core.codecs :as codecs]- [metabase.metabot.agent.links :as links]- [metabase.metabot.scope :as scope]- [metabase.metabot.tools.shared :as shared]- [metabase.util.json :as json]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- create-sql-editor-hash- "Create a hash for the SQL editor with optional database ID."- [database-id]- (let [query-data {:dataset_query {:database database-id- :type "native"- :native {:query ""}}}]- (-> query-data- json/encode- (.getBytes "UTF-8")- codecs/bytes->b64-str)))--(defn- page->path- "Convert a page name to a URL path."- [page database-id]- (case page- "notebook_editor" "/question/notebook"- "metrics_browser" "/browse/metrics"- "model_browser" "/browse/models"- "database_browser" "/browse/databases"- "sql_editor" (str "/question#" (create-sql-editor-hash database-id))- "home" "/"- (throw (ex-info (str "Unknown page: " page ". Valid pages: notebook_editor, metrics_browser, model_browser, database_browser, sql_editor, home")- {:agent-error? true :page page}))))--(defn- entity->path- "Convert an entity type and ID to a URL path."- [entity-type entity-id]- (case entity-type- "table" (str "/table/" entity-id)- "model" (str "/model/" entity-id)- "question" (str "/question/" entity-id)- "metric" (str "/metric/" entity-id)- "dashboard" (str "/dashboard/" entity-id)- "database" (str "/browse/databases/" entity-id)- "collection" (str "/collection/" entity-id)- (throw (ex-info (str "Unknown entity type: " entity-type ". Valid types: table, model, question, metric, dashboard, database, collection")- {:agent-error? true :entity-type entity-type}))))--(defn- destination->path- "Convert navigation destination to a URL path.- Handles page navigation, entity navigation, and query/chart link resolution."- [destination memory]- (cond- ;; Page navigation- (:page destination)- (page->path (:page destination) (:database_id destination))-- ;; Entity navigation- (and (:entity_type destination) (:entity_id destination))- (entity->path (:entity_type destination) (:entity_id destination))-- ;; Query result navigation (resolve from memory)- (:query_id destination)- (let [queries-state (get-in memory [:state :queries] {})- charts-state (get-in memory [:state :charts] {})]- (or (links/resolve-metabase-uri (str "metabase://query/" (:query_id destination))- queries-state- charts-state)- (throw (ex-info (str "Query not found: " (:query_id destination))- {:agent-error? true :query-id (:query_id destination)}))))-- ;; Chart navigation (resolve from memory)- (:chart_id destination)- (let [queries-state (get-in memory [:state :queries] {})- charts-state (get-in memory [:state :charts] {})]- (or (links/resolve-metabase-uri (str "metabase://chart/" (:chart_id destination))- queries-state- charts-state)- (throw (ex-info (str "Chart not found: " (:chart_id destination))- {:agent-error? true :chart-id (:chart_id destination)}))))-- :else- (throw (ex-info "Invalid destination: must specify page, entity_type+entity_id, query_id, or chart_id"- {:agent-error? true :destination destination}))))--(defn- format-navigation-message- "Format a user-friendly message describing the navigation."- [destination]- (cond- (:page destination)- (str "Navigating to " (name (:page destination)) " page.")-- (and (:entity_type destination) (:entity_id destination))- (str "Navigating to " (:entity_type destination) " " (:entity_id destination) ".")-- (:query_id destination)- "Navigating to query results."-- (:chart_id destination)- "Navigating to chart."-- :else- "Navigating to destination."))--(defn navigate- "Navigate user to a specific page in Metabase UI.-- Parameters:- - destination: Map describing where to navigate. One of:- - {:page \"page_name\"} - Navigate to a specific page- - {:page \"sql_editor\" :database_id 123} - Navigate to SQL editor with database- - {:entity_type \"model\" :entity_id 123} - Navigate to an entity- - {:query_id \"abc123\"} - Navigate to query results- - {:chart_id \"xyz789\"} - Navigate to chart- - memory-atom: Atom containing agent memory (for link resolution)-- Returns map with:- - :structured-output - Message for the LLM- - :reactions - Navigation action"- [{:keys [destination memory-atom]}]- (log/info "Navigating user" {:destination destination})- (let [memory (when memory-atom @memory-atom)- path (destination->path destination memory)- message (format-navigation-message destination)]- (log/debug "Resolved navigation path" {:path path})- {:structured-output {:message message- :path path}- :reactions [{:type :metabot.reaction/redirect :url path}]}))--(def ^:private navigation-schema- [:map {:closed true}- [:destination [:or- [:map {:closed true}- [:page [:enum "notebook_editor" "metrics_browser" "model_browser" "database_browser"]]]- [:map {:closed true}- [:page [:enum "sql_editor"]]- [:database_id :int]]- [:map {:closed true}- [:entity_type [:enum "table" "model" "question" "metric" "dashboard"]]- [:entity_id :int]]- [:map {:closed true}- [:query_id :string]]- [:map {:closed true}- [:chart_id :string]]]]])--(mu/defn ^{:tool-name "navigate_user"- :scope scope/agent-viz-navigate- :capabilities #{:frontend-navigate-user-v1}}- navigate-user-tool- "Navigate the user to a specific page or entity in Metabase.-- Use this tool to direct users to:- - Pages: notebook_editor, metrics_browser, model_browser, database_browser, sql_editor- - Entities: table, model, question, metric, dashboard- - Query results or charts from the current conversation"- [{:keys [destination]} :- navigation-schema]- (try- (let [result (navigate {:destination destination- :memory-atom shared/*memory-atom*})- structured (:structured-output result)- reactions (:reactions result)]- (cond-> {:output (:message structured)- :structured-output structured}- (seq reactions) (assoc :reactions reactions)))- (catch Exception e- (log/error e "Error navigating")- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to navigate: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/tools/shared.clj b/src/metabase/metabot/tools/shared.cljindex 7a96ac549e1..0a28d7fb52b 100644--- a/src/metabase/metabot/tools/shared.clj+++ b/src/metabase/metabot/tools/shared.clj@@ -53,11 +53,6 @@[](get (current-memory) :context))-(defn inline-viz-capable?- "True when the current profile should render visualizations inline."- []- (= *profile-id* :nlq))-(defn with-memory"Helper for debugging memory-bound tools when needed."[f]diff --git a/src/metabase/metabot/tools/sql.clj b/src/metabase/metabot/tools/sql.cljindex 28942578b13..c5539548831 100644--- a/src/metabase/metabot/tools/sql.clj+++ b/src/metabase/metabot/tools/sql.clj@@ -96,17 +96,14 @@{:keys [query-id query]} action-result](if valid?(let [structured (assoc action-result :result-type :query)- instr (instructions/query-created-instructions-for query-id)- results-url (streaming/query->question-url query)]+ instr (instructions/query-created-instructions-for query-id)]{:output (format-query-output structured instr {:preamble? true}):structured-output structured:instructions instr- :data-parts [(streaming/viz-part {:inline? (shared/inline-viz-capable?)- :entity-id (str (random-uuid))+ :data-parts [(streaming/viz-part {:entity-id (str (random-uuid)):query-id query-id:query (links/->legacy-mbql query)- :title title- :link results-url})]})+ :title title})]})(let [instr (instructions/sql-validation-error-instructions dialect error-message)]{:output (format-validation-error-output instr):instructions instr})))@@ -175,19 +172,16 @@(if valid?(let [structured (assoc action-result :result-type :query)instr (instructions/edit-sql-query-instructions-for query-id)- results-url (streaming/query->question-url query)buffer-id (first-code-editor-buffer-id)]{:output (format-query-output structured instr):structured-output structured:instructions instr:data-parts [(if buffer-id(code-edit-part buffer-id query-content)- (streaming/viz-part {:inline? (shared/inline-viz-capable?)- :entity-id (str (random-uuid))+ (streaming/viz-part {:entity-id (str (random-uuid)):query-id query-id:query (links/->legacy-mbql query)- :title title- :link results-url}))]})+ :title title}))]})(let [instr (instructions/sql-validation-error-instructions dialect error-message)]{:output (format-validation-error-output instr):instructions instr})))@@ -227,19 +221,16 @@(if valid?(let [structured (assoc action-result :result-type :query)instr (instructions/replace-sql-query-instructions-for query-id)- results-url (streaming/query->question-url query)buffer-id (first-code-editor-buffer-id)]{:output (format-query-output structured instr):structured-output structured:instructions instr:data-parts [(if buffer-id(code-edit-part buffer-id query-content)- (streaming/viz-part {:inline? (shared/inline-viz-capable?)- :entity-id (str (random-uuid))+ (streaming/viz-part {:entity-id (str (random-uuid)):query-id query-id:query (links/->legacy-mbql query)- :title title- :link results-url}))]})+ :title title}))]})(let [instr (instructions/sql-validation-error-instructions dialect error-message)]{:output (format-validation-error-output instr):instructions instr})))diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.cljindex 511c92149ab..065d1aecfec 100644--- a/test/metabase/metabot/agent/core_test.clj+++ b/test/metabase/metabot/agent/core_test.clj@@ -362,7 +362,7 @@{:type :tool-output:function "construct_notebook_query":result {:structured-output {:query {:database (mt/id)}}}}- {:type :data :data-type "navigate_to"}+ {:type :data :data-type "generated_entity"}{:type :start};; has final text part{:type :text}diff --git a/test/metabase/metabot/agent/profiles_test.clj b/test/metabase/metabot/agent/profiles_test.cljindex 16efcb4dcd8..4a70747429a 100644--- a/test/metabase/metabot/agent/profiles_test.clj+++ b/test/metabase/metabot/agent/profiles_test.clj@@ -111,27 +111,24 @@(is (contains? tools "search"))(is (contains? tools "create_autogenerated_dashboard"));; Capability-gated tools should be excluded- (is (not (contains? tools "navigate_user")))))))+ (is (not (contains? tools "create_sql_query")))))))(deftest get-tools-for-profile-includes-capability-gated-tools-test(binding [scope/*current-user-scope* api-scope/unrestricted](testing "providing a capability includes tools gated by that capability"- (let [tools (profiles/get-tools-for-profile :internal [:frontend-navigate-user-v1])]- (is (contains? tools "navigate_user"))))))+ (let [tools (profiles/get-tools-for-profile :internal [:permission-write-sql-queries])]+ (is (contains? tools "create_sql_query"))))))(deftest get-tools-for-profile-string-capabilities-test(binding [scope/*current-user-scope* api-scope/unrestricted](testing "capabilities as strings (as sent by the API / benchmark client)"- (testing "NLQ-only capabilities should exclude SQL tools and include navigate_user"+ (testing "NLQ-only capabilities should exclude SQL tools but include ungated tools"(let [;; This is what the NLQ benchmark actually sends via the API:- nlq-capabilities ["frontend:navigate_user_v1"- "permission:save_questions"]+ nlq-capabilities ["permission:save_questions"]tools (profiles/get-tools-for-profile :internal nlq-capabilities)](is (contains? tools "search") "search should always be available")(is (contains? tools "construct_notebook_query") "notebook queries should be available")(is (contains? tools "read_resource") "read_resource should always be available")- (is (contains? tools "navigate_user")- "navigate_user should be available when frontend:navigate_user_v1 is in capabilities")(is (not (contains? tools "create_sql_query"))"create_sql_query should NOT be available without permission:write_sql_queries")(is (not (contains? tools "edit_sql_query"))@@ -139,14 +136,11 @@(is (not (contains? tools "replace_sql_query"))"replace_sql_query should NOT be available without permission:write_sql_queries")))(testing "full capabilities including SQL write permission should include SQL tools"- (let [full-capabilities ["frontend:navigate_user_v1"- "permission:save_questions"+ (let [full-capabilities ["permission:save_questions""permission:write_sql_queries"]tools (profiles/get-tools-for-profile :internal full-capabilities)](is (contains? tools "search"))(is (contains? tools "construct_notebook_query"))- (is (contains? tools "navigate_user")- "navigate_user should be available with frontend:navigate_user_v1")(is (contains? tools "create_sql_query")"create_sql_query should be available with permission:write_sql_queries")(is (contains? tools "edit_sql_query")@@ -156,7 +150,6 @@(testing "empty capabilities should exclude all capability-gated tools"(let [tools (profiles/get-tools-for-profile :internal [])](is (contains? tools "search") "ungated tools should remain")- (is (not (contains? tools "navigate_user")))(is (not (contains? tools "create_sql_query"))"SQL tools should be gated by permission:write_sql_queries"))))))@@ -173,14 +166,10 @@;; the curated profile is the same set with retrieve_library_entities in place of `search`(is (= curated (-> embedding (disj "search") (conj "retrieve_library_entities"))))))(binding [scope/*current-user-scope* api-scope/unrestricted]- (testing "navigate_user is excluded without the capability"+ (testing "ungated tools are available with empty capabilities"(let [tools (profiles/get-tools-for-profile :embedding_next [])](is (contains? tools "search"))- (is (contains? tools "construct_notebook_query"))- (is (not (contains? tools "navigate_user")))))- (testing "navigate_user is included with the capability"- (let [tools (profiles/get-tools-for-profile :embedding_next ["frontend:navigate_user_v1"])]- (is (contains? tools "navigate_user"))))))+ (is (contains? tools "construct_notebook_query"))))))(deftest nlq-data-discovery-fallback-test(testing "the :nlq profile always keeps a data-discovery tool, swapping by index availability"diff --git a/test/metabase/metabot/agent/streaming_test.clj b/test/metabase/metabot/agent/streaming_test.cljindex 24ca4b6931e..14779234f25 100644--- a/test/metabase/metabot/agent/streaming_test.clj+++ b/test/metabase/metabot/agent/streaming_test.clj@@ -4,20 +4,46 @@[clojure.test :refer :all][metabase.metabot.agent.streaming :as streaming]))-(deftest navigate-to-part-test- (testing "creates correct navigate_to data part structure"- (let [url "/question#abc123"- part (streaming/navigate-to-part url)]+(deftest viz-part-test+ (testing "always emits a card generated_entity"+ (let [query {:database 1 :type :query :query {:source-table 1}}+ part (streaming/viz-part {:entity-id "card-1"+ :query-id "q1"+ :query query+ :display :bar+ :title "My Chart"})](is (= :data (:type part)))- (is (= "navigate_to" (:data-type part)))- (is (= url (:data part)))))- (testing "works with various URL formats"- (let [part1 (streaming/navigate-to-part "/model/123")- part2 (streaming/navigate-to-part "/metric/456")- part3 (streaming/navigate-to-part "/dashboard/789")]- (is (= "/model/123" (:data part1)))- (is (= "/metric/456" (:data part2)))- (is (= "/dashboard/789" (:data part3))))))+ (is (= "generated_entity" (:data-type part)))+ (is (= {:type "card"+ :id "card-1"+ :title "My Chart"+ :query {:id "q1" :query query}+ :display "bar"}+ (:data part)))))+ (testing "omits :display when not provided"+ (let [part (streaming/viz-part {:entity-id "card-2"+ :query-id "q2"+ :query {:database 1}+ :title "No Display"})]+ (is (= {:type "card"+ :id "card-2"+ :title "No Display"+ :query {:id "q2" :query {:database 1}}}+ (:data part)))+ (is (not (contains? (:data part) :display))))))++(deftest dashboard-entity-part-test+ (testing "emits a dashboard generated_entity"+ (let [part (streaming/dashboard-entity-part {:title "Orders" :url "/auto/dashboard/table/123"})]+ (is (= :data (:type part)))+ (is (= "generated_entity" (:data-type part)))+ (is (= {:type "dashboard" :url "/auto/dashboard/table/123" :title "Orders"}+ (:data part)))+ (is (not (contains? (:data part) :id)))))+ (testing "includes :id when provided"+ (let [part (streaming/dashboard-entity-part {:title "Orders" :url "/dashboard/9" :id 9})]+ (is (= {:type "dashboard" :url "/dashboard/9" :title "Orders" :id 9}+ (:data part))))))(deftest query->question-url-test(testing "converts query to /question# URL"@@ -34,32 +60,6 @@url (streaming/query->question-url query)](is (str/starts-with? url "/question#")))))-(deftest reactions->data-parts-test- (testing "converts redirect reactions to navigate_to data parts"- (let [reactions [{:type :metabot.reaction/redirect :url "/question#xyz"}]- parts (streaming/reactions->data-parts reactions)]- (is (= 1 (count parts)))- (is (= :data (:type (first parts))))- (is (= "navigate_to" (:data-type (first parts))))- (is (= "/question#xyz" (:data (first parts))))))- (testing "handles multiple reactions"- (let [reactions [{:type :metabot.reaction/redirect :url "/model/1"}- {:type :metabot.reaction/redirect :url "/metric/2"}]- parts (streaming/reactions->data-parts reactions)]- (is (= 2 (count parts)))- (is (= "/model/1" (:data (first parts))))- (is (= "/metric/2" (:data (second parts))))))- (testing "ignores non-redirect reactions"- (let [reactions [{:type :metabot.reaction/message :message "hello"}- {:type :metabot.reaction/redirect :url "/model/1"}- {:type :unknown/reaction :data "foo"}]- parts (streaming/reactions->data-parts reactions)]- (is (= 1 (count parts)))- (is (= "/model/1" (:data (first parts))))))- (testing "returns empty vector for empty reactions"- (is (= [] (streaming/reactions->data-parts [])))- (is (= [] (streaming/reactions->data-parts nil)))))-(deftest state-part-test(testing "creates state data part"(let [state {:queries {"q1" {:database 1}} :charts {"c1" {:type :bar}}}@@ -144,40 +144,8 @@(is (= "static_viz" (:data-type part)))(is (= value (:data part))))))-(deftest viz-part-test- (testing "inline -> generated_entity card embedding the query"- (let [part (streaming/viz-part {:inline? true- :entity-id "c-1"- :query-id "q-1"- :query {:database 1}- :display :bar- :title "Orders by month"- :link "/question#abc"})]- (is (= :data (:type part)))- (is (= "generated_entity" (:data-type part)))- (is (= {:type "card"- :id "c-1"- :query {:id "q-1" :query {:database 1}}- :title "Orders by month"- :display "bar"}- (:data part)))))- (testing "omits display when absent"- (let [part (streaming/viz-part {:inline? true- :entity-id "c-1"- :query-id "q-1"- :query {:database 1}- :title "Orders by month"})]- (is (= "Orders by month" (:title (:data part))))- (is (not (contains? (:data part) :display)))))- (testing "non-inline -> navigate_to link"- (let [part (streaming/viz-part {:inline? false- :link "/question#abc"})]- (is (= "navigate_to" (:data-type part)))- (is (= "/question#abc" (:data part))))))-(deftest data-type-constants-test(testing "data type constants are defined correctly"- (is (= "navigate_to" streaming/navigate-to-type))(is (= "state" streaming/state-type))(is (= "todo_list" streaming/todo-list-type))(is (= "code_edit" streaming/code-edit-type))@@ -190,42 +158,11 @@(testing "state parts are not persisted (value lives on MetabotConversation.state)"(is (false? (streaming/persistable-data-part? (streaming/state-part {:queries {}})))))(testing "other parts are persisted"- (is (true? (streaming/persistable-data-part? (streaming/navigate-to-part "/question/1"))))+ (is (true? (streaming/persistable-data-part? (streaming/todo-list-part []))))(is (true? (streaming/persistable-data-part? {:type :text :text "hi"})))));;; Transducer Tests-(deftest expand-reactions-xf-test- (testing "expands reactions from tool-output parts"- (let [parts [{:type :tool-output- :id "t1"- :result {:output "done"- :reactions [{:type :metabot.reaction/redirect :url "/question#abc"}]}}]- result (into [] streaming/expand-reactions-xf parts)]- (is (= 2 (count result)))- (is (= :tool-output (:type (first result))))- (is (= :data (:type (second result))))- (is (= "navigate_to" (:data-type (second result))))))- (testing "passes through non-tool-output parts unchanged"- (let [parts [{:type :text :text "hello"}- {:type :usage :tokens 100}]- result (into [] streaming/expand-reactions-xf parts)]- (is (= parts result))))- (testing "handles tool-output without reactions"- (let [parts [{:type :tool-output :id "t1" :result {:output "done"}}]- result (into [] streaming/expand-reactions-xf parts)]- (is (= 1 (count result)))- (is (= :tool-output (:type (first result))))))- (testing "handles multiple reactions from single tool"- (let [parts [{:type :tool-output- :id "t1"- :result {:reactions [{:type :metabot.reaction/redirect :url "/a"}- {:type :metabot.reaction/redirect :url "/b"}]}}]- result (into [] streaming/expand-reactions-xf parts)]- (is (= 3 (count result)))- (is (= "/a" (:data (second result))))- (is (= "/b" (:data (nth result 2)))))))-(deftest expand-data-parts-xf-test(testing "expands data-parts from tool-output results"(let [todo-part {:type :data :data-type "todo_list" :data [{:id "1"}]}@@ -293,27 +230,23 @@parts [{:type :tool-output:id "t1":result {:structured-output {:query-id "q1" :query query}- :reactions [{:type :metabot.reaction/redirect :url "/nav"}]:data-parts [{:type :data :data-type "todo_list" :data []}]}}{:type :text :text "[Link](metabase://query/q1)"}]result (into [] (streaming/post-process-xf {} {} (atom {})) parts)]- ;; Should have: tool-output, navigate_to data part, todo_list data part, resolved text- (is (= 4 (count result)))+ ;; Should have: tool-output, todo_list data part, resolved text+ (is (= 3 (count result)))(is (= :tool-output (:type (nth result 0))))- (is (= "navigate_to" (:data-type (nth result 1))))- (is (= "todo_list" (:data-type (nth result 2))))- (is (re-find #"\[Link\]\(/question#" (:text (nth result 3))))))+ (is (= "todo_list" (:data-type (nth result 1))))+ (is (re-find #"\[Link\]\(/question#" (:text (nth result 2))))))(testing "works with empty parts"(let [result (into [] (streaming/post-process-xf {} {} (atom {})) [])](is (= [] result))))- (testing "preserves order: tool-output, reactions, data-parts, text"+ (testing "preserves order: tool-output, data-parts, text"(let [parts [{:type :tool-output:id "t1"- :result {:reactions [{:type :metabot.reaction/redirect :url "/r"}]- :data-parts [{:type :data :data-type "dp"}]}}+ :result {:data-parts [{:type :data :data-type "dp"}]}}{:type :text :text "text"}]result (into [] (streaming/post-process-xf {} {} (atom {})) parts)](is (= :tool-output (:type (nth result 0))))- (is (= "navigate_to" (:data-type (nth result 1))))- (is (= "dp" (:data-type (nth result 2))))- (is (= "text" (:text (nth result 3)))))))+ (is (= "dp" (:data-type (nth result 1))))+ (is (= "text" (:text (nth result 2)))))))diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex d85ad3ad3f4..638b99e3908 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -1435,7 +1435,7 @@assistant-msg-id[{:type :start :id "msg-1"}{:type :text :text "Hi"}- {:type :data :data-type "navigate_to" :data "/question/1"}+ {:type :data :data-type "generated_entity" :version 1 :data {:type "card" :id "c1" :title "Q" :query {:id "q1" :query {}}}}{:type :data :data-type "todo_list" :version 1 :data [{:id "1" :content "x" :status "pending" :priority "low"}]}{:type :data :data-type "code_edit" :version 1 :data {:buffer_id "b" :value "v"}}{:type :data :data-type "transform_suggestion" :version 1 :data {}}@@ -1450,7 +1450,7 @@data-types (into #{}(keep #(when (str/starts-with? % "data-") (subs % 5)))part-types)]- (is (= #{"navigate_to" "todo_list" "code_edit" "transform_suggestion" "adhoc_viz" "static_viz"}+ (is (= #{"generated_entity" "todo_list" "code_edit" "transform_suggestion" "adhoc_viz" "static_viz"}data-types)"all persistable data parts (not state) should be in :data")(is (contains? part-types "text")@@ -1477,7 +1477,7 @@:result {:output "<result>XML</result>":resources [{:id 1 :name "Orders" :columns [{:field_values [1 2 3]}]}]:structured-output {:result-type :search :data [{:id 1}]}- :data-parts [{:type :data :data-type "navigate_to"}]}}])))))+ :data-parts [{:type :data :data-type "generated_entity"}]}}])))))(deftest parts->storable-content-structured-output-subset-test(testing "keeps the query-related subset of structured output, canonicalized to :structured_output"diff --git a/test/metabase/metabot/persistence_test.clj b/test/metabase/metabot/persistence_test.cljindex a0f9ff51d8c..06837a44469 100644--- a/test/metabase/metabot/persistence_test.clj+++ b/test/metabase/metabot/persistence_test.clj@@ -129,10 +129,10 @@(deftest ^:parallel message->chat-messages-test-9(testing "data parts are converted to data_part chat messages"- (let [blocks [{:type "data-navigate_to" :data "/question/1"}+ (let [blocks [{:type "data-generated_entity" :data {:type "dashboard" :url "/auto/dashboard/table/1"}}{:type "data-todo_list" :data [{:id "t1"}]}{:type "data-code_edit" :data {:buffer_id "b" :value "v"}}]]- (is (=? [{:role "agent" :type "data_part" :part {:type "data-navigate_to" :data "/question/1"}}+ (is (=? [{:role "agent" :type "data_part" :part {:type "data-generated_entity" :data {:type "dashboard" :url "/auto/dashboard/table/1"}}}{:role "agent" :type "data_part" :part {:type "data-todo_list" :data [{:id "t1"}]}}{:role "agent" :type "data_part" :part {:type "data-code_edit" :data {:buffer_id "b" :value "v"}}}](metabot-persistence/message->chat-messages {:role :assistant :data blocks}))))))diff --git a/test/metabase/metabot/tools/autogen_dashboard_test.clj b/test/metabase/metabot/tools/autogen_dashboard_test.cljindex 10ce7b1d24a..3b7c87c5f23 100644--- a/test/metabase/metabot/tools/autogen_dashboard_test.clj+++ b/test/metabase/metabot/tools/autogen_dashboard_test.clj@@ -36,14 +36,18 @@{:source {:table_id (:id table)}:memory-atom (atom {:state {}})})](is (string? (:instructions result))))))- (testing "returns redirect reaction"+ (testing "returns a dashboard generated_entity data part"(mt/with-temp [:model/Table table {:name (mt/random-name) :db_id (mt/id)}](let [result (autogen-dashboard/create-autogenerated-dashboard{:source {:table_id (:id table)}- :memory-atom (atom {:state {}})})]- (is (contains? result :reactions))- (is (= :metabot.reaction/redirect (:type (first (:reactions result)))))- (is (str/starts-with? (:url (first (:reactions result))) "/auto/dashboard/")))))+ :memory-atom (atom {:state {}})})+ part (first (:data-parts result))+ entity (:data part)]+ (is (contains? result :data-parts))+ (is (= "generated_entity" (:data-type part)))+ (is (= "dashboard" (:type entity)))+ (is (str/starts-with? (:url entity) "/auto/dashboard/"))+ (is (= (or (:display_name table) (:name table)) (:title entity))))))(testing "returns user-friendly message"(mt/with-temp [:model/Table table {:name (mt/random-name) :db_id (mt/id)}](let [result (autogen-dashboard/create-autogenerated-dashboarddiff --git a/test/metabase/metabot/tools/charts_test.clj b/test/metabase/metabot/tools/charts_test.cljindex fec0b3b3961..745330a9a35 100644--- a/test/metabase/metabot/tools/charts_test.clj+++ b/test/metabase/metabot/tools/charts_test.clj@@ -1,7 +1,8 @@(ns metabase.metabot.tools.charts-test- "Tests that chart tools emit inline results in the NLQ profile and `navigate_to` otherwise."+ "Tests that the chart tools always emit a `generated_entity` card data part. The+ inline-vs-navigate decision now lives on the frontend, so the backend no longer+ branches on a capability."(:require- [clojure.string :as str][clojure.test :refer :all][metabase.metabot.tools.charts :as charts][metabase.metabot.tools.shared :as shared]))@@ -13,21 +14,19 @@{:database 1 :type "query" :query {:source-table 1}})(defn- run-create-chart- ([profile-id]- (run-create-chart profile-id "bar"))- ([profile-id chart-type]- (let [memory (atom {:state {:queries {"q-1" stub-query}}- :context {}})]- (binding [shared/*memory-atom* memory- shared/*profile-id* profile-id]+ ([]+ (run-create-chart "bar"))+ ([chart-type]+ (let [memory (atom {:state {:queries {"q-1" stub-query}}})]+ (binding [shared/*memory-atom* memory](charts/create-chart-tool {:data_source {:query_id "q-1"}:viz_settings {:chart_type chart-type}: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"- (let [result (run-create-chart :nlq)+(deftest create-chart-generated-entity-test+ (testing "emits a single generated_entity card part"+ (let [result (run-create-chart)parts (:data-parts result)entity (:data (first parts))](is (= 1 (count parts)))@@ -41,18 +40,11 @@(is (= "q-1" (get-in entity [:query :id])))(is (some? (get-in entity [:query :query]))))(testing "keeps the query in structured-output so chart memory stores it for later edits"- (is (= stub-query (get-in result [:structured-output :query]))))- (is (not-any? #(= "navigate_to" (:data-type %)) parts))))- (testing "emits a single navigate_to data part outside the NLQ profile"- (let [parts (:data-parts (run-create-chart :sql))]- (is (= 1 (count parts)))- (is (= "navigate_to" (:data-type (first parts))))- (is (str/starts-with? (:data (first parts)) "/question#"))- (is (not-any? #(= "generated_entity" (:data-type %)) parts)))))+ (is (= stub-query (get-in result [:structured-output :query])))))))(deftest create-chart-treemap-test(testing "the tool schema accepts treemap as a chart type"- (let [result (run-create-chart :nlq "treemap")]+ (let [result (run-create-chart "treemap")](is (= :treemap (get-in result [:structured-output :chart-type])))(is (= "treemap" (get-in result [:data-parts 0 :data :display]))))))@@ -64,8 +56,7 @@:queries [nil]:visualization_settings {:chart_type :bar}}}}:context {}})- result (binding [shared/*memory-atom* memory- shared/*profile-id* :nlq]+ result (binding [shared/*memory-atom* memory](charts/edit-chart-tool {:chart_id "c-1":new_viz_settings {:chart_type "pie"}:title "Orders by month"diff --git a/test/metabase/metabot/tools/navigation_test.clj b/test/metabase/metabot/tools/navigation_test.cljdeleted file mode 100644index 98ac15face7..00000000000--- a/test/metabase/metabot/tools/navigation_test.clj+++ /dev/null@@ -1,160 +0,0 @@-(ns metabase.metabot.tools.navigation-test- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase.metabot.tools.navigation :as navigate]))--(deftest page->path-test- (testing "page navigation produces correct paths"- ;; Test through the public navigate function- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (testing "notebook_editor"- (let [result (navigate/navigate {:destination {:page "notebook_editor"}- :memory-atom memory-atom})]- (is (= "/question/notebook" (get-in result [:structured-output :path])))))- (testing "metrics_browser"- (let [result (navigate/navigate {:destination {:page "metrics_browser"}- :memory-atom memory-atom})]- (is (= "/browse/metrics" (get-in result [:structured-output :path])))))- (testing "model_browser"- (let [result (navigate/navigate {:destination {:page "model_browser"}- :memory-atom memory-atom})]- (is (= "/browse/models" (get-in result [:structured-output :path])))))- (testing "database_browser"- (let [result (navigate/navigate {:destination {:page "database_browser"}- :memory-atom memory-atom})]- (is (= "/browse/databases" (get-in result [:structured-output :path])))))- (testing "home"- (let [result (navigate/navigate {:destination {:page "home"}- :memory-atom memory-atom})]- (is (= "/" (get-in result [:structured-output :path])))))- (testing "sql_editor with database_id"- (let [result (navigate/navigate {:destination {:page "sql_editor" :database_id 123}- :memory-atom memory-atom})]- (is (string? (get-in result [:structured-output :path])))- (is (str/starts-with? (get-in result [:structured-output :path]) "/question#")))))))--(deftest entity->path-test- (testing "entity navigation produces correct paths"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (testing "table navigation"- (let [result (navigate/navigate {:destination {:entity_type "table" :entity_id 42}- :memory-atom memory-atom})]- (is (= "/table/42" (get-in result [:structured-output :path])))))- (testing "model navigation"- (let [result (navigate/navigate {:destination {:entity_type "model" :entity_id 100}- :memory-atom memory-atom})]- (is (= "/model/100" (get-in result [:structured-output :path])))))- (testing "question navigation"- (let [result (navigate/navigate {:destination {:entity_type "question" :entity_id 55}- :memory-atom memory-atom})]- (is (= "/question/55" (get-in result [:structured-output :path])))))- (testing "metric navigation"- (let [result (navigate/navigate {:destination {:entity_type "metric" :entity_id 77}- :memory-atom memory-atom})]- (is (= "/metric/77" (get-in result [:structured-output :path])))))- (testing "dashboard navigation"- (let [result (navigate/navigate {:destination {:entity_type "dashboard" :entity_id 88}- :memory-atom memory-atom})]- (is (= "/dashboard/88" (get-in result [:structured-output :path])))))- (testing "database navigation"- (let [result (navigate/navigate {:destination {:entity_type "database" :entity_id 99}- :memory-atom memory-atom})]- (is (= "/browse/databases/99" (get-in result [:structured-output :path])))))- (testing "collection navigation"- (let [result (navigate/navigate {:destination {:entity_type "collection" :entity_id 111}- :memory-atom memory-atom})]- (is (= "/collection/111" (get-in result [:structured-output :path]))))))))--(deftest query-navigation-test- (testing "query navigation resolves from memory"- (let [query {:lib/type :mbql/query- :database 1- :stages [{:lib/type :mbql.stage/mbql- :source-table 10}]}- memory-atom (atom {:state {:queries {"test-query-id" query}- :charts {}}})]- (is (=? {:structured-output {:path #(str/starts-with? % "/question#")}}- (navigate/navigate {:destination {:query_id "test-query-id"}- :memory-atom memory-atom})))))- (testing "query navigation fails for missing query"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"Query not found"- (navigate/navigate {:destination {:query_id "nonexistent"}- :memory-atom memory-atom}))))))--(deftest chart-navigation-test- (testing "chart navigation resolves from memory"- (let [query {:lib/type :mbql/query :database 1 :stages [{:lib/type :mbql.stage/mbql :source-table 10}]}- memory-atom (atom {:state {:queries {"q1" query}- :charts {"chart1" {:chart_id "chart1" :queries [query]- :visualization_settings {:chart-type :bar}}}}})]- (is (=? {:structured-output {:path #(str/starts-with? % "/question#")}}- (navigate/navigate {:destination {:chart_id "chart1"}- :memory-atom memory-atom})))))- (testing "chart navigation falls back to query lookup if chart not found"- (let [query {:lib/type :mbql/query :database 1 :stages [{:lib/type :mbql.stage/mbql :source-table 10}]}- memory-atom (atom {:state {:queries {"chart1" query}- :charts {}}})]- (is (=? {:structured-output {:path #(str/starts-with? % "/question#")}}- (navigate/navigate {:destination {:chart_id "chart1"}- :memory-atom memory-atom})))))- (testing "chart navigation fails for missing chart and query"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"Chart not found"- (navigate/navigate {:destination {:chart_id "nonexistent"}- :memory-atom memory-atom}))))))--(deftest navigate-returns-reactions-test- (testing "navigate returns redirect reaction"- (let [memory-atom (atom {:state {:queries {} :charts {}}})- result (navigate/navigate {:destination {:page "home"}- :memory-atom memory-atom})]- (is (contains? result :reactions))- (is (= 1 (count (:reactions result))))- (let [reaction (first (:reactions result))]- (is (= :metabot.reaction/redirect (:type reaction)))- (is (= "/" (:url reaction)))))))--(deftest navigate-format-message-test- (testing "navigate returns user-friendly messages"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (testing "page navigation message"- (let [result (navigate/navigate {:destination {:page "home"}- :memory-atom memory-atom})]- (is (string? (get-in result [:structured-output :message])))))- (testing "entity navigation message"- (let [result (navigate/navigate {:destination {:entity_type "model" :entity_id 1}- :memory-atom memory-atom})]- (is (string? (get-in result [:structured-output :message]))))))))--(deftest navigate-invalid-destination-test- (testing "navigate fails for invalid destination"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"Invalid destination"- (navigate/navigate {:destination {}- :memory-atom memory-atom}))))))--(deftest navigate-unknown-page-test- (testing "navigate fails for unknown page"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"Unknown page"- (navigate/navigate {:destination {:page "unknown_page"}- :memory-atom memory-atom}))))))--(deftest navigate-unknown-entity-type-test- (testing "navigate fails for unknown entity type"- (let [memory-atom (atom {:state {:queries {} :charts {}}})]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"Unknown entity type"- (navigate/navigate {:destination {:entity_type "unknown" :entity_id 1}- :memory-atom memory-atom}))))))diff --git a/test/metabase/metabot/tools/sql_test.clj b/test/metabase/metabot/tools/sql_test.cljindex bce08bc745c..6d2df4b4419 100644--- a/test/metabase/metabot/tools/sql_test.clj+++ b/test/metabase/metabot/tools/sql_test.clj@@ -145,8 +145,8 @@(is (str/starts-with? instructions "The SQL query has a syntax error"))(is (str/starts-with? output "<result>\nSQL query construction failed.\n</result>\n<instructions>\nThe SQL query has a syntax error")))))))))-(deftest edit-sql-query-inline-viz-test- (testing "edit_sql_query surfaces results inline in the NLQ profile and navigate otherwise"+(deftest edit-sql-query-viz-part-test+ (testing "edit_sql_query emits a generated_entity card unless an open code-editor buffer wins"(mt/test-drivers #{:h2}(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Database {:as db} {:engine :h2}]@@ -154,30 +154,24 @@(let [mp (mt/metadata-provider)query-id "test-inline-q"query (-> (lib/native-query mp "SELECT * FROM t") lib/->legacy-MBQL)- run (fn [{:keys [context profile-id]}]+ run (fn [context](let [memory (atom {:state {:queries {query-id query}}:context context})]- (binding [shared/*memory-atom* memory- shared/*profile-id* profile-id]+ (binding [shared/*memory-atom* memory](agent-sql/edit-sql-query-tool{:query_id query-id:checklist "- [x] checked":edits [{:old_string "SELECT *" :new_string "SELECT id"}]:title "Results"}))))]- (testing "NLQ profile -> a single generated_entity (native) part"- (let [parts (:data-parts (run {:profile-id :nlq}))+ (testing "no code-editor buffer -> a single generated_entity (native) part"+ (let [parts (:data-parts (run {}))entity (:data (first parts))](is (= 1 (count parts)))(is (= "generated_entity" (:data-type (first parts))))(is (= "card" (:type entity)))(is (= :native (get-in entity [:query :query :type])))))- (testing "non-NLQ profile -> a single navigate_to part"- (let [parts (:data-parts (run {:profile-id :sql}))]- (is (= 1 (count parts)))- (is (= "navigate_to" (:data-type (first parts))))))- (testing "an open code-editor buffer wins regardless of profile"- (let [parts (:data-parts (run {:profile-id :nlq- :context {:user_is_viewing [{:type "code_editor"- :buffers [{:id "buf-1"}]}]}}))]+ (testing "an open code-editor buffer wins"+ (let [parts (:data-parts (run {:user_is_viewing [{:type "code_editor"+ :buffers [{:id "buf-1"}]}]}))](is (= 1 (count parts)))(is (= "code_edit" (:data-type (first parts)))))))))))))diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.cljindex b159ae17736..adfd48b87e2 100644--- a/test/metabase/metabot/tools_test.clj+++ b/test/metabase/metabot/tools_test.clj@@ -28,13 +28,13 @@(#'profiles/filter-by-capabilities tool-vars #{})))))(testing "filters out tools that require missing capabilities"(let [tool-vars [#'agent-tools/search-tool- #'agent-tools/navigate-user-tool]+ #'agent-tools/create-sql-query-tool]capabilities #{}result (#'profiles/filter-by-capabilities tool-vars capabilities)](is (= ["search"] (mapv #(:tool-name (meta %)) result)))))(testing "includes tools when capabilities are provided"- (let [tool-vars [#'agent-tools/search-tool #'agent-tools/navigate-user-tool #'agent-tools/create-chart-tool]- capabilities #{:frontend-navigate-user-v1}+ (let [tool-vars [#'agent-tools/search-tool #'agent-tools/create-sql-query-tool #'agent-tools/create-chart-tool]+ capabilities #{:permission-write-sql-queries}result (#'profiles/filter-by-capabilities tool-vars capabilities)](is (= tool-vars result)))))@@ -174,7 +174,6 @@(is (contains? @#'agent-tools/state-dependent-tools "construct_notebook_query"))(is (contains? @#'agent-tools/state-dependent-tools "todo_write"))(is (contains? @#'agent-tools/state-dependent-tools "todo_read"))- (is (contains? @#'agent-tools/state-dependent-tools "navigate_user"))(is (contains? @#'agent-tools/state-dependent-tools "write_transform_sql"))(is (contains? @#'agent-tools/state-dependent-tools "write_transform_python"))(is (contains? @#'agent-tools/state-dependent-tools "create_autogenerated_dashboard"))@@ -225,13 +224,6 @@(is (map? (get wrapped-tools "construct_notebook_query")))(is (fn? (:fn (get wrapped-tools "construct_notebook_query")))))))-(deftest inline-viz-capable-test- (testing "only the nlq profile emits inline visualizations"- (binding [shared/*profile-id* :nlq]- (is (true? (shared/inline-viz-capable?))))- (binding [shared/*profile-id* :sql]- (is (false? (shared/inline-viz-capable?))))))-(deftest tool-schemas-exclude-state-keys-test(testing "create_chart schema does not expose state keys"(let [{:keys [schema]} (meta #'agent-tools/create-chart-tool)