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
Remove Explorations dimension anchored blocks (#80554)
Kevin Kelleher8c3ea6f40b6e
diff --git a/e2e/support/helpers/e2e-explorations-helpers.ts b/e2e/support/helpers/e2e-explorations-helpers.tsindex 84877320e53..9bbfd4acb31 100644--- a/e2e/support/helpers/e2e-explorations-helpers.ts+++ b/e2e/support/helpers/e2e-explorations-helpers.ts@@ -39,7 +39,7 @@ export function visitNewExploration(): void {*/export function startManualExploration(): void {cy.findByRole("button", { name: /Manual setup/i }).click();- cy.findByRole("button", { name: /Data/ }).should("be.visible");+ cy.findByRole("button", { name: /Metrics/ }).should("be.visible");}/**@@ -52,35 +52,23 @@ export function selectAllMetricsTab(): void {cy.findByRole("dialog").findByRole("tab", { name: "All" }).click();}-export interface AddMetricsAndDimensionsOptions {+export interface AddMetricsToExplorationOptions {metrics: string[];- dimensions?: string[];}/**- * Pick metrics + dimensions through the "+ Data" picker.+ * Pick metrics through the "+ Metrics" picker.*/-export function addMetricsAndDimensions({+export function addMetricsToExploration({metrics,- dimensions = [],-}: AddMetricsAndDimensionsOptions): void {- cy.findByRole("button", { name: /Data/ }).click();- cy.findByRole("menuitem", { name: "Metrics" }).click();+}: AddMetricsToExplorationOptions): void {+ cy.findByRole("button", { name: /Metrics/ }).click();cy.wait("@getDimensions");selectAllMetricsTab();for (const name of metrics) {cy.findByRole("checkbox", { name }).check({ force: true });}cy.findByRole("button", { name: "Add" }).click();-- if (dimensions.length > 0) {- cy.findByRole("button", { name: /Data/ }).click();- cy.findByRole("menuitem", { name: "Dimensions" }).click();- for (const name of dimensions) {- cy.findByRole("checkbox", { name }).check({ force: true });- }- cy.findByRole("button", { name: "Add" }).click();- }}/**@@ -263,7 +251,6 @@ export function createExplorationViaApi({});const blocks = metrics.map((metric) => ({- type: "metric" as const,metrics: [metric],dimensions,}));diff --git a/e2e/test/scenarios/explorations/explorations.cy.spec.ts b/e2e/test/scenarios/explorations/explorations.cy.spec.tsindex de249fb5698..553fe400fe6 100644--- a/e2e/test/scenarios/explorations/explorations.cy.spec.ts+++ b/e2e/test/scenarios/explorations/explorations.cy.spec.ts@@ -124,7 +124,7 @@ describe("scenarios > explorations > new research > manual flow", () => {// instead of leaving the research flow (UXW-4832).cy.location("pathname").should("eq", "/question/research/plan");- H.addMetricsAndDimensions({+ H.addMetricsToExploration({metrics: [ORDERS_COUNT_METRIC_NAME],});@@ -188,9 +188,8 @@ describe("scenarios > explorations > new research > manual flow", () => {H.visitNewExploration();H.startManualExploration();- // --- "+ Data" → Metrics modal search ---- cy.findByRole("button", { name: /Data/ }).click();- cy.findByRole("menuitem", { name: "Metrics" }).click();+ // --- "+ Metrics" modal search ---+ cy.findByRole("button", { name: /Metrics/ }).click();// Seeded names are "Count of orders" + "Count of orders over time".cy.wait("@getDimensions");// Seeded metrics aren't in the library; switch off the default Library tab.@@ -300,7 +299,7 @@ describe("scenarios > explorations > new research > metabot flow", () => {result: {metrics: [firstMetric],dimension_groups: [interestingGroup],- groups: [{ anchor: "metric", metric_id: firstMetric.id }],+ groups: [{ metric_id: firstMetric.id }],},},{diff --git a/frontend/src/metabase-types/api/exploration.ts b/frontend/src/metabase-types/api/exploration.tsindex 418492fbe16..2e711b8c723 100644--- a/frontend/src/metabase-types/api/exploration.ts+++ b/frontend/src/metabase-types/api/exploration.ts@@ -35,23 +35,14 @@ export type GetExplorationDataResponse = {dimension_groups: ExplorationDimensionGroup[];};-// One group Metabot authored via the `add_research_groups` tool: either a metric sliced by chosen-// dimensions, or a dimension slicing a chosen set of (by default, all) related metrics.-export type ResearchGroupSpec =- | {- anchor: "metric";- metric_id: number;- dimension_ids?: DimensionId[];- // When true, slice the metric by exactly `dimension_ids` instead of adding them on top of- // the automatically-selected interesting dimensions.- replace_default_dimensions?: boolean;- }- | {- anchor: "dimension";- dimension_id: DimensionId;- // When present, include only these metrics instead of every related metric.- metric_ids?: number[];- };+// One group Metabot authored via the `add_research_groups` tool+export type ResearchGroupSpec = {+ metric_id: number;+ dimension_ids?: DimensionId[];+ // When true, slice the metric by exactly `dimension_ids` instead of adding them on top of+ // the automatically-selected interesting dimensions.+ replace_default_dimensions?: boolean;+};// Result of the `add_research_groups` tool: the picker hydration for the referenced metrics, plus// the validated group specs the chat handler turns into picker blocks.@@ -66,19 +57,11 @@ export type ResearchPlanMetricRef = { id: number; name: string };export type ResearchPlanDimensionRef = { id: DimensionId; name: string };export type ResearchPlanTimelineRef = { id: TimelineId; name: string };-export type ResearchPlanGroup =- | {- block_id: string;- anchor: "metric";- metric: ResearchPlanMetricRef;- dimensions: ResearchPlanDimensionRef[];- }- | {- block_id: string;- anchor: "dimension";- dimension: ResearchPlanDimensionRef;- metrics: ResearchPlanMetricRef[];- };+export type ResearchPlanGroup = {+ block_id: string;+ metric: ResearchPlanMetricRef;+ dimensions: ResearchPlanDimensionRef[];+};export type ResearchPlanContext = {name: string;@@ -88,12 +71,10 @@ export type ResearchPlanContext = {// Result of the `remove_from_research_plan` tool: the validated ids the front-end removes from the// draft plan. The tool is pure-echo (no DB), so this just mirrors what the agent asked to remove.-// `block_ids` drop whole groups; `members` deselect metrics/dimensions within a group (emptying a-// group drops it).+// `block_ids` drop whole groups; `members` deselect dimensions within a group (emptying a group drops it).export type RemoveFromResearchPlanMember = {block_id: string;- metric_ids?: number[];- dimension_ids?: DimensionId[];+ dimension_ids: DimensionId[];};export type RemoveFromResearchPlanResponse = {@@ -126,7 +107,6 @@ export interface CreateExplorationRequest {collection_id?: number | null;timeline_ids?: TimelineId[];blocks: {- type: "metric" | "dimension";metrics: ExplorationMetricSelection[];dimensions: ExplorationDimensionSelection[];}[];@@ -292,11 +272,8 @@ export interface ExplorationPageNode {hidden?: boolean;}-export type ExplorationBlockNodeType = "metric" | "dimension";-export interface ExplorationBlockNode {id: number;- type: ExplorationBlockNodeType;name: string | null;position: number;pages: ExplorationPageNode[];diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.tsindex 4f03f1e7dad..698f6e0082f 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts@@ -593,42 +593,41 @@ describe("getExplorationSidebarTree sorting", () => {});describe("getExplorationSidebarTree passes BE-computed names through", () => {- const DIM_BLOCK_ID = 30;+ const BLOCK_ID = 30;it("uses the block's name for the heading and each page's name for sub-items", () => {- const signups = createQuery({+ const country = createQuery({id: 1,- name: "Signups",+ name: "Country",status: "done",interestingness_score: 0.9,});- const revenue = createQuery({+ const plan = createQuery({id: 2,- name: "Revenue",+ name: "Plan",status: "done",interestingness_score: 0.8,});const tree = getAllTabExplorationSidebarTree({- queries: [signups, revenue],+ queries: [country, plan],blocks: [createBlock({- id: DIM_BLOCK_ID,- type: "dimension",- name: "By Country",+ id: BLOCK_ID,+ name: "Revenue",position: 0,pages: [createPage({id: 10,- name: "Signups",+ name: "Country",position: 0,- query_ids: [signups.id],+ query_ids: [country.id],}),createPage({id: 11,- name: "Revenue",+ name: "Plan",position: 1,- query_ids: [revenue.id],+ query_ids: [plan.id],}),],}),@@ -636,10 +635,10 @@ describe("getExplorationSidebarTree passes BE-computed names through", () => {});const heading = getMetricHeadings(tree)[0];- expect(heading?.name).toBe("By Country");+ expect(heading?.name).toBe("Revenue");expect((heading?.children ?? []).map((child) => child.name)).toEqual([- "Signups",- "Revenue",+ "Country",+ "Plan",]);});});diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsxindex da234322841..c6265f4f6a2 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx@@ -25,7 +25,6 @@ import { LEGEND_ITEM_FONT_SIZE } from "metabase/visualizations/components/legendimport type { ClickActionsMode, OnBrush } from "metabase/visualizations/types";import { type HighlightedObject, isCartesianChart } from "metabase/viz-core";import type {- ExplorationBlockNodeType,ExplorationId,ExplorationPageNode,ExplorationQuery,@@ -59,7 +58,6 @@ interface ExplorationGroupVisualizationProps {explorationId: ExplorationId;page: ExplorationPageNode;queries: ExplorationQuery[];- blockType: ExplorationBlockNodeType;exploreFilters?: HydratedExplorationExploreFilter[] | null;availableTimelines: Timeline[];selectedTimelineId: TimelineId | null;@@ -150,7 +148,6 @@ function ExplorationGroupVisualizationChart({explorationId,page,queries,- blockType,exploreFilters,availableTimelines,selectedTimelineId,@@ -178,7 +175,6 @@ function ExplorationGroupVisualizationChart({const clickActionsMode = useExplorationClickActionsMode({explorationId,pageId: page.id,- blockType,queryType: queries[0].query_type,commentDrafts,setCommentDrafts,diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsxindex ab8aa857222..9ea64ba51dd 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx@@ -10,7 +10,6 @@ import { registerVisualizations } from "metabase/visualizations/register";import type { ClickObject } from "metabase/visualizations/types";import type {Dataset,- ExplorationBlockNodeType,ExplorationPageNode,ExplorationQuery,HydratedExplorationExploreFilter,@@ -221,7 +220,6 @@ interface SetupOpts {isCommentsSidebarOpen?: boolean;wasCommentsSidebarOpen?: boolean;onCloseCommentsSidebar?: () => void;- blockType?: ExplorationBlockNodeType;page?: ExplorationPageNode;exploreFilters?: HydratedExplorationExploreFilter[] | null;}@@ -237,7 +235,6 @@ function setup({isCommentsSidebarOpen = false,wasCommentsSidebarOpen = false,onCloseCommentsSidebar = jest.fn(),- blockType = "metric",page: pageOverride,exploreFilters,}: SetupOpts) {@@ -267,7 +264,6 @@ function setup({query_ids: queries.map((q) => q.id),}}queries={queries}- blockType={blockType}exploreFilters={exploreFilters}availableTimelines={availableTimelines}selectedTimelineId={selectedTimelineId}@@ -589,7 +585,6 @@ describe("ExplorationGroupVisualization", () => {explorationId={1}page={{ ...page, query_ids: [101] }}queries={queries}- blockType="metric"availableTimelines={[]}selectedTimelineId={null}onSelectTimelineId={jest.fn()}@@ -780,23 +775,14 @@ describe("ExplorationGroupVisualization", () => {expect(typeof lastVisualizationProps?.onBrush).toBe("function");});- it("includes explore further for eligible metric blocks", () => {- setup({ ...timeseriesSetup, blockType: "metric" });+ it("includes explore further", () => {+ setup({ ...timeseriesSetup });expect(screen.getByTestId("visualization-stub")).toHaveAttribute("data-action-names","explore-further,add-comment",);});-- it("omits explore further for ineligible dimension blocks", () => {- setup({ ...timeseriesSetup, blockType: "dimension" });-- expect(screen.getByTestId("visualization-stub")).toHaveAttribute(- "data-action-names",- "add-comment",- );- });});describe("cartesian combined chart", () => {diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.tsindex 4305ec5f825..37966453f9d 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts@@ -45,7 +45,6 @@ import type {Dataset,DatasetColumn,DateTimeAbsoluteUnit,- ExplorationBlockNodeType,ExplorationExploreFilter,ExplorationQuery,ExplorationQueryId,@@ -619,15 +618,9 @@ export function getExploreFurtherFilters(export function canExploreFurther(clicked: ClickObject,- blockType?: ExplorationBlockNodeType,queryType?: ExplorationQueryType,): boolean {- if (blockType == null || queryType == null) {- return false;- }- // disable for dimension blocks - every query in a dimension block is cut by the same dimension- // so filtering on a single dimension value doesn't provide a new view of the data- if (blockType === "dimension") {+ if (queryType == null) {return false;}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.tsindex 08022348e06..ece26efac17 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts@@ -176,27 +176,16 @@ function makeClickObject(}describe("canExploreFurther", () => {- it("returns false when blockType or queryType is omitted", () => {+ it("returns false when queryType is omitted", () => {expect(canExploreFurther(makeClickObject())).toBe(false);- expect(canExploreFurther(makeClickObject(), "metric")).toBe(false);});it("returns false when there are no dimensions", () => {expect(- canExploreFurther(- makeClickObject({ dimensions: [] }),- "metric",- "default",- ),+ canExploreFurther(makeClickObject({ dimensions: [] }), "default"),).toBe(false);});- it("returns false for dimension blocks", () => {- expect(canExploreFurther(makeClickObject(), "dimension", "default")).toBe(- false,- );- });-it("returns false for top-n-other clicks on the Other bucket", () => {expect(canExploreFurther(@@ -211,16 +200,13 @@ describe("canExploreFurther", () => {},],}),- "metric","top-n-other",),).toBe(false);});it("returns true for eligible metric-block clicks with real dimension values", () => {- expect(canExploreFurther(makeClickObject(), "metric", "default")).toBe(- true,- );+ expect(canExploreFurther(makeClickObject(), "default")).toBe(true);});it("returns true when multiple dimensions are present", () => {@@ -241,7 +227,6 @@ describe("canExploreFurther", () => {},],}),- "metric","default",),).toBe(true);@@ -263,33 +248,10 @@ describe("canExploreFurther", () => {event: new MouseEvent("click"),settings: {},},- "metric","default",),).toBe(true);});-- it("returns false for brush clicks on dimension blocks", () => {- expect(- canExploreFurther(- {- brushRange: {- type: "numeric",- start: 1,- end: 4,- },- column: createMockColumn({- name: "PRICE",- field_ref: ["field", 21, null],- }),- event: new MouseEvent("click"),- settings: {},- },- "dimension",- "default",- ),- ).toBe(false);- });});describe("getExploreFurtherFilters", () => {@@ -500,7 +462,7 @@ describe("getExploreFurtherFilters", () => {};expect(getExploreFurtherFilters(clicked)).toEqual([]);- expect(canExploreFurther(clicked, "metric", "default")).toBe(false);+ expect(canExploreFurther(clicked, "default")).toBe(false);});it("projects a numeric brush range into a between explore filter", () => {diff --git a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsxindex 55392d1c396..7f9d0b0546b 100644--- a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx@@ -10,10 +10,7 @@ import {} from "metabase/explorations/analytics";import type { ExplorationSelection } from "metabase/explorations/hooks";import { selectionToResearchPlanContext } from "metabase/explorations/research-plan-context";-import {- groupMetricsByDimension,- indexDimensionsById,-} from "metabase/explorations/utils";+import { indexDimensionsById } from "metabase/explorations/utils";import { AIProviderConfigurationModal } from "metabase/metabot/components/AIProviderConfigurationModal";import { AIProviderConfigurationNotice } from "metabase/metabot/components/AIProviderConfigurationNotice";import { MetabotChatEditor } from "metabase/metabot/components/MetabotChat/MetabotChatEditor";@@ -53,12 +50,11 @@ export interface NewExplorationChatProps {export function NewExplorationChat({ selection }: NewExplorationChatProps) {const {addMetric,- addDimension,setName,addTimelinesById,removeTimelinesById,removeBlock,- removeBlockMembers,+ removeBlockDimensions,blocks,timelines,name,@@ -112,9 +108,6 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {const trackMetricsEdited = once(() =>trackExplorationPlanEdited("agent", "metrics"),);- const trackDimensionsEdited = once(() =>- trackExplorationPlanEdited("agent", "dimensions"),- );try {for (const message of messages) {@@ -125,40 +118,18 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {const metricsById = new Map(metrics.map((m) => [m.id, m] as const));const dimensionsById = indexDimensionsById(dimension_groups);- const metricsByDimension = groupMetricsByDimension(metrics);- // Any dimension id (not just the head) -> its dimension group, so a dimension-anchored- // group authored on any member resolves to the whole group, like the manual picker.- const groupByDimensionId = new Map(- dimension_groups.flatMap((group) =>- group.dimensions.map((d) => [d.id, group] as const),- ),- );for (const group of groups) {- if (group.anchor === "metric") {- const metric = metricsById.get(group.metric_id);- if (metric) {- addMetric(metric, {- dimensionsById,- additionalSelectedDimensionIds: new Set(- group.dimension_ids ?? [],- ),- replace: group.replace_default_dimensions,- });- trackMetricsEdited();- }- } else {- const dimensionGroup = groupByDimensionId.get(group.dimension_id);- if (dimensionGroup?.dimensions[0]) {- addDimension(dimensionGroup.dimensions[0], {- group: dimensionGroup,- metricsByDimension,- selectedMetricIds: group.metric_ids- ? new Set(group.metric_ids)- : undefined,- });- trackDimensionsEdited();- }+ const metric = metricsById.get(group.metric_id);+ if (metric) {+ addMetric(metric, {+ dimensionsById,+ additionalSelectedDimensionIds: new Set(+ group.dimension_ids ?? [],+ ),+ replace: group.replace_default_dimensions,+ });+ trackMetricsEdited();}}}@@ -171,7 +142,7 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {});}},- [addMetric, addDimension, sendToast],+ [addMetric, sendToast],);const handleRemoveFromResearchPlanToolCallMessages = useCallback(@@ -194,23 +165,11 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {) as RemoveFromResearchPlanResponse;for (const blockId of block_ids ?? []) {removeBlock(blockId);- if (blockId.startsWith("metric:")) {- trackMetricsEdited();- } else if (blockId.startsWith("dim:")) {- trackDimensionsEdited();- }+ trackMetricsEdited();}for (const member of members ?? []) {- removeBlockMembers(member.block_id, {- metricIds: member.metric_ids,- dimensionIds: member.dimension_ids,- });- if (member.metric_ids?.length) {- trackMetricsEdited();- }- if (member.dimension_ids?.length) {- trackDimensionsEdited();- }+ removeBlockDimensions(member.block_id, member.dimension_ids);+ trackDimensionsEdited();}if (timeline_ids?.length) {removeTimelinesById(timeline_ids);@@ -226,7 +185,7 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {});}},- [removeBlock, removeBlockMembers, removeTimelinesById, sendToast],+ [removeBlock, removeBlockDimensions, removeTimelinesById, sendToast],);const handleSetExplorationNameToolCallMessages = useCallback(diff --git a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsxindex d17fe2a45b8..8fc96ff35dc 100644--- a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx@@ -138,14 +138,13 @@ const addResearchGroupsResponse: AddResearchGroupsResponse = {},],groups: [- // metric-anchored: Revenue with an explicitly-chosen dimension{- anchor: "metric",metric_id: metricRevenue.id,dimension_ids: [revenueDateDimension.id],},- // dimension-anchored: slice every related metric by Customer Segment- { anchor: "dimension", dimension_id: customerSegmentDimension.id },+ {+ metric_id: metricChurn.id,+ },],};@@ -174,7 +173,7 @@ const removeFromResearchPlanToolCallMessage: MetabotDebugToolCallMessage = {name: "remove_from_research_plan",status: "ended",result: JSON.stringify({- block_ids: ["metric:1", "dim:customer.segment"],+ block_ids: ["metric:1", "metric:2"],}),};@@ -303,7 +302,7 @@ describe("NewExplorationChat", () => {});});- it("adds metric- and dimension-anchored groups from an add_research_groups tool call response", async () => {+ it("adds groups from an add_research_groups tool call response", async () => {const { selection, rerender } = setup();rerender({@@ -320,7 +319,6 @@ describe("NewExplorationChat", () => {});expect(selection.addMetric).not.toHaveBeenCalled();- expect(selection.addDimension).not.toHaveBeenCalled();rerender({messages: [@@ -332,22 +330,29 @@ describe("NewExplorationChat", () => {isDoingScience: false,});- // metric-anchored group -> addMetric, carrying the explicitly-chosen dimension idsawait waitFor(() => {- expect(selection.addMetric).toHaveBeenCalledTimes(1);+ expect(selection.addMetric).toHaveBeenCalledTimes(2);});expect(selection.addMetric).toHaveBeenCalledWith(expect.objectContaining({id: metricRevenue.id,name: metricRevenue.name,}),- {+ expect.objectContaining({dimensionsById: expect.any(Map),additionalSelectedDimensionIds: new Set([revenueDateDimension.id]),- },+ }),+ );+ expect(selection.addMetric).toHaveBeenCalledWith(+ expect.objectContaining({+ id: metricChurn.id,+ name: metricChurn.name,+ }),+ expect.objectContaining({+ additionalSelectedDimensionIds: new Set(),+ }),);- // The dimensionsById map should contain every dimension from the groups.const { dimensionsById } = jest.mocked(selection.addMetric).mock.calls[0][1];expect(dimensionsById.size).toBe(3);@@ -355,24 +360,14 @@ describe("NewExplorationChat", () => {revenueDateDimension,);- // dimension-anchored group -> addDimension with the resolved dimension group- expect(selection.addDimension).toHaveBeenCalledTimes(1);- expect(selection.addDimension).toHaveBeenCalledWith(- expect.objectContaining({ id: customerSegmentDimension.id }),- {- group: customerSegmentGroup,- metricsByDimension: expect.any(Map),- },- );-expect(trackExplorationPlanEdited).toHaveBeenCalledWith("agent", "metrics");- expect(trackExplorationPlanEdited).toHaveBeenCalledWith(+ expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith("agent","dimensions",);});- it("forwards replace_default_dimensions and metric_ids to the selection mutators", async () => {+ it("forwards replace_default_dimensions to addMetric", async () => {const { selection, rerender } = setup();const message: MetabotDebugToolCallMessage = {@@ -382,16 +377,10 @@ describe("NewExplorationChat", () => {...addResearchGroupsResponse,groups: [{- anchor: "metric",metric_id: metricRevenue.id,dimension_ids: [revenueDateDimension.id],replace_default_dimensions: true,},- {- anchor: "dimension",- dimension_id: customerSegmentDimension.id,- metric_ids: [metricRevenue.id],- },],}),};@@ -405,18 +394,10 @@ describe("NewExplorationChat", () => {await waitFor(() => {expect(selection.addMetric).toHaveBeenCalled();});- // metric anchor forwards the replace flagexpect(selection.addMetric).toHaveBeenCalledWith(expect.objectContaining({ id: metricRevenue.id }),expect.objectContaining({ replace: true }),);- // dimension anchor forwards the curated metric subset- expect(selection.addDimension).toHaveBeenCalledWith(- expect.objectContaining({ id: customerSegmentDimension.id }),- expect.objectContaining({- selectedMetricIds: new Set([metricRevenue.id]),- }),- );});it("sets the exploration name from a set name tool call response", async () => {@@ -462,10 +443,10 @@ describe("NewExplorationChat", () => {await waitFor(() => {expect(selection.removeBlock).toHaveBeenCalledWith("metric:1");});- expect(selection.removeBlock).toHaveBeenCalledWith("dim:customer.segment");+ expect(selection.removeBlock).toHaveBeenCalledWith("metric:2");expect(selection.removeBlock).toHaveBeenCalledTimes(2);expect(trackExplorationPlanEdited).toHaveBeenCalledWith("agent", "metrics");- expect(trackExplorationPlanEdited).toHaveBeenCalledWith(+ expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith("agent","dimensions",);@@ -487,7 +468,6 @@ describe("NewExplorationChat", () => {result: JSON.stringify({members: [{ block_id: "metric:1", dimension_ids: ["revenue.created_at"] },- { block_id: "dim:customer.segment", metric_ids: [2] },],}),};@@ -498,21 +478,19 @@ describe("NewExplorationChat", () => {});await waitFor(() => {- expect(selection.removeBlockMembers).toHaveBeenCalledWith("metric:1", {- metricIds: undefined,- dimensionIds: ["revenue.created_at"],- });+ expect(selection.removeBlockDimensions).toHaveBeenCalledWith("metric:1", [+ "revenue.created_at",+ ]);});- expect(selection.removeBlockMembers).toHaveBeenCalledWith(- "dim:customer.segment",- { metricIds: [2], dimensionIds: undefined },- );expect(selection.removeBlock).not.toHaveBeenCalled();- expect(trackExplorationPlanEdited).toHaveBeenCalledWith("agent", "metrics");expect(trackExplorationPlanEdited).toHaveBeenCalledWith("agent","dimensions",);+ expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith(+ "agent",+ "metrics",+ );expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith("agent","timelines",diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/EntityBlock.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/EntityBlock.tsxindex 1e8301dad39..2d84fcc66fd 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/EntityBlock.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationData/EntityBlock.tsx@@ -1,7 +1,6 @@import { t } from "ttag";-import { getDimensionIcon } from "metabase/common/utils/columns";-import type { DimensionBlock, MetricBlock } from "metabase/explorations/hooks";+import type { ExplorationBlock } from "metabase/explorations/hooks";import {ActionIcon,Box,@@ -11,12 +10,7 @@ import {Stack,Text,} from "metabase/ui";-import * as LibMetric from "metabase-lib/metric/core";-import type {- DimensionId,- ExplorationMetric,- IconName,-} from "metabase-types/api";+import type { DimensionId, IconName } from "metabase-types/api";import S from "./NewExplorationData.module.css";import { SelectedPills, TogglePill } from "./Pills";@@ -98,7 +92,7 @@ export function EntityBlock({}interface MetricBlockItemProps {- block: MetricBlock;+ block: ExplorationBlock;expanded: boolean;disabled: boolean;onToggleExpand: () => void;@@ -155,67 +149,3 @@ export function MetricBlockItem({</EntityBlock>);}--interface DimensionBlockItemProps {- block: DimensionBlock;- expanded: boolean;- disabled: boolean;- onToggleExpand: () => void;- onRemoveBlock: () => void;- onToggleMetric: (metricId: ExplorationMetric["id"]) => void;-}--export function DimensionBlockItem({- block,- expanded,- disabled,- onToggleExpand,- onRemoveBlock,- onToggleMetric,-}: DimensionBlockItemProps) {- const iconName = getDimensionIcon(- LibMetric.fromMetricDimension(block.dimension),- );- const selectedPills = block.metrics- .filter((m) => block.selectedMetricIds.has(m.id))- .map((m) => ({ label: m.name }));-- return (- <EntityBlock- iconName={iconName}- iconLabel={t`Dimension`}- title={formatDimensionLabel(block.dimension)}- expanded={expanded}- disabled={disabled}- onToggleExpand={onToggleExpand}- onRemoveBlock={onRemoveBlock}- >- {expanded ? (- <Stack gap="md">- <Text size="sm" c="text-secondary">- {t`Modify which metrics to look at for this dimension`}- </Text>- {block.metrics.length === 0 ? (- <Text size="sm" c="text-secondary">- {t`No related metrics.`}- </Text>- ) : (- <Group align="center" gap="sm" wrap="wrap">- {block.metrics.map((metric) => (- <TogglePill- key={metric.id}- label={metric.name}- selected={block.selectedMetricIds.has(metric.id)}- disabled={disabled}- onToggle={() => onToggleMetric(metric.id)}- />- ))}- </Group>- )}- </Stack>- ) : (- <SelectedPills pills={selectedPills} />- )}- </EntityBlock>- );-}diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsxindex a72fcf32cc9..b58166e6169 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx@@ -14,7 +14,6 @@ import type {ExplorationBlock,ExplorationSelection,} from "metabase/explorations/hooks";-import { isMetricBlock } from "metabase/explorations/hooks";import { useMetabotAgent } from "metabase/metabot/hooks";import { useNavigate } from "metabase/router";import {@@ -23,7 +22,6 @@ import {Center,Group,Icon,- Menu,Stack,Switch,Title,@@ -39,17 +37,13 @@ import type {import { EXPLORATIONS_AGENT_ID } from "../NewExplorationChat/NewExplorationChat";-import { DimensionBlockItem, MetricBlockItem } from "./EntityBlock";+import { MetricBlockItem } from "./EntityBlock";import S from "./NewExplorationData.module.css";import { SelectedTimelinePills } from "./Pills";import { ResearchModeIntro } from "./ResearchModeIntro";-import {- AddDimensionsModal,- AddMetricsModal,- AddTimelinesModal,-} from "./modals";+import { AddMetricsModal, AddTimelinesModal } from "./modals";-type ActiveModal = "metrics" | "dimensions" | "events" | null;+type ActiveModal = "metrics" | "events" | null;export interface NewExplorationDataProps {selection: ExplorationSelection;@@ -72,21 +66,11 @@ function dimensionToSelection(d: MetricDimension) {}function blockToSelection(block: ExplorationBlock) {- if (isMetricBlock(block)) {- return {- type: "metric" as const,- metrics: [metricToSelection(block.metric)],- dimensions: block.dimensions- .filter((d) => block.selectedDimensionIds.has(d.id))- .map(dimensionToSelection),- };- }return {- type: "dimension" as const,- metrics: block.metrics- .filter((m) => block.selectedMetricIds.has(m.id))- .map(metricToSelection),- dimensions: block.groupDimensions.map(dimensionToSelection),+ metrics: [metricToSelection(block.metric)],+ dimensions: block.dimensions+ .filter((d) => block.selectedDimensionIds.has(d.id))+ .map(dimensionToSelection),};}@@ -117,7 +101,6 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {collection,removeBlock,toggleDimensionSelected,- toggleMetricSelected,removeTimelinesById,} = selection;const navigate = useNavigate();@@ -156,9 +139,9 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {}, []);const handleRemoveBlock = useCallback(- (blockId: string, type: "metrics" | "dimensions") => {+ (blockId: string) => {removeBlock(blockId);- trackExplorationPlanEdited("manual", type);+ trackExplorationPlanEdited("manual", "metrics");setExpandedIds((prev) => {if (prev.has(blockId)) {const next = new Set(prev);@@ -226,27 +209,16 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {><Group justify="space-between" align="center" flex="none"><Title order={3} fs="1rem" lh={1.4}>{t`Research plan`}</Title>- <Group gap="xs">- <Menu position="bottom-end">- <Menu.Target>- <Button- variant="outline"- color="text-primary"- bd="1px solid text-tertiary"- size="sm"- disabled={isManualDataPickingDisabled}- >{t`+ Data`}</Button>- </Menu.Target>- <Menu.Dropdown>- <Menu.Item onClick={() => setActiveModal("metrics")}>- {t`Metrics`}- </Menu.Item>- <Menu.Item onClick={() => setActiveModal("dimensions")}>- {t`Dimensions`}- </Menu.Item>- </Menu.Dropdown>- </Menu>- </Group>+ <Button+ variant="outline"+ color="text-primary"+ bd="1px solid text-tertiary"+ size="sm"+ disabled={isManualDataPickingDisabled}+ onClick={() => setActiveModal("metrics")}+ >+ {t`+ Metrics`}+ </Button></Group><Group gap="xs" data-testid="selected-timelines-container">@@ -296,37 +268,20 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {</Center>) : (<Stack gap="md" mb="lg">- {blocks.map((block) =>- isMetricBlock(block) ? (- <MetricBlockItem- key={block.id}- block={block}- expanded={getIsExpanded(block.id)}- disabled={isManualDataPickingDisabled}- onToggleExpand={() => toggleExpanded(block.id)}- onRemoveBlock={() => handleRemoveBlock(block.id, "metrics")}- onToggleDimension={(dimensionId) => {- toggleDimensionSelected(block.id, dimensionId);- trackExplorationPlanEdited("manual", "dimensions");- }}- />- ) : (- <DimensionBlockItem- key={block.id}- block={block}- expanded={getIsExpanded(block.id)}- disabled={isManualDataPickingDisabled}- onToggleExpand={() => toggleExpanded(block.id)}- onRemoveBlock={() =>- handleRemoveBlock(block.id, "dimensions")- }- onToggleMetric={(metricId) => {- toggleMetricSelected(block.id, metricId);- trackExplorationPlanEdited("manual", "metrics");- }}- />- ),- )}+ {blocks.map((block) => (+ <MetricBlockItem+ key={block.id}+ block={block}+ expanded={getIsExpanded(block.id)}+ disabled={isManualDataPickingDisabled}+ onToggleExpand={() => toggleExpanded(block.id)}+ onRemoveBlock={() => handleRemoveBlock(block.id)}+ onToggleDimension={(dimensionId) => {+ toggleDimensionSelected(block.id, dimensionId);+ trackExplorationPlanEdited("manual", "dimensions");+ }}+ />+ ))}</Stack>)}</Box>@@ -357,11 +312,6 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {onClose={() => setActiveModal(null)}selection={selection}/>- <AddDimensionsModal- opened={activeModal === "dimensions"}- onClose={() => setActiveModal(null)}- selection={selection}- /><AddTimelinesModalopened={activeModal === "events"}onClose={() => setActiveModal(null)}@@ -372,8 +322,5 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {}function isNonEmptyBlock(block: ExplorationBlock): boolean {- if (isMetricBlock(block)) {- return block.selectedDimensionIds.size > 0;- }- return block.selectedMetricIds.size > 0;+ return block.selectedDimensionIds.size > 0;}diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsxindex d7b64da36af..e27965780a1 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx@@ -8,8 +8,7 @@ import type { ExplorationBlock } from "metabase/explorations/hooks";import {createExploration,makeMockSelection,- mockDimensionBlock,- mockMetricBlock,+ mockExplorationBlock,} from "metabase/explorations/test-utils";import { useMetabotAgent } from "metabase/metabot/hooks";import type { ExplorationMetric, Timeline } from "metabase-types/api";@@ -103,11 +102,13 @@ describe("NewExplorationData (Research plan)", () => {});describe("empty state", () => {- it("renders the header + the +Data / +Events affordances, with the Start research CTA disabled", () => {+ it("renders the header + the + Metrics / + Events affordances, with the Start research CTA disabled", () => {setup();expect(screen.getByText("Research plan")).toBeInTheDocument();- expect(screen.getByRole("button", { name: /Data/ })).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Metrics/ }),+ ).toBeInTheDocument();expect(screen.getByRole("button", { name: /Events/ }),).toBeInTheDocument();@@ -116,11 +117,10 @@ describe("NewExplorationData (Research plan)", () => {).toBeDisabled();});- it("opens the metrics modal from the +Data menu", async () => {+ it("opens the metrics modal from the + Metrics button", async () => {setup();- await userEvent.click(screen.getByRole("button", { name: /Data/ }));- await userEvent.click(screen.getByRole("menuitem", { name: "Metrics" }));+ await userEvent.click(screen.getByRole("button", { name: /Metrics/ }));expect(await screen.findByText("Add metrics to your research plan"),@@ -128,10 +128,10 @@ describe("NewExplorationData (Research plan)", () => {});});- describe("metric block", () => {+ describe("block", () => {it("renders collapsed by default, showing selected dimensions as plain (non-toggle) pills", () => {setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt, dimPlan])],+ blocks: [mockExplorationBlock(revenueMetric, [dimCreatedAt, dimPlan])],});expect(screen.getByText("Revenue")).toBeInTheDocument();@@ -146,7 +146,7 @@ describe("NewExplorationData (Research plan)", () => {it("expands a collapsed block when its (read-only) body is clicked", async () => {setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt, dimPlan])],+ blocks: [mockExplorationBlock(revenueMetric, [dimCreatedAt, dimPlan])],});// Collapsed: the dimension is a plain pill, not a toggle button.@@ -164,7 +164,7 @@ describe("NewExplorationData (Research plan)", () => {it("expanding groups dimensions into source sections of toggle pills", async () => {setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt, dimPlan])],+ blocks: [mockExplorationBlock(revenueMetric, [dimCreatedAt, dimPlan])],});await userEvent.click(screen.getByRole("button", { name: "Expand" }));@@ -179,7 +179,7 @@ describe("NewExplorationData (Research plan)", () => {it("toggling a dimension pill calls toggleDimensionSelected", async () => {const { selection } = setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt, dimPlan])],+ blocks: [mockExplorationBlock(revenueMetric, [dimCreatedAt, dimPlan])],});await userEvent.click(screen.getByRole("button", { name: "Expand" }));@@ -202,7 +202,7 @@ describe("NewExplorationData (Research plan)", () => {it("clicking the area's remove button calls selection.removeBlock", async () => {const { selection } = setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt])],+ blocks: [mockExplorationBlock(revenueMetric, [dimCreatedAt])],});await userEvent.click(screen.getByLabelText("Remove area"));@@ -220,67 +220,6 @@ describe("NewExplorationData (Research plan)", () => {});});- describe("dimension block", () => {- it("expanding renders related metrics as toggle pills", async () => {- setup({- blocks: [mockDimensionBlock(dimPlan, [revenueMetric, churnMetric])],- });-- await userEvent.click(screen.getByRole("button", { name: "Expand" }));-- expect(screen.getByRole("button", { name: "Revenue" })).toHaveAttribute(- "aria-pressed",- "true",- );- expect(screen.getByRole("button", { name: "Churn" })).toHaveAttribute(- "aria-pressed",- "true",- );- });-- it("toggling a metric pill calls toggleMetricSelected", async () => {- const { selection } = setup({- blocks: [mockDimensionBlock(dimPlan, [revenueMetric, churnMetric])],- });-- await userEvent.click(screen.getByRole("button", { name: "Expand" }));- await userEvent.click(screen.getByRole("button", { name: "Revenue" }));-- expect(selection.toggleMetricSelected).toHaveBeenCalledWith(- "dim:accounts.plan",- revenueMetric.id,- );- expect(trackExplorationPlanEdited).toHaveBeenCalledTimes(1);- expect(trackExplorationPlanEdited).toHaveBeenCalledWith(- "manual",- "metrics",- );- expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith(- "manual",- "dimensions",- );- });-- it("clicking the area's remove button tracks a dimensions edit", async () => {- const { selection } = setup({- blocks: [mockDimensionBlock(dimPlan, [revenueMetric, churnMetric])],- });-- await userEvent.click(screen.getByLabelText("Remove area"));-- expect(selection.removeBlock).toHaveBeenCalledWith("dim:accounts.plan");- expect(trackExplorationPlanEdited).toHaveBeenCalledTimes(1);- expect(trackExplorationPlanEdited).toHaveBeenCalledWith(- "manual",- "dimensions",- );- expect(trackExplorationPlanEdited).not.toHaveBeenCalledWith(- "manual",- "metrics",- );- });- });-describe("selected events pills", () => {const releasesTimeline = createMockTimeline({ id: 7, name: "Releases" });const marketingTimeline = createMockTimeline({ id: 9, name: "Marketing" });@@ -327,8 +266,8 @@ describe("NewExplorationData (Research plan)", () => {const releasesTimeline = createMockTimeline({ id: 7, name: "Releases" });const launchTimeline = createMockTimeline({ id: 9, name: "Launches" });- it("sends only the selected dimensions of a metric block", () => {- const block = mockMetricBlock(+ it("sends only the selected dimensions of a block", () => {+ const block = mockExplorationBlock(revenueMetric,[dimCreatedAt, dimPlan],new Set([dimCreatedAt.id]),@@ -340,27 +279,13 @@ describe("NewExplorationData (Research plan)", () => {]);});- it("sends only the selected metrics of a dimension block", () => {- const block = mockDimensionBlock(- dimPlan,- [revenueMetric, churnMetric],- [dimPlan],- new Set([churnMetric.id]),- );- const request = buildCreateExplorationRequest("n", "", [block], [], null);-- expect(request.blocks[0].metrics.map((m) => m.card_id)).toEqual([- churnMetric.id,- ]);- });-- it("sends thread-scoped timeline_ids at the top level (not per block) and tags each block's anchor type", () => {+ it("sends thread-scoped timeline_ids at the top level (not per block)", () => {const request = buildCreateExplorationRequest("My exploration","",[- mockMetricBlock(revenueMetric, [dimCreatedAt]),- mockDimensionBlock(dimPlan, [churnMetric]),+ mockExplorationBlock(revenueMetric, [dimCreatedAt]),+ mockExplorationBlock(churnMetric, [dimPlan]),],[releasesTimeline, launchTimeline],null,@@ -368,19 +293,17 @@ describe("NewExplorationData (Research plan)", () => {expect(request.timeline_ids).toEqual([7, 9]);expect(request.blocks).toHaveLength(2);- // blocks no longer carry timeline_idsfor (const block of request.blocks) {expect(block).not.toHaveProperty("timeline_ids");+ expect(block).not.toHaveProperty("type");}- expect(request.blocks[0].type).toBe("metric");- expect(request.blocks[1].type).toBe("dimension");});it("uses empty timeline_ids when none are selected", () => {const request = buildCreateExplorationRequest("My exploration","",- [mockMetricBlock(revenueMetric, [dimCreatedAt])],+ [mockExplorationBlock(revenueMetric, [dimCreatedAt])],[],null,);@@ -402,21 +325,14 @@ describe("NewExplorationData (Research plan)", () => {"n","",[- mockMetricBlock(revenueMetric, [dimCreatedAt], new Set()),- mockDimensionBlock(dimPlan, [churnMetric]),- mockDimensionBlock(- dimCreatedAt,- [revenueMetric],- [dimCreatedAt],- new Set(),- ),+ mockExplorationBlock(revenueMetric, [dimCreatedAt], new Set()),+ mockExplorationBlock(churnMetric, [dimPlan]),],[],null,);expect(request.blocks).toHaveLength(1);- expect(request.blocks[0].type).toBe("dimension");expect(request.blocks[0].metrics.map((m) => m.card_id)).toEqual([churnMetric.id,]);@@ -424,7 +340,7 @@ describe("NewExplorationData (Research plan)", () => {});describe("contextual interestingness toggle", () => {- const metricBlock = mockMetricBlock(revenueMetric, [dimCreatedAt]);+ const metricBlock = mockExplorationBlock(revenueMetric, [dimCreatedAt]);const userQuestion = "What drives churn?";it("hides the toggle when there are no user messages", () => {@@ -486,22 +402,6 @@ describe("NewExplorationData (Research plan)", () => {});});- describe("mixed Research plan", () => {- it("renders metric and dimension blocks each with their own controls and enables Start research", () => {- setup({- blocks: [- mockMetricBlock(revenueMetric, [dimCreatedAt]),- mockDimensionBlock(dimPlan, [revenueMetric, churnMetric]),- ],- });-- expect(screen.getAllByLabelText("Remove area")).toHaveLength(2);- expect(- screen.getByRole("button", { name: "Start research" }),- ).toBeEnabled();- });- });-describe("Start research", () => {it("is disabled when there are no blocks", () => {setup();@@ -511,43 +411,14 @@ describe("NewExplorationData (Research plan)", () => {).toBeDisabled();});- it("is disabled when a metric block has no selected dimensions", () => {- setup({- blocks: [mockMetricBlock(revenueMetric, [dimCreatedAt], new Set())],- });-- expect(screen.getByText("Revenue")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Start research" }),- ).toBeDisabled();- });-- it("is disabled when a dimension block has no selected metrics", () => {- setup({- blocks: [- mockDimensionBlock(dimPlan, [revenueMetric], [dimPlan], new Set()),- ],- });-- expect(screen.getByText("Plan")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Start research" }),- ).toBeDisabled();- });-- it("is disabled when every block is empty", () => {+ it("is disabled when a block has no selected dimensions", () => {setup({blocks: [- mockMetricBlock(revenueMetric, [dimCreatedAt], new Set()),- mockDimensionBlock(- dimPlan,- [revenueMetric, churnMetric],- [dimPlan],- new Set(),- ),+ mockExplorationBlock(revenueMetric, [dimCreatedAt], new Set()),],});+ expect(screen.getByText("Revenue")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Start research" }),).toBeDisabled();@@ -556,8 +427,8 @@ describe("NewExplorationData (Research plan)", () => {it("is enabled when at least one block has a selection", () => {setup({blocks: [- mockMetricBlock(revenueMetric, [dimCreatedAt], new Set()),- mockDimensionBlock(dimPlan, [churnMetric]),+ mockExplorationBlock(revenueMetric, [dimCreatedAt], new Set()),+ mockExplorationBlock(churnMetric, [dimPlan]),],});diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.tsxdeleted file mode 100644index b3bc0594704..00000000000--- a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.tsx+++ /dev/null@@ -1,155 +0,0 @@-import { useMemo, useState } from "react";-import { t } from "ttag";--import { useGetExplorationDataQuery } from "metabase/api";-import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";-import { trackExplorationPlanEdited } from "metabase/explorations/analytics";-import type { ExplorationSelection } from "metabase/explorations/hooks";-import { groupMetricsByDimension } from "metabase/explorations/utils";-import { Tabs } from "metabase/ui";-import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";-import type {- DimensionId,- ExplorationDimensionGroup,-} from "metabase-types/api";--import {- DIMENSION_TYPE_ORDER,- filterDimensionGroupsBySearch,- formatDimensionLabel,- getDimensionTypeKey,- getDimensionTypeLabel,-} from "../utils";--import {- AddEntitiesModal,- type AddEntitiesModalItem,-} from "./AddEntitiesModal";--const ALL_TAB = "all";--export interface AddDimensionsModalProps {- opened: boolean;- onClose: () => void;- selection: ExplorationSelection;-}--function groupTypeKey(group: ExplorationDimensionGroup) {- return getDimensionTypeKey(group.dimensions[0]);-}--export function AddDimensionsModal({- opened,- onClose,- selection,-}: AddDimensionsModalProps) {- const { addDimension, dimensionBlockIds } = selection;-- const [tab, setTab] = useState<string>(ALL_TAB);- const [search, setSearch] = useState("");- const debouncedSearch = useDebouncedValue(search, SEARCH_DEBOUNCE_DURATION);-- const {- data: response,- isFetching,- error,- } = useGetExplorationDataQuery({- q: debouncedSearch.trim() || undefined,- });-- const groups = useMemo(- () =>- filterDimensionGroupsBySearch(- response?.dimension_groups ?? [],- debouncedSearch,- ).filter(- (group) =>- group.dimensions.length > 0 && // BE ensures group.dimensions is not empty, but check again just in case- !dimensionBlockIds.has(group.dimensions[0].id),- ),- [response, debouncedSearch, dimensionBlockIds],- );-- const groupByHeadId = useMemo(() => {- const map = new Map<DimensionId, ExplorationDimensionGroup>();- for (const group of groups) {- map.set(group.dimensions[0].id, group);- }- return map;- }, [groups]);-- const metricsByDimension = useMemo(- () => groupMetricsByDimension(response?.metrics ?? []),- [response],- );-- const presentTypes = useMemo(() => {- const present = new Set(groups.map(groupTypeKey));- return DIMENSION_TYPE_ORDER.filter((key) => present.has(key));- }, [groups]);- const showTabs = presentTypes.length > 1;- const activeTab =- showTabs && presentTypes.some((key) => key === tab) ? tab : ALL_TAB;-- const items = useMemo<AddEntitiesModalItem[]>(() => {- const visible =- activeTab === ALL_TAB- ? groups- : groups.filter((group) => groupTypeKey(group) === activeTab);- return [...visible]- .sort(- (a, b) =>- (b.dimension_interestingness ?? 0) -- (a.dimension_interestingness ?? 0),- )- .map((group) => ({- key: group.dimensions[0].id,- label: formatDimensionLabel(group.dimensions[0]),- interestingness: group.dimension_interestingness,- }));- }, [groups, activeTab]);-- const handleAdd = (keys: string[]) => {- trackExplorationPlanEdited("manual", "dimensions");- for (const key of keys) {- const group = groupByHeadId.get(key);- if (group) {- addDimension(group.dimensions[0], { group, metricsByDimension });- }- }- };-- const handleClose = () => {- setTab(ALL_TAB);- onClose();- };-- const tabs = showTabs ? (- <Tabs value={activeTab} onChange={(value) => value && setTab(value)}>- <Tabs.List>- <Tabs.Tab value={ALL_TAB} px="md">{t`All`}</Tabs.Tab>- {presentTypes.map((key) => (- <Tabs.Tab key={key} value={key} px="md">- {getDimensionTypeLabel(key)}- </Tabs.Tab>- ))}- </Tabs.List>- </Tabs>- ) : undefined;-- return (- <AddEntitiesModal- opened={opened}- onClose={handleClose}- title={t`Add dimensions of interest to your research plan`}- searchPlaceholder={t`Search for a dimension`}- search={search}- onSearchChange={setSearch}- items={items}- isLoading={isFetching}- error={error}- onAdd={handleAdd}- tabs={tabs}- />- );-}diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.unit.spec.tsxdeleted file mode 100644index 2c1e2abdf1b..00000000000--- a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddDimensionsModal.unit.spec.tsx+++ /dev/null@@ -1,130 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";-import { useState } from "react";--import {- mockGetBoundingClientRect,- renderWithProviders,- screen,-} from "__support__/ui";-import { makeMockSelection } from "metabase/explorations/test-utils";-import { Button } from "metabase/ui";-import type {- ExplorationDimensionGroup,- GetExplorationDataResponse,-} from "metabase-types/api";--import { AddDimensionsModal } from "./AddDimensionsModal";--const dateGroup: ExplorationDimensionGroup = {- name: "Created At",- dimension_interestingness: 0.9,- dimensions: [- {- id: "created_at",- name: "Created At",- display_name: "Created At",- effective_type: "type/DateTime",- semantic_type: null,- },- ],-};--const categoryGroup: ExplorationDimensionGroup = {- name: "Category",- dimension_interestingness: 0.5,- dimensions: [- {- id: "category",- name: "Category",- display_name: "Category",- effective_type: "type/Text",- semantic_type: null,- },- ],-};--function setupEndpoint(dimensionGroups: ExplorationDimensionGroup[]) {- const response: GetExplorationDataResponse = {- metrics: [],- dimension_groups: dimensionGroups,- };- fetchMock.get("path:/api/exploration/dimensions", response);-}--function renderModal(opened: boolean) {- return renderWithProviders(- <AddDimensionsModal- opened={opened}- onClose={jest.fn()}- selection={makeMockSelection()}- />,- );-}--// Mirrors the parent: the modal stays mounted and its `opened` prop is toggled,-// with closing routed through `onClose` (as Escape/backdrop/Add all do).-function Harness() {- const [opened, setOpened] = useState(true);- return (- <>- <Button onClick={() => setOpened(true)}>reopen</Button>- <AddDimensionsModal- opened={opened}- onClose={() => setOpened(false)}- selection={makeMockSelection()}- />- </>- );-}--describe("AddDimensionsModal", () => {- beforeAll(() => {- mockGetBoundingClientRect({ height: 600, width: 600 });- });-- afterAll(() => {- jest.restoreAllMocks();- });-- it("shows type tabs when more than one dimension type is present", async () => {- setupEndpoint([dateGroup, categoryGroup]);- renderModal(true);-- expect(await screen.findByText("Created At")).toBeInTheDocument();- expect(screen.getByRole("tab", { name: "All" })).toHaveAttribute(- "aria-selected",- "true",- );- expect(screen.getByRole("tab", { name: "Date" })).toBeInTheDocument();- expect(screen.getByRole("tab", { name: "Category" })).toBeInTheDocument();- });-- it("resets the selected tab to All after the modal is closed and reopened", async () => {- setupEndpoint([dateGroup, categoryGroup]);- renderWithProviders(<Harness />);-- expect(await screen.findByText("Created At")).toBeInTheDocument();-- // Select a non-default tab.- await userEvent.click(screen.getByRole("tab", { name: "Date" }));- expect(screen.getByRole("tab", { name: "Date" })).toHaveAttribute(- "aria-selected",- "true",- );-- // Close via Escape (routes through onClose), then reopen.- await userEvent.keyboard("{Escape}");- await userEvent.click(screen.getByRole("button", { name: "reopen" }));-- expect(await screen.findByText("Created At")).toBeInTheDocument();- expect(screen.getByRole("tab", { name: "All" })).toHaveAttribute(- "aria-selected",- "true",- );- expect(screen.getByRole("tab", { name: "Date" })).toHaveAttribute(- "aria-selected",- "false",- );- });-});diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.tsxindex e74029ad410..0ac01b6a4f1 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.tsx@@ -25,7 +25,7 @@ export function AddMetricsModal({onClose,selection,}: AddMetricsModalProps) {- const { addMetric, metricBlockIds } = selection;+ const { addMetric } = selection;const libraryEnabled = PLUGIN_LIBRARY.isEnabled;const [tab, setTab] = useState<MetricsTab | null>(null);@@ -53,6 +53,10 @@ export function AddMetricsModal({[response],);+ const metricBlockIds = useMemo(() => {+ return new Set(selection.blocks.map((b) => b.metric.id));+ }, [selection.blocks]);+const metrics = useMemo(() => (response?.metrics ?? []).filter((m) => !metricBlockIds.has(m.id)),[response, metricBlockIds],diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.unit.spec.tsxindex 7e577623f52..d28f7627c17 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/NewExplorationData/modals/AddMetricsModal.unit.spec.tsx@@ -10,7 +10,7 @@ import {import type { ExplorationBlock } from "metabase/explorations/hooks";import {makeMockSelection,- mockMetricBlock,+ mockExplorationBlock,} from "metabase/explorations/test-utils";import { PLUGIN_LIBRARY } from "metabase/plugins";import type { ExplorationMetric } from "metabase-types/api";@@ -115,7 +115,7 @@ describe("AddMetricsModal", () => {it("switches to the All tab when every library metric is already in the plan", async () => {setup({metrics: [libraryMetric, otherMetric],- blocks: [mockMetricBlock(libraryMetric)],+ blocks: [mockExplorationBlock(libraryMetric)],});expect(await screen.findByText("Churn")).toBeInTheDocument();@@ -153,7 +153,7 @@ describe("AddMetricsModal", () => {await userEvent.click(libraryTab());const planWithLibraryMetric = makeMockSelection({- blocks: [mockMetricBlock(libraryMetric)],+ blocks: [mockExplorationBlock(libraryMetric)],});rerender(<AddMetricsModaldiff --git a/frontend/src/metabase/explorations/components/NewExplorationData/modals/index.ts b/frontend/src/metabase/explorations/components/NewExplorationData/modals/index.tsindex 5a3e41350eb..a9badb08a7c 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/modals/index.ts+++ b/frontend/src/metabase/explorations/components/NewExplorationData/modals/index.ts@@ -1,3 +1,2 @@export { AddMetricsModal } from "./AddMetricsModal";-export { AddDimensionsModal } from "./AddDimensionsModal";export { AddTimelinesModal } from "./AddTimelinesModal";diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/utils.ts b/frontend/src/metabase/explorations/components/NewExplorationData/utils.tsindex 1f3c8524fb4..f7baa4d61ac 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/utils.ts+++ b/frontend/src/metabase/explorations/components/NewExplorationData/utils.ts@@ -1,98 +1,4 @@-import { t } from "ttag";--import { COORDINATE, LOCATION } from "metabase-lib/v1/types/constants";-import {- isBoolean,- isCategory,- isDate,- isFieldType,- isNumeric,- isString,- isStringLike,-} from "metabase-lib/v1/types/utils/isa";-import type {- ExplorationDimensionGroup,- MetricDimension,-} from "metabase-types/api";--export type DimensionTypeKey =- | "date"- | "geolocation"- | "category"- | "number"- | "other";--export const DIMENSION_TYPE_ORDER: DimensionTypeKey[] = [- "date",- "geolocation",- "category",- "number",- "other",-];--export function getDimensionTypeKey(- dimension: MetricDimension,-): DimensionTypeKey {- if (isDate(dimension)) {- return "date";- }- if (isFieldType(LOCATION, dimension) || isFieldType(COORDINATE, dimension)) {- return "geolocation";- }- if (- isCategory(dimension) ||- isString(dimension) ||- isStringLike(dimension) ||- isBoolean(dimension)- ) {- return "category";- }- if (isNumeric(dimension)) {- return "number";- }- return "other";-}--export function getDimensionTypeLabel(key: DimensionTypeKey): string {- switch (key) {- case "date":- return t`Date`;- case "geolocation":- return t`Geo`;- case "category":- return t`Category`;- case "number":- return t`Numeric`;- case "other":- return t`Other`;- }-}--// `/api/exploration/dimensions` matches metrics by name OR dimension, then-// returns *every* dimension of each matching metric — so a dimension search-// drags along the metric's other dimensions. Re-filter client-side.-export function filterDimensionGroupsBySearch(- groups: ExplorationDimensionGroup[],- query: string,-): ExplorationDimensionGroup[] {- const normalizedQuery = query.trim().toLowerCase();- if (normalizedQuery === "") {- return groups;- }-- const matches = (value: string | null | undefined) =>- value != null && value.toLowerCase().includes(normalizedQuery);-- return groups.filter(- (group) =>- matches(group.name) ||- group.dimensions.some(- (dimension) =>- matches(dimension.display_name) ||- matches(dimension.group?.display_name),- ),- );-}+import type { MetricDimension } from "metabase-types/api";export function formatDimensionLabel(dim: MetricDimension): string {return dim.display_name ?? dim.id;diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/utils.unit.spec.ts b/frontend/src/metabase/explorations/components/NewExplorationData/utils.unit.spec.tsindex f3c3d79ac8d..acf5915589f 100644--- a/frontend/src/metabase/explorations/components/NewExplorationData/utils.unit.spec.ts+++ b/frontend/src/metabase/explorations/components/NewExplorationData/utils.unit.spec.ts@@ -1,67 +1,6 @@-import type {- ExplorationDimensionGroup,- MetricDimension,-} from "metabase-types/api";import { createMockMetricDimension } from "metabase-types/api/mocks/metric";-import { filterDimensionGroupsBySearch, formatDimensionLabel } from "./utils";--describe("filterDimensionGroupsBySearch", () => {- function makeGroup(- name: string,- dimensions: MetricDimension[] = [],- ): ExplorationDimensionGroup {- return { name, dimension_interestingness: null, dimensions };- }-- const country = makeGroup("Country", [- createMockMetricDimension({ id: "g1", display_name: "Country" }),- ]);- const plan = makeGroup("Plan", [- createMockMetricDimension({ id: "g2", display_name: "Plan" }),- ]);-- it("returns every group untouched for an empty / whitespace query", () => {- const groups = [country, plan];- expect(filterDimensionGroupsBySearch(groups, "")).toBe(groups);- expect(filterDimensionGroupsBySearch(groups, " ")).toBe(groups);- });-- it("keeps only groups whose name matches the query (case-insensitive)", () => {- expect(filterDimensionGroupsBySearch([country, plan], "COUN")).toEqual([- country,- ]);- });-- it("matches on a contained dimension's display name even when the group name doesn't", () => {- const orders = makeGroup("Orders", [- createMockMetricDimension({ id: "d1", display_name: "Quantity" }),- createMockMetricDimension({ id: "d2", display_name: "Created At" }),- ]);-- expect(filterDimensionGroupsBySearch([orders, plan], "created")).toEqual([- orders,- ]);- });-- it("matches on a dimension's source-group display name", () => {- const sourced = makeGroup("Total", [- createMockMetricDimension({- id: "s1",- display_name: "Total",- group: { id: "grp", type: "main", display_name: "Products" },- }),- ]);-- expect(filterDimensionGroupsBySearch([sourced, plan], "produc")).toEqual([- sourced,- ]);- });-- it("returns [] when nothing matches", () => {- expect(filterDimensionGroupsBySearch([country, plan], "zzz")).toEqual([]);- });-});+import { formatDimensionLabel } from "./utils";describe("formatDimensionLabel", () => {it("uses the dimension's own curated name, not an '<origin> - <name>' combination", () => {diff --git a/frontend/src/metabase/explorations/hooks/index.ts b/frontend/src/metabase/explorations/hooks/index.tsindex 31b1b779983..337a958a37c 100644--- a/frontend/src/metabase/explorations/hooks/index.ts+++ b/frontend/src/metabase/explorations/hooks/index.ts@@ -1,13 +1,7 @@export {useExplorationSelection,- isMetricBlock,- isDimensionBlock,metricBlockId,- dimensionBlockId,type ExplorationSelection,type ExplorationBlock,- type MetricBlock,- type DimensionBlock,type ToggleMetricContext,- type ToggleDimensionContext,} from "./useExplorationSelection";diff --git a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsxindex 99c74374843..7f4f84032d6 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx+++ b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx@@ -23,7 +23,6 @@ import { isBrushClickObject } from "metabase/visualizations/types";import type { ComputedVisualizationSettings } from "metabase/viz-core";import type {DocumentContent,- ExplorationBlockNodeType,ExplorationId,ExplorationPageId,ExplorationQuery,@@ -37,7 +36,6 @@ import type { CommentDrafts } from "../types";interface UseExplorationClickActionsModeParams {explorationId?: ExplorationId;pageId?: ExplorationPageId;- blockType?: ExplorationBlockNodeType;queryType?: ExplorationQueryType;commentDrafts: CommentDrafts;setCommentDrafts: Dispatch<SetStateAction<CommentDrafts>>;@@ -48,7 +46,6 @@ interface UseExplorationClickActionsModeParams {export function useExplorationClickActionsMode({explorationId,pageId,- blockType,queryType,commentDrafts,setCommentDrafts,@@ -76,7 +73,7 @@ export function useExplorationClickActionsMode({return actions;}- if (canExploreFurther(clicked, blockType, queryType)) {+ if (canExploreFurther(clicked, queryType)) {const handleExploreFurther = async () => {const exploreFilters = getExploreFurtherFilters(clicked);sendToast({ icon: "bolt", message: t`Exploring further…` });@@ -170,7 +167,6 @@ export function useExplorationClickActionsMode({}, [explorationId,pageId,- blockType,queryType,setCommentDrafts,exploreFurther,diff --git a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsxindex 875b2a7ea79..34f0d26b2ba 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx+++ b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx@@ -111,7 +111,6 @@ function renderMode(useExplorationClickActionsMode({explorationId: 42,pageId: 7,- blockType: "metric",queryType: "default",commentDrafts,setCommentDrafts,@@ -150,13 +149,6 @@ describe("useExplorationClickActionsMode", () => {]);});- it("omits explore further for ineligible clicks but still offers add comment", () => {- const { result } = renderMode({ blockType: "dimension" });- const actions = result.current.actionsForClick(makeClicked());-- expect(actions.map((action) => action.name)).toEqual(["add-comment"]);- });-it("fires explore further with filters and closes the popover", async () => {const closePopover = jest.fn();const { result } = renderMode();@@ -279,9 +271,8 @@ describe("useExplorationClickActionsMode", () => {);});- it("offers add-comment but not explore-further when blockType/queryType are omitted", () => {+ it("offers add-comment but not explore-further when queryType is omitted", () => {const { result } = renderMode({- blockType: undefined,queryType: undefined,});const actions = result.current.actionsForClick(makeClicked());diff --git a/frontend/src/metabase/explorations/hooks/useExplorationSelection.ts b/frontend/src/metabase/explorations/hooks/useExplorationSelection.tsindex a469b611a4c..847b51d6f98 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationSelection.ts+++ b/frontend/src/metabase/explorations/hooks/useExplorationSelection.ts@@ -3,7 +3,6 @@ import {type SetStateAction,useCallback,useEffect,- useMemo,useRef,useState,} from "react";@@ -19,49 +18,22 @@ import type { ExplorationCollection } from "metabase/explorations/types";import { useSelector } from "metabase/redux";import type {DimensionId,- ExplorationDimensionGroup,ExplorationMetric,MetricDimension,Timeline,} from "metabase-types/api";-export interface MetricBlock {- kind: "metric";+export interface ExplorationBlock {id: string;metric: ExplorationMetric;dimensions: MetricDimension[]; // sorted by interestingnessselectedDimensionIds: Set<DimensionId>;}-export interface DimensionBlock {- kind: "dimension";- id: string;- dimension: MetricDimension;- groupDimensions: MetricDimension[];- metrics: ExplorationMetric[];- selectedMetricIds: Set<ExplorationMetric["id"]>;-}--export type ExplorationBlock = MetricBlock | DimensionBlock;--export function isMetricBlock(block: ExplorationBlock): block is MetricBlock {- return block.kind === "metric";-}--export function isDimensionBlock(- block: ExplorationBlock,-): block is DimensionBlock {- return block.kind === "dimension";-}-export function metricBlockId(metricId: ExplorationMetric["id"]): string {return `metric:${metricId}`;}-export function dimensionBlockId(dimensionId: DimensionId): string {- return `dim:${dimensionId}`;-}-export interface ToggleMetricContext {dimensionsById: Map<DimensionId, MetricDimension>;additionalSelectedDimensionIds?: Set<DimensionId>;@@ -71,57 +43,24 @@ export interface ToggleMetricContext {replace?: boolean;}-export interface ToggleDimensionContext {- group: ExplorationDimensionGroup | null;- metricsByDimension: Map<DimensionId, ExplorationMetric[]>;- // When set, select only these metrics (e.g. the few the agent curated) instead of every related- // metric. Restricted to the block's candidate metrics.- selectedMetricIds?: Set<ExplorationMetric["id"]>;-}-export interface ExplorationSelection {blocks: ExplorationBlock[];- metricBlockIds: Set<ExplorationMetric["id"]>;- dimensionBlockIds: Set<DimensionId>;-timelines: Timeline[];-allTimelines: Timeline[];timelinesLoading: boolean;timelinesError: unknown;-name: string;collection: ExplorationCollection;-setBlocks: Dispatch<SetStateAction<ExplorationBlock[]>>;setTimelines: Dispatch<SetStateAction<Timeline[]>>;setName: Dispatch<SetStateAction<string>>;setCollection: (collection: Required<ExplorationCollection>) => void;-addMetric: (metric: ExplorationMetric, context: ToggleMetricContext) => void;- addDimension: (- dimension: MetricDimension,- context: ToggleDimensionContext,- ) => void;-addTimelinesById: (timelineIds: number[]) => void;removeTimelinesById: (timelineIds: number[]) => void;-removeBlock: (blockId: string) => void;-- removeBlockMembers: (- blockId: string,- members: {- metricIds?: ExplorationMetric["id"][];- dimensionIds?: DimensionId[];- },- ) => void;-+ removeBlockDimensions: (blockId: string, dimensionIds: DimensionId[]) => void;toggleDimensionSelected: (blockId: string, dimensionId: DimensionId) => void;- toggleMetricSelected: (- blockId: string,- metricId: ExplorationMetric["id"],- ) => void;}function sortDimensionsByInterestingness(@@ -133,12 +72,12 @@ function sortDimensionsByInterestingness();}-function buildMetricBlock(+function buildExplorationBlock(metric: ExplorationMetric,dimensionsById: Map<DimensionId, MetricDimension>,additionalSelectedDimensionIds?: Set<DimensionId>,replace?: boolean,-): MetricBlock {+): ExplorationBlock {const referencedDims = sortDimensionsByInterestingness(metric.dimension_ids.map((id) => dimensionsById.get(id))@@ -164,7 +103,6 @@ function buildMetricBlock(}}return {- kind: "metric",id: metricBlockId(metric.id),metric,dimensions: referencedDims,@@ -172,37 +110,6 @@ function buildMetricBlock(};}-function buildDimensionBlock(- dimension: MetricDimension,- context: ToggleDimensionContext,-): DimensionBlock {- const groupDimensions = context.group?.dimensions ?? [dimension];- const seenMetricIds = new Set<ExplorationMetric["id"]>();- const metrics: ExplorationMetric[] = [];- for (const groupDim of groupDimensions) {- for (const metric of context.metricsByDimension.get(groupDim.id) ?? []) {- if (!seenMetricIds.has(metric.id)) {- seenMetricIds.add(metric.id);- metrics.push(metric);- }- }- }- const requested = context.selectedMetricIds;- // Default to every related metric; when a subset is requested, select just those (bounded by- // the block's candidate metrics).- const selectedMetricIds = requested- ? new Set(metrics.filter((m) => requested.has(m.id)).map((m) => m.id))- : new Set(metrics.map((m) => m.id));- return {- kind: "dimension",- id: dimensionBlockId(dimension.id),- dimension,- groupDimensions,- metrics,- selectedMetricIds,- };-}-export function useExplorationSelection(): ExplorationSelection {const personalCollectionId = useSelector(getUserPersonalCollectionId);@@ -251,10 +158,7 @@ export function useExplorationSelection(): ExplorationSelection {}: ToggleMetricContext,) => {setBlocks((prevBlocks) => {- const existing = prevBlocks.find(- (b): b is MetricBlock =>- isMetricBlock(b) && b.metric.id === metric.id,- );+ const existing = prevBlocks.find((b) => b.metric.id === metric.id);if (existing) {// Create-or-grow: the block already exists, so union the explicitly-requested// dimensions into its selection (never deselects). With no explicit dimensions there is@@ -280,7 +184,7 @@ export function useExplorationSelection(): ExplorationSelection {}return [...prevBlocks,- buildMetricBlock(+ buildExplorationBlock(metric,dimensionsById,additionalSelectedDimensionIds,@@ -292,37 +196,6 @@ export function useExplorationSelection(): ExplorationSelection {[],);- const addDimension = useCallback(- (dimension: MetricDimension, context: ToggleDimensionContext) => {- const id = dimensionBlockId(dimension.id);- setBlocks((prevBlocks) => {- const existing = prevBlocks.find(- (b): b is DimensionBlock => b.id === id && isDimensionBlock(b),- );- if (existing) {- // Create-or-grow: the block already exists, so re-select every related metric (union;- // never deselects), bounded by the block's candidate metrics.- const rebuilt = buildDimensionBlock(dimension, context);- const candidateIds = new Set(existing.metrics.map((m) => m.id));- const selected = new Set(existing.selectedMetricIds);- for (const metricId of rebuilt.selectedMetricIds) {- if (candidateIds.has(metricId)) {- selected.add(metricId);- }- }- if (selected.size === existing.selectedMetricIds.size) {- return prevBlocks;- }- return prevBlocks.map((b) =>- b === existing ? { ...existing, selectedMetricIds: selected } : b,- );- }- return [...prevBlocks, buildDimensionBlock(dimension, context)];- });- },- [],- );-const addTimelinesById = useCallback((timelineIds: number[]) => {const timelinesById = new Map(allTimelines.map((t) => [t.id, t]));@@ -357,17 +230,8 @@ export function useExplorationSelection(): ExplorationSelection {});}, []);- const removeBlockMembers = useCallback(- (- blockId: string,- {- metricIds,- dimensionIds,- }: {- metricIds?: ExplorationMetric["id"][];- dimensionIds?: DimensionId[];- },- ) => {+ const removeBlockDimensions = useCallback(+ (blockId: string, dimensionIds: DimensionId[]) => {setBlocks((prev) => {let changed = false;const next: ExplorationBlock[] = [];@@ -376,45 +240,19 @@ export function useExplorationSelection(): ExplorationSelection {next.push(block);continue;}- if (isMetricBlock(block)) {- // Dimension ids deselect candidate dimensions; metric ids don't apply here.- if (!dimensionIds?.length) {- next.push(block);- continue;- }- const selected = new Set(block.selectedDimensionIds);- for (const id of dimensionIds) {- selected.delete(id);- }- if (selected.size === block.selectedDimensionIds.size) {- // Nothing was actually deselected.- next.push(block);- continue;- }- changed = true;- // A metric block with no selected dimensions is invalid — drop it entirely.- if (selected.size > 0) {- next.push({ ...block, selectedDimensionIds: selected });- }- } else {- // Metric ids deselect candidate metrics; dimension ids don't apply here.- if (!metricIds?.length) {- next.push(block);- continue;- }- const selected = new Set(block.selectedMetricIds);- for (const id of metricIds) {- selected.delete(id);- }- if (selected.size === block.selectedMetricIds.size) {- // Nothing was actually deselected.- next.push(block);- continue;- }- changed = true;- if (selected.size > 0) {- next.push({ ...block, selectedMetricIds: selected });- }+ const selected = new Set(block.selectedDimensionIds);+ for (const id of dimensionIds) {+ selected.delete(id);+ }+ if (selected.size === block.selectedDimensionIds.size) {+ // Nothing was actually deselected.+ next.push(block);+ continue;+ }+ changed = true;+ // A metric block with no selected dimensions is invalid — drop it entirely.+ if (selected.size > 0) {+ next.push({ ...block, selectedDimensionIds: selected });}}return changed ? next : prev;@@ -427,7 +265,7 @@ export function useExplorationSelection(): ExplorationSelection {(blockId: string, dimensionId: DimensionId) => {setBlocks((prev) =>prev.map((block) => {- if (block.id !== blockId || !isMetricBlock(block)) {+ if (block.id !== blockId) {return block;}const next = new Set(block.selectedDimensionIds);@@ -443,53 +281,8 @@ export function useExplorationSelection(): ExplorationSelection {[],);- const toggleMetricSelected = useCallback(- (blockId: string, metricId: ExplorationMetric["id"]) => {- setBlocks((prev) =>- prev.map((block) => {- if (block.id !== blockId || !isDimensionBlock(block)) {- return block;- }- const next = new Set(block.selectedMetricIds);- if (next.has(metricId)) {- next.delete(metricId);- } else {- next.add(metricId);- }- return { ...block, selectedMetricIds: next };- }),- );- },- [],- );-- // Derived aggregations: flat metrics / dimensions across blocks.- const metricBlockIds = useMemo(() => {- const ids = new Set<ExplorationMetric["id"]>();- for (const block of blocks) {- if (isMetricBlock(block)) {- ids.add(block.metric.id);- }- }- return ids;- }, [blocks]);-- const dimensionBlockIds = useMemo(() => {- const ids = new Set<DimensionId>();- for (const block of blocks) {- if (isDimensionBlock(block)) {- for (const d of block.groupDimensions) {- ids.add(d.id);- }- }- }- return ids;- }, [blocks]);-return {blocks,- metricBlockIds,- dimensionBlockIds,timelines,allTimelines,timelinesLoading,@@ -501,12 +294,10 @@ export function useExplorationSelection(): ExplorationSelection {setName,setCollection: setCollectionExplicitly,addMetric,- addDimension,addTimelinesById,removeTimelinesById,removeBlock,- removeBlockMembers,+ removeBlockDimensions,toggleDimensionSelected,- toggleMetricSelected,};}diff --git a/frontend/src/metabase/explorations/hooks/useExplorationSelection.unit.spec.ts b/frontend/src/metabase/explorations/hooks/useExplorationSelection.unit.spec.tsindex ee6e48bcc42..9596f6896a9 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationSelection.unit.spec.ts+++ b/frontend/src/metabase/explorations/hooks/useExplorationSelection.unit.spec.ts@@ -19,8 +19,6 @@ import {} from "metabase-types/api/mocks";import {- type DimensionBlock,- isMetricBlock,metricBlockId,useExplorationSelection,} from "./useExplorationSelection";@@ -56,12 +54,12 @@ function renderSelection(timelines: Timeline[] = []) {return renderHookWithProviders(() => useExplorationSelection(), {});}-function metricBlockOf(result: {+function firstBlockOf(result: {current: ReturnType<typeof useExplorationSelection>;}) {const block = result.current.blocks[0];- if (!block || !isMetricBlock(block)) {- throw new Error("expected a metric block");+ if (!block) {+ throw new Error("expected a block");}return block;}@@ -80,7 +78,7 @@ describe("useExplorationSelection", () => {result.current.addMetric(metric, { dimensionsById });});- const block = metricBlockOf(result);+ const block = firstBlockOf(result);expect(block.dimensions.map((d) => d.id)).toEqual(["dim-high","dim-low",@@ -100,7 +98,7 @@ describe("useExplorationSelection", () => {result.current.addMetric(metric, { dimensionsById });});- expect([...metricBlockOf(result).selectedDimensionIds].sort()).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds].sort()).toEqual(["dim-a","dim-b",]);@@ -119,7 +117,7 @@ describe("useExplorationSelection", () => {result.current.addMetric(metric, { dimensionsById });});- expect(metricBlockOf(result).dimensions.map((d) => d.id)).toEqual([+ expect(firstBlockOf(result).dimensions.map((d) => d.id)).toEqual(["dim-high","dim-mid","dim-low",@@ -157,7 +155,7 @@ describe("useExplorationSelection", () => {act(() => {result.current.addMetric(metric, { dimensionsById });});- expect([...metricBlockOf(result).selectedDimensionIds]).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds]).toEqual(["dim-high",]);@@ -170,7 +168,7 @@ describe("useExplorationSelection", () => {});expect(result.current.blocks).toHaveLength(1);- expect([...metricBlockOf(result).selectedDimensionIds].sort()).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds].sort()).toEqual(["dim-high","dim-low",]);@@ -194,7 +192,7 @@ describe("useExplorationSelection", () => {// Without replace this would select dim-high (interesting) ∪ dim-low; with replace it is// exactly the requested dim-low.- expect([...metricBlockOf(result).selectedDimensionIds]).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds]).toEqual(["dim-low",]);});@@ -265,7 +263,7 @@ describe("useExplorationSelection", () => {});describe("toggleDimensionSelected", () => {- it("flips a candidate dimension's selected state within a metric block", () => {+ it("flips a candidate dimension's selected state", () => {const dimHigh = makeDim("dim-high", 0.9);const dimLow = makeDim("dim-low", 0.3);const metric = makeMetric(1, ["dim-high", "dim-low"]);@@ -281,7 +279,7 @@ describe("useExplorationSelection", () => {act(() => {result.current.toggleDimensionSelected(blockId, "dim-low");});- expect([...metricBlockOf(result).selectedDimensionIds].sort()).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds].sort()).toEqual(["dim-high","dim-low",]);@@ -289,145 +287,15 @@ describe("useExplorationSelection", () => {act(() => {result.current.toggleDimensionSelected(blockId, "dim-high");});- expect([...metricBlockOf(result).selectedDimensionIds]).toEqual([+ expect([...firstBlockOf(result).selectedDimensionIds]).toEqual(["dim-low",]);});});- describe("addDimension", () => {- it("adds a dimension block, all related metrics selected, and is idempotent", () => {- const dimA = makeDim("dim-a", 0.9);- const metric1 = makeMetric(1, ["dim-a"]);- const metric2 = makeMetric(2, ["dim-a"]);- const metricsByDimension = new Map([["dim-a", [metric1, metric2]]]);-- const { result } = renderSelection();-- act(() => {- result.current.addDimension(dimA, {- group: null,- metricsByDimension,- });- });-- const block = result.current.blocks[0];- if (block.kind !== "dimension") {- throw new Error("expected a dimension block");- }- expect(block.metrics.map((m) => m.id)).toEqual([1, 2]);- expect([...block.selectedMetricIds].sort()).toEqual([1, 2]);-- const blocksAfterFirst = result.current.blocks;- act(() => {- result.current.addDimension(dimA, {- group: null,- metricsByDimension,- });- });- expect(result.current.blocks).toBe(blocksAfterFirst);- });-- it("selects only the requested metrics when a subset is given", () => {- const dimA = makeDim("dim-a", 0.9);- const metric1 = makeMetric(1, ["dim-a"]);- const metric2 = makeMetric(2, ["dim-a"]);- const metricsByDimension = new Map([["dim-a", [metric1, metric2]]]);-- const { result } = renderSelection();-- act(() => {- result.current.addDimension(dimA, {- group: null,- metricsByDimension,- selectedMetricIds: new Set([1]),- });- });-- const block = result.current.blocks[0];- if (block.kind !== "dimension") {- throw new Error("expected a dimension block");- }- // Both metrics remain candidates, but only the requested one is selected.- expect(block.metrics.map((m) => m.id).sort()).toEqual([1, 2]);- expect([...block.selectedMetricIds]).toEqual([1]);- });-- it("grows an existing dimension block by re-selecting related metrics", () => {- const dimA = makeDim("dim-a", 0.9);- const metric1 = makeMetric(1, ["dim-a"]);- const metric2 = makeMetric(2, ["dim-a"]);- const metricsByDimension = new Map([["dim-a", [metric1, metric2]]]);-- const { result } = renderSelection();-- // Existing block with metric 2 deselected.- act(() => {- result.current.setBlocks([- {- kind: "dimension",- id: "dim:dim-a",- dimension: dimA,- groupDimensions: [dimA],- metrics: [metric1, metric2],- selectedMetricIds: new Set([1]),- },- ]);- });-- act(() => {- result.current.addDimension(dimA, {- group: null,- metricsByDimension,- });- });-- expect(result.current.blocks).toHaveLength(1);- expect(- [- // Unjustified type cast. FIXME- ...(result.current.blocks[0] as DimensionBlock).selectedMetricIds,- ].sort(),- ).toEqual([1, 2]);- });- });-- describe("toggleMetricSelected", () => {- it("flips a candidate metric's selected state within a dimension block", () => {- const dimA = makeDim("dim-a", 0.9);- const metric1 = makeMetric(1, ["dim-a"]);- const metric2 = makeMetric(2, ["dim-a"]);-- const { result } = renderSelection();-- act(() => {- result.current.setBlocks([- {- kind: "dimension",- id: "dim:dim-a",- dimension: dimA,- groupDimensions: [dimA],- metrics: [metric1, metric2],- selectedMetricIds: new Set([1, 2]),- },- ]);- });-- act(() => {- result.current.toggleMetricSelected("dim:dim-a", 1);- });-- expect([- // Unjustified type cast. FIXME- ...(result.current.blocks[0] as DimensionBlock).selectedMetricIds,- ]).toEqual([2]);- });- });-- describe("removeBlockMembers", () => {- function metricBlockWith(dims: MetricDimension[], selected: DimensionId[]) {+ describe("removeBlockDimensions", () => {+ function blockWith(dims: MetricDimension[], selected: DimensionId[]) {return {- kind: "metric" as const,id: metricBlockId(1),metric: makeMetric(1,@@ -438,113 +306,49 @@ describe("useExplorationSelection", () => {};}- function dimensionBlockWith(- metrics: ExplorationMetric[],- selected: number[],- ) {- const dimA = makeDim("dim-a", 0.9);- return {- kind: "dimension" as const,- id: "dim:dim-a",- dimension: dimA,- groupDimensions: [dimA],- metrics,- selectedMetricIds: new Set(selected),- };- }-- it("deselects a dimension within a metric block, keeping the block", () => {+ it("deselects a dimension, keeping the block", () => {const dimA = makeDim("dim-a", 0.9);const dimB = makeDim("dim-b", 0.8);const { result } = renderSelection();act(() => {- result.current.setBlocks([- metricBlockWith([dimA, dimB], ["dim-a", "dim-b"]),- ]);+ result.current.setBlocks([blockWith([dimA, dimB], ["dim-a", "dim-b"])]);});act(() => {- result.current.removeBlockMembers(metricBlockId(1), {- dimensionIds: ["dim-a"],- });+ result.current.removeBlockDimensions(metricBlockId(1), ["dim-a"]);});- expect([...metricBlockOf(result).selectedDimensionIds]).toEqual([- "dim-b",- ]);+ expect([...firstBlockOf(result).selectedDimensionIds]).toEqual(["dim-b"]);});- it("drops the metric block when its last selected dimension is removed", () => {+ it("drops the block when its last selected dimension is removed", () => {const dimA = makeDim("dim-a", 0.9);const { result } = renderSelection();act(() => {- result.current.setBlocks([metricBlockWith([dimA], ["dim-a"])]);+ result.current.setBlocks([blockWith([dimA], ["dim-a"])]);});act(() => {- result.current.removeBlockMembers(metricBlockId(1), {- dimensionIds: ["dim-a"],- });+ result.current.removeBlockDimensions(metricBlockId(1), ["dim-a"]);});expect(result.current.blocks).toHaveLength(0);});- it("deselects a metric within a dimension block, keeping the block", () => {- const metric1 = makeMetric(1, ["dim-a"]);- const metric2 = makeMetric(2, ["dim-a"]);- const { result } = renderSelection();-- act(() => {- result.current.setBlocks([- dimensionBlockWith([metric1, metric2], [1, 2]),- ]);- });- act(() => {- result.current.removeBlockMembers("dim:dim-a", { metricIds: [1] });- });-- expect([- // Unjustified type cast. FIXME- ...(result.current.blocks[0] as DimensionBlock).selectedMetricIds,- ]).toEqual([2]);- });-- it("drops the dimension block when its last selected metric is removed", () => {- const metric1 = makeMetric(1, ["dim-a"]);- const { result } = renderSelection();-- act(() => {- result.current.setBlocks([dimensionBlockWith([metric1], [1])]);- });- act(() => {- result.current.removeBlockMembers("dim:dim-a", { metricIds: [1] });- });-- expect(result.current.blocks).toHaveLength(0);- });-- it("ignores a mismatched member family", () => {+ it("is a no-op when none of the given dimensions are selected", () => {const dimA = makeDim("dim-a", 0.9);const dimB = makeDim("dim-b", 0.8);const { result } = renderSelection();act(() => {- result.current.setBlocks([- metricBlockWith([dimA, dimB], ["dim-a", "dim-b"]),- ]);+ result.current.setBlocks([blockWith([dimA, dimB], ["dim-a", "dim-b"])]);});- // metric ids don't apply to a metric block — nothing changes+ const blocksBefore = result.current.blocks;act(() => {- result.current.removeBlockMembers(metricBlockId(1), {- metricIds: [1, 2],- });+ result.current.removeBlockDimensions(metricBlockId(1), ["dim-missing"]);});- expect([...metricBlockOf(result).selectedDimensionIds].sort()).toEqual([- "dim-a",- "dim-b",- ]);+ expect(result.current.blocks).toBe(blocksBefore);});it("is a no-op when the block id is not present", () => {@@ -552,18 +356,14 @@ describe("useExplorationSelection", () => {const { result } = renderSelection();act(() => {- result.current.setBlocks([metricBlockWith([dimA], ["dim-a"])]);+ result.current.setBlocks([blockWith([dimA], ["dim-a"])]);});act(() => {- result.current.removeBlockMembers("metric:999", {- dimensionIds: ["dim-a"],- });+ result.current.removeBlockDimensions("metric:999", ["dim-a"]);});expect(result.current.blocks).toHaveLength(1);- expect([...metricBlockOf(result).selectedDimensionIds]).toEqual([- "dim-a",- ]);+ expect([...firstBlockOf(result).selectedDimensionIds]).toEqual(["dim-a"]);});});diff --git a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx b/frontend/src/metabase/explorations/pages/ExplorationPage.tsxindex 92aecd0b8f1..4da69b6b415 100644--- a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx+++ b/frontend/src/metabase/explorations/pages/ExplorationPage.tsx@@ -638,7 +638,6 @@ function ExplorationPageForId({ view }: ExplorationPageProps) {explorationId={exploration.id}page={selectedPage.page}queries={selectedPage.queries}- blockType={selectedPage.block.type}exploreFilters={selectedPage.block.explore_filters}availableTimelines={availableTimelines}selectedTimelineId={selectedTimelineId}diff --git a/frontend/src/metabase/explorations/research-plan-context.ts b/frontend/src/metabase/explorations/research-plan-context.tsindex c9a87d4f102..279d2b4acc2 100644--- a/frontend/src/metabase/explorations/research-plan-context.ts+++ b/frontend/src/metabase/explorations/research-plan-context.ts@@ -1,5 +1,4 @@import type { ExplorationBlock } from "metabase/explorations/hooks";-import { isMetricBlock } from "metabase/explorations/hooks";import type {ResearchPlanContext,ResearchPlanGroup,@@ -7,24 +6,12 @@ import type {} from "metabase-types/api";function blockToGroup(block: ExplorationBlock): ResearchPlanGroup {- if (isMetricBlock(block)) {- return {- block_id: block.id,- anchor: "metric",- metric: { id: block.metric.id, name: block.metric.name },- dimensions: block.dimensions- .filter((d) => block.selectedDimensionIds.has(d.id))- .map((d) => ({ id: d.id, name: d.display_name })),- };- }-return {block_id: block.id,- anchor: "dimension",- dimension: { id: block.dimension.id, name: block.dimension.display_name },- metrics: block.metrics- .filter((m) => block.selectedMetricIds.has(m.id))- .map((m) => ({ id: m.id, name: m.name })),+ metric: { id: block.metric.id, name: block.metric.name },+ dimensions: block.dimensions+ .filter((d) => block.selectedDimensionIds.has(d.id))+ .map((d) => ({ id: d.id, name: d.display_name })),};}diff --git a/frontend/src/metabase/explorations/research-plan-context.unit.spec.ts b/frontend/src/metabase/explorations/research-plan-context.unit.spec.tsindex 0a4e53f519f..a9a139a6323 100644--- a/frontend/src/metabase/explorations/research-plan-context.unit.spec.ts+++ b/frontend/src/metabase/explorations/research-plan-context.unit.spec.ts@@ -7,7 +7,7 @@ import { createMockMetric } from "metabase-types/api/mocks/metric";import { createMockTimeline } from "metabase-types/api/mocks/timeline";import { selectionToResearchPlanContext } from "./research-plan-context";-import { mockDimensionBlock, mockMetricBlock } from "./test-utils";+import { mockExplorationBlock } from "./test-utils";function metric(id: number, name: string): ExplorationMetric {// Unjustified type cast. FIXME@@ -29,10 +29,10 @@ function dimension(}describe("selectionToResearchPlanContext", () => {- it("serializes a metric block as a metric-anchored group with only selected dimensions", () => {+ it("serializes a block with only selected dimensions", () => {const region = dimension("d1", { display_name: "Region" });const plan = dimension("d2", { display_name: "Plan" });- const block = mockMetricBlock(+ const block = mockExplorationBlock(metric(42, "Revenue"),[region, plan],new Set(["d1"]), // only Region selected@@ -48,38 +48,12 @@ describe("selectionToResearchPlanContext", () => {expect(result.groups).toEqual([{block_id: "metric:42",- anchor: "metric",metric: { id: 42, name: "Revenue" },dimensions: [{ id: "d1", name: "Region" }],},]);});- it("serializes a dimension block as a dimension-anchored group with only selected metrics", () => {- const planDim = dimension("d7", { display_name: "Plan" });- const block = mockDimensionBlock(- planDim,- [metric(42, "Revenue"), metric(43, "Churn")],- [planDim],- new Set([42]), // only Revenue selected- );-- const result = selectionToResearchPlanContext({- blocks: [block],- timelines: [],- name: "",- });-- expect(result.groups).toEqual([- {- block_id: "dim:d7",- anchor: "dimension",- dimension: { id: "d7", name: "Plan" },- metrics: [{ id: 42, name: "Revenue" }],- },- ]);- });-it("includes selected timelines", () => {const timelines: Timeline[] = [createMockTimeline({ id: 1, name: "Releases" }),diff --git a/frontend/src/metabase/explorations/test-utils.ts b/frontend/src/metabase/explorations/test-utils.tsindex bb0a652b218..508cce7d337 100644--- a/frontend/src/metabase/explorations/test-utils.ts+++ b/frontend/src/metabase/explorations/test-utils.ts@@ -11,16 +11,8 @@ import type {Timeline,} from "metabase-types/api";-import type {- DimensionBlock,- ExplorationBlock,- ExplorationSelection,- MetricBlock,-} from "./hooks";-import {- dimensionBlockId,- metricBlockId,-} from "./hooks/useExplorationSelection";+import type { ExplorationBlock, ExplorationSelection } from "./hooks";+import { metricBlockId } from "./hooks/useExplorationSelection";export const INITIAL_BLOCK_ID = 1;@@ -30,13 +22,12 @@ export interface MockSelectionOpts {allTimelines?: Timeline[];}-export function mockMetricBlock(+export function mockExplorationBlock(metric: ExplorationMetric,dimensions: MetricDimension[] = [],selectedDimensionIds?: Set<MetricDimension["id"]>,-): MetricBlock {+): ExplorationBlock {return {- kind: "metric",id: metricBlockId(metric.id),metric,dimensions,@@ -45,22 +36,6 @@ export function mockMetricBlock(};}-export function mockDimensionBlock(- dimension: MetricDimension,- metrics: ExplorationMetric[] = [],- groupDimensions?: MetricDimension[],- selectedMetricIds?: Set<ExplorationMetric["id"]>,-): DimensionBlock {- return {- kind: "dimension",- id: dimensionBlockId(dimension.id),- dimension,- groupDimensions: groupDimensions ?? [dimension],- metrics,- selectedMetricIds: selectedMetricIds ?? new Set(metrics.map((m) => m.id)),- };-}-export function makeMockSelection(opts: MockSelectionOpts = {},): ExplorationSelection {@@ -68,47 +43,26 @@ export function makeMockSelection(const timelines = opts.timelines ?? [];const allTimelines = opts.allTimelines ?? [];- const metricBlockIds = new Set<ExplorationMetric["id"]>();- const dimensionBlockIds = new Set<MetricDimension["id"]>();const metricSeen = new Set<ExplorationMetric["id"]>();const metrics: ExplorationMetric[] = [];const dimensionSeen = new Set<MetricDimension["id"]>();const dimensions: MetricDimension[] = [];for (const block of blocks) {- if (block.kind === "metric") {- metricBlockIds.add(block.metric.id);- if (!metricSeen.has(block.metric.id)) {- metricSeen.add(block.metric.id);- metrics.push(block.metric);- }- for (const d of block.dimensions) {- if (block.selectedDimensionIds.has(d.id) && !dimensionSeen.has(d.id)) {- dimensionSeen.add(d.id);- dimensions.push(d);- }- }- } else {- for (const d of block.groupDimensions) {- dimensionBlockIds.add(d.id);- if (!dimensionSeen.has(d.id)) {- dimensionSeen.add(d.id);- dimensions.push(d);- }- }- for (const m of block.metrics) {- if (block.selectedMetricIds.has(m.id) && !metricSeen.has(m.id)) {- metricSeen.add(m.id);- metrics.push(m);- }+ if (!metricSeen.has(block.metric.id)) {+ metricSeen.add(block.metric.id);+ metrics.push(block.metric);+ }+ for (const d of block.dimensions) {+ if (block.selectedDimensionIds.has(d.id) && !dimensionSeen.has(d.id)) {+ dimensionSeen.add(d.id);+ dimensions.push(d);}}}return {blocks,- metricBlockIds,- dimensionBlockIds,timelines,allTimelines,timelinesLoading: false,@@ -120,13 +74,11 @@ export function makeMockSelection(setBlocks: jest.fn(),setTimelines: jest.fn(),addMetric: jest.fn(),- addDimension: jest.fn(),addTimelinesById: jest.fn(),removeTimelinesById: jest.fn(),removeBlock: jest.fn(),- removeBlockMembers: jest.fn(),+ removeBlockDimensions: jest.fn(),toggleDimensionSelected: jest.fn(),- toggleMetricSelected: jest.fn(),};}@@ -175,7 +127,6 @@ export function createBlock(overrides: Partial<ExplorationBlockNode> & Pick<ExplorationBlockNode, "id">,): ExplorationBlockNode {return {- type: "metric",name: null,position: 0,pages: [],@@ -223,7 +174,6 @@ export function createExploration({const finalBlocks: ExplorationBlockNode[] = blocks ?? [{id: INITIAL_BLOCK_ID,- type: "metric",position: 0,name: "Initial investigation",pages: queries.map((q, i) => ({diff --git a/frontend/src/metabase/explorations/utils.ts b/frontend/src/metabase/explorations/utils.tsindex f62f4aa6fe2..44cf6dfbb2a 100644--- a/frontend/src/metabase/explorations/utils.ts+++ b/frontend/src/metabase/explorations/utils.ts@@ -1,7 +1,6 @@import type {DimensionId,ExplorationDimensionGroup,- ExplorationMetric,MetricDimension,} from "metabase-types/api";@@ -58,17 +57,3 @@ export function indexDimensionsById(),);}--export function groupMetricsByDimension(- metrics: ExplorationMetric[],-): Map<DimensionId, ExplorationMetric[]> {- const map = new Map<DimensionId, ExplorationMetric[]>();- for (const metric of metrics) {- for (const id of metric.dimension_ids) {- const list = map.get(id) ?? [];- list.push(metric);- map.set(id, list);- }- }- return map;-}diff --git a/resources/metabot/prompts/system/explorations.selmer b/resources/metabot/prompts/system/explorations.selmerindex fa85ddaea2d..b038371ffee 100644--- a/resources/metabot/prompts/system/explorations.selmer+++ b/resources/metabot/prompts/system/explorations.selmer@@ -10,10 +10,7 @@ If the user has not asked a question related to their data, provide an overview# Research plan structure-A research plan is made of one or more **groups**. Each group is one of:--- **Metric-anchored**: a single metric sliced by a set of dimensions (e.g. "Revenue by Region, by Plan, by Channel"). Use this when the user cares about a particular metric and you want to break it down several ways.-- **Dimension-anchored**: a single dimension that slices a set of related metrics (e.g. "everything by Region"). Use this when the user cares about a particular cut of the business across several metrics.+A research plan is made of one or more **groups**. Each group is a single metric sliced by a set of dimensions (e.g. "Revenue by Region, by Plan, by Channel").# Using Tools@@ -23,10 +20,9 @@ A research plan is made of one or more **groups**. Each group is one of:- If you're unsure whether a metric is relevant, you can use `read_resource` to examine it. `metabase://metric/{id}/dimensions/{dimension_id}` returns sample values for a dimension.- Try to identify multiple relevant metrics and decompose the problem. For example, if the user's question is related to revenue, also consider metrics related to churn, page views, conversion, pricing, etc.- Once you've decided on the plan, call `add_research_groups` once with all the groups, and explain your rationale to the user. No need to ask for confirmation - the user can easily add or remove groups, metrics, and dimensions themselves.- - For a metric-anchored group, pass `{"anchor": "metric", "metric_id": <id>, "dimension_ids": [<id>, ...]}`. The most interesting dimensions are selected automatically; only pass `dimension_ids` for dimensions you specifically want because they fit the user's question (e.g. you'd slice revenue by region when the user asks whether a revenue drop was regional in nature). Most of the time you can simply omit `dimension_ids` to accept just the automatic selection. If the user wants the metric sliced by *only* certain dimensions, pass those `dimension_ids` and add `"replace_default_dimensions": true` to drop the automatic ones.- - For a dimension-anchored group, pass `{"anchor": "dimension", "dimension_id": <id>}` and every metric related to that dimension is included automatically. To include only a chosen few, also pass `"metric_ids": [<id>, ...]`. Prefer this — a single dimension-anchored group with a curated `metric_ids` — when the user asks to look at a handful of metrics by one dimension (e.g. "add a few metrics I can look at by State"): it reads as one "by State" block, which is clearer than several separate metric-anchored groups.- - To add to a group that already exists in the current plan, call `add_research_groups` again for the same anchor with the extra members you want — for a metric-anchored group the extra `dimension_ids`, for a dimension-anchored group the extra `metric_ids` — and they are added to that group's existing selection without removing anything. For example, if the plan already has a Revenue group and the user says "also break revenue down by plan", call `add_research_groups` with the revenue metric and the plan dimension id.-- Use `remove_from_research_plan` to prune the plan. To drop whole groups the user no longer wants, pass their `block_id`s from the current research plan: `{"block_ids": ["metric:42"]}` (e.g. "actually I don't care about revenue" → find the revenue group and remove it by `block_id`). To deselect individual metrics or dimensions within a group, pass `members` instead — `dimension_ids` to stop slicing a metric-anchored group by some dimension, or `metric_ids` to drop a metric from a dimension-anchored group: `{"members": [{"block_id": "metric:42", "dimension_ids": ["d1"]}]}`. Removing the last member of a group drops the whole group. To remove timelines the user no longer wants, pass `timeline_ids` with the ids from the current plan's selected timelines: `{"timeline_ids": [7]}`.+ - For each group, pass `{"metric_id": <id>, "dimension_ids": [<id>, ...]}`. The most interesting dimensions are selected automatically; only pass `dimension_ids` for dimensions you specifically want because they fit the user's question (e.g. you'd slice revenue by region when the user asks whether a revenue drop was regional in nature). Most of the time you can simply omit `dimension_ids` to accept just the automatic selection. If the user wants the metric sliced by *only* certain dimensions, pass those `dimension_ids` and add `"replace_default_dimensions": true` to drop the automatic ones.+ - To add to a group that already exists in the current plan, call `add_research_groups` again for the same metric with the extra `dimension_ids` you want — they are added to that group's existing selection without removing anything. For example, if the plan already has a Revenue group and the user says "also break revenue down by plan", call `add_research_groups` with the revenue metric and the plan dimension id.+- Use `remove_from_research_plan` to prune the plan. To drop whole groups the user no longer wants, pass their `block_id`s from the current research plan: `{"block_ids": ["metric:42"]}` (e.g. "actually I don't care about revenue" → find the revenue group and remove it by `block_id`). To deselect individual dimensions within a group, pass `members` instead, with the `dimension_ids` to stop slicing that group's metric by: `{"members": [{"block_id": "metric:42", "dimension_ids": ["d1"]}]}`. Removing the last member of a group drops the whole group. To remove timelines the user no longer wants, pass `timeline_ids` with the ids from the current plan's selected timelines: `{"timeline_ids": [7]}`.- Use `list_timelines` to identify relevant timelines, then add them with `select_research_timelines`. The user can easily add and remove timelines while visualizing metrics, so bias towards inclusion if you're unsure whether a timeline is relevant. However, timelines are completely optional in Research mode, so you don't need to add them if the user doesn't have any existing timelines or if all the existing timelines are irrelevant.# Important Instructionsdiff --git a/resources/migrations/064/20260831_drop_exploration_block_type.yaml b/resources/migrations/064/20260831_drop_exploration_block_type.yamlnew file mode 100644index 00000000000..8e055557c32--- /dev/null+++ b/resources/migrations/064/20260831_drop_exploration_block_type.yaml@@ -0,0 +1,26 @@+## Drop exploration_block.type. It recorded whether a Research-plan block was anchored on its+## metric ("metric") or its dimension ("dimension"). Dimension-anchored blocks were removed, so+## every block is now a metric crossed with its dimensions and nothing reads or writes the+## column. The rollback recreates it in its pre-drop state (nullable, no default), so existing+## rows come back with a NULL type — the read path treated that as metric-anchored anyway.++databaseChangeLog:++ - changeSet:+ id: v64.2026-08-31T00:00:00+ author: nvoxland+ comment: Drop the unused exploration_block.type column+ changes:+ - dropColumn:+ tableName: exploration_block+ columnName: type+ rollback:+ - addColumn:+ tableName: exploration_block+ columns:+ - column:+ name: type+ type: ${text.type}+ remarks: Block anchor — "metric" or "dimension"+ constraints:+ nullable: truediff --git a/src/metabase/explorations/api.clj b/src/metabase/explorations/api.cljindex 1ccc8fec217..ceb6d841d57 100644--- a/src/metabase/explorations/api.clj+++ b/src/metabase/explorations/api.clj@@ -130,7 +130,7 @@`:dimension_name` labels for `thread` from its pre-fetched `blocks`, `pages`, and`card-name-by-id` (metric Card id → name, for page/heading names)."[thread blocks pages card-name-by-id]- ;; Label queries first so blocks-tree can name metric-anchored pages "By <dimension>".+ ;; Label queries first so blocks-tree can name pages after their dimension.(let [labeled (attach-query-dimension-labels thread blocks)](assoc labeled :blocks (explorations.blocks/blocks-treeblocks pages card-name-by-id (:queries labeled)))))@@ -257,7 +257,7 @@(when (seq blocks)(t2/insert! :model/ExplorationBlock(positional-rows thread-id- (map #(select-keys % [:type :metrics :dimensions]) blocks)))))+ (map #(select-keys % [:metrics :dimensions]) blocks)))))(defn- insert-thread-timelines!"Attach `timeline-ids` to the thread, in payload order. Deduped (`distinct`, keeping first@@ -384,15 +384,11 @@[:semantic-type {:optional true} [:maybe :string]]])(def ^:private BlockSelection- "One Research-plan area on the FE — either a metric area (one primary metric + chosen dimensions)- or a dimension area (the dimension's group + referencing metrics). Persisted verbatim as one- `ExplorationBlock` row; the planners cross this block's metrics with this block's+ "One Research-plan area on the FE — a metric plus its chosen dimensions. Persisted verbatim as+ one `ExplorationBlock` row; the planners cross this block's metrics with this block'sdimensions only. The sidebar heading is computed read-side (the `:name` of an`ExplorationBlockNode`), not supplied here."[:map- ;; Whether the block is anchored on its metric or its dimension. The read side- ;; uses this to build the sidebar heading + sub-item names.- [:type {:optional true} [:maybe [:enum "metric" "dimension"]]][:metrics {:optional true} [:maybe [:sequential MetricSelection]]][:dimensions {:optional true} [:maybe [:sequential DimensionSelection]]]])@@ -440,12 +436,10 @@[:hidden :boolean]])(mr/def ::ExplorationBlockNode- "A block (the FE's sidebar group): a heading plus its pages. `:type` is whether the block is- anchored on its metric or its dimension; `:name` is the computed heading (the metric name, or- `By <dimension>`). `:position` is the block's 0-indexed authoring slot."+ "A block (the FE's sidebar group): a heading plus its pages. `:name` is the computed heading+ (the metric name). `:position` is the block's 0-indexed authoring slot."[:map[:id ms/PositiveInt]- [:type [:enum "metric" "dimension"]][:name [:maybe :string]][:position ms/IntGreaterThanOrEqualToZero][:explore_filters {:optional true}@@ -766,7 +760,6 @@tid (:id thread)](t2/insert! :model/ExplorationBlock{:exploration_thread_id tid- :type (:type block):metrics metrics':dimensions (stringify-dim-types (:dimensions block)):position 0})diff --git a/src/metabase/explorations/blocks.clj b/src/metabase/explorations/blocks.cljindex dd030a08995..94ab83f6672 100644--- a/src/metabase/explorations/blocks.clj+++ b/src/metabase/explorations/blocks.clj@@ -7,7 +7,6 @@page's display name are computed here — they're not persisted."(:require[clojure.string :as str]- [metabase.explorations.models.exploration-block :as block][metabase.explorations.query-plan.variants :as variants][metabase.util.i18n :refer [tru]]))@@ -21,35 +20,12 @@;;; ------------------------------------------- names --------------------------------------------(defn- dimension-anchored?- "Whether `block` is anchored on its dimension (one dimension crossed with several metrics)- rather than its metric. Reads the FE-supplied `:type`; legacy rows (no `:type`) are inferred- — a dimension block is the only shape with more than one metric."- [block]- (case (:type block)- "dimension" true- "metric" false- (> (count (:metrics block)) 1)))--(defn- anchor-dimension- "The dimension a dimension-anchored block is built around (its first/only dimension)."- [block]- (first (:dimensions block)))--(defn- by-dimension- "Render a `By <dimension>` label."- [label]- (tru "By {0}" label))-(defn block-display-name- "Sidebar heading for a block: `By <dimension>` for a dimension-anchored block (using the- dim's curated [[block/dimension-label]]), otherwise the metric's name. `card-name-by-id`- maps a metric Card id to its name. Public so the LLM planner context can label a block- the same way the read tree does."+ "Sidebar heading for a block: its metric's name. `card-name-by-id` maps a metric Card id to+ its name. Public so the LLM planner context can label a block the same way the read tree+ does."[block card-name-by-id]- (if (dimension-anchored? block)- (by-dimension (or (block/dimension-label (anchor-dimension block)) ""))- (or (get card-name-by-id (:card_id (first (:metrics block)))) "")))+ (or (get card-name-by-id (:card_id (first (:metrics block)))) ""))(defn- page-metric-name"The metric (Card) name for `page` — present even on an empty (comment-retained) page."@@ -84,21 +60,14 @@(tru "{0} by {1}" metric dim))))(defn- page-short-name- "A page's name with the axis its block heading already shows removed: for a metric-anchored- block (heading = the metric) the pages vary by dimension, so `<dimension> <variant>`; for- a dimension-anchored block (heading = `By <dimension>`) they vary by metric, so `<metric>- <variant>`."- [block page queries card-name-by-id]- (let [qualifier (page-qualifier page)]- (if (dimension-anchored? block)- (let [metric (page-metric-name page card-name-by-id)]- (if qualifier- (str metric " " qualifier)- metric))- (let [dim (page-dimension-label page queries)]- (if qualifier- (str dim " " qualifier)- dim)))))+ "A page's name with the axis its block heading already shows removed: the heading is the+ metric, and the pages vary by dimension, so `<dimension> <variant>`."+ [page queries]+ (let [qualifier (page-qualifier page)+ dim (page-dimension-label page queries)]+ (if qualifier+ (str dim " " qualifier)+ dim)));;; ------------------------------------------ scoring ------------------------------------------@@ -123,9 +92,9 @@;;; -------------------------------------------- tree -------------------------------------------(defn- page-node- [block page queries card-name-by-id]+ [page queries card-name-by-id]{:id (:id page)- :name (page-short-name block page queries card-name-by-id)+ :name (page-short-name page queries):long_name (page-long-name page queries card-name-by-id):query_ids (mapv :id queries):starred (:starred page)@@ -137,7 +106,6 @@rows, and its hydrated query rows, return the nested vector the FE renders:[{:id <block-pk>- :type \"metric\" | \"dimension\":name <computed heading>:position <0-indexed slot among blocks>:pages [{:id <page-pk>@@ -151,14 +119,14 @@Pages are sorted by interestingness desc within their block. Pages whose block isn't in`blocks` are dropped; queries are matched to their page via `page_id`."[blocks pages card-name-by-id queries]- (let [queries-by-page (group-by :page_id queries)- pages-by-block (group-by :exploration_block_id pages)]+ (let [queries-by-page (group-by :page_id queries)+ pages-by-block (group-by :exploration_block_id pages)](into [](map-indexed(fn [block-pos block](let [block-pages (->> (get pages-by-block (:id block) [])(map (fn [page]- (page-node block page+ (page-node page(get queries-by-page (:id page) [])card-name-by-id)))(sort-by page-sort-key)@@ -168,7 +136,6 @@(dissoc ::max-score))))vec)]{:id (:id block)- :type (if (dimension-anchored? block) "dimension" "metric"):name (block-display-name block card-name-by-id):position block-pos:explore_filters (:explore_filters (first (:metrics block)))diff --git a/src/metabase/explorations/impl.clj b/src/metabase/explorations/impl.cljindex 58aec70fea0..1f837b6bc0d 100644--- a/src/metabase/explorations/impl.clj+++ b/src/metabase/explorations/impl.clj@@ -425,7 +425,7 @@Rows are always ordered by [[rank-metrics]], so a metric doesn't move just because theinstance grew past the cap. More than [[research-metric-index-max-metrics]] matches aretruncated and stamped `{:truncated true :shown <n> :matched <m>}` so the model knows to narrow- with `:q`. A metric with no candidate dimensions still gets a row — it can anchor a group on+ with `:q`. A metric with no candidate dimensions still gets a row — it can form a group onits own — but ranks below every metric that has one."[opts](let [ranked (rank-metrics (mapv with-candidate-dimensions (index-metrics opts)))@@ -512,69 +512,34 @@(defn research-groups"Validate Metabot's chosen research groups and return the FE picker payload for them.- `:groups` is a sequence of maps, each either- `{:anchor \"metric\" :metric_id <int> :dimension_ids [<str> ...]}` (`:dimension_ids` optional)- or `{:anchor \"dimension\" :dimension_id <str>}`.+ `:groups` is a sequence of `{:metric_id <int> :dimension_ids [<str> ...]}` maps+ (`:dimension_ids` optional).- Hard-errors (throws) on any unknown/inaccessible metric id, unknown dimension id, or a- dimension id that isn't a candidate of its metric — one bad id fails the whole batch.+ Hard-errors (throws) on any unknown/inaccessible metric id or a dimension id that isn't a+ candidate of its metric — one bad id fails the whole batch.On success returns `{:metrics [...] :dimension_groups [...] :groups [...]}`, where`:metrics`/`:dimension_groups` are the [[exploration-data]] hydration restricted to the- referenced metrics (a metric anchor pulls its metric; a dimension anchor pulls every metric- exposing any dimension in that dimension's group), and `:groups` echoes the validated specs- for the FE to turn into picker blocks."+ referenced metrics, and `:groups` echoes the validated specs for the FE to turn into picker+ blocks."[{:keys [groups]}](let [all (mapv with-candidate-dimensions (hydrated-metrics {}))- metric-by-id (u/index-by :id all)- dim->metrics (dimension-id->metric-ids all)- all-dim-ids (set (keys dim->metrics))- ;; dimension id -> the set of dimension ids in its group (same-source bundle)- dim->group (into {} (mapcat (fn [g]- (let [ids (set (map :id (:dimensions g)))]- (map (fn [id] [id ids]) ids)))- (group-dimensions all)))]+ metric-by-id (u/index-by :id all)](doseq [g groups]- (case (:anchor g)- "metric"- (let [metric-id (:metric_id g)- metric (get metric-by-id metric-id)]- (when (nil? metric-id)- (throw (ex-info "A metric-anchored group requires a metric_id" {:group g})))- (when-not metric- (throw (ex-info (format "Unknown or inaccessible metric id %s" metric-id)- {:anchor "metric" :metric_id metric-id})))- (when (and (:replace_default_dimensions g) (empty? (:dimension_ids g)))- (throw (ex-info "replace_default_dimensions requires at least one dimension_id"- {:anchor "metric" :metric_id metric-id})))- (let [valid (set (map :id (:dimensions metric)))]- (doseq [d (:dimension_ids g)]- (when-not (contains? valid d)- (throw (ex-info (format "Dimension %s is not a candidate of metric %s" d metric-id)- {:anchor "metric" :metric_id metric-id :dimension_id d}))))))- "dimension"- (let [dimension-id (:dimension_id g)]- (when (nil? dimension-id)- (throw (ex-info "A dimension-anchored group requires a dimension_id" {:group g})))- (when-not (contains? all-dim-ids dimension-id)- (throw (ex-info (format "Unknown dimension id %s" dimension-id)- {:anchor "dimension" :dimension_id dimension-id})))- (when-let [mids (seq (:metric_ids g))]- (let [related (into #{} (mapcat dim->metrics) (dim->group dimension-id))]- (doseq [mid mids]- (when-not (contains? related mid)- (throw (ex-info (format "Metric %s is not related to dimension %s" mid dimension-id)- {:anchor "dimension" :dimension_id dimension-id :metric_id mid})))))))- (throw (ex-info (format "Unknown anchor %s" (:anchor g)) {:group g}))))- (let [relevant (reduce (fn [acc g]- (case (:anchor g)- "metric" (conj acc (:metric_id g))- "dimension" (let [related (into #{} (mapcat dim->metrics)- (dim->group (:dimension_id g)))]- (into acc (if-let [mids (seq (:metric_ids g))]- (filter related mids)- related)))))- #{} groups)+ (let [metric-id (:metric_id g)+ metric (get metric-by-id metric-id)]+ (when-not metric+ (throw (ex-info (format "Unknown or inaccessible metric id %s" metric-id)+ {:metric_id metric-id})))+ (when (and (:replace_default_dimensions g) (empty? (:dimension_ids g)))+ (throw (ex-info "replace_default_dimensions requires at least one dimension_id"+ {:metric_id metric-id})))+ (let [valid (set (map :id (:dimensions metric)))]+ (doseq [d (:dimension_ids g)]+ (when-not (contains? valid d)+ (throw (ex-info (format "Dimension %s is not a candidate of metric %s" d metric-id)+ {:metric_id metric-id :dimension_id d})))))))+ (let [relevant (into #{} (map :metric_id) groups)relevant-metrics (filterv #(contains? relevant (:id %)) all)]{:metrics (mapv slim-metric relevant-metrics):dimension_groups (group-dimensions relevant-metrics)diff --git a/src/metabase/metabot/tools/explorations.clj b/src/metabase/metabot/tools/explorations.cljindex 4f95b64e6a7..d44c1a94e1b 100644--- a/src/metabase/metabot/tools/explorations.clj+++ b/src/metabase/metabot/tools/explorations.clj@@ -25,16 +25,10 @@(defn- format-research-plan-group"Format one group of the draft Research plan as a single line the LLM can act on. The`block_id` is surfaced verbatim so the agent can echo it back to plan-editing tools, and each- member dimension/metric carries its id in parentheses."- [{:keys [block_id anchor metric dimensions dimension metrics]}]- (case anchor- "metric"- (str "- [" block_id "] " (:name metric)- ", broken out by: " (str/join ", " (map named-with-id dimensions)))- "dimension"- (str "- [" block_id "] by " (:name dimension)- ", slicing: " (str/join ", " (map named-with-id metrics)))- nil))+ member dimension carries its id in parentheses."+ [{:keys [block_id metric dimensions]}]+ (str "- [" block_id "] " (:name metric)+ ", broken out by: " (str/join ", " (map named-with-id dimensions))))(defn format-research-plan"Format the user's in-progress draft Research plan for injection into the system message.@@ -57,7 +51,7 @@""(te/field "Plan name" (not-empty name))(when (seq groups)- (te/lines "Groups:" (keep format-research-plan-group groups)))+ (te/lines "Groups:" (map format-research-plan-group groups)))(when (seq timelines)(te/field "Selected timelines" (str/join ", " (map named-with-id timelines)))))))))@@ -122,28 +116,19 @@[:groups[:sequential[:map {:closed true}- [:anchor [:enum "metric" "dimension"]]- [:metric_id {:optional true} :int]- [:dimension_id {:optional true} :string]+ [:metric_id :int][:dimension_ids {:optional true} [:sequential :string]]- [:metric_ids {:optional true} [:sequential :int]][:replace_default_dimensions {:optional true} :boolean]]]]])(mu/defn ^{:tool-name "add_research_groups":scope scope/agent-explorations-write}add-research-groups-tool- "Add one or more groups to the research artifact. Each group is either:- - metric-anchored: `{\"anchor\": \"metric\", \"metric_id\": <id>, \"dimension_ids\": [<id>, ...]}`- — the metric sliced by the chosen dimensions. By default `dimension_ids` are added on top of- the automatically-selected interesting dimensions; omit it to use only the automatic- selection. To pin the metric to exactly the dimensions you list (no automatic ones), also- pass `\"replace_default_dimensions\": true` - then `dimension_ids` must be non-empty.- - dimension-anchored: `{\"anchor\": \"dimension\", \"dimension_id\": <id>}`, the dimension- slicing every related metric. To slice only a chosen few, pass- `\"metric_ids\": [<id>, ...]` and just those metrics are included. Prefer this (a single- dimension-anchored group with a curated `metric_ids`) when the user asks to look at a handful- of metrics by one dimension — it reads as one \"by <dimension>\" block rather than several- loose metrics."+ "Add one or more groups to the research artifact. Each group is a metric sliced by chosen+ dimensions: `{\"metric_id\": <id>, \"dimension_ids\": [<id>, ...]}`. By default+ `dimension_ids` are added on top of the automatically-selected interesting dimensions; omit+ it to use only the automatic selection. To pin the metric to exactly the dimensions you+ list (no automatic ones), also pass `\"replace_default_dimensions\": true` - then+ `dimension_ids` must be non-empty."[{:keys [groups]} :- add-research-groups-schema]{:output (json/encode (explorations/exploration-data->api(explorations/research-groups {:groups groups})))})@@ -155,23 +140,20 @@[:sequential[:map {:closed true}[:block_id :string]- [:metric_ids {:optional true} [:sequential :int]]- [:dimension_ids {:optional true} [:sequential :string]]]]]+ [:dimension_ids [:sequential :string]]]]][:timeline_ids {:optional true} [:sequential :int]]])(mu/defn ^{:tool-name "remove_from_research_plan":scope scope/agent-explorations-write}remove-from-research-plan-tool- "Remove groups, individual metrics/dimensions within a group, or timelines from the research- plan. Address groups by the `block_id` shown in brackets for each group in the current research- plan (e.g. `metric:42`, `dim:7`).+ "Remove groups, individual dimensions within a group, or timelines from the research plan.+ Address groups by the `block_id` shown in brackets for each group in the current research+ plan (e.g. `metric:42`).- To drop whole groups, pass `block_ids`: `{\"block_ids\": [\"metric:42\"]}`. Use this when the- user no longer wants a metric or dimension area at all (e.g. \"actually I don't care about- revenue\").- - To prune within a group, pass `members`. For a metric-anchored group, list the- `dimension_ids` to stop slicing by; for a dimension-anchored group, list the `metric_ids` to- stop including: `{\"members\": [{\"block_id\": \"metric:42\", \"dimension_ids\": [\"d1\"]}]}`.+ user no longer wants a metric at all (e.g. \"actually I don't care about revenue\").+ - To prune within a group, pass `members` with the `dimension_ids` to stop slicing that+ group's metric by: `{\"members\": [{\"block_id\": \"metric:42\", \"dimension_ids\": [\"d1\"]}]}`.- To drop timelines, pass `timeline_ids` (the ids shown in the current plan's selectedtimelines): `{\"timeline_ids\": [7]}`.diff --git a/test/metabase/explorations/api_test.clj b/test/metabase/explorations/api_test.cljindex 6fd8ae4abc4..aeb8065cac9 100644--- a/test/metabase/explorations/api_test.clj+++ b/test/metabase/explorations/api_test.clj@@ -143,7 +143,7 @@body(-> body(dissoc :metrics :dimensions)- (assoc :blocks [{:type "metric" :metrics metrics :dimensions dimensions}]))))+ (assoc :blocks [{:metrics metrics :dimensions dimensions}]))))(defn- create-exploration!"POST a new exploration as `user`, then synchronously run the query planner for@@ -369,8 +369,8 @@(is (= "Releases" (-> timelines first :timeline :name))"nested :timeline is hydrated for the picker")))))-(deftest exploration-block-naming-by-type-test- (testing "GET builds block headings + page names from the block :type"+(deftest exploration-block-naming-test+ (testing "GET builds block headings (the metric name) + dimension-named pages"(mt/with-temp [:model/User u {:email "[email protected]"}:model/Card revenue (assoc (valid-metric-card (:id u)) :name "Revenue"):model/Card signups (assoc (valid-metric-card (:id u)) :name "Signups")]@@ -381,69 +381,26 @@:card_id card-id}])dims [{:dimension_id (duid "d1") :display_name "Price" :effective_type "type/Number"}]body {:name "Naming"- :blocks [;; metric-anchored: one metric crossed with a dimension- {:type "metric"- :metrics [{:card_id (:id revenue)+ :blocks [{:metrics [{:card_id (:id revenue):dimension_mappings (mapping (:id revenue))}]:dimensions dims}- ;; dimension-anchored: one dimension crossed with two metrics- {:type "dimension"- :metrics [{:card_id (:id revenue)- :dimension_mappings (mapping (:id revenue))}- {:card_id (:id signups)+ {:metrics [{:card_id (:id signups):dimension_mappings (mapping (:id signups))}]:dimensions dims}]}resp (create-exploration! u body)blocks (-> resp :threads first :blocks)- metric-block (first (filter #(= "metric" (:type %)) blocks))- dimension-block (first (filter #(= "dimension" (:type %)) blocks))+ revenue-block (first (filter #(= "Revenue" (:name %)) blocks))+ signups-block (first (filter #(= "Signups" (:name %)) blocks))page-names (fn [block] (set (map :name (:pages block))))long-names (fn [block] (set (map :long_name (:pages block))))]- (testing "metric-anchored block: heading is the metric, pages are the dimension"- (is (= "Revenue" (:name metric-block)))- (is (= #{"Price"} (page-names metric-block)))- (testing "long_name is self-describing (carries the metric the heading drops)"- (is (= #{"Revenue by Price"} (long-names metric-block)))))- (testing "dimension-anchored block: heading is By <dimension>, pages are the metrics"- (is (= "By Price" (:name dimension-block)))- (is (= #{"Revenue" "Signups"} (page-names dimension-block)))- (testing "long_name is self-describing (carries the dimension the heading drops)"- (is (= #{"Revenue by Price" "Signups by Price"} (long-names dimension-block)))))))))--(deftest exploration-dimension-group-heading-uses-curated-name-test- (testing "GET uses each dimension's curated display_name for dimension-anchored headings"- (let [users-created "00000000-0000-0000-0000-0000000a1111"- orders-created "00000000-0000-0000-0000-0000000b2222"]- (mt/with-temp- [:model/User u {:email "[email protected]"}- :model/Card revenue (assoc (valid-metric-card (:id u))- :name "Revenue"- :dimensions- [{:id users-created :name "CREATED_AT" :display-name "Created At"- :group {:id "g-users" :type "main" :display-name "Users"}}- {:id orders-created :name "CREATED_AT" :display-name "Created At"- :group {:id "g-orders" :type "connection" :display-name "Orders"}}])]- (let [mapping (fn [dim-id field-id]- [{:dimension_id dim-id :table_id 1 :target ["field" {} field-id]}])- dim-grp (fn [dim-id field-id]- {:type "dimension"- :metrics [{:card_id (:id revenue)- :dimension_mappings (mapping dim-id field-id)}]- :dimensions [{:dimension_id dim-id :display_name "Created At"}]})- headings (fn [body]- (->> (create-exploration! u body) :threads first :blocks- (filter #(= "dimension" (:type %)))- (map :name)- set))]- (testing "two dimension blocks sharing a display_name keep the curated heading (no group prefix)"- (is (= #{"By Created At"}- (headings {:name "ambig-headings"- :blocks [(dim-grp users-created 1)- (dim-grp orders-created 2)]}))))- (testing "a single dimension group uses the curated heading"- (is (= #{"By Created At"}- (headings {:name "single-heading"- :blocks [(dim-grp users-created 1)]})))))))))+ (is (some? revenue-block))+ (is (some? signups-block))+ (testing "pages are named after the dimension"+ (is (= #{"Price"} (page-names revenue-block)))+ (is (= #{"Price"} (page-names signups-block))))+ (testing "long_name is self-describing (carries the metric the heading drops)"+ (is (= #{"Revenue by Price"} (long-names revenue-block)))+ (is (= #{"Signups by Price"} (long-names signups-block))))))))(deftest exploration-create-persists-blocks-verbatim-test(testing "POST / persists each :blocks entry as its own ExplorationBlock row — no dedup across blocks"@@ -453,19 +410,16 @@(let [mapping [{:dimension_id (duid "d1"):table_id (mt/id :venues):target ["field" {} (mt/id :venues :price)]}]- ;; Two blocks sharing the same metric: a metric block (metric + d1) and a- ;; dimension block (the same metric, with d2). Timelines are thread-scoped,- ;; sent once at the top level. Each block is stored verbatim — the shared- ;; metric is NOT deduped across blocks.+ ;; Two blocks sharing the same metric: one with d1, one with d2. Timelines are+ ;; thread-scoped, sent once at the top level. Each block is stored verbatim — the+ ;; shared metric is NOT deduped across blocks.body {:name "Blocked create":prompt "via blocks":timeline_ids [(:id tl)]- :blocks [{:type "metric"- :metrics [{:card_id (:id metric) :dimension_mappings mapping}]+ :blocks [{:metrics [{:card_id (:id metric) :dimension_mappings mapping}]:dimensions [{:dimension_id (duid "d1") :display_name "Price":effective_type "type/Number"}]}- {:type "dimension"- :metrics [{:card_id (:id metric) :dimension_mappings mapping}]+ {:metrics [{:card_id (:id metric) :dimension_mappings mapping}]:dimensions [{:dimension_id (duid "d2") :display_name "Category":effective_type "type/Text"}]}]}resp (mt/user-http-request u :post 200 "exploration" body)@@ -474,7 +428,6 @@:exploration_thread_id tid {:order-by [[:position :asc]]})](is (= "Blocked create" (:name resp)))(is (= 2 (count blocks)) "one row per block, no dedup")- (is (= ["metric" "dimension"] (map :type blocks)) "anchor type stored in payload order")(is (= [0 1] (map :position blocks)))(testing "each block keeps its own metrics + dimensions selection"(is (= [(:id metric) (:id metric)] (map #(-> % :metrics first :card_id) blocks)))@@ -1432,9 +1385,8 @@(is (nil? (:source_page_id orig))))(is (= "Number of venues → Price: 2" (:name new))"thread name uses Metric → Column: Value for top-level follow-ups")- (testing "new block copies type/dimensions and appends explore_filters onto metrics"+ (testing "new block copies dimensions and appends explore_filters onto metrics"(let [persisted (t2/select-one :model/ExplorationBlock :exploration_thread_id (:id new))]- (is (= "metric" (:type new-block)))(is (= [(duid "category") (duid "price")] (mapv :dimension-id (:dimensions persisted))))(let [persisted-filters (:explore_filters (first (:metrics persisted)))](is (= 1 (count persisted-filters)))@@ -1976,10 +1928,9 @@p-> (page-by-id tree)](is (= [1 2] (mapv :id tree)) "one node per block, in authoring order")(is (= [0 1] (mapv :position tree)) ":position reifies block order")- (testing "block headings come from the metric card name; all metric-anchored here"+ (testing "block headings come from the metric card name"(is (= "Revenue block" (:name (by-id 1))))- (is (= "Count block" (:name (by-id 2))))- (is (every? #(= "metric" (:type %)) tree)))+ (is (= "Count block" (:name (by-id 2)))))(testing "pages nest under their block (score-sorted)"(is (= [100 101] (mapv :id (:pages (by-id 1)))) "page 100 (max 0.7) before page 101 (0.4)")(is (= [200] (mapv :id (:pages (by-id 2))))))@@ -2107,11 +2058,10 @@pages (mapcat :pages blocks)](is (= 9 (count queries))"category (default+top-n-other) × 3 + price (default) × 3 = 9 queries")- (testing "one metric-anchored block"+ (testing "one block"(is (= 1 (count blocks)))(let [[b] blocks]- (is (= "Revenue" (:name b)) "metric-anchored heading is the metric name")- (is (= "metric" (:type b)))+ (is (= "Revenue" (:name b)) "heading is the metric name")(is (= block-id (:id b)) "block node id is the persisted block PK")(is (= 0 (:position b)))))(testing "pages partition the queries by (card, dim, query_type)"@@ -2143,11 +2093,9 @@(let [dims [{:dimension_id (duid "category") :display_name "Category"}{:dimension_id (duid "price") :display_name "Price"}]body {:name "multi"- :blocks [{:type "metric"- :metrics [{:card_id (:id m1) :dimension_mappings (venues-dimension-mappings)}]+ :blocks [{:metrics [{:card_id (:id m1) :dimension_mappings (venues-dimension-mappings)}]:dimensions dims}- {:type "metric"- :metrics [{:card_id (:id m2) :dimension_mappings (venues-dimension-mappings)}]+ {:metrics [{:card_id (:id m2) :dimension_mappings (venues-dimension-mappings)}]:dimensions dims}]}{eid :id} (create-exploration! u body)resp (mt/user-http-request u :get 200 (format "exploration/%d" eid))@@ -2155,8 +2103,7 @@blocks (:blocks thread)](is (= 2 (count blocks)) "two blocks → two top-level nodes")(is (= #{"Revenue" "Order count"} (set (map :name blocks)))- "metric-anchored headings are the metric names")- (is (every? #(= "metric" (:type %)) blocks))+ "headings are the metric names")(is (every? #(int? (:id %)) blocks) "block node ids are the persisted block PKs")(testing "each block has its own pages (category default+top-n-other + price default = 3)"(is (every? #(= 3 (count (:pages %))) blocks)))@@ -2513,7 +2460,7 @@{:exploration_id (:id expl) :name "t" :position 0}))block (first (t2/insert-returning-instances! :model/ExplorationBlock{:exploration_thread_id (:id thread)- :type "metric" :metrics metrics+ :metrics metrics:dimensions (or dimensions []) :position 0}))page (first (t2/insert-returning-instances! :model/ExplorationPage{:exploration_block_id (:id block)@@ -2771,12 +2718,10 @@:collection_id (:id (collection/user->personal-collection (:id u)))}](testing "an unreadable card id is a 403"(mt/user-http-request u :post 403 "exploration"- (assoc base :blocks [{:type "metric"- :metrics [{:card_id (:id secret)}]}])))+ (assoc base :blocks [{:metrics [{:card_id (:id secret)}]}])))(testing "a nonexistent card id is a 404"(mt/user-http-request u :post 404 "exploration"- (assoc base :blocks [{:type "metric"- :metrics [{:card_id Integer/MAX_VALUE}]}])))+ (assoc base :blocks [{:metrics [{:card_id Integer/MAX_VALUE}]}])))(testing "nothing was persisted by the rejected requests"(is (zero? (t2/count :model/Exploration :name "block perm check"))))))))diff --git a/test/metabase/explorations/blocks_test.clj b/test/metabase/explorations/blocks_test.cljnew file mode 100644index 00000000000..dd49f296d6c--- /dev/null+++ b/test/metabase/explorations/blocks_test.clj@@ -0,0 +1,26 @@+(ns metabase.explorations.blocks-test+ (:require+ [clojure.test :refer :all]+ [metabase.explorations.blocks :as explorations.blocks]))++(deftest ^:parallel blocks-tree-renders-legacy-dimension-anchored-rows-test+ (testing "an ExplorationBlock row persisted before dimension-anchored blocks were removed+ (`:type \"dimension\"`, several metrics) still renders — as a plain metric-headed+ block — rather than crashing the read path"+ (let [block {:id 1+ :type "dimension"+ :metrics [{:card_id 10} {:card_id 11}]+ :dimensions [{:dimension-id "d1" :display-name "Region"}]}+ pages [{:id 5 :exploration_block_id 1 :card_id 10 :dimension_id "d1"+ :query_type "default" :starred false :hidden false}+ {:id 6 :exploration_block_id 1 :card_id 11 :dimension_id "d1"+ :query_type "default" :starred false :hidden false}]+ queries [{:id 100 :page_id 5 :dimension_name "Region"}+ {:id 101 :page_id 6 :dimension_name "Region"}]+ [node] (explorations.blocks/blocks-tree [block] pages+ {10 "Revenue" 11 "Signups"} queries)]+ (is (= "Revenue" (:name node)) "heading falls back to the first metric's name")+ (is (not (contains? node :type)) "the read tree no longer reports a block type")+ (is (= ["Region" "Region"] (map :name (:pages node))))+ (is (= #{"Revenue by Region" "Signups by Region"}+ (set (map :long_name (:pages node))))))))diff --git a/test/metabase/explorations/impl_test.clj b/test/metabase/explorations/impl_test.cljindex 9a571fa7692..a6fd67508f9 100644--- a/test/metabase/explorations/impl_test.clj+++ b/test/metabase/explorations/impl_test.clj@@ -333,72 +333,35 @@(is (true? (:truncated payload)))(is (> 20000 (count (json/encode payload)))))))-(deftest research-groups-metric-anchored-test+(deftest research-groups-test(with-synthetic-metrics- (testing "a valid metric-anchored group echoes its spec and restricts to that metric"- (let [spec {:anchor "metric" :metric_id 1 :dimension_ids ["plan-1"]}+ (testing "a valid group echoes its spec and restricts to that metric"+ (let [spec {:metric_id 1 :dimension_ids ["plan-1"]}{:keys [metrics groups]} (explorations.impl/research-groups {:groups [spec]})](is (= [spec] groups))(is (= [1] (mapv :id metrics)))(is (= ["region-1" "plan-1"] (:dimension_ids (first metrics))))))(testing "dimension_ids is optional"(is (= [1] (mapv :id (:metrics (explorations.impl/research-groups- {:groups [{:anchor "metric" :metric_id 1}]}))))))))--(deftest research-groups-dimension-anchored-test- (with-synthetic-metrics- (testing "a dimension-anchored group pulls every metric exposing a dimension in that group"- (let [{:keys [metrics groups]} (explorations.impl/research-groups- {:groups [{:anchor "dimension" :dimension_id "region-1"}]})]- (is (= [{:anchor "dimension" :dimension_id "region-1"}] groups))- ;; region-1 and region-2 share a source -> one group across metrics 1 and 2- (is (= [1 2] (sort (mapv :id metrics))))))))--(deftest research-groups-dimension-anchored-metric-subset-test- (with-synthetic-metrics- (testing "metric_ids restricts a dimension-anchored group to the chosen metrics"- (let [spec {:anchor "dimension" :dimension_id "region-1" :metric_ids [1]}- {:keys [metrics groups]} (explorations.impl/research-groups {:groups [spec]})]- (is (= [spec] groups))- (is (= [1] (mapv :id metrics)))))- (testing "omitting metric_ids still pulls every metric exposing the dimension"+ {:groups [{:metric_id 1}]}))))))+ (testing "several groups pull the union of their metrics"(is (= [1 2] (sort (mapv :id (:metrics (explorations.impl/research-groups- {:groups [{:anchor "dimension" :dimension_id "region-1"}]})))))))))+ {:groups [{:metric_id 1} {:metric_id 2}]})))))))))(deftest research-groups-hard-errors-test(with-synthetic-metrics(testing "unknown metric id"(is (thrown-with-msg? Exception #"Unknown or inaccessible metric id 999"(explorations.impl/research-groups- {:groups [{:anchor "metric" :metric_id 999}]}))))+ {:groups [{:metric_id 999}]}))))(testing "dimension that isn't a candidate of its metric"(is (thrown-with-msg? Exception #"not a candidate of metric"(explorations.impl/research-groups- {:groups [{:anchor "metric" :metric_id 1 :dimension_ids ["region-2"]}]}))))- (testing "unknown dimension id"- (is (thrown-with-msg? Exception #"Unknown dimension id"- (explorations.impl/research-groups- {:groups [{:anchor "dimension" :dimension_id "bogus"}]}))))+ {:groups [{:metric_id 1 :dimension_ids ["region-2"]}]}))))(testing "replace_default_dimensions with no dimension_ids"(is (thrown-with-msg? Exception #"replace_default_dimensions requires"(explorations.impl/research-groups- {:groups [{:anchor "metric" :metric_id 1 :replace_default_dimensions true}]}))))- (testing "metric_id not related to a dimension-anchored group's dimension"- (is (thrown-with-msg? Exception #"not related to dimension"- (explorations.impl/research-groups- {:groups [{:anchor "dimension" :dimension_id "plan-1" :metric_ids [2]}]}))))- (testing "unknown anchor"- (is (thrown-with-msg? Exception #"Unknown anchor"- (explorations.impl/research-groups- {:groups [{:anchor "segment" :metric_id 1}]}))))- (testing "metric anchor missing metric_id"- (is (thrown-with-msg? Exception #"requires a metric_id"- (explorations.impl/research-groups- {:groups [{:anchor "metric"}]}))))- (testing "dimension anchor missing dimension_id"- (is (thrown-with-msg? Exception #"requires a dimension_id"- (explorations.impl/research-groups- {:groups [{:anchor "dimension"}]}))))))+ {:groups [{:metric_id 1 :replace_default_dimensions true}]}))))));;; ------------------------------------------ exploration-data ------------------------------------------diff --git a/test/metabase/metabot/tools/explorations_test.clj b/test/metabase/metabot/tools/explorations_test.cljindex bb280a2ff4a..756b3933cc7 100644--- a/test/metabase/metabot/tools/explorations_test.clj+++ b/test/metabase/metabot/tools/explorations_test.clj@@ -59,19 +59,19 @@(deftest ^:parallel remove-from-research-plan-tool-test(testing "echoes the block ids the agent asked to remove (pure-echo; the FE applies them)"- (is (= {:block_ids ["metric:42" "dim:7"] :members nil :timeline_ids nil}+ (is (= {:block_ids ["metric:42" "metric:43"] :members nil :timeline_ids nil}(decoded-output(tools.explorations/remove-from-research-plan-tool- {:block_ids ["metric:42" "dim:7"]})))))- (testing "echoes member-level removals (deselect dimensions/metrics within a group)"+ {:block_ids ["metric:42" "metric:43"]})))))+ (testing "echoes member-level removals (deselect dimensions within a group)"(is (= {:block_ids nil:members [{:block_id "metric:42" :dimension_ids ["d1"]}- {:block_id "dim:7" :metric_ids [43]}]+ {:block_id "metric:43" :dimension_ids ["d2" "d3"]}]:timeline_ids nil}(decoded-output(tools.explorations/remove-from-research-plan-tool{:members [{:block_id "metric:42" :dimension_ids ["d1"]}- {:block_id "dim:7" :metric_ids [43]}]})))))+ {:block_id "metric:43" :dimension_ids ["d2" "d3"]}]})))))(testing "echoes timeline removals"(is (= {:block_ids nil :members nil :timeline_ids [7 9]}(decoded-output@@ -116,24 +116,20 @@(deftest ^:parallel format-research-plan-test(let [plan {:name "Why was revenue down?":groups [{:block_id "metric:42"- :anchor "metric":metric {:id 42 :name "Revenue"}:dimensions [{:id "d1" :name "Region"}{:id "d2" :name "Plan"}]}- {:block_id "dim:7"- :anchor "dimension"- :dimension {:id "d7" :name "Plan"}- :metrics [{:id 42 :name "Revenue"}- {:id 43 :name "Churn"}]}]+ {:block_id "metric:43"+ :metric {:id 43 :name "Churn"}+ :dimensions [{:id "d7" :name "Plan"}]}]:timelines [{:id 1 :name "Releases"}]}](testing "renders groups with block ids, name, and timelines"(let [result (tools.explorations/format-research-plan {:research_plan plan})](is (string? result))(is (str/includes? result "Why was revenue down?"))- ;; metric-anchored group surfaces its block id and selected dimensions with their ids+ ;; each group surfaces its block id and selected dimensions with their ids(is (str/includes? result "[metric:42] Revenue, broken out by: Region (d1), Plan (d2)"))- ;; dimension-anchored group surfaces its block id and the metrics it slices with their ids- (is (str/includes? result "[dim:7] by Plan, slicing: Revenue (42), Churn (43)"))+ (is (str/includes? result "[metric:43] Churn, broken out by: Plan (d7)"))(is (str/includes? result "Selected timelines: Releases (1)"))))(testing "returns nil when there is no plan in context"(is (nil? (tools.explorations/format-research-plan {}))))@@ -151,7 +147,6 @@(let [profile (profiles/get-profile :explorations)plan {:name "Why was revenue down?":groups [{:block_id "metric:42"- :anchor "metric":metric {:id 42 :name "Revenue"}:dimensions [{:id "d1" :name "Region"}]}]}content (:content (messages/build-system-message {:research_plan plan} profile {}))]