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
Show the SQL editor when useMetabot opens a native question (#77370)
Sébastien0b9e1c0be4ff
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 2d5fd2dee64..c1082932ee7 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@@ -35,6 +35,21 @@ const adHocQuestionPathProducts = buildAdHocPath({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})`),@@ -43,9 +58,10 @@ const buildNavigateToResponse = (path: string) =>type MetabotConsumerProps = {prompts: string[];+ drills?: boolean;};-const MetabotConsumer = ({ prompts }: MetabotConsumerProps) => {+const MetabotConsumer = ({ prompts, drills = false }: MetabotConsumerProps) => {const metabot = useMetabot();if (!metabot) {@@ -79,7 +95,7 @@ const MetabotConsumer = ({ prompts }: MetabotConsumerProps) => {{metabot.CurrentChart && (<div data-testid="metabot-current-chart">- <metabot.CurrentChart />+ <metabot.CurrentChart drills={drills} /></div>)}</div>@@ -120,6 +136,33 @@ describe("scenarios > embedding-sdk > use-metabot hook", () => {});});+ it("opens the SQL editor when Metabot navigates to a native question (EMB-2042)", () => {+ H.mockMetabotResponse({+ statusCode: 200,+ body: buildNavigateToResponse(nativeQuestionPath),+ });++ mountSdkContent(+ <MetabotConsumer prompts={["Open the SQL editor"]} drills />,+ );++ getSdkRoot().within(() => {+ cy.button("Open the SQL editor").click();+ });++ cy.wait("@metabotAgent", { timeout: 20_000 });++ getSdkRoot().within(() => {+ cy.findByTestId("native-query-editor-container")+ .should("be.visible")+ .within(() => {+ // The run button lives inside the editor chrome, confirming the SQL+ // builder actually rendered — not just an empty container.+ cy.icon("play").should("be.visible");+ });+ });+ });+it("swaps CurrentChart when a second navigate_to reaction arrives with a new path", () => {cy.intercept("POST", "/api/metabot/agent-streaming", (request) => {const path =diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsxindex 0cac87f8bd4..0eb4f95a264 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx@@ -2,12 +2,12 @@ import { useMemo } from "react";import type { SdkQuestionProps } from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";-import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";import { deserializeCard, parseHash } from "metabase/common/utils/card";-import * as Urls from "metabase/urls";import type { QuestionMockLocationParameters } from "../SdkQuestion/context";+import { resolveQuestionId } from "./utils";+interface SdkAdHocQuestionProps {questionPath: string; // route path to load a question, e.g. /question/140-best-selling-products - for saved, or /question/xxxxxxx for ad-hoc encoded question configonNavigateBack?: () => void;@@ -104,25 +104,6 @@ export const SdkAdHocQuestion = ({);};-/**- * Derives the questionId from URL slug and deserialized card.- * Returns "new-native" for hash-encoded native cards (e.g. Metabot SQL editor navigation),- * a numeric/string ID for saved questions, or null for new notebook questions.- */-export function resolveQuestionId(- slug: string | undefined,- deserializedCard: { dataset_query?: { type?: string } } | undefined,-): SdkQuestionId | null {- const extractedId = Urls.extractEntityId(slug) ?? null;- if (extractedId !== null) {- return extractedId;- }- if (deserializedCard?.dataset_query?.type === "native") {- return "new-native";- }- return null;-}-/*** This generates route parameters based on the provided URL path* to load the interactive questions. See [use-load-question.ts]diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.unit.spec.tsxindex de2dd63cc94..37ece96c890 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.unit.spec.tsx@@ -1,4 +1,4 @@-import { getQuestionParameters, resolveQuestionId } from "./SdkAdHocQuestion";+import { getQuestionParameters } from "./SdkAdHocQuestion";describe("getQuestionParameters", () => {it("should generate proper URL params for ad-hoc question", () => {@@ -28,39 +28,3 @@ describe("getQuestionParameters", () => {});});});--describe("resolveQuestionId", () => {- it("returns 'new-native' for a native card hash with no slug", () => {- expect(- resolveQuestionId(undefined, {- dataset_query: { type: "native" },- }),- ).toBe("new-native");- });-- it("returns null for a structured (MBQL) card hash with no slug", () => {- expect(- resolveQuestionId(undefined, {- dataset_query: { type: "query" },- }),- ).toBeNull();- });-- it("returns numeric ID for a saved question slug", () => {- expect(- resolveQuestionId("109-days-when-orders-were-added", undefined),- ).toBe(109);- });-- it("returns null when there is no slug and no deserialized card", () => {- expect(resolveQuestionId(undefined, undefined)).toBeNull();- });-- it("numeric slug takes precedence over a native card", () => {- expect(- resolveQuestionId("42-my-question", {- dataset_query: { type: "native" },- }),- ).toBe(42);- });-});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.tsnew file mode 100644index 00000000000..23dc97a1ff6--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.ts@@ -0,0 +1,21 @@+import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";+import * as Urls from "metabase/urls";++/**+ * Derives the questionId from URL slug and deserialized card.+ * Returns "new-native" for hash-encoded native cards (e.g. Metabot SQL editor navigation),+ * a numeric/string ID for saved questions, or null for new notebook questions.+ */+export function resolveQuestionId(+ slug: string | undefined,+ deserializedCard: { dataset_query?: { type?: string } } | undefined,+): SdkQuestionId | null {+ const extractedId = Urls.extractEntityId(slug) ?? null;+ if (extractedId !== null) {+ return extractedId;+ }+ if (deserializedCard?.dataset_query?.type === "native") {+ return "new-native";+ }+ return null;+}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.unit.spec.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.unit.spec.tsnew file mode 100644index 00000000000..644e09a60ea--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils.unit.spec.ts@@ -0,0 +1,37 @@+import { resolveQuestionId } from "./utils";++describe("resolveQuestionId", () => {+ it("returns 'new-native' for a native card hash with no slug", () => {+ expect(+ resolveQuestionId(undefined, {+ dataset_query: { type: "native" },+ }),+ ).toBe("new-native");+ });++ it("returns null for a structured (MBQL) card hash with no slug", () => {+ expect(+ resolveQuestionId(undefined, {+ dataset_query: { type: "query" },+ }),+ ).toBeNull();+ });++ it("returns numeric ID for a saved question slug", () => {+ expect(+ resolveQuestionId("109-days-when-orders-were-added", undefined),+ ).toBe(109);+ });++ it("returns null when there is no slug and no deserialized card", () => {+ expect(resolveQuestionId(undefined, undefined)).toBeNull();+ });++ it("numeric slug takes precedence over a native card", () => {+ expect(+ resolveQuestionId("42-my-question", {+ dataset_query: { type: "native" },+ }),+ ).toBe(42);+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsxindex 9d6cfcce8d7..3d4eb47e131 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx@@ -56,7 +56,6 @@ export function QueryEditorAndResults(props: QueryEditorAndResultsProps) {onChangeUiState={setUiState}onAcceptProposed={handleRunQuery}onRejectProposed={() => {}}- height={hasVisualizeButton ? "calc(100% - 100px)" : undefined}extraEditorButton={hasVisualizeButton && runQuestionQuery && result && !result?.error ? (<VisualizeButtondiff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsxindex fea24578761..5d3aec58c5b 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx@@ -3,6 +3,7 @@ import { useMemo } from "react";import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { resolveQuestionId } from "embedding-sdk-bundle/components/private/SdkAdHocQuestion/utils";import { SdkInternalNavigationBackButton } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton";import {BackButton,@@ -113,16 +114,33 @@ function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {...rest} = props;- const isNewQuestion = questionId === "new" || questionId === "new-native";- const trackingEntityId = questionId != null ? questionId : null;+ const deserializedCard = useMemo(+ () => (query ? deserializeCardFromQuery(query) : undefined),+ [query],+ );++ // When rendered via the `query` prop (Metabot `navigate_to`), no questionId is+ // passed. Derive it from the card so a native query opens the SQL editor,+ // matching SdkAdHocQuestion / MetabotQuestion. See EMB-2042.+ const resolvedQuestionId = query+ ? resolveQuestionId(+ undefined,+ deserializedCard as { dataset_query?: { type?: string } } | undefined,+ )+ : questionId;++ const isNewQuestion =+ resolvedQuestionId === "new" || resolvedQuestionId === "new-native";+ const trackingEntityId =+ resolvedQuestionId != null ? resolvedQuestionId : null;useTrackSdkComponentMount("InteractiveQuestion",trackingEntityId,isNewQuestion? {- id_new: questionId === "new",- id_new_native: questionId === "new-native",+ id_new: resolvedQuestionId === "new",+ id_new_native: resolvedQuestionId === "new-native",is_save_enabled: isSaveEnabled,with_title: title !== false,with_downloads: withDownloads,@@ -136,15 +154,10 @@ function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {},);- const deserializedCard = useMemo(- () => (query ? deserializeCardFromQuery(query) : undefined),- [query],- );-return (<SdkQuestion{...rest}- questionId={questionId}+ questionId={resolvedQuestionId}title={title}withDownloads={withDownloads}isSaveEnabled={isSaveEnabled}diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsxindex d1c4a8fd1a1..abd902f4f7e 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupEnterprisePlugins,} from "__support__/enterprise";import {+ setupAdhocQueryMetadataEndpoint,setupAlertsEndpoints,setupCardEndpoints,setupCardQueryEndpoints,@@ -45,6 +46,7 @@ import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";import type { EmbeddingDataPicker } from "metabase/redux/store/embedding-data-picker";+import { utf8_to_b64url } from "metabase/utils/encoding";import {createMockCard,createMockCardQueryMetadata,@@ -347,3 +349,61 @@ describe('questionId: "new"', () => {expect(withinPopover.getByText("Models")).toBeVisible();});});++// Regression test for EMB-2042: the `useMetabot` hook renders `CurrentChart`+// via `InteractiveQuestionInternal` with a `query` prop (Metabot's+// `navigate_to` path). When that card is native, the SQL editor must open.+describe("native query prop (Metabot SQL editor)", () => {+ const NATIVE_QUERY_PATH = `/question#${utf8_to_b64url(+ JSON.stringify({+ dataset_query: {+ database: TEST_DB.id,+ type: "native",+ native: { query: "" },+ },+ }),+ )}`;++ async function setup() {+ setupDatabasesEndpoints([TEST_DB]);+ setupAdhocQueryMetadataEndpoint(+ createMockCardQueryMetadata({ databases: [TEST_DB] }),+ );+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: 1 })],+ });+ setupSearchEndpoints([]);++ renderWithSDKProviders(+ <InteractiveQuestionInternal query={NATIVE_QUERY_PATH} />,+ {+ componentProviderProps: {+ authConfig: createMockSdkConfig(),+ },+ },+ );++ await waitForLoaderToBeRemoved();+ }++ beforeAll(() => {+ mockGetBoundingClientRect();+ });++ beforeEach(() => {+ setupEnterprisePlugins();+ });++ it("opens the SQL editor when the query is a native card", async () => {+ await setup();++ const editor = await screen.findByTestId("mock-native-query-editor");+ expect(editor).toBeInTheDocument();++ // Assert the SQL builder chrome actually rendered inside the editor, not+ // just an empty container: the data source selector shows the database.+ expect(within(editor).getByTestId("selected-database")).toHaveTextContent(+ TEST_DB.name,+ );+ });+});