The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(sdk): Custom visualizations in the Embedding SDK (#75920)
Nicolò Pretto598fc88b6886
diff --git a/e2e/test-component/scenarios/embedding-sdk/custom-visualizations.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/custom-visualizations.cy.spec.tsxnew file mode 100644index 00000000000..96c7a32b3a4--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/custom-visualizations.cy.spec.tsx@@ -0,0 +1,317 @@+import { InteractiveQuestion } from "@metabase/embedding-sdk-react";++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ CUSTOM_VIZ_DISPLAY,+ CUSTOM_VIZ_FIXTURE_TGZ,+ CUSTOM_VIZ_IDENTIFIER,+ addCustomVizPlugin,+ createQuestion,+} from "e2e/support/helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";+import type { CardId } from "metabase-types/api";++const { ORDERS_ID } = SAMPLE_DATABASE;++const setup = () => {+ signInAsAdminAndEnableEmbeddingSdk();++ cy.log("Turn on the prereqs for custom visualizations");+ cy.request("PUT", "/api/setting", {+ "csp-img-enabled": true, // csp-img is required to enable custom-viz+ "custom-viz-enabled": true,+ });++ cy.log("Upload the demo-viz custom visualization plugin");+ addCustomVizPlugin(CUSTOM_VIZ_FIXTURE_TGZ);++ cy.log("Create a question that targets the demo-viz custom display");+ // demo-viz expects exactly one row with one numeric column.+ createQuestion({+ name: "Custom Viz SDK Question",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ },+ display: CUSTOM_VIZ_DISPLAY,+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });++ cy.log("Create a question with a regular display, for dropdown selection");+ createQuestion({+ name: "Default Display SDK Question",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ },+ display: "table",+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("defaultDisplayQuestionId");+ });++ cy.signOut();+ mockAuthProviderAndJwtSignIn();+};++describe("scenarios > embedding-sdk > custom visualizations", () => {+ beforeEach(() => {+ setup();+ });++ it("renders the custom visualization when the identifier is in allowedCustomVisualizations", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("be.visible");+ cy.findByText(/Value: \d+/).should("be.visible");+ });+ });++ it("allows selecting the custom visualization from the chart type dropdown", () => {+ cy.get<CardId>("@defaultDisplayQuestionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.log("The default visualization renders first");+ cy.findByText("18,760").should("be.visible");+ cy.findByText("Custom viz rendered successfully").should("not.exist");++ cy.log("The custom viz is listed in the chart type dropdown");+ cy.findByTestId("chart-type-selector-button").click();+ cy.findByRole("listbox").within(() => {+ cy.findByText(CUSTOM_VIZ_IDENTIFIER).click();+ });++ cy.log("Selecting it renders the custom visualization");+ cy.findByText("Custom viz rendered successfully").should("be.visible");+ cy.findByText(/Value: \d+/).should("be.visible");+ });+ });++ it("falls back to the default visualization when the prop is omitted", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: undefined,+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });++ it("falls back to the default visualization when allowedCustomVisualizations is empty", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: [],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });++ // temporarily disabled (npretto 2026-06-18): we're experimenting with another approach that would not require this new prop+ describe.skip("initialVisualization", () => {+ it("applies a custom visualization as the initial visualization when enabled", () => {+ cy.get<CardId>("@defaultDisplayQuestionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization={CUSTOM_VIZ_DISPLAY}+ />,+ {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ },+ );+ });++ getSdkRoot().within(() => {+ cy.log("The custom viz renders instead of the saved table display");+ cy.findByText("Custom viz rendered successfully").should("be.visible");+ cy.findByText(/Value: \d+/).should("be.visible");++ cy.log("The chart type dropdown shows the custom viz as selected");+ cy.findByTestId("chart-type-selector-button").should(+ "contain.text",+ CUSTOM_VIZ_IDENTIFIER,+ );+ cy.findByTestId("chart-type-selector-button").click();+ cy.findByRole("listbox")+ .findByRole("option", { name: CUSTOM_VIZ_IDENTIFIER })+ .should("have.attr", "data-combobox-selected", "true");+ });+ });++ it("applies a regular visualization as the initial visualization", () => {+ cy.get<CardId>("@defaultDisplayQuestionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization="scalar"+ />,+ );+ });++ getSdkRoot().within(() => {+ cy.log("The Number viz renders instead of the saved table display");+ cy.findByTestId("scalar-value").should("have.text", "18,760");+ cy.findByTestId("chart-type-selector-button").should(+ "contain.text",+ "Number",+ );+ });+ });++ it("applies the custom visualization when it is both the saved display and the initial visualization", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization={CUSTOM_VIZ_DISPLAY}+ />,+ {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ },+ );+ });++ getSdkRoot().within(() => {+ cy.log("The custom viz plugin is only loaded once and renders");+ cy.findByText("Custom viz rendered successfully").should("be.visible");+ cy.findByText(/Value: \d+/).should("be.visible");+ });+ });++ it("applies a regular initial visualization over a saved custom display", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization="scalar"+ />,+ {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ },+ );+ });++ getSdkRoot().within(() => {+ cy.log("The Number viz renders instead of the saved custom display");+ cy.findByTestId("scalar-value").should("have.text", "18,760");+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ });+ });++ it("falls back to the saved visualization when the custom viz is not enabled", () => {+ cy.get<CardId>("@defaultDisplayQuestionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization={CUSTOM_VIZ_DISPLAY}+ />,+ );+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });++ it("falls back to the saved visualization when the custom viz doesn't exist", () => {+ cy.get<CardId>("@defaultDisplayQuestionId").then((questionId) => {+ mountSdkContent(+ <InteractiveQuestion+ questionId={questionId}+ initialVisualization="custom:does-not-exist"+ />,+ {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ },+ );+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });+ });++ describe("allowlist via allowedCustomVisualizations", () => {+ it("renders the custom visualization when the identifier is in the allowlist", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: [CUSTOM_VIZ_DISPLAY],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("be.visible");+ });+ });++ it("falls back to the default visualization when the identifier is not in the allowlist", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: ["custom:some-other-plugin"],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });++ it("falls back to the default visualization when the allowlist is empty", () => {+ cy.get<CardId>("@questionId").then((questionId) => {+ mountSdkContent(<InteractiveQuestion questionId={questionId} />, {+ sdkProviderProps: {+ allowedCustomVisualizations: [],+ },+ });+ });++ getSdkRoot().within(() => {+ cy.findByText("Custom viz rendered successfully").should("not.exist");+ cy.findByText("18,760").should("be.visible");+ });+ });+ });+});diff --git a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.tsindex 63658adfadc..57edba0b7d8 100644--- a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts+++ b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts@@ -2374,7 +2374,6 @@ describe("sandbox", () => {H.visitQuestion("@sandboxCardId", {onBeforeLoad(win) {cy.spy(win.console, "log").as("consoleLog");- cy.spy(win.console, "error").as("consoleError");},});cy.wait("@injectedBundle");@@ -2396,12 +2395,6 @@ describe("sandbox", () => {"sandbox-decoy",);- // The swap is reported to host console for diagnostics.- cy.get("@consoleError").should(- "have.been.calledWithMatch",- /\[plugin \d+\] swapped out-of-scope <div id="root"> with decoy/,- );-// The real host element was untouched.cy.get(hostSelector).should("not.have.attr", "data-pwned-by-plugin");});@@ -2434,7 +2427,6 @@ describe("sandbox", () => {H.visitQuestion("@sandboxCardId", {onBeforeLoad(win) {cy.spy(win.console, "log").as("consoleLog");- cy.spy(win.console, "error").as("consoleError");},});cy.wait("@injectedBundle");@@ -2459,11 +2451,6 @@ describe("sandbox", () => {"true",);- cy.get("@consoleError").should(- "have.been.calledWithMatch",- /\[plugin \d+\] swapped out-of-scope <div.*> with decoy/,- );-cy.get("[data-plugin-sandbox]").parent().should("not.have.attr", "data-pwned-by-plugin");@@ -2495,7 +2482,6 @@ describe("sandbox", () => {H.visitQuestion("@sandboxCardId", {onBeforeLoad(win) {cy.spy(win.console, "log").as("consoleLog");- cy.spy(win.console, "error").as("consoleError");},});cy.wait("@injectedBundle");@@ -2517,9 +2503,10 @@ describe("sandbox", () => {doc.body.removeAttribute("data-mutation-probe-attr");});- cy.get("@consoleError").should(- "have.been.calledWithMatch",- /\[plugin \d+\] swapped out-of-scope <body> with decoy/,+ cy.get("@consoleLog").should(+ "have.been.calledWith",+ "plugin observed mutations:",+ 0,);});diff --git a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.tsnew file mode 100644index 00000000000..1c030d1524b--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts@@ -0,0 +1,309 @@+import { useCallback, useEffect, useMemo, useState } from "react";++import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";+import { api } from "metabase/api/client";+import type { IconData } from "metabase/common/utils/icon";+import { 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,+ CustomVizPluginRuntime,+ VisualizationDisplay,+} from "metabase-types/api";+import { isCustomVizDisplay } from "metabase-types/guards/visualization";++import { CustomVizSettingWidget } from "../../metabase-enterprise/custom_viz/components/CustomVizSettingWidget";+import type { LoadCustomVizPluginOptions } from "../../metabase-enterprise/custom_viz/custom-viz-plugins";+import {+ loadCustomVizPlugin as eeLoadCustomVizPlugin,+ useAutoLoadCustomVizPlugin as eeUseAutoLoadCustomVizPlugin,+ useCustomVizPlugins as eeUseCustomVizPlugins,+ unregisterCustomVizDisplay,+ useCustomVizPlugins,+} from "../../metabase-enterprise/custom_viz/custom-viz-plugins";+import { isWidgetMount } from "../../metabase-enterprise/custom_viz/widget-mount";++/**+ * Allowlist of plugin identifiers from the `allowedCustomVisualizations`+ * MetabaseProvider prop. Empty / undefined = no custom viz allowed.+ */+function useAllowlist(): string[] {+ const { state } = useMetabaseProviderPropsStore();+ return state?.props?.allowedCustomVisualizations ?? [];+}++function getAllowlist(): string[] {+ return (+ ensureMetabaseProviderPropsStore().getState().props+ ?.allowedCustomVisualizations ?? []+ );+}++/**+ * Whether `display` is an allowed `custom:*` visualization. False for+ * non-custom displays and for custom ones missing from the allowlist.+ */+function isCustomVizAllowed(+ display: string | undefined,+ allowlist: string[],+): boolean {+ return isCustomVizDisplay(display) && allowlist.includes(display);+}++const warnedUnknownCustomViz = new Set<string>();+function warnUnknownCustomViz(display: string) {+ if (!warnedUnknownCustomViz.has(display)) {+ warnedUnknownCustomViz.add(display);+ console.warn(+ `Custom visualization "${display}" was requested but no matching ` ++ `installed plugin was found. Check the name and that the plugin is uploaded.`,+ );+ }+}++const pluginToIconBlob = new Map<CustomVizPluginId, string>();+const pluginToIconBlobPromise = new Map<+ CustomVizPluginId,+ Promise<string | undefined>+>();++// A cross-origin `<img>` can't carry the session header, so we fetch the icon+// with the auth in the headers and hand back a same-origin `blob:` url.+export const sdkCustomVizAssetManager = {+ resolveCustomVizAssetUrl: async (+ pluginId: CustomVizPluginId,+ assetPath: string | null | undefined,+ ): Promise<string | undefined> => {+ if (!assetPath) {+ return undefined;+ }+ let promise = pluginToIconBlobPromise.get(pluginId);+ if (!promise) {+ promise = (async () => {+ try {+ const res = await api.fetch({+ method: "GET",+ url: `/api/ee/custom-viz-plugin/${pluginId}/asset`,+ params: { path: assetPath },+ });+ if (!res.ok) {+ throw new Error(`HTTP ${res.status}`);+ }+ const objectUrl = URL.createObjectURL(await res.blob());+ pluginToIconBlob.set(pluginId, objectUrl);+ return objectUrl;+ } catch {+ // Drop the failed promise so a later call can retry+ pluginToIconBlobPromise.delete(pluginId);+ return getPluginAssetUrl(pluginId, assetPath);+ }+ })();+ pluginToIconBlobPromise.set(pluginId, promise);+ }+ return promise;+ },+ releaseCustomVizAsset: (pluginId: CustomVizPluginId) => {+ const objectUrl = pluginToIconBlob.get(pluginId);+ if (objectUrl) {+ URL.revokeObjectURL(objectUrl);+ }+ pluginToIconBlob.delete(pluginId);+ pluginToIconBlobPromise.delete(pluginId);+ },+};++export function initializeSdkCustomVizPlugin() {+ if (!hasPremiumFeature("custom-viz")) {+ return;+ }++ Object.assign(PLUGIN_CUSTOM_VIZ, {+ ...sdkCustomVizAssetManager,++ loadCustomVizPlugin: (+ plugin: CustomVizPluginRuntime,+ options: LoadCustomVizPluginOptions = {},+ ) => {+ // We should only be calling this for allowed plugins, but this checks again to be safer+ if (!getAllowlist().includes(getCustomPluginIdentifier(plugin))) {+ return Promise.resolve(null);+ }+ return eeLoadCustomVizPlugin(plugin, {+ ...options,+ // Note: in the future we might want to check the domain to check if we need "blank" or "sandbox" mode, to support data apps+ sandboxMode: "blank",+ });+ },++ loadCustomVizPluginForDisplay: async (+ dispatch: DispatchFn,+ display: string,+ ): Promise<string | null> => {+ 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: "blank",+ });+ } catch {+ return null;+ } finally {+ action.unsubscribe();+ }+ },++ useAutoLoadCustomVizPlugin: (display: string | undefined) => {+ const allowlist = useAllowlist();+ const allowed =+ // Regular (non-custom) displays are always allowed.+ !isCustomVizDisplay(display) || isCustomVizAllowed(display, allowlist);++ useEffect(() => {+ if (isCustomVizDisplay(display) && !allowed) {+ unregisterCustomVizDisplay(display);+ }+ }, [display, allowed]);++ return eeUseAutoLoadCustomVizPlugin(allowed ? display : undefined, {+ sandboxMode: "blank",+ });+ },++ useCustomVizPlugins: (opts?: { enabled?: boolean }) => {+ const allowlist = useAllowlist();+ const result = eeUseCustomVizPlugins(opts);+ // Key on the allowlist contents, not the array identity: the host may+ // pass a new (inline) array on every render.+ const allowlistKey = JSON.stringify(allowlist);+ // Memoized so consumers can use `plugins` as an effect dependency:+ // returning a fresh `.filter()` array on every render would re-trigger+ // those effects in a render loop.+ const plugins = useMemo(+ () =>+ result.plugins?.filter((p) =>+ allowlist.includes(getCustomPluginIdentifier(p)),+ ) ?? [],+ // eslint-disable-next-line react-hooks/exhaustive-deps -- allowlistKey stands in for `allowlist`+ [result.plugins, allowlistKey],+ );++ // Warn the developers of the host app if they're passing a custom viz that we haven't found in the instance+ useEffect(() => {+ if (result.isLoading || !result.plugins) {+ return;+ }+ const installed: string[] = result.plugins.map((p) =>+ getCustomPluginIdentifier(p),+ );+ allowlist+ .filter((name) => !installed.includes(name))+ .forEach(warnUnknownCustomViz);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- allowlistKey stands in for `allowlist`+ }, [result.plugins, result.isLoading, allowlistKey]);++ return { ...result, plugins };+ },++ useCustomVizPluginsIcon: () => {+ const [blobs, setBlobs] = useState(new Map<CustomVizPluginId, string>());+ const allowlist = useAllowlist();++ const { plugins, isLoading } = useCustomVizPlugins();++ const allowlistKey = JSON.stringify(allowlist); // stable reference as the array can be a new one on every render++ useEffect(() => {+ let cancelled = false;+ const toResolve = (plugins ?? []).filter(+ (plugin) =>+ isCustomVizAllowed(getCustomPluginIdentifier(plugin), allowlist) &&+ plugin.icon,+ );+ Promise.all(+ toResolve.map(+ async (plugin) =>+ [+ plugin.id,+ await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ plugin.id,+ plugin.icon,+ ),+ ] as const,+ ),+ ).then((entries) => {+ if (!cancelled) {+ setBlobs(+ new Map(+ entries.filter(+ (entry): entry is [CustomVizPluginId, string] =>+ entry[1] != null,+ ),+ ),+ );+ }+ });+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- allowlistKey stands in for `allowlist`+ }, [plugins, allowlistKey]);++ return useCallback(+ (+ display: VisualizationDisplay,+ ): { icon: IconData | undefined; isLoading: boolean } => {+ if (isLoading) {+ return { icon: undefined, isLoading: true };+ }+ const currentPlugin = plugins?.find(+ (plugin) => getCustomPluginIdentifier(plugin) === display,+ );++ // not an allowed custom-viz plugin: no icon+ if (!currentPlugin || !isCustomVizAllowed(display, allowlist)) {+ return { icon: undefined, isLoading: false };+ }++ // resolved blob is ready: use it+ const blobUrl = blobs.get(currentPlugin.id);+ if (blobUrl) {+ return {+ icon: { name: "unknown", iconUrl: blobUrl },+ isLoading: false,+ };+ }++ // otherwise still loading (the effect is resolving it), unless the+ // plugin has no icon to resolve at all+ return { icon: undefined, isLoading: Boolean(currentPlugin.icon) };+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps -- allowlistKey stands in for `allowlist`+ [plugins, isLoading, allowlistKey, blobs],+ );+ },+ getPluginAssetUrl,+ isCustomVizDisplay,+ isWidgetMount,+ CustomVizSettingWidget,+ // Admin pages (ManageCustomVizPage, CustomVizPage, CustomVizDevPage) are+ // intentionally omitted — the SDK never renders them.+ });+}diff --git a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.tsnew file mode 100644index 00000000000..0a439b88bcc--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts@@ -0,0 +1,103 @@+import { api } from "metabase/api/client";+import { getPluginAssetUrl } from "metabase/visualizations/custom-visualizations/custom-viz-utils";++import { sdkCustomVizAssetManager } from "./initialize";++const okResponse = () =>+ ({+ ok: true,+ blob: async () => new Blob(["<svg/>"], { type: "image/svg+xml" }),+ }) as Response;++describe("sdkCustomVizAssetManager", () => {+ const createObjectURL = jest.fn(() => "blob:fake");+ const revokeObjectURL = jest.fn();++ beforeAll(() => {+ global.URL.createObjectURL = createObjectURL;+ global.URL.revokeObjectURL = revokeObjectURL;+ });++ beforeEach(() => {+ jest.restoreAllMocks();+ createObjectURL.mockClear().mockReturnValue("blob:fake");+ revokeObjectURL.mockClear();+ });++ it("fetches the asset with auth and returns a same-origin blob: URL", async () => {+ const fetchSpy = jest.spyOn(api, "fetch").mockResolvedValue(okResponse());++ const url = await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ 1,+ "icon.svg",+ );++ expect(fetchSpy).toHaveBeenCalledWith({+ method: "GET",+ url: "/api/ee/custom-viz-plugin/1/asset",+ params: { path: "icon.svg" },+ });+ expect(createObjectURL).toHaveBeenCalledTimes(1);+ expect(url).toBe("blob:fake");+ });++ it("reuses the cached blob on re-resolve, without refetching or revoking", async () => {+ const fetchSpy = jest.spyOn(api, "fetch").mockResolvedValue(okResponse());+ createObjectURL.mockReturnValue("blob:cached");++ const first = await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ 7,+ "icon.svg",+ );+ const second = await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ 7,+ "icon.svg",+ );++ expect(first).toBe("blob:cached");+ expect(second).toBe("blob:cached");+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ expect(createObjectURL).toHaveBeenCalledTimes(1);+ expect(revokeObjectURL).not.toHaveBeenCalled();+ });++ it("falls back to the plain asset URL when the fetch rejects", async () => {+ jest.spyOn(api, "fetch").mockRejectedValue(new Error("network"));++ const url = await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ 2,+ "icon.svg",+ );++ expect(url).toBe(getPluginAssetUrl(2, "icon.svg"));+ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it("falls back to the plain asset URL on a non-ok response", async () => {+ // A 404 with a usable blob(): proves the fallback comes from the !res.ok+ // check. If it were missing, the code would read blob() and build a url.+ jest.spyOn(api, "fetch").mockResolvedValue({+ ok: false,+ status: 404,+ blob: async () => new Blob(["<svg/>"], { type: "image/svg+xml" }),+ } as Response);++ const url = await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(+ 3,+ "icon.svg",+ );++ expect(url).toBe(getPluginAssetUrl(3, "icon.svg"));+ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it("release revokes the stored blob for the plugin", async () => {+ jest.spyOn(api, "fetch").mockResolvedValue(okResponse());+ createObjectURL.mockReturnValue("blob:to-release");++ await sdkCustomVizAssetManager.resolveCustomVizAssetUrl(9, "icon.svg");+ sdkCustomVizAssetManager.releaseCustomVizAsset(9);++ expect(revokeObjectURL).toHaveBeenCalledWith("blob:to-release");+ });+});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.tsxindex 39047c44df5..8fd1febefef 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@@ -9,10 +9,12 @@ import type {import { useCallback, useEffect, useRef, useState } from "react";import { t } from "ttag";+import { api } from "metabase/api/client";import { ExplicitSize } from "metabase/common/components/ExplicitSize";import { 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 { useColorScheme } from "metabase/ui";import { getSubpathSafeUrl } from "metabase/urls";import visualizations, { registerVisualization } from "metabase/visualizations";@@ -43,7 +45,7 @@ import { usePluginMount } from "./use-plugin-mount";// 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<- number,+ CustomVizPluginId,{ identifier: string; hash: string | null }>();@@ -52,6 +54,26 @@ const failedPluginHashes = new Map<CustomVizPluginRuntime["bundle_hash"]>();+/**+ * Remove a previously-loaded custom-viz display from the global+ * visualizations registry and drop its load/failure cache entries, so a+ * question with this display falls back to the default visualization on+ * the next render (and a future `loadCustomVizPlugin` call re-fetches+ * and re-registers instead of returning the cached registration).+ */+export function unregisterCustomVizDisplay(display: VisualizationDisplay) {+ if (visualizations.has(display)) {+ visualizations.delete(display);+ for (const [id, entry] of loadedPlugins) {+ if (entry.identifier === display) {+ PLUGIN_CUSTOM_VIZ.releaseCustomVizAsset(id);+ loadedPlugins.delete(id);+ failedPluginHashes.delete(id);+ }+ }+ }+}+/*** Hook that fetches the list of active custom visualization plugins.*/@@ -79,6 +101,7 @@ function useCustomVizDevReload(plugins: CustomVizPluginRuntime[] | undefined,setLoading: (loading: boolean) => void,onInfo: (message: string) => void,+ sandboxMode: SandboxMode = "hosted",) {useEffect(() => {if (!isCustomVizDisplay(display) || !plugins) {@@ -107,6 +130,7 @@ function useCustomVizDevReload(await loadCustomVizPlugin(plugin, {cacheBustSuffix: `?t=${Date.now()}`,onInfo,+ sandboxMode,});} finally {setLoading(false);@@ -120,9 +144,13 @@ function useCustomVizDevReload(return () => {eventSource.close();};- }, [display, onInfo, plugins, setLoading]);+ }, [display, onInfo, plugins, setLoading, sandboxMode]);}+export type UseAutoLoadCustomVizPluginOptions = {+ sandboxMode?: SandboxMode;+};+/*** Hook that auto-loads a custom viz plugin bundle when the current display* type starts with "custom:". Returns `true` while loading so the caller@@ -131,9 +159,13 @@ function useCustomVizDevReload(* For plugins with `dev_bundle_url` set, polls the bundle endpoint via HEAD* every 2s and reloads when the ETag changes.*/-export function useAutoLoadCustomVizPlugin(display: string | undefined): {+export function useAutoLoadCustomVizPlugin(+ display: string | undefined,+ options: UseAutoLoadCustomVizPluginOptions = {},+): {loading: boolean;} {+ const { sandboxMode = "hosted" } = options;const { plugins, disabled } = useCustomVizPlugins();const [sendToast] = useToast();const [loading, setLoading] = useState(false);@@ -163,13 +195,16 @@ export function useAutoLoadCustomVizPlugin(display: string | undefined): {loadingRef.current = identifier;setLoading(true);try {- await loadCustomVizPlugin(pluginToLoad, { onInfo });+ await loadCustomVizPlugin(pluginToLoad, {+ onInfo,+ sandboxMode,+ });} finally {loadingRef.current = null;setLoading(false);}},- [onInfo],+ [onInfo, sandboxMode],);useEffect(() => {@@ -186,7 +221,7 @@ export function useAutoLoadCustomVizPlugin(display: string | undefined): {load(plugin);}, [display, plugins, load]);- useCustomVizDevReload(display, plugins, setLoading, onInfo);+ useCustomVizDevReload(display, plugins, setLoading, onInfo, sandboxMode);// `loading` state drives re-renders when async load completes.// Without it, the Map-based check alone wouldn't trigger a re-render.@@ -212,15 +247,7 @@ export function useAutoLoadCustomVizPlugin(display: string | undefined): {plugins &&!plugins.find((p) => `custom:${p.identifier}` === display)) {- if (visualizations.has(display)) {- visualizations.delete(display);- for (const [id, entry] of loadedPlugins) {- if (entry.identifier === display) {- loadedPlugins.delete(id);- failedPluginHashes.delete(id);- }- }- }+ unregisterCustomVizDisplay(display);return { loading: false };}@@ -278,16 +305,18 @@ export async function loadCustomVizPlugin(ensureVizApi();try {- const bundleUrl = new URL(- getSubpathSafeUrl(plugin.bundle_url),- window.location.origin,- );+ const params: Record<string, string> = {};if (cacheBustSuffix) {- bundleUrl.searchParams.set("t", Date.now().toString());+ params.t = Date.now().toString();} else if (currentHash) {- bundleUrl.searchParams.set("v", currentHash);+ params.v = currentHash;}- const res = await fetch(bundleUrl.href, { cache: "no-store" });+ const res = await api.fetch({+ method: "GET",+ url: plugin.bundle_url,+ params,+ cache: "no-store",+ });if (!res.ok) {throw new Error(`HTTP ${res.status}`);}@@ -337,6 +366,14 @@ export async function loadCustomVizPlugin(plugin.id,);+ // core app resolves these to a plain same-origin url like+ // `/api/ee/custom-viz-plugin/1/asset?path=icon.svg`, the SDK to an inline+ // `blob:` url to avoid the cross-origin auth issue (see the slot).+ const resolvedIconUrl = await PLUGIN_CUSTOM_VIZ.resolveCustomVizAssetUrl(+ plugin.id,+ plugin.icon,+ );+// Attach the required static properties onto the component functionconst Component = ExplicitSize<VisualizationProps>({ wrapped: true })(Wrapper,@@ -345,7 +382,7 @@ export async function loadCustomVizPlugin(identifier,pluginId: plugin.id,getUiName: () => plugin.display_name,- iconUrl: getPluginAssetUrl(plugin.id, plugin.icon),+ iconUrl: resolvedIconUrl,isDev: Boolean(plugin.dev_bundle_url),});diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/index.tsindex d347cba90c8..ff55d84539e 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/index.ts@@ -1,5 +1,8 @@import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";-import { getPluginAssetUrl } from "metabase/visualizations/custom-visualizations/custom-viz-utils";+import {+ getPluginAssetUrl,+ resolveCustomVizAssetUrl,+} from "metabase/visualizations/custom-visualizations/custom-viz-utils";import { hasPremiumFeature } from "metabase-enterprise/settings";import { isCustomVizDisplay } from "metabase-types/guards/visualization";@@ -25,6 +28,8 @@ export function initializePlugin() {useCustomVizPlugins,loadCustomVizPlugin,getPluginAssetUrl,+ resolveCustomVizAssetUrl,+ releaseCustomVizAsset: () => {},useCustomVizPluginsIcon,isCustomVizDisplay,isWidgetMount,diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.tsindex 6652dd3cc43..659c71cc2b7 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts@@ -86,24 +86,6 @@ export function isDomNode(obj: unknown): obj is Node {return false;}-function describeNode(node: Node): string {- if (node.nodeType === Node.ELEMENT_NODE) {- const el = node as Element;- const tag = el.nodeName.toLowerCase();- if (el.id) {- return `<${tag} id="${el.id}">`;- }- const testId = el.getAttribute("data-testid");- if (testId) {- return `<${tag} data-testid="${testId}">`;- }- return `<${tag}>`;- }- // For non-Elements, `nodeName` is the canonical descriptor (e.g.- // `#text`, `#comment`, `#document`, `#document-fragment`).- return `<${node.nodeName.toLowerCase()}>`;-}-function createDecoyForNode(node: Node): Node {switch (node.nodeType) {case Node.ELEMENT_NODE: {@@ -129,8 +111,6 @@ function makeDecoyNode(pluginId: CustomVizPluginId, node: Node): Node {if (decoy === node) {return node;}- console.error(- `[plugin ${pluginId}] swapped out-of-scope ${describeNode(node)} with decoy`,- );+return decoy;}diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.tsindex b6c613d56f2..f19d5b38d18 100644--- a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts@@ -1,6 +1,7 @@/* eslint-disable import/order */import { PLUGIN_IS_EE_BUILD } from "metabase/plugins";+import { initializeSdkCustomVizPlugin } from "../embedding-sdk-ee/custom-viz/initialize";import { initializeHandleLinkPlugin } from "../embedding-sdk-ee/handle-link/handle-link";// SETTINGS OVERRIDES:@@ -33,6 +34,7 @@ export function initializePlugins() {initializeNotifications();initializeSharing();initializeHandleLinkPlugin();+ initializeSdkCustomVizPlugin();}// "SDK EE-plugins", that are specific to the embedding sdk.diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ChartTypeDropdown/ChartTypeDropdown.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ChartTypeDropdown/ChartTypeDropdown.tsxindex dfc42a68ff4..bda36ece81a 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ChartTypeDropdown/ChartTypeDropdown.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ChartTypeDropdown/ChartTypeDropdown.tsx@@ -90,6 +90,7 @@ export const ChartTypeDropdownInner = (props: ChartTypeDropdownInnerProps) => {value: CardDisplayType;label: ReturnType<Visualization["getUiName"]>;iconName: IconName;+ iconUrl?: string;} | null => {const visualization = visualizations.get(visualizationType);if (!visualization) {@@ -100,6 +101,7 @@ export const ChartTypeDropdownInner = (props: ChartTypeDropdownInnerProps) => {value: visualizationType,label: visualization.getUiName(),iconName: visualization.iconName,+ iconUrl: visualization.iconUrl,};};@@ -136,6 +138,7 @@ export const ChartTypeDropdownInner = (props: ChartTypeDropdownInnerProps) => {disabled={!selectedElement}label={selectedElement?.label}icon={selectedElement?.iconName}+ iconUrl={selectedElement?.iconUrl}isHighlighted={false}variant="default"px={undefined}@@ -177,16 +180,27 @@ interface OptionProps {value: CardDisplayType;label: ReturnType<Visualization["getUiName"]>;iconName: IconName;+ iconUrl?: string;selected: boolean;}function Option(props: OptionProps) {- const { value, selected, iconName, label } = props;+ const { value, selected, iconName, iconUrl, label } = props;return (<Combobox.Option px="sm" py="xs" value={value} selected={selected}><Flex align="center" gap="sm">- {iconName ? <Icon name={iconName} flex="0 0 1rem" /> : null}+ {iconUrl ? (+ <img+ src={iconUrl}+ alt=""+ width={16}+ height={16}+ style={{ flex: "0 0 1rem" }}+ />+ ) : iconName ? (+ <Icon name={iconName} flex="0 0 1rem" />+ ) : null}<Text c="inherit" style={{ whiteSpace: "nowrap" }}>{label}</Text>diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/ToolbarButton/ToolbarButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/ToolbarButton/ToolbarButton.tsxindex 83d97366f45..751d99fb0d1 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/ToolbarButton/ToolbarButton.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/ToolbarButton/ToolbarButton.tsx@@ -9,11 +9,13 @@ function _ToolbarButton({label,icon,+ iconUrl,isHighlighted,...buttonProps}: {label: ReactNode;icon?: IconName;+ iconUrl?: string;isHighlighted?: boolean;} & ButtonProps,ref: Ref<HTMLButtonElement>,@@ -22,7 +24,13 @@ function _ToolbarButton(<Buttonref={ref}variant={isHighlighted ? "filled" : "subtle"}- leftSection={icon ? <Icon name={icon} /> : undefined}+ leftSection={+ iconUrl ? (+ <img src={iconUrl} alt="" width={16} height={16} />+ ) : icon ? (+ <Icon name={icon} />+ ) : undefined+ }py="sm"px="md"{...buttonProps}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex 92bd1c2ca45..f1f7d5d7dc9 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -87,6 +87,7 @@ export const SdkQuestionProvider = ({navigateToNewCard: userNavigateToNewCard,onDrillThrough,onVisualizationChange,+ initialVisualization,}: SdkQuestionProviderProps) => {const isGuestEmbed = useSdkSelector(getIsGuestEmbed);const dispatch = useSdkDispatch();@@ -192,6 +193,7 @@ export const SdkQuestionProvider = ({deserializedCard,initialSqlParameters: effectiveInitialSqlParameters,targetDashboardId,+ initialVisualization,});useWarnConflictingParameterProps({diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.tsindex 081c465ec47..67a69b8df47 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts@@ -146,6 +146,18 @@ type SdkQuestionConfig = {* @param display the new display type*/onVisualizationChange?: (display: CardDisplayType) => void;++ /**+ * The visualization type to select when the question loads, overriding the+ * question's saved visualization. Accepts chart types such as `"bar"` or+ * `"table"`, and custom visualization displays (`"custom:<identifier>"`,+ * requires the plugin to be installed and enabled via+ * `allowedCustomVisualizations`).+ * <br/>+ * Falls back to the question's saved visualization when the requested one+ * doesn't exist or isn't allowed.+ **/+ initialVisualization?: CardDisplayType | `custom:${string}`;};export type QuestionMockLocationParameters = {diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/hooks/use-sensible-visualizations.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/hooks/use-sensible-visualizations.tsindex 97894b015dc..9293b52d22a 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/hooks/use-sensible-visualizations.ts+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/hooks/use-sensible-visualizations.ts@@ -1,5 +1,7 @@-import { useMemo, useRef } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useToast } from "metabase/common/hooks";+import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";import { getSensibleVisualizations } from "metabase/visualizations/lib/sensibility";import type { CardDisplayType } from "metabase-types/api";@@ -7,17 +9,45 @@ import { useSdkQuestionContext } from "../context";export const useSensibleVisualizations = () => {const { queryResults } = useSdkQuestionContext();+ const [sendToast] = useToast();+ const { plugins: customVizPlugins } = PLUGIN_CUSTOM_VIZ.useCustomVizPlugins();+ const [pluginsLoadedVersion, setPluginsLoadedVersion] = useState(0);- const result = queryResults?.[0];+ const onInfo = useCallback(+ (message: string) => sendToast({ message }),+ [sendToast],+ );- const initialResultRef = useRef(result);- const { sensibleVisualizations, nonSensibleVisualizations } = useMemo(- () => getSensibleVisualizations({ result: initialResultRef.current }),+ // Eagerly load all custom-viz plugins so their displays register in the+ // visualizations Map and appear in the chart-type picker. Mirrors the+ // main-app ChartTypeSidebar.+ useEffect(() => {+ if (!customVizPlugins?.length) {+ return;+ }+ let cancelled = false;+ Promise.all(+ customVizPlugins.map((plugin) =>+ PLUGIN_CUSTOM_VIZ.loadCustomVizPlugin(plugin, { onInfo }),+ ),+ ).then(() => {+ if (!cancelled) {+ setPluginsLoadedVersion((version) => version + 1);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [customVizPlugins, onInfo]);- [],+ const result = queryResults?.[0] ?? null;++ const { sensibleVisualizations, nonSensibleVisualizations } = useMemo(+ () => getSensibleVisualizations({ result }),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `pluginsLoadedVersion` isn't read in the body; it's the signal that custom-viz plugins registered in the global `visualizations` Map, which `getSensibleVisualizations` reads.+ [result, pluginsLoadedVersion],);- // SDK doesn't support custom viz plugins, so we safely narrow the type here.return {sensibleVisualizations: sensibleVisualizations as CardDisplayType[],nonSensibleVisualizations: nonSensibleVisualizations as CardDisplayType[],diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsxindex 3b88cf1606b..d1fa87a4c7e 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx@@ -83,7 +83,13 @@ export type DrillThroughQuestionProps = Omit<* @category InteractiveQuestion*/export type SdkQuestionProps = SdkQuestionDefaultViewProps &- Omit<SdkQuestionProviderProps, "componentPlugins"> & {+ // TEMP: initialVisualization is disabled at the public boundary. The internal+ // plumbing (provider, use-load-question, run-question-query) is kept; re-enable+ // by removing it from this Omit and restoring the prop forwarding below.+ Omit<+ SdkQuestionProviderProps,+ "componentPlugins" | "initialVisualization"+ > & {plugins?: SdkQuestionProviderProps["componentPlugins"];};diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex 4b7390c16b8..8c1a63c6fee 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -19,7 +19,10 @@ import type {import { isAbortError } from "metabase/api/client";import { isStaticEmbeddingEntityLoadingError } from "metabase/utils/errors/is-static-embedding-entity-loading-error";import type Question from "metabase-lib/v1/Question";-import type { ParameterValuesMap } from "metabase-types/api";+import type {+ ParameterValuesMap,+ QueryVisualizationDisplayType,+} from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";type LoadQuestionResult = Promise<@@ -60,6 +63,7 @@ export interface LoadQuestionHookResult {type UseLoadQuestionParams = LoadSdkQuestionParams & {isGuestEmbed: boolean;token: EntityToken | null | undefined;+ initialVisualization?: QueryVisualizationDisplayType;};export function useLoadQuestion({@@ -70,6 +74,7 @@ export function useLoadQuestion({deserializedCard,initialSqlParameters,targetDashboardId,+ initialVisualization,}: UseLoadQuestionParams): LoadQuestionHookResult {const dispatch = useSdkDispatch();@@ -142,6 +147,7 @@ export function useLoadQuestion({parameterValues: questionState.parameterValues,signal: nextSignal(),dispatch,+ initialVisualization,});mergeQuestionState(results);@@ -185,6 +191,7 @@ export function useLoadQuestion({sqlParameterKey,questionId,targetDashboardId,+ initialVisualization,]);const [runQuestionState, queryQuestion] = useAsyncFn(async () => {diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.tsindex 9ba96c2a529..2da6c9b3575 100644--- a/frontend/src/embedding-sdk-bundle/index.ts+++ b/frontend/src/embedding-sdk-bundle/index.ts@@ -1,5 +1,17 @@/* eslint-disable import/order */+// Dynamic chunks (e.g. await import("./sandbox")) must load from the Metabase+// origin, not the host page. This chunk is served at+// `<metabase>/app/embedding-sdk/chunks/embedding-sdk-chunked.<hash>.js`; its+// parent directory is the publicPath webpack needs for sibling chunks.+// eslint-disable-next-line no-var+declare var __webpack_public_path__: string;+const currentScriptUrl = (document.currentScript as HTMLScriptElement | null)+ ?.src;+if (currentScriptUrl) {+ __webpack_public_path__ = new URL("../", currentScriptUrl).href;+}+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";// Enable SDK mode as we are in the SDK bundlediff --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.tsindex 2593d4d4e7b..64c905fbfe6 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@@ -1,10 +1,16 @@import { getGuestEmbedFilteredParameters } from "embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters";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 { getSensibleDisplays } from "metabase/visualizations";+import { isNotNull } from "metabase/utils/types";+import visualizations, { getSensibleDisplays } from "metabase/visualizations";import type Question from "metabase-lib/v1/Question";-import type { DatasetData, ParameterValuesMap } from "metabase-types/api";+import type {+ DatasetData,+ ParameterValuesMap,+ QueryVisualizationDisplayType,+} from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";interface RunQuestionQueryParams {@@ -15,6 +21,7 @@ interface RunQuestionQueryParams {parameterValues?: ParameterValuesMap;signal?: AbortSignal;dispatch: Dispatch;+ initialVisualization?: QueryVisualizationDisplayType;}export async function runQuestionQuerySdk(@@ -28,6 +35,7 @@ export async function runQuestionQuerySdk(parameterValues,signal,dispatch,+ initialVisualization,} = params;if (question.isSaved()) {@@ -50,18 +58,61 @@ export async function runQuestionQuerySdk(parameterValues,);- queryResults = await runQuestionQuery(question, {- dispatch,- signal,- ignoreCache: false,- isDirty: isQueryDirty,- token,- ...(isGuestEmbed && {- queryParamsOverride: {- parameters: JSON.stringify(filteredParameters),- },+ const display = question.display();++ // We try to load both the `initialVisualization` override (if provided) and+ // the saved question's current display in case the override fails to load+ // or is not enabled+ const customDisplaysToLoad = [+ ...new Set(+ [display, initialVisualization].filter(+ PLUGIN_CUSTOM_VIZ.isCustomVizDisplay,+ ),+ ),+ ];++ const loadCustomDisplays = async () =>+ new Set(+ (+ await Promise.all(+ customDisplaysToLoad.map((customDisplay) =>+ PLUGIN_CUSTOM_VIZ.loadCustomVizPluginForDisplay(+ dispatch,+ customDisplay,+ ),+ ),+ )+ ).filter(isNotNull),+ );++ // The query and the custom-viz load are independent, so run them+ // concurrently.+ const [results, loadedDisplays] = await Promise.all([+ runQuestionQuery(question, {+ dispatch,+ signal,+ ignoreCache: false,+ isDirty: isQueryDirty,+ token,+ ...(isGuestEmbed && {+ queryParamsOverride: {+ parameters: JSON.stringify(filteredParameters),+ },+ }),}),- });+ loadCustomDisplays(),+ ]);+ queryResults = results;++ const isDisplayAvailable = (d: QueryVisualizationDisplayType) =>+ PLUGIN_CUSTOM_VIZ.isCustomVizDisplay(d)+ ? loadedDisplays.has(d)+ : visualizations.has(d);++ const initialDisplay =+ initialVisualization && isDisplayAvailable(initialVisualization)+ ? initialVisualization+ : null;// Default values for rows/cols are needed because the `data` is missing in the case of Guest Embedconst [{ data = isGuestEmbed ? { rows: [], cols: [] } : undefined }] =@@ -70,12 +121,26 @@ export async function runQuestionQuerySdk(// `data` may be a partial (guest embed) or absent (error result); the// viz helpers tolerate it, matching the prior untyped behavior.const datasetData = data as DatasetData;- const sensibleDisplays = getSensibleDisplays(datasetData);- question = question.maybeResetDisplay(- datasetData,- sensibleDisplays,- undefined,- );++ if (initialDisplay) {+ // Mirrors picking the visualization from the chart-type dropdown:+ // lock it so the data shape doesn't auto-reset it.+ question = question.setDisplay(initialDisplay).lockDisplay();+ } else {+ // Built-in sensibles only (custom viz never report sensible, no `isSensible`),+ // plus the current display if it's a custom viz that loaded this run.+ const sensibleDisplays = getSensibleDisplays(datasetData).filter(+ (d) => !PLUGIN_CUSTOM_VIZ.isCustomVizDisplay(d),+ );+ if (loadedDisplays.has(display)) {+ sensibleDisplays.push(display);+ }+ question = question.maybeResetDisplay(+ datasetData,+ sensibleDisplays,+ undefined,+ );+ }}return { question, queryResults };diff --git a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts b/frontend/src/embedding-sdk-bundle/types/metabase-provider.tsindex c50a8df452e..2a844433bec 100644--- a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts+++ b/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts@@ -75,4 +75,17 @@ export interface MetabaseProviderProps {* Defaults to false (uses the optimized bootstrap loader).**/useLegacyMonolithicBundle?: boolean;++ /**+ * Opt-in support for EE custom visualization plugins inside the SDK.+ * When set, the SDK loads custom-viz bundles into an `about:blank`+ * sandbox (no hosted-sandbox endpoint required).+ *+ * Pass an allowlist of `custom:`-prefixed plugin identifiers (manifest+ * `name`), e.g. `["custom:Thumbs", "custom:Calendar"]`. Only+ * listed plugins are loaded. Omit or pass `[]` to disable.+ *+ * Requires the `custom-viz` premium feature.+ **/+ allowedCustomVisualizations?: `custom:${string}`[];}diff --git a/frontend/src/metabase/api/client/types.ts b/frontend/src/metabase/api/client/types.tsindex 6514dd8d0b9..fde712052fe 100644--- a/frontend/src/metabase/api/client/types.ts+++ b/frontend/src/metabase/api/client/types.ts@@ -4,6 +4,8 @@ export type RequestOptions<RawResponse extends boolean = boolean> = {noEvent?: boolean;headers?: Record<string, string>;signal?: AbortSignal;+ /** Forwarded to the underlying `fetch` (e.g. `"no-store"` to skip the cache). */+ cache?: RequestCache;/*** When `true`, resolve with the raw `Response` instead of the parsed body —* for callers that read it themselves (binary downloads, map tiles as a blob).diff --git a/frontend/src/metabase/plugins/oss/custom-viz.ts b/frontend/src/metabase/plugins/oss/custom-viz.tsindex 435250d6f46..aaff4fa94f1 100644--- a/frontend/src/metabase/plugins/oss/custom-viz.ts+++ b/frontend/src/metabase/plugins/oss/custom-viz.ts@@ -3,7 +3,9 @@ import type { ComponentType } from "react";import type { IconData } from "metabase/common/utils/icon";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";+import type { Dispatch } from "metabase/redux/store";import type {+ CustomVizPluginId,CustomVizPluginRuntime,VisualizationDisplay,} from "metabase-types/api";@@ -39,8 +41,30 @@ const getDefaultPluginCustomViz = () => ({onInfo?: (message: string) => void;},) => null as string | null,- getPluginAssetUrl: (_pluginId: number, _assetPath: string | null) =>- undefined as string | undefined,+ /**+ * 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.+ */+ loadCustomVizPluginForDisplay: async (+ _dispatch: Dispatch,+ _display: string,+ ): Promise<VisualizationDisplay | null> => null,+ getPluginAssetUrl: (+ _pluginId: CustomVizPluginId,+ _assetPath: string | null,+ ) => undefined as string | undefined,++ // Only the SDK really implements these: its icon `<img>` is cross-origin and+ // can't carry the session header, so the sdk fetches the asset with auth, hands back+ // a `blob:` url, and revokes it via `releaseCustomVizAsset`. The main app just+ // builds a plain url.+ resolveCustomVizAssetUrl: (+ _pluginId: CustomVizPluginId,+ _assetPath: string | null | undefined,+ ): Promise<string | undefined> => Promise.resolve(undefined),+ releaseCustomVizAsset: (_pluginId: CustomVizPluginId) => {},+useCustomVizPluginsIcon: () => noopCustomVizIcon,// Must be functional in OSS — pure string check used by getSensibleVisualizationsdiff --git a/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts b/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.tsindex 49644f55c92..922027a6f38 100644--- a/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts+++ b/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts@@ -30,6 +30,16 @@ export function getPluginAssetUrl();}+/**+ * Plain same-origin asset URL. The SDK overrides this to fetch the asset with auth headers and return a blob.+ */+export function resolveCustomVizAssetUrl(+ pluginId: CustomVizPluginId,+ assetPath: string | null | undefined,+): Promise<string | undefined> {+ return Promise.resolve(getPluginAssetUrl(pluginId, assetPath));+}+export function getCustomPluginIdentifier(pluginOrIdentifier: Pick<CustomVizPluginRuntime, "identifier"> | string,): VisualizationDisplay {