Skip to content

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

GDGT-2646 Refresh leads to custom viz reverting to standard viz (#79888)

Kamil Mielnik7470cf248504
diff --git a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts
index e3e6f1fe1a5..bbbc1bf9029 100644
--- a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts
+++ b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts
@@ -1,10 +1,15 @@
-import { SAMPLE_DB_TABLES, USER_GROUPS } from "e2e/support/cypress_data";
+import {
+ SAMPLE_DB_ID,
+ SAMPLE_DB_TABLES,
+ USER_GROUPS,
+} from "e2e/support/cypress_data";
import {
type DashboardDetails,
type StructuredQuestionDetails,
adminAppLinkText,
mainAppLinkText,
} from "e2e/support/helpers";
+import { b64hash_to_utf8 } from "metabase/utils/encoding";
import { checkNotNull } from "metabase/utils/types";
import type {
CardId,
@@ -12,6 +17,7 @@ import type {
DashboardId,
DocumentContent,
Parameter,
+ UnsavedCard,
} from "metabase-types/api";
const { H } = cy;
@@ -625,6 +631,39 @@ describe("admin > custom visualizations", () => {
H.main().findByText("Threshold: 42").should("be.visible");
});
+ it("keeps an unsaved question's custom viz after a browser reload (metabase#76065)", () => {
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ },
+ });
+
+ switchToDemoViz();
+ H.main()
+ .findByText("Custom viz rendered successfully")
+ .should("be.visible");
+
+ cy.location("hash").should((hash) => {
+ const card: UnsavedCard = JSON.parse(b64hash_to_utf8(hash));
+ expect(card.display).to.eq(H.CUSTOM_VIZ_DISPLAY);
+ expect(card.displayIsLocked).to.eq(true);
+ });
+
+ H.interceptPluginBundle();
+ cy.reload();
+ cy.wait("@pluginBundle");
+
+ H.main()
+ .findByText("Custom viz rendered successfully")
+ .should("be.visible");
+ cy.findByTestId("scalar-value").should("not.exist");
+ });
+
it("opens the column formatting popover from a field setting (metabase#78039)", () => {
H.visitQuestion("@questionId");
switchToDemoViz();
diff --git a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
index b5fb7082c60..f4df2f7ce7b 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
@@ -6,13 +6,15 @@ import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensur
import { api } from "metabase/api/client";
import type { IconData } from "metabase/common/utils/icon";
import { isEmbeddingEajs } from "metabase/embedding-sdk/config";
-import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
+import {
+ type LoadCustomVizPluginForDisplayResult,
+ PLUGIN_CUSTOM_VIZ,
+} from "metabase/plugins";
import type { DispatchFn } from "metabase/redux/hooks";
import {
getCustomPluginIdentifier,
getPluginAssetUrl,
} from "metabase/visualizations/custom-visualizations/custom-viz-utils";
-import { customVizPluginApi } from "metabase-enterprise/api/custom-viz-plugin";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import type {
CustomVizPluginId,
@@ -25,6 +27,7 @@ import { CustomVizSettingWidget } from "../../metabase-enterprise/custom_viz/com
import type { LoadCustomVizPluginOptions } from "../../metabase-enterprise/custom_viz/custom-viz-plugins";
import {
loadCustomVizPlugin as eeLoadCustomVizPlugin,
+ loadCustomVizPluginForDisplay as eeLoadCustomVizPluginForDisplay,
useAutoLoadCustomVizPlugin as eeUseAutoLoadCustomVizPlugin,
useCustomVizPlugins as eeUseCustomVizPlugins,
unregisterCustomVizDisplay,
@@ -157,30 +160,14 @@ export function initializeSdkCustomVizPlugin() {
loadCustomVizPluginForDisplay: async (
dispatch: DispatchFn,
display: string,
- ): Promise<string | null> => {
+ ): Promise<LoadCustomVizPluginForDisplayResult> => {
if (!isCustomVizAllowed(display, getAllowlist())) {
- return null;
- }
- const identifier = display.slice("custom:".length);
- const action = dispatch(
- customVizPluginApi.endpoints.listCustomVizPlugins.initiate(undefined),
- );
- try {
- const plugins = await action.unwrap();
- const plugin = plugins.find((p) => p.identifier === identifier);
- if (!plugin) {
- warnUnknownCustomViz(display);
- return null;
- }
- return await eeLoadCustomVizPlugin(plugin, {
- sandboxMode: getSdkSandboxMode(),
- onMessage: logUnavailableCustomVizMessage,
- });
- } catch {
- return null;
- } finally {
- action.unsubscribe();
+ return { status: "unavailable" };
}
+ return eeLoadCustomVizPluginForDisplay(dispatch, display, {
+ sandboxMode: getSdkSandboxMode(),
+ onMessage: logUnavailableCustomVizMessage,
+ });
},
useAutoLoadCustomVizPlugin: (display: string | undefined) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx
index 6f035415e54..3a4b8f66af2 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx
@@ -14,7 +14,11 @@ import { ExplicitSize } from "metabase/common/components/ExplicitSize";
import { type ToastArgs, useToast } from "metabase/common/hooks";
import type { IconData } from "metabase/common/utils/icon";
import { useEmbeddingEntityContext } from "metabase/embedding/context";
-import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
+import {
+ type LoadCustomVizPluginForDisplayResult,
+ PLUGIN_CUSTOM_VIZ,
+} from "metabase/plugins";
+import type { DispatchFn } from "metabase/redux/hooks";
import { getSubpathSafeUrl } from "metabase/urls";
import { measureText } from "metabase/utils/measure-text";
import { retry } from "metabase/utils/retry";
@@ -26,6 +30,7 @@ import {
import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";
import type { VisualizationProps } from "metabase/visualizations/types/visualization";
import { useListCustomVizPluginsQuery } from "metabase-enterprise/api";
+import { customVizPluginApi } from "metabase-enterprise/api/custom-viz-plugin";
import type {
CustomVizPluginId,
CustomVizPluginRuntime,
@@ -40,12 +45,9 @@ import type { SandboxMode } from "./sandbox";
import { usePluginMount } from "./use-plugin-mount";
import { reportUnavailableCustomVizPlugin } from "./utils/unavailable-toast";
-// Track which plugins have already been loaded to avoid re-execution.
-// Maps plugin id → { identifier, hash } so we can detect when a re-uploaded
-// bundle (or a dev server reload) produced new bytes.
const loadedPlugins = new Map<
CustomVizPluginId,
- { identifier: string; hash: string | null }
+ { identifier: VisualizationDisplay; hash: string | null }
>();
const failedPluginHashes = new Map<
@@ -58,6 +60,11 @@ const failedPluginHashes = new Map<
const loadStartedSeqByPluginId = new Map<CustomVizPluginId, number>();
const loadAppliedSeqByPluginId = new Map<CustomVizPluginId, number>();
+const inFlightPluginLoads = new Map<
+ CustomVizPluginId,
+ { hash: string | null; promise: Promise<VisualizationDisplay | null> }
+>();
+
/**
* Remove a previously-loaded custom-viz display from the global
* visualizations registry and drop its load/failure cache entries, so a
@@ -305,19 +312,44 @@ class BundleFetchError extends Error {
export async function loadCustomVizPlugin(
plugin: CustomVizPluginRuntime,
options: LoadCustomVizPluginOptions = {},
-): Promise<string | null> {
- const { cacheBustSuffix, onMessage, sandboxMode = "hosted" } = options;
- const existing = loadedPlugins.get(plugin.id);
+): Promise<VisualizationDisplay | null> {
const currentHash = plugin.bundle_hash ?? null;
- if (
- existing &&
- existing.hash === currentHash &&
- !plugin.dev_bundle_url &&
- !cacheBustSuffix
- ) {
+ const isFreshLoadForced = Boolean(
+ plugin.dev_bundle_url || options.cacheBustSuffix,
+ );
+
+ if (isFreshLoadForced) {
+ return fetchAndRegisterCustomVizPlugin(plugin, options);
+ }
+
+ const existing = loadedPlugins.get(plugin.id);
+ if (existing && existing.hash === currentHash) {
return existing.identifier;
}
+ const inFlight = inFlightPluginLoads.get(plugin.id);
+ if (inFlight && inFlight.hash === currentHash) {
+ return inFlight.promise;
+ }
+
+ const promise = fetchAndRegisterCustomVizPlugin(plugin, options);
+ inFlightPluginLoads.set(plugin.id, { hash: currentHash, promise });
+ try {
+ return await promise;
+ } finally {
+ if (inFlightPluginLoads.get(plugin.id)?.promise === promise) {
+ inFlightPluginLoads.delete(plugin.id);
+ }
+ }
+}
+
+async function fetchAndRegisterCustomVizPlugin(
+ plugin: CustomVizPluginRuntime,
+ options: LoadCustomVizPluginOptions,
+): Promise<VisualizationDisplay | null> {
+ const { cacheBustSuffix, onMessage, sandboxMode = "hosted" } = options;
+ const currentHash = plugin.bundle_hash ?? null;
+
ensureVizApi();
const loadSeq = (loadStartedSeqByPluginId.get(plugin.id) ?? 0) + 1;
@@ -457,6 +489,62 @@ export async function loadCustomVizPlugin(
}
}
+/**
+ * Imperatively load (and register) the plugin backing a `custom:*` display,
+ * if it is installed and enabled. Never rejects.
+ */
+export async function loadCustomVizPluginForDisplay(
+ dispatch: DispatchFn,
+ display: string,
+ {
+ sandboxMode,
+ onMessage,
+ }: {
+ sandboxMode?: SandboxMode;
+ onMessage?: (toast: ToastArgs) => void;
+ } = {},
+): Promise<LoadCustomVizPluginForDisplayResult> {
+ if (!isCustomVizDisplay(display)) {
+ return { status: "unavailable" };
+ }
+
+ const action = dispatch(
+ customVizPluginApi.endpoints.listCustomVizPlugins.initiate(undefined),
+ );
+
+ try {
+ const plugins = await action.unwrap();
+ const plugin = plugins.find(
+ (plugin) => getCustomPluginIdentifier(plugin) === display,
+ );
+
+ if (!plugin) {
+ onMessage?.({
+ icon: "warning_triangle_filled",
+ iconColor: "feedback-warning",
+ message: t`Custom visualization "${display}" was requested but no matching installed plugin was found. Check the name and that the plugin is uploaded.`,
+ });
+ return { status: "unavailable" };
+ }
+
+ const loadedDisplay = await loadCustomVizPlugin(plugin, {
+ onMessage,
+ sandboxMode,
+ });
+ return loadedDisplay
+ ? { status: "loaded", display: loadedDisplay }
+ : { status: "unavailable" };
+ } catch (error) {
+ console.error(
+ t`Failed to look up the plugin for custom visualization "${display}":`,
+ error,
+ );
+ return { status: "error" };
+ } finally {
+ action.unsubscribe();
+ }
+}
+
export const useCustomVizPluginsIcon = () => {
const { plugins, isLoading } = useCustomVizPlugins();
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-unsaved-reload.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-unsaved-reload.unit.spec.tsx
new file mode 100644
index 00000000000..a4e535a7b7a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-unsaved-reload.unit.spec.tsx
@@ -0,0 +1,215 @@
+import type { CustomVisualization } from "custom-viz";
+
+import { screen, waitFor } from "__support__/ui";
+import { serializeCardForUrl } from "metabase/common/utils/card";
+import {
+ type LoadCustomVizPluginForDisplayResult,
+ PLUGIN_CUSTOM_VIZ,
+} from "metabase/plugins";
+import { cancelQuery } from "metabase/query_builder/actions";
+import { setup } from "metabase/query_builder/containers/test-utils";
+import {
+ getCard,
+ getFirstQueryResult,
+ getIsRunning,
+} from "metabase/query_builder/selectors";
+import type { Dispatch } from "metabase/redux/store";
+import { checkNotNull } from "metabase/utils/types";
+import { registerVisualization } from "metabase/visualizations";
+import { registerVisualizations } from "metabase/visualizations/register";
+import { isDate } from "metabase-lib/v1/types/utils/isa";
+import type { CustomVizDisplayType, UnsavedCard } from "metabase-types/api";
+import {
+ createMockCustomVizPluginRuntime,
+ createMockDataset,
+ createMockDatasetData,
+ createMockNumericColumn,
+ createMockUnsavedCard,
+} from "metabase-types/api/mocks";
+import {
+ ORDERS,
+ ORDERS_ID,
+ SAMPLE_DB_ID,
+ createOrdersCreatedAtDatasetColumn,
+} from "metabase-types/api/mocks/presets";
+
+import { applyDefaultVisualizationProps } from "./custom-viz-common";
+import { unregisterCustomVizDisplay } from "./custom-viz-plugins";
+
+registerVisualizations();
+
+const DISPLAY: CustomVizDisplayType = "custom:reload-demo-viz";
+const MISSING_DISPLAY: CustomVizDisplayType = "custom:missing-viz";
+
+const DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createOrdersCreatedAtDatasetColumn({
+ source: "breakout",
+ unit: "month",
+ field_ref: ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ }),
+ createMockNumericColumn({
+ name: "count",
+ display_name: "Count",
+ semantic_type: "type/Quantity",
+ source: "aggregation",
+ field_ref: ["aggregation", 0],
+ }),
+ ],
+ rows: [
+ ["2026-01-01T00:00:00Z", 10],
+ ["2026-02-01T00:00:00Z", 20],
+ ],
+ }),
+});
+
+function createUnsavedCustomVizCard(display: CustomVizDisplayType) {
+ return createMockUnsavedCard({
+ display,
+ displayIsLocked: true,
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
+ },
+ },
+ });
+}
+
+function registerDemoViz() {
+ const vizDef: CustomVisualization<Record<string, unknown>> = {
+ id: DISPLAY,
+ getName: () => "Reload demo viz",
+ checkRenderable: ([{ data }]) => {
+ if (!data?.cols.some(isDate)) {
+ throw new Error("Needs a date column");
+ }
+ },
+ mount: () => ({ update: () => undefined, unmount: () => undefined }),
+ VisualizationComponent: () => null,
+ };
+
+ const settings: Parameters<typeof applyDefaultVisualizationProps>[2] = {
+ identifier: DISPLAY,
+ plugin: createMockCustomVizPluginRuntime(),
+ getUiName: () => "Reload demo viz",
+ };
+
+ registerVisualization(
+ applyDefaultVisualizationProps(
+ () => <span>Custom viz rendered</span>,
+ vizDef,
+ settings,
+ ),
+ );
+}
+
+function setupFromUrlHash(card: UnsavedCard) {
+ return setup({
+ card,
+ dataset: DATASET,
+ initialRoute: `/question#${serializeCardForUrl(card, {
+ includeDatasetQuery: true,
+ includeDisplayIsLocked: true,
+ })}`,
+ });
+}
+
+describe("query builder > unsaved question with a custom viz restored from the URL (metabase#76065)", () => {
+ const originalLoadForDisplay =
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay;
+
+ afterEach(() => {
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay = originalLoadForDisplay;
+ unregisterCustomVizDisplay(DISPLAY);
+ });
+
+ it("keeps the custom viz when its plugin loads during query completion", async () => {
+ const loadForDisplay = jest.fn(
+ async (): Promise<LoadCustomVizPluginForDisplayResult> => {
+ registerDemoViz();
+ return { status: "loaded", display: DISPLAY };
+ },
+ );
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay = loadForDisplay;
+
+ const { store } = await setupFromUrlHash(
+ createUnsavedCustomVizCard(DISPLAY),
+ );
+
+ expect(await screen.findByText("Custom viz rendered")).toBeInTheDocument();
+ expect(loadForDisplay).toHaveBeenCalledWith(expect.anything(), DISPLAY);
+
+ const card = checkNotNull(getCard(store.getState()));
+ expect(card.display).toBe(DISPLAY);
+ });
+
+ it("falls back to the default display when the plugin is unavailable", async () => {
+ const loadForDisplay = jest.fn(
+ async (): Promise<LoadCustomVizPluginForDisplayResult> => ({
+ status: "unavailable",
+ }),
+ );
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay = loadForDisplay;
+
+ const { store } = await setupFromUrlHash(
+ createUnsavedCustomVizCard(MISSING_DISPLAY),
+ );
+
+ await waitFor(() => {
+ expect(checkNotNull(getCard(store.getState())).display).not.toBe(
+ MISSING_DISPLAY,
+ );
+ });
+ expect(loadForDisplay).toHaveBeenCalledWith(
+ expect.anything(),
+ MISSING_DISPLAY,
+ );
+ expect(await screen.findByTestId("chart-container")).toBeInTheDocument();
+ });
+
+ it("keeps the custom viz when plugin availability can't be determined", async () => {
+ const loadForDisplay = jest.fn(
+ async (): Promise<LoadCustomVizPluginForDisplayResult> => ({
+ status: "error",
+ }),
+ );
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay = loadForDisplay;
+
+ const { store } = await setupFromUrlHash(
+ createUnsavedCustomVizCard(DISPLAY),
+ );
+
+ await waitFor(() => {
+ expect(getFirstQueryResult(store.getState())).toBeTruthy();
+ });
+ const card = checkNotNull(getCard(store.getState()));
+ expect(card.display).toBe(DISPLAY);
+ expect(card.displayIsLocked).toBe(true);
+ });
+
+ it("discards the completed run when the query is cancelled while the plugin loads", async () => {
+ const loadForDisplay = jest.fn(
+ async (
+ dispatch: Dispatch,
+ ): Promise<LoadCustomVizPluginForDisplayResult> => {
+ dispatch(cancelQuery());
+ registerDemoViz();
+ return { status: "loaded", display: DISPLAY };
+ },
+ );
+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay = loadForDisplay;
+
+ const { store } = await setupFromUrlHash(
+ createUnsavedCustomVizCard(DISPLAY),
+ );
+
+ await waitFor(() => expect(loadForDisplay).toHaveBeenCalled());
+ expect(getFirstQueryResult(store.getState())).toBeFalsy();
+ expect(getIsRunning(store.getState())).toBe(false);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts
index ff55d84539e..47271e9ab80 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts
@@ -1,4 +1,6 @@
import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
+import type { DispatchFn } from "metabase/redux/hooks";
+import { addUndo } from "metabase/redux/undo";
import {
getPluginAssetUrl,
resolveCustomVizAssetUrl,
@@ -12,6 +14,7 @@ import { CustomVizSettingWidget } from "./components/CustomVizSettingWidget";
import { ManageCustomVizPage } from "./components/ManageCustomVizPage";
import {
loadCustomVizPlugin,
+ loadCustomVizPluginForDisplay,
useAutoLoadCustomVizPlugin,
useCustomVizPlugins,
useCustomVizPluginsIcon,
@@ -27,6 +30,10 @@ export function initializePlugin() {
useAutoLoadCustomVizPlugin,
useCustomVizPlugins,
loadCustomVizPlugin,
+ loadCustomVizPluginForDisplay: (dispatch: DispatchFn, display: string) =>
+ loadCustomVizPluginForDisplay(dispatch, display, {
+ onMessage: (toast) => dispatch(addUndo(toast)),
+ }),
getPluginAssetUrl,
resolveCustomVizAssetUrl,
releaseCustomVizAsset: () => {},
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/load-custom-viz-plugin-for-display.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/load-custom-viz-plugin-for-display.unit.spec.ts
new file mode 100644
index 00000000000..9c1e8e47ffa
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/load-custom-viz-plugin-for-display.unit.spec.ts
@@ -0,0 +1,123 @@
+import { waitFor } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import { getStore } from "__support__/entities-store";
+import { Api } from "metabase/api";
+import { createMockCustomVizPluginRuntime } from "metabase-types/api/mocks";
+
+import { loadCustomVizPluginForDisplay } from "./custom-viz-plugins";
+
+const PLUGIN = createMockCustomVizPluginRuntime({
+ id: 901,
+ identifier: "loader-demo-viz",
+ bundle_url: "/api/ee/custom-viz-plugin/901/bundle",
+});
+
+const DISPLAY = "custom:loader-demo-viz";
+const LIST_ROUTE = "path:/api/ee/custom-viz-plugin/list";
+const BUNDLE_ROUTE = "path:/api/ee/custom-viz-plugin/901/bundle";
+
+function setup() {
+ const store = getStore({ [Api.reducerPath]: Api.reducer }, {}, [
+ Api.middleware,
+ ]);
+ const listCalls = () => fetchMock.callHistory.calls(LIST_ROUTE);
+ const bundleCalls = () => fetchMock.callHistory.calls(BUNDLE_ROUTE);
+ return { dispatch: store.dispatch, listCalls, bundleCalls };
+}
+
+describe("loadCustomVizPluginForDisplay", () => {
+ afterEach(() => {
+ fetchMock.removeRoutes().clearHistory();
+ jest.restoreAllMocks();
+ });
+
+ it("resolves unavailable for a non-custom display without hitting the plugin list", async () => {
+ fetchMock.get(LIST_ROUTE, [PLUGIN]);
+ const { dispatch, listCalls } = setup();
+
+ const result = await loadCustomVizPluginForDisplay(dispatch, "table");
+
+ expect(result).toEqual({ status: "unavailable" });
+ expect(listCalls()).toHaveLength(0);
+ });
+
+ it("resolves error and logs when the plugin list request fails", async () => {
+ fetchMock.get(LIST_ROUTE, 500);
+ const consoleError = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => undefined);
+ const { dispatch } = setup();
+
+ const result = await loadCustomVizPluginForDisplay(dispatch, DISPLAY);
+
+ expect(result).toEqual({ status: "error" });
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("Failed to look up the plugin"),
+ expect.anything(),
+ );
+ });
+
+ it("resolves unavailable and reports not-found when no plugin backs the display", async () => {
+ fetchMock.get(LIST_ROUTE, []);
+ const { dispatch } = setup();
+ const onMessage = jest.fn();
+
+ const result = await loadCustomVizPluginForDisplay(dispatch, DISPLAY, {
+ onMessage,
+ });
+
+ expect(result).toEqual({ status: "unavailable" });
+ expect(onMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining("no matching installed plugin"),
+ }),
+ );
+ });
+
+ it("resolves unavailable and reports when the plugin bundle fails to load", async () => {
+ fetchMock.get(LIST_ROUTE, [PLUGIN]);
+ fetchMock.get(BUNDLE_ROUTE, 500);
+ jest.spyOn(console, "error").mockImplementation(() => undefined);
+ const { dispatch, bundleCalls } = setup();
+ const onMessage = jest.fn();
+
+ const result = await loadCustomVizPluginForDisplay(dispatch, DISPLAY, {
+ onMessage,
+ });
+
+ expect(result).toEqual({ status: "unavailable" });
+ expect(bundleCalls()).toHaveLength(1);
+ await waitFor(() => {
+ expect(onMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining("currently unavailable"),
+ }),
+ );
+ });
+ });
+
+ it("shares a single in-flight load between concurrent callers", async () => {
+ const plugin = createMockCustomVizPluginRuntime({
+ id: 902,
+ identifier: "dedup-demo-viz",
+ bundle_url: "/api/ee/custom-viz-plugin/902/bundle",
+ });
+ const bundleRoute = "path:/api/ee/custom-viz-plugin/902/bundle";
+ fetchMock.get(LIST_ROUTE, [plugin]);
+ fetchMock.get(bundleRoute, 500);
+ jest.spyOn(console, "error").mockImplementation(() => undefined);
+ const { dispatch } = setup();
+
+ const results = await Promise.all([
+ loadCustomVizPluginForDisplay(dispatch, "custom:dedup-demo-viz"),
+ loadCustomVizPluginForDisplay(dispatch, "custom:dedup-demo-viz"),
+ ]);
+
+ expect(results).toEqual([
+ { status: "unavailable" },
+ { status: "unavailable" },
+ ]);
+ expect(fetchMock.callHistory.calls(bundleRoute)).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
index 652dd1abd53..88b86fdc87a 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
@@ -3,7 +3,6 @@ import type { SdkQuestionState } from "embedding-sdk-bundle/types/question";
import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
import { runQuestionQuery } from "metabase/querying/run-query";
import type { Dispatch } from "metabase/redux/store";
-import { isNotNull } from "metabase/utils/types";
import { visualizations } from "metabase/visualizations";
import { getSensibleDisplays } from "metabase/visualizations/lib/sensibility";
import type Question from "metabase-lib/v1/Question";
@@ -83,7 +82,9 @@ export async function runQuestionQuerySdk(
),
),
)
- ).filter(isNotNull),
+ ).flatMap((result) =>
+ result.status === "loaded" ? [result.display] : [],
+ ),
);
// The query and the custom-viz load are independent, so run them
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index da7a69de87f..b4399ef58c0 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -40,7 +40,10 @@ export {
type CollectionAuthorityLevelIcon,
} from "./oss/collections";
export { PLUGIN_CONTENT_TRANSLATION } from "./oss/content-translation";
-export { PLUGIN_CUSTOM_VIZ } from "./oss/custom-viz";
+export {
+ type LoadCustomVizPluginForDisplayResult,
+ PLUGIN_CUSTOM_VIZ,
+} from "./oss/custom-viz";
export {
PLUGIN_CONTENT_VERIFICATION,
type ModelFilterControlsProps,
diff --git a/frontend/src/metabase/plugins/oss/custom-viz.ts b/frontend/src/metabase/plugins/oss/custom-viz.ts
index 49e6e12128f..2131b7c4810 100644
--- a/frontend/src/metabase/plugins/oss/custom-viz.ts
+++ b/frontend/src/metabase/plugins/oss/custom-viz.ts
@@ -12,6 +12,11 @@ import type {
} from "metabase-types/api";
import { isCustomVizDisplay } from "metabase-types/guards";
+export type LoadCustomVizPluginForDisplayResult =
+ | { status: "loaded"; display: VisualizationDisplay }
+ | { status: "unavailable" }
+ | { status: "error" };
+
// prevents infinite render loop
const noopCustomVizIcon = (
_display: VisualizationDisplay,
@@ -44,17 +49,17 @@ const getDefaultPluginCustomViz = () => ({
cacheBustSuffix?: string;
onMessage?: (toast: ToastArgs) => void;
},
- // Unjustified type cast. FIXME
- ) => null as string | null,
+ ): Promise<VisualizationDisplay | null> => null,
/**
* Load (and register) the plugin backing a `custom:*` display, if it is
- * installed and enabled. Resolves to the registered display identifier, or
- * null when the plugin is unavailable. No-op in OSS.
+ * installed and enabled. No-op in OSS.
*/
loadCustomVizPluginForDisplay: async (
_dispatch: Dispatch,
_display: string,
- ): Promise<VisualizationDisplay | null> => null,
+ ): Promise<LoadCustomVizPluginForDisplayResult> => ({
+ status: "unavailable",
+ }),
getPluginAssetUrl: (
_pluginId: CustomVizPluginId,
_assetPath: string | null,
diff --git a/frontend/src/metabase/query_builder/actions/querying.ts b/frontend/src/metabase/query_builder/actions/querying.ts
index 953b653710f..f465ec1907b 100644
--- a/frontend/src/metabase/query_builder/actions/querying.ts
+++ b/frontend/src/metabase/query_builder/actions/querying.ts
@@ -2,6 +2,7 @@ import { createAction } from "redux-actions";
import { t } from "ttag";
import { isAbortError } from "metabase/api/client";
+import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
import { runQuestionQuery as apiRunQuestionQuery } from "metabase/querying/run-query";
import { syncVizSettingsWithSeries } from "metabase/querying/viz-settings/utils/sync-viz-settings";
import { createThunkAction } from "metabase/redux";
@@ -16,6 +17,7 @@ import {
} from "metabase/redux/query-builder";
import type { Dispatch, GetState } from "metabase/redux/store";
import { getWhiteLabeledLoadingMessageFactory } from "metabase/selectors/whitelabel";
+import { visualizations } from "metabase/visualizations";
import { getSensibleDisplays } from "metabase/visualizations/lib/sensibility";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -210,6 +212,34 @@ export const queryCompleted = (question: Question, queryResults: Dataset[]) => {
(!originalQuestion || question.isDirtyComparedTo(originalQuestion));
if (isDirty) {
+ // A `custom:*` display counts as sensible only once its plugin is in
+ // the visualizations registry, so register it before deciding whether
+ // to reset the display (metabase#76065).
+ const display = question.display();
+ let skipDisplayReset = false;
+ if (
+ PLUGIN_CUSTOM_VIZ.isCustomVizDisplay(display) &&
+ !visualizations.has(display)
+ ) {
+ const runController = getState().qb.cancelQueryController;
+ const { status } =
+ await PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay(
+ dispatch,
+ display,
+ );
+
+ // Drop this completion if the run was superseded or cancelled
+ if (getState().qb.cancelQueryController !== runController) {
+ return;
+ }
+ if (runController?.signal.aborted) {
+ dispatch({ type: CANCEL_QUERY });
+ return;
+ }
+
+ skipDisplayReset = status === "error";
+ }
+
const series = [{ card: question.card(), data, error }];
const previousSeries =
prevCard && prevData
@@ -226,11 +256,13 @@ export const queryCompleted = (question: Question, queryResults: Dataset[]) => {
);
}
- question = question.maybeResetDisplay(
- data,
- getSensibleDisplays(series),
- previousSeries ? getSensibleDisplays(previousSeries) : undefined,
- );
+ if (!skipDisplayReset) {
+ question = question.maybeResetDisplay(
+ data,
+ getSensibleDisplays(series),
+ previousSeries ? getSensibleDisplays(previousSeries) : undefined,
+ );
+ }
}
const card = question.card();