Skip to content

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

Enhance DevToolBar (#78539)

Timofey Kachalovf923c031c222
diff --git a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx
index 666f16c5580..f1427aacd30 100644
--- a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx
+++ b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx
@@ -34,6 +34,13 @@ export default function App() {
</div>
<SandboxProbe />
+
+ <button
+ data-testid="dev-app-error-probe"
+ onClick={() => console.error("dev-app probe error")}
+ >
+ Probe error
+ </button>
</div>
);
}
diff --git a/e2e/support/component-webpack.config.js b/e2e/support/component-webpack.config.js
index 048bc50d948..cef19bfa5d2 100644
--- a/e2e/support/component-webpack.config.js
+++ b/e2e/support/component-webpack.config.js
@@ -13,8 +13,11 @@ const {
const SDK_PACKAGE_NAME = "@metabase/embedding-sdk-react";
-const { isEmbeddingSdkPackageInstalled, embeddingSdkPath } =
- resolveEmbeddingSdkPackage();
+const {
+ isEmbeddingSdkPackageInstalled,
+ embeddingSdkPath,
+ embeddingSdkDistPath,
+} = resolveEmbeddingSdkPackage();
console.log(
`Embedding SDK is ${isEmbeddingSdkPackageInstalled ? chalk.green("installed") : `${chalk.red("NOT installed")}, ${chalk.bold("using locally built version")} from "resources/embedding-sdk"'}`}`,
@@ -29,6 +32,14 @@ module.exports = {
extensions: [".ts", ".tsx", ".js", ".jsx", ".css", ".svg"],
alias: {
...RESOLVE_ALIASES,
+ ...(embeddingSdkDistPath
+ ? {
+ [`${SDK_PACKAGE_NAME}/data-app-dev`]: path.join(
+ embeddingSdkDistPath,
+ "data-app-dev.js",
+ ),
+ }
+ : null),
...(embeddingSdkPath ? { [SDK_PACKAGE_NAME]: embeddingSdkPath } : null),
},
fallback: {
@@ -112,6 +123,7 @@ function resolveEmbeddingSdkPackage() {
return {
isEmbeddingSdkPackageInstalled: true,
embeddingSdkPath: sdkInNodeModulesPath,
+ embeddingSdkDistPath: path.join(sdkInNodeModulesPath, "dist"),
};
}
@@ -122,6 +134,7 @@ function resolveEmbeddingSdkPackage() {
return {
isEmbeddingSdkPackageInstalled: true,
embeddingSdkPath: requirePackagePath,
+ embeddingSdkDistPath: path.dirname(requirePackagePath),
};
}
} catch (err) {
@@ -137,6 +150,7 @@ function resolveEmbeddingSdkPackage() {
return {
isEmbeddingSdkPackageInstalled: false,
embeddingSdkPath: sdkLocalPackagePath,
+ embeddingSdkDistPath: path.dirname(sdkLocalPackagePath),
};
}
@@ -147,5 +161,6 @@ function resolveEmbeddingSdkPackage() {
return {
isEmbeddingSdkPackageInstalled: false,
embeddingSdkPath: null,
+ embeddingSdkDistPath: null,
};
}
diff --git a/e2e/support/cypress-embedding-sdk-component-test.config.js b/e2e/support/cypress-embedding-sdk-component-test.config.js
index 8ba5ef848a0..edb09b7bf22 100644
--- a/e2e/support/cypress-embedding-sdk-component-test.config.js
+++ b/e2e/support/cypress-embedding-sdk-component-test.config.js
@@ -9,7 +9,7 @@ const embeddingSdkComponentTestConfig = {
video: false,
experimentalMemoryManagement: true,
numTestsKeptInMemory: 1,
- specPattern: "e2e/test-component/scenarios/embedding-sdk/**/*.cy.spec.tsx",
+ specPattern: "e2e/test-component/scenarios/**/*.cy.spec.tsx",
indexHtmlFile: "e2e/support/component-index.html",
supportFile: "e2e/support/component-cypress.js",
diff --git a/e2e/support/helpers/e2e-data-app-dev-component-helpers.tsx b/e2e/support/helpers/e2e-data-app-dev-component-helpers.tsx
new file mode 100644
index 00000000000..b9afca83ebe
--- /dev/null
+++ b/e2e/support/helpers/e2e-data-app-dev-component-helpers.tsx
@@ -0,0 +1,90 @@
+import {
+ DEV_SESSION_ID,
+ DataAppDevProvider,
+ type DataAppDiagnosticPayload,
+ type DataAppDiagnosticsReport,
+ DevToolbar,
+ type DevToolbarProps,
+} from "@metabase/embedding-sdk-react/data-app-dev";
+
+import { DATA_APP_DEV_DIAGNOSTICS_PATH } from "e2e/support/helpers/e2e-data-app-dev-helpers";
+import { DEFAULT_SDK_AUTH_PROVIDER_CONFIG } from "e2e/support/helpers/embedding-sdk-component-testing";
+
+const FEED = `**${DATA_APP_DEV_DIAGNOSTICS_PATH}*`;
+
+/**
+ * A served entry, tagged with this page's session — the toolbar shows only its
+ * own page's entries, so an untagged one would be filtered out of the panel.
+ */
+export const diagnosticEntry = (
+ over: Partial<DataAppDiagnosticPayload> = {},
+): DataAppDiagnosticPayload => ({
+ eventId: 1,
+ sessionId: DEV_SESSION_ID,
+ time: Date.parse("2026-01-01T10:00:00Z"),
+ kind: "error",
+ summary: "boom",
+ detail: null,
+ hint: null,
+ alert: true,
+ ...over,
+});
+
+export const diagnosticsReport = (
+ entries: DataAppDiagnosticPayload[],
+ over: Partial<DataAppDiagnosticsReport> = {},
+): DataAppDiagnosticsReport => ({
+ entries,
+ connection: null,
+ manifest: null,
+ clients: 1,
+ lastReportAt: 1,
+ lastRebuildAt: 1,
+ nextEventId: (entries.at(-1)?.eventId ?? 0) + 1,
+ sessionId: DEV_SESSION_ID,
+ ...over,
+});
+
+/**
+ * Serve a fixed buffer with the dev server's contract — `startEventId`
+ * filtering included — and clear it on DELETE.
+ */
+export function serveDiagnosticsFeed(
+ entries: DataAppDiagnosticPayload[],
+ reportOver: Partial<DataAppDiagnosticsReport> = {},
+) {
+ const buffer = [...entries];
+
+ cy.intercept("GET", FEED, (req) => {
+ const start = Number(
+ new URL(req.url, "http://localhost").searchParams.get("startEventId"),
+ );
+ const shown = Number.isFinite(start)
+ ? buffer.filter((e) => e.eventId >= start)
+ : buffer;
+ req.reply(diagnosticsReport(shown, reportOver));
+ }).as("feed");
+
+ cy.intercept("DELETE", FEED, (req) => {
+ buffer.length = 0;
+ req.reply({ statusCode: 204 });
+ }).as("clear");
+}
+
+/** Fail the feed at the transport level, as a stopped dev server would. */
+export function serveUnreachableDiagnosticsFeed() {
+ cy.intercept("GET", FEED, { forceNetworkError: true }).as("feed");
+}
+
+export const mountDevToolbar = (props: Partial<DevToolbarProps> = {}) =>
+ cy.mount(
+ <>
+ <DataAppDevProvider
+ appSlug="sales"
+ authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}
+ >
+ <div />
+ </DataAppDevProvider>
+ <DevToolbar {...props} />
+ </>,
+ );
diff --git a/e2e/support/helpers/e2e-data-app-dev-helpers.ts b/e2e/support/helpers/e2e-data-app-dev-helpers.ts
new file mode 100644
index 00000000000..7b82766aa49
--- /dev/null
+++ b/e2e/support/helpers/e2e-data-app-dev-helpers.ts
@@ -0,0 +1,43 @@
+// Type-only SDK imports: host-app suites bundle this file with the plain
+// esbuild preprocessor, which can't resolve the SDK's own deps. Helpers that
+// need SDK *values* live in `e2e-data-app-dev-component-helpers`.
+import type { DataAppDiagnosticsReport } from "@metabase/embedding-sdk-react/data-app-dev";
+
+export const DATA_APP_DEV_DIAGNOSTICS_PATH = "/__data-app/diagnostics";
+
+export const devToolbarRoot = () => cy.get("[data-cy-root]");
+
+export const devToolbarPanel = () => cy.findByTestId("dev-toolbar-panel");
+
+export const devToolbarToggle = () =>
+ cy.findByRole("button", { name: /Diagnostics/ });
+
+export const openDevToolbar = () => devToolbarToggle().click();
+
+/** Tabs holding problems append a count, so match on the label prefix. */
+export const devToolbarTab = (name: string) =>
+ cy.findByRole("tab", { name: new RegExp(`^${name}`) });
+
+/**
+ * Poll the real diagnostics endpoint until `predicate` holds — the page's
+ * reporter batches, so the feed converges rather than reflecting an event
+ * instantly. Host-app suites only.
+ */
+export const readDiagnosticsUntil = (
+ url: string,
+ description: string,
+ predicate: (report: DataAppDiagnosticsReport) => boolean,
+ attempt = 0,
+): Cypress.Chainable<DataAppDiagnosticsReport> =>
+ cy
+ .request<DataAppDiagnosticsReport>(url)
+ .then(({ body }): Cypress.Chainable<DataAppDiagnosticsReport> => {
+ if (predicate(body)) {
+ return cy.wrap(body, { log: false });
+ }
+ if (attempt >= 30) {
+ throw new Error(`Diagnostics endpoint never reported: ${description}`);
+ }
+ cy.wait(1000);
+ return readDiagnosticsUntil(url, description, predicate, attempt + 1);
+ });
diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.ts
index ecf9c469795..d836595bad8 100644
--- a/e2e/support/helpers/e2e-data-app-helpers.ts
+++ b/e2e/support/helpers/e2e-data-app-helpers.ts
@@ -137,8 +137,29 @@ export function dataAppIframe(displayName: string) {
return getIframeBody(`iframe[title="${displayName}"]`);
}
-const DATA_APP_DEV_ENV_PATH =
- "e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.env.local";
+const DATA_APP_DEV_HOST_APP_DIR =
+ "e2e/embedding-sdk-host-apps/vite-6-data-app-host-app";
+
+const DATA_APP_DEV_ENV_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/.env.local`;
+
+/** The dev host app's manifest — the live manifest-validation suite edits it. */
+export const DATA_APP_DEV_MANIFEST_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/data_app.yaml`;
+
+/** The dev host app's source entry — the soft-reload suite edits it. */
+export const DATA_APP_DEV_APP_SRC_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/src/App.tsx`;
+
+const DATA_APP_DEV_CONTENT_TIMEOUT_MS = 40000;
+
+/**
+ * Visit the dev host app and wait for the sandboxed bundle to render — the
+ * point at which the dev entry has booted (toolbar mounted, probes fired).
+ */
+export function visitDataAppDevApp(clientHost: string) {
+ cy.visit(clientHost);
+ cy.findByTestId("dev-app-content", {
+ timeout: DATA_APP_DEV_CONTENT_TIMEOUT_MS,
+ }).should("exist");
+}
/**
* Provision auth for the data-app dev-server host app: create an API key and
@@ -151,6 +172,9 @@ export function setUpDataAppDevServer(clientHost: string) {
throw new Error("baseUrl must be set for the data-app dev-server suite");
}
+ cy.exec(`rm -f ${DATA_APP_DEV_ENV_PATH}`);
+ waitForDataAppDevServerEnv(clientHost, mbUrl, { expectPresent: false });
+
cy.request("POST", "/api/api-key", {
name: `data-app-dev-e2e-${Date.now()}`,
group_id: USER_GROUPS.ADMIN_GROUP,
@@ -161,18 +185,19 @@ export function setUpDataAppDevServer(clientHost: string) {
);
});
- waitForDataAppDevServerEnv(clientHost, mbUrl);
+ waitForDataAppDevServerEnv(clientHost, mbUrl, { expectPresent: true });
}
export function tearDownDataAppDevServer() {
cy.exec(`rm -f ${DATA_APP_DEV_ENV_PATH}`);
}
-// `DATA_APP_MB_URL` shows up in the served CSP once Vite has restarted onto the
-// new env — poll that before visiting.
+// `DATA_APP_MB_URL` shows up in (or drops out of) the served CSP once Vite has
+// restarted onto the changed env — poll for the expected state before visiting.
function waitForDataAppDevServerEnv(
clientHost: string,
mbUrl: string,
+ { expectPresent }: { expectPresent: boolean },
attempt = 0,
) {
const MAX_ATTEMPTS = 40;
@@ -185,17 +210,22 @@ function waitForDataAppDevServerEnv(
}).then((res) => {
const csp = String(res.headers["content-security-policy"] ?? "");
- if (csp.includes(origin)) {
+ if (csp.includes(origin) === expectPresent) {
return;
}
if (attempt >= MAX_ATTEMPTS) {
throw new Error(
- `Dev server never picked up DATA_APP_MB_URL (${origin}) in its CSP; last CSP: "${csp}"`,
+ `Dev server never restarted onto DATA_APP_MB_URL ${expectPresent ? "present" : "absent"} (${origin}); last CSP: "${csp}"`,
);
}
cy.wait(1000);
- waitForDataAppDevServerEnv(clientHost, mbUrl, attempt + 1);
+ waitForDataAppDevServerEnv(
+ clientHost,
+ mbUrl,
+ { expectPresent },
+ attempt + 1,
+ );
});
}
diff --git a/e2e/test-component/scenarios/data-apps/diagnostics-toolbar.cy.spec.tsx b/e2e/test-component/scenarios/data-apps/diagnostics-toolbar.cy.spec.tsx
new file mode 100644
index 00000000000..0769fe36fd1
--- /dev/null
+++ b/e2e/test-component/scenarios/data-apps/diagnostics-toolbar.cy.spec.tsx
@@ -0,0 +1,364 @@
+import {
+ diagnosticEntry,
+ mountDevToolbar,
+ serveDiagnosticsFeed,
+ serveUnreachableDiagnosticsFeed,
+} from "e2e/support/helpers/e2e-data-app-dev-component-helpers";
+import {
+ devToolbarPanel,
+ devToolbarRoot,
+ devToolbarToggle,
+ openDevToolbar,
+} from "e2e/support/helpers/e2e-data-app-dev-helpers";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+
+describe("scenarios > data-apps > dev diagnostics toolbar", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ describe("closed", () => {
+ it("badges the alert count on the toggle", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({ eventId: 1, kind: "error", summary: "boom" }),
+ // a successful query is not an alert, so it must not inflate the badge
+ diagnosticEntry({
+ eventId: 2,
+ kind: "sdk-call",
+ summary: "GET /api/card/1 → 200",
+ alert: false,
+ }),
+ ]);
+
+ mountDevToolbar();
+
+ devToolbarToggle().should("contain.text", "⚠ Diagnostics (1)");
+ });
+ });
+
+ describe("open", () => {
+ it("opens the full panel with tabs on a single click", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({ eventId: 1, kind: "error", summary: "boom" }),
+ ]);
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ // No intermediate popover: tabs are there at once and the toggle is gone.
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Errors/ })
+ .should("be.visible");
+ devToolbarRoot()
+ .findByRole("button", { name: /Diagnostics/ })
+ .should("not.exist");
+ devToolbarRoot().findByText("boom").should("be.visible");
+ });
+
+ it("hides a stack behind a disclosure until it's expanded", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({
+ eventId: 1,
+ kind: "error",
+ summary: "TypeError: nope",
+ detail: " at App (src/App.tsx:12:3)",
+ }),
+ ]);
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ devToolbarRoot().findByText("TypeError: nope").should("be.visible");
+ // The stack is in the DOM but collapsed inside a <details>, DevTools-style.
+ devToolbarRoot()
+ .findByText(/at App \(src\/App\.tsx:12:3\)/)
+ .should("not.be.visible");
+ devToolbarRoot().findByText("TypeError: nope").click();
+ devToolbarRoot()
+ .findByText(/at App \(src\/App\.tsx:12:3\)/)
+ .should("be.visible");
+ });
+
+ it("shows all five tabs, Errors active, with each tab's empty state", () => {
+ serveDiagnosticsFeed([]);
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ for (const label of [
+ "Errors",
+ "Blocked",
+ "Queries",
+ "Manifest",
+ "Connection",
+ ]) {
+ devToolbarRoot()
+ .findByRole("tab", { name: new RegExp(`^${label}`) })
+ .should("be.visible");
+ }
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Errors/ })
+ .should("have.attr", "aria-selected", "true");
+ devToolbarRoot().findByText("No errors captured.").should("be.visible");
+
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Blocked/ })
+ .click();
+ devToolbarRoot().findByText("Nothing blocked.").should("be.visible");
+
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Queries/ })
+ .click();
+ devToolbarRoot()
+ .findByText("No Metabase calls captured.")
+ .should("be.visible");
+
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Manifest/ })
+ .click();
+ devToolbarRoot()
+ .findByText("Manifest has not been validated yet.")
+ .should("be.visible");
+
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Connection/ })
+ .click();
+ devToolbarRoot()
+ .findByText("Connection check has not run yet.")
+ .should("be.visible");
+ });
+
+ it("splits errors and blocked entries across their tabs, with the fix hint", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({ eventId: 1, kind: "error", summary: "plain error" }),
+ diagnosticEntry({
+ eventId: 2,
+ kind: "blocked-network",
+ summary: "Blocked fetch to api.example.com (not in allowed_hosts)",
+ hint: "Add https://api.example.com to allowed_hosts in data_app.yaml (dev server restart required).",
+ }),
+ ]);
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ devToolbarRoot().findByText("plain error").should("be.visible");
+ devToolbarRoot()
+ .findByText(/Blocked fetch to/)
+ .should("not.exist");
+
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Blocked/ })
+ .click();
+ devToolbarRoot()
+ .findByText(/Blocked fetch to api\.example\.com/)
+ .should("be.visible");
+ devToolbarRoot()
+ .findByText(/Add https:\/\/api\.example\.com to allowed_hosts/)
+ .should("be.visible");
+ devToolbarRoot().findByText("plain error").should("not.exist");
+ });
+
+ it("lists Metabase calls and filters the Queries tab to failures", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({
+ eventId: 1,
+ kind: "sdk-call",
+ summary: "POST /api/dataset → 400 (12ms)",
+ alert: true,
+ }),
+ diagnosticEntry({
+ eventId: 2,
+ kind: "sdk-call",
+ summary: "GET /api/card/1 → 200 (8ms)",
+ alert: false,
+ }),
+ ]);
+
+ mountDevToolbar();
+ openDevToolbar();
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Queries/ })
+ .click();
+
+ devToolbarRoot()
+ .findByText(/Dev runs with an API key/)
+ .should("be.visible");
+ devToolbarRoot()
+ .findByText(/api\/card\/1/)
+ .should("be.visible");
+
+ devToolbarRoot()
+ .findByRole("checkbox", { name: /Failed only/ })
+ .click();
+
+ devToolbarRoot()
+ .findByText(/api\/dataset/)
+ .should("be.visible");
+ devToolbarRoot()
+ .findByText(/api\/card\/1/)
+ .should("not.exist");
+ });
+
+ it("shows why a query failed, behind the same disclosure as a stack", () => {
+ serveDiagnosticsFeed([
+ diagnosticEntry({
+ eventId: 1,
+ kind: "sdk-call",
+ summary: "POST /api/dataset → 400 (12ms)",
+ detail: 'Table "orders" is not in the manifest',
+ alert: true,
+ }),
+ ]);
+
+ mountDevToolbar();
+ openDevToolbar();
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Queries/ })
+ .click();
+
+ // Without the reason the author only learns *that* a query failed, and
+ // has to leave the toolbar for the browser's Network tab to find out why.
+ devToolbarRoot()
+ .findByText(/POST \/api\/dataset → 400/)
+ .should("be.visible");
+ devToolbarRoot()
+ .findByText(/is not in the manifest/)
+ .should("not.be.visible");
+
+ devToolbarRoot()
+ .findByText(/POST \/api\/dataset → 400/)
+ .click();
+ devToolbarRoot()
+ .findByText(/is not in the manifest/)
+ .should("be.visible");
+ });
+
+ it("renders the manifest status the feed carries", () => {
+ serveDiagnosticsFeed([], {
+ manifest: {
+ name: "Demo",
+ bundlePath: "dist/index.js",
+ bundlePathExists: false,
+ allowedHosts: ["https://api.example.com"],
+ errors: ["path is required"],
+ warnings: ["bundle is large"],
+ restartRequired: true,
+ },
+ });
+
+ mountDevToolbar();
+ openDevToolbar();
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Manifest/ })
+ .click();
+
+ // The tab is showing (top row visible); the rest is rendered further down
+ // the scrollable panel body, so assert it exists rather than fighting the
+ // scroll fold.
+ devToolbarRoot().findByText("path is required").should("be.visible");
+ devToolbarRoot().findByText("bundle is large").should("exist");
+ devToolbarRoot()
+ .findByText(/allowed_hosts changed/)
+ .should("exist");
+ devToolbarRoot().findByText("Demo").should("exist");
+ devToolbarRoot()
+ .findByText(/file not found/)
+ .should("exist");
+ devToolbarRoot().findByText("https://api.example.com").should("exist");
+ });
+
+ it("renders the connection status the feed carries", () => {
+ serveDiagnosticsFeed([], {
+ connection: {
+ checkedAt: 1,
+ metabaseUrl: "http://localhost:3000",
+ reachable: true,
+ sdkVersion: "0.64.0",
+ error: "The API key was rejected (401).",
+ },
+ });
+
+ mountDevToolbar();
+ openDevToolbar();
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Connection/ })
+ .click();
+
+ devToolbarRoot().findByText("http://localhost:3000").should("be.visible");
+ devToolbarRoot().findByText("✓").should("exist");
+ devToolbarRoot().findByText("0.64.0").should("exist");
+ devToolbarRoot()
+ .findByText("The API key was rejected (401).")
+ .should("exist");
+ });
+
+ it("says so, instead of looking healthy, when the dev server is unreachable", () => {
+ serveUnreachableDiagnosticsFeed();
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ devToolbarRoot()
+ .findByText(/Can't reach the dev server/)
+ .should("be.visible");
+ });
+
+ it("clears through the endpoint, emptying the panel", () => {
+ serveDiagnosticsFeed([diagnosticEntry({ eventId: 1, summary: "boom" })]);
+
+ mountDevToolbar();
+ openDevToolbar();
+ devToolbarRoot().findByText("boom").should("be.visible");
+
+ devToolbarRoot().findByRole("button", { name: "Clear" }).click();
+
+ cy.wait("@clear");
+ devToolbarRoot().findByText("boom").should("not.exist");
+ });
+
+ it("resizes by dragging the top edge, and Close returns to the toggle", () => {
+ serveDiagnosticsFeed([]);
+
+ mountDevToolbar();
+ openDevToolbar();
+
+ let before = 0;
+ devToolbarPanel()
+ .invoke("outerHeight")
+ .then((h) => {
+ before = h ?? 0;
+ expect(before).to.be.greaterThan(0);
+ });
+
+ // Drag the top edge up ~140px; the bottom-docked panel grows. The handler
+ // listens on `window` for the duration of the drag, so fire the move/up
+ // there directly rather than relying on bubbling from a thin 6px handle.
+ devToolbarRoot()
+ .findByRole("separator", { name: /Resize diagnostics panel/ })
+ .trigger("mousedown", { clientY: 400, force: true });
+ cy.window().then((win) => {
+ win.dispatchEvent(
+ new win.MouseEvent("mousemove", { clientY: 260, bubbles: true }),
+ );
+ win.dispatchEvent(new win.MouseEvent("mouseup", { bubbles: true }));
+ });
+
+ devToolbarPanel()
+ .invoke("outerHeight")
+ .should((h) => {
+ expect(h).to.be.greaterThan(before);
+ });
+
+ // Close dismisses the whole panel back to just the toggle button.
+ devToolbarRoot().findByRole("button", { name: "Close" }).click();
+ devToolbarRoot()
+ .findByRole("tab", { name: /^Errors/ })
+ .should("not.exist");
+ devToolbarToggle().should("be.visible");
+ });
+ });
+});
diff --git a/e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.ts b/e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.ts
new file mode 100644
index 00000000000..9e1550b83b8
--- /dev/null
+++ b/e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.ts
@@ -0,0 +1,337 @@
+import {
+ DATA_APP_DEV_DIAGNOSTICS_PATH,
+ devToolbarPanel,
+ devToolbarTab,
+ openDevToolbar,
+ readDiagnosticsUntil,
+} from "e2e/support/helpers/e2e-data-app-dev-helpers";
+import {
+ DATA_APP_DEV_APP_SRC_PATH,
+ DATA_APP_DEV_MANIFEST_PATH,
+ setUpDataAppDevServer,
+ tearDownDataAppDevServer,
+ visitDataAppDevApp,
+} from "e2e/support/helpers/e2e-data-app-helpers";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+
+const TIMEOUT_MS = 40000;
+
+const CLIENT_PORT = Cypress.expose("CLIENT_PORT");
+const CLIENT_HOST = `http://localhost:${CLIENT_PORT}`;
+
+const DIAGNOSTICS_URL = `${CLIENT_HOST}${DATA_APP_DEV_DIAGNOSTICS_PATH}`;
+
+describe("Embedding SDK: data-app dev diagnostics", () => {
+ before(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ setUpDataAppDevServer(CLIENT_HOST);
+ });
+
+ after(() => {
+ tearDownDataAppDevServer();
+ });
+
+ describe("dev diagnostics", () => {
+ beforeEach(() => {
+ // The dev server's buffer outlives page loads by design; start each test
+ // from an empty feed so assertions only see this test's events.
+ cy.request("DELETE", DIAGNOSTICS_URL);
+
+ visitDataAppDevApp(CLIENT_HOST);
+ });
+
+ it("surfaces the sandbox-blocked request in the Blocked tab, with the fix hint", () => {
+ openDevToolbar();
+ devToolbarTab("Blocked").click();
+
+ // `AllBy`: the app remounts once when the SDK store initializes, so its
+ // mount-time probe can legitimately record the same block twice.
+ devToolbarPanel()
+ .findAllByText(/Blocked fetch to blocked\.data-app\.test/, {
+ timeout: TIMEOUT_MS,
+ })
+ .first()
+ .should("be.visible");
+ devToolbarPanel()
+ .findAllByText(
+ /Add https:\/\/blocked\.data-app\.test to allowed_hosts in data_app\.yaml/,
+ )
+ .first()
+ .should("be.visible");
+ });
+
+ it("captures an error thrown inside the sandboxed app end to end", () => {
+ cy.findByTestId("dev-app-error-probe").click();
+
+ openDevToolbar();
+ devToolbarPanel()
+ .findByText("dev-app probe error", { timeout: TIMEOUT_MS })
+ .should("be.visible");
+
+ readDiagnosticsUntil(DIAGNOSTICS_URL, "the probe error entry", (report) =>
+ report.entries.some(
+ (entry) =>
+ entry.kind === "error" && entry.summary === "dev-app probe error",
+ ),
+ );
+ });
+
+ it("lists the app's real Metabase calls in the Queries tab", () => {
+ cy.findByTestId("table-body", { timeout: TIMEOUT_MS }).should("exist");
+
+ openDevToolbar();
+ devToolbarTab("Queries").click();
+
+ devToolbarPanel()
+ .findByText(/Dev runs with an API key/)
+ .should("be.visible");
+ devToolbarPanel()
+ .findAllByText(/\/api\/(dataset|card)/, { timeout: TIMEOUT_MS })
+ .its("length")
+ .should("be.gte", 1);
+ });
+
+ it("shows the real connection and manifest state in their tabs", () => {
+ const mbUrl = String(Cypress.config("baseUrl"));
+
+ openDevToolbar();
+
+ devToolbarTab("Connection").click();
+ devToolbarPanel()
+ .findByText(mbUrl, { timeout: TIMEOUT_MS })
+ .should("be.visible");
+ devToolbarPanel().findByText("✓").should("exist");
+
+ devToolbarTab("Manifest").click();
+ devToolbarPanel().findByText("Vite 6 Data App").should("exist");
+ // Regex: the allowed_hosts row joins the list into one text node.
+ devToolbarPanel()
+ .findByText(/https:\/\/allowed\.data-app\.test/)
+ .should("exist");
+ });
+
+ it("serves the report to shell agents, with cursor filtering", () => {
+ readDiagnosticsUntil(
+ DIAGNOSTICS_URL,
+ "a blocked-network entry and a healthy connection",
+ (report) =>
+ report.entries.some((entry) => entry.kind === "blocked-network") &&
+ report.connection?.reachable === true,
+ ).then((report) => {
+ expect(report.manifest?.errors).to.have.length(0);
+ expect(report.clients).to.be.gte(1);
+
+ // A reader that has consumed everything sees an empty page, not a replay.
+ cy.request(`${DIAGNOSTICS_URL}?startEventId=${report.nextEventId}`)
+ .its("body.entries")
+ .should("be.empty");
+ });
+ });
+
+ it("keeps the buffer across a page reload, with continuous event ids", () => {
+ readDiagnosticsUntil(
+ DIAGNOSTICS_URL,
+ "the first page session's blocked entry",
+ (report) =>
+ report.entries.some((entry) => entry.kind === "blocked-network"),
+ ).then((before) => {
+ cy.reload();
+ cy.findByTestId("dev-app-content", { timeout: TIMEOUT_MS }).should(
+ "exist",
+ );
+
+ // A reload must not empty the buffer — the errors that prompted the
+ // reload are the ones a reader most needs. The server appends the new
+ // session's events under its own id sequence, so a reader that
+ // consumed up to N never skips or re-reads anything.
+ readDiagnosticsUntil(
+ DIAGNOSTICS_URL,
+ "the reloaded page's events appended after the first session's",
+ (report) => report.entries.length > before.entries.length,
+ ).then((after) => {
+ const beforeIds = before.entries.map((entry) => entry.eventId);
+ const afterIds = after.entries.map((entry) => entry.eventId);
+
+ expect(afterIds.slice(0, beforeIds.length)).to.deep.equal(beforeIds);
+ afterIds.forEach((id, index) => {
+ if (index > 0) {
+ expect(id).to.be.greaterThan(afterIds[index - 1]);
+ }
+ });
+
+ // Every session is in the buffer, tagged with the page load that
+ // reported it — that stamp is what the toolbar filters on.
+ const sessions = new Set(after.entries.map((e) => e.sessionId));
+ expect(sessions.size).to.be.gte(2);
+ });
+ });
+ });
+
+ it("shows only the current page's entries in the panel after a reload", () => {
+ openDevToolbar();
+ devToolbarTab("Blocked").click();
+ devToolbarPanel()
+ .findAllByText(/Blocked fetch to blocked\.data-app\.test/, {
+ timeout: TIMEOUT_MS,
+ })
+ .then(($before) => {
+ const beforeCount = $before.length;
+
+ cy.reload();
+ cy.findByTestId("dev-app-content", { timeout: TIMEOUT_MS }).should(
+ "exist",
+ );
+ openDevToolbar();
+ devToolbarTab("Blocked").click();
+
+ // The reloaded page re-fires the same blocked request. Without the
+ // per-session filter the panel would stack a copy per reload, so the
+ // count must not grow even though the server kept both sessions.
+ devToolbarPanel()
+ .findAllByText(/Blocked fetch to blocked\.data-app\.test/, {
+ timeout: TIMEOUT_MS,
+ })
+ .should("have.length.at.most", beforeCount);
+ });
+ });
+
+ it("empties the open toolbar when an agent clears over the endpoint", () => {
+ openDevToolbar();
+ devToolbarTab("Blocked").click();
+ devToolbarPanel()
+ .findAllByText(/Blocked fetch to blocked\.data-app\.test/, {
+ timeout: TIMEOUT_MS,
+ })
+ .first()
+ .should("be.visible");
+
+ cy.request("DELETE", DIAGNOSTICS_URL);
+
+ // No reload: the DELETE broadcast nudges this page's toolbar to re-read.
+ devToolbarPanel()
+ .findAllByText(/Blocked fetch to blocked\.data-app\.test/, {
+ timeout: TIMEOUT_MS,
+ })
+ .should("not.exist");
+ devToolbarPanel().findByText("Nothing blocked.").should("be.visible");
+ });
+ });
+
+ describe("live manifest validation", () => {
+ let originalManifest: string;
+
+ before(() => {
+ cy.readFile(DATA_APP_DEV_MANIFEST_PATH).then((content: string) => {
+ // Strip this suite's own appended host first: an interrupted earlier
+ // run can leave it behind, and capturing that as "original" would
+ // restore the pollution forever after.
+ originalManifest = content
+ .split("\n")
+ .filter((line) => !line.includes("https://added.example"))
+ .join("\n");
+
+ cy.writeFile(DATA_APP_DEV_MANIFEST_PATH, originalManifest);
+ });
+ });
+
+ afterEach(() => {
+ cy.writeFile(DATA_APP_DEV_MANIFEST_PATH, originalManifest);
+ });
+
+ it("pushes re-validation to the open toolbar when data_app.yaml changes", () => {
+ visitDataAppDevApp(CLIENT_HOST);
+ openDevToolbar();
+ devToolbarTab("Manifest").click();
+ devToolbarPanel()
+ .findByText("Vite 6 Data App", { timeout: TIMEOUT_MS })
+ .should("exist");
+ devToolbarPanel()
+ .findByText(/allowed_hosts changed since the dev server started/)
+ .should("not.exist");
+
+ // `allowed_hosts` is the manifest's last key, so appending stays valid YAML.
+ cy.writeFile(
+ DATA_APP_DEV_MANIFEST_PATH,
+ `${originalManifest} - https://added.example\n`,
+ );
+
+ // No reload and no dev-server restart: the watcher re-validates and the
+ // changed-event nudge makes the open toolbar re-read — the drifted
+ // allowlist shows up along with the restart-required notice.
+ devToolbarPanel()
+ .findByText(/allowed_hosts changed since the dev server started/, {
+ timeout: TIMEOUT_MS,
+ })
+ .should("be.visible");
+ devToolbarPanel()
+ .findByText(/https:\/\/added\.example/)
+ .should("exist");
+
+ cy.writeFile(DATA_APP_DEV_MANIFEST_PATH, originalManifest);
+ cy.request("DELETE", DIAGNOSTICS_URL);
+
+ devToolbarPanel()
+ .findByText(/allowed_hosts changed since the dev server started/, {
+ timeout: TIMEOUT_MS,
+ })
+ .should("not.exist");
+ });
+ });
+
+ describe("soft reload", () => {
+ let originalAppSrc: string;
+
+ before(() => {
+ cy.readFile(DATA_APP_DEV_APP_SRC_PATH).then((content: string) => {
+ // Strip this suite's own marker first — see the manifest suite's note
+ // on healing an interrupted earlier run.
+ originalAppSrc = content.replaceAll(" — rebuilt", "");
+
+ cy.writeFile(DATA_APP_DEV_APP_SRC_PATH, originalAppSrc);
+ });
+ });
+
+ afterEach(() => {
+ cy.writeFile(DATA_APP_DEV_APP_SRC_PATH, originalAppSrc);
+ });
+
+ it("rebuilds and re-renders a source change in place, without a page reload", () => {
+ visitDataAppDevApp(CLIENT_HOST);
+
+ cy.window().then((win) => {
+ // A full navigation would wipe this; the soft reload must not.
+ Object.assign(win, { __softReloadCanary: true });
+ });
+
+ cy.request(DIAGNOSTICS_URL)
+ .its("body.lastRebuildAt")
+ .then((rebuiltAtBefore: number | null) => {
+ cy.writeFile(
+ DATA_APP_DEV_APP_SRC_PATH,
+ originalAppSrc.replace(
+ "Vite 6 data app",
+ "Vite 6 data app — rebuilt",
+ ),
+ );
+
+ // The dev plugin rebuilds the bundle in memory and the entry
+ // re-evaluates it in the live sandbox — the change shows up in place.
+ cy.findByTestId("dev-app-content")
+ .findByText("Vite 6 data app — rebuilt", { timeout: TIMEOUT_MS })
+ .should("be.visible");
+
+ cy.window().its("__softReloadCanary").should("equal", true);
+
+ // The feed timestamps the rebuild, so a shell agent can tell the
+ // running bundle changed.
+ readDiagnosticsUntil(
+ DIAGNOSTICS_URL,
+ "a fresh lastRebuildAt",
+ (report) =>
+ report.lastRebuildAt != null &&
+ report.lastRebuildAt !== rebuiltAtBefore,
+ );
+ });
+ });
+ });
+});
diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json
index 8daace16e40..a9bcb0b0a26 100644
--- a/e2e/tsconfig.json
+++ b/e2e/tsconfig.json
@@ -2,7 +2,9 @@
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "build",
+ "noEmit": true,
"baseUrl": "./",
+ "rootDir": "..",
"types": [
"cypress",
"@testing-library/cypress",
@@ -18,6 +20,9 @@
"@metabase/embedding-sdk-react/data-app": [
"../enterprise/frontend/src/embedding-sdk-package/data-app.ts"
],
+ "@metabase/embedding-sdk-react/data-app-dev": [
+ "../enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts"
+ ],
"*": ["../frontend/src/*"]
}
},
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/private/SdkThemeProvider/SdkThemeProvider.tsx b/enterprise/frontend/src/embedding-sdk-package/components/private/SdkThemeProvider/SdkThemeProvider.tsx
deleted file mode 100644
index c31d9f21fb2..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/components/private/SdkThemeProvider/SdkThemeProvider.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { PropsWithChildren } from "react";
-
-import { getWindow } from "embedding-sdk-shared/lib/get-window";
-import type { MetabaseEmbeddingTheme } from "metabase/embedding-sdk/theme";
-
-/**
- * The bundle's theme provider, reached through the bundle global rather than
- * imported: the package and the bundle are separate builds, so a static import
- * would inline a second copy along with its React context.
- *
- * Renders children untouched until the bundle has loaded, so a consumer never
- * waits on the theme to see its own markup.
- */
-export const SdkThemeProvider = ({
- theme,
- children,
-}: PropsWithChildren<{ theme?: MetabaseEmbeddingTheme }>) => {
- const BundleSdkThemeProvider =
- getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.SdkThemeProvider;
-
- if (!BundleSdkThemeProvider) {
- return <>{children}</>;
- }
-
- return (
- <BundleSdkThemeProvider theme={theme}>{children}</BundleSdkThemeProvider>
- );
-};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
index 42b31d25684..034bff4231a 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
@@ -19,6 +19,7 @@ import {
allowedHosts,
appSlug,
bundleUrl,
+ diagnosticsChangedEvent,
rebuiltEvent,
sdkVersion,
} from "virtual:metabase-data-app-dev-config";
@@ -28,14 +29,6 @@ import { createRoot } from "react-dom/client";
// dev preview matches production. style-loader injects it at runtime.
import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";
-// Built by rspack into the SDK dist (`rspack.embedding-sdk-package.config.js`).
-// React, the SDK subpaths and the virtual config stay EXTERNAL so the consumer's
-// Vite resolves them: the preview has to run against the same React and SDK
-// instances the app bundle is endowed with, not copies of them.
-
-// Either may be missing from `.env.local`. Rendering anyway is deliberate: the
-// requests then fail, and the diagnostics feed names the env var to fill — which
-// beats a blank page with the reason only in the terminal.
const authConfig = {
metabaseInstanceUrl: import.meta.env.DATA_APP_MB_URL ?? "",
apiKey: import.meta.env.DATA_APP_MB_API_KEY ?? "",
@@ -52,10 +45,20 @@ sdkCallCapture.install(authConfig.metabaseInstanceUrl);
const hot = import.meta.hot;
+const subscribeToDiagnostics = hot
+ ? (onChange: () => void) => {
+ hot.on(diagnosticsChangedEvent, onChange);
+
+ return () => hot.off(diagnosticsChangedEvent, onChange);
+ }
+ : undefined;
+
const toolbarRoot = document.createElement("div");
document.body.appendChild(toolbarRoot);
-createRoot(toolbarRoot).render(<DevToolbar />);
+createRoot(toolbarRoot).render(
+ <DevToolbar subscribe={subscribeToDiagnostics} />,
+);
const root = document.getElementById("root");
@@ -109,11 +112,9 @@ loadAndRender().catch((error) => {
console.error(error);
});
-if (hot) {
- // Mirror the toolbar's data to the dev server, which re-serves it as JSON for
- // tools that have a shell but no browser (see `diagnostics-channel.ts`).
- installDiagnosticsReporter(hot);
+installDiagnosticsReporter();
+if (hot) {
hot.on(rebuiltEvent, () => {
loadAndRender().catch((error) => {
console.error(error);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts
index c58fcddc370..a2385574842 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts
@@ -1,9 +1,17 @@
// Browser subpath `@metabase/embedding-sdk-react/data-app-dev` with dev app client exports.
// The Node Vite config preset lives at `/data-app-dev/config` (data-app-dev.config.ts).
export { DataAppDevProvider } from "./data-app-dev/components/DataAppDevProvider/DataAppDevProvider";
-export { DevToolbar } from "./data-app-dev/components/DevToolbar/DevToolbar";
+export {
+ DevToolbar,
+ type DevToolbarProps,
+} from "./data-app-dev/components/DevToolbar/DevToolbar";
export { devDiagnostics } from "./data-app-dev/components/DevToolbar/diagnostics";
+export { DEV_SESSION_ID } from "./data-app-dev/lib/dev-session";
export { instanceConnectionCheck } from "./data-app-dev/lib/instance-connection-check";
export { installDiagnosticsReporter } from "./data-app-dev/lib/diagnostics-reporter";
export { sdkCallCapture } from "./data-app-dev/lib/sdk-call-capture";
+export type {
+ DataAppDiagnosticPayload,
+ DataAppDiagnosticsReport,
+} from "./data-app-dev/types/diagnostics-channel";
export { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx
index 2a371240446..5e74acdd1b6 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx
@@ -1,8 +1,8 @@
import { once } from "underscore";
import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-provider";
-import { SdkThemeProvider } from "embedding-sdk-package/components/private/SdkThemeProvider/SdkThemeProvider";
import { MetabaseProvider } from "embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider";
+import { SdkThemeProviderWithStore } from "embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore";
import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
const registerDataAppDevContext = once((appSlug: string) => {
@@ -24,7 +24,9 @@ export const DataAppDevProvider = ({
return (
<MetabaseProvider {...props}>
- <SdkThemeProvider theme={props.theme}>{children}</SdkThemeProvider>
+ <SdkThemeProviderWithStore theme={props.theme}>
+ {children}
+ </SdkThemeProviderWithStore>
</MetabaseProvider>
);
};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ConnectionTab/ConnectionTab.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ConnectionTab/ConnectionTab.tsx
new file mode 100644
index 00000000000..5c62f3310ee
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ConnectionTab/ConnectionTab.tsx
@@ -0,0 +1,28 @@
+/* eslint-disable i18next/no-literal-string */
+/* eslint-disable metabase/no-literal-metabase-strings -- dev-only toolbar for data-app authors */
+import type { InstanceConnectionStatus } from "../../../types/diagnostics-channel";
+import S from "../DevToolbar.module.css";
+import { StatusRow } from "../StatusRow/StatusRow";
+
+type Props = {
+ connection: InstanceConnectionStatus | null;
+};
+
+export const ConnectionTab = ({ connection }: Props) => {
+ if (!connection) {
+ return <div className={S.Empty}>Connection check has not run yet.</div>;
+ }
+
+ return (
+ <div className={S.StatusBody}>
+ <StatusRow label="Metabase URL">{connection.metabaseUrl}</StatusRow>
+ <StatusRow label="Reachable">
+ {connection.reachable ? "✓" : "✗"}
+ </StatusRow>
+ <StatusRow label="SDK version">
+ {connection.sdkVersion ?? "unknown"}
+ </StatusRow>
+ {connection.error && <div className={S.Problem}>{connection.error}</div>}
+ </div>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css
index 6c6dc5ff5a1..6956443907e 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css
@@ -1,7 +1,21 @@
-/* The dev toolbar renders in the host page, potentially before the SDK bundle
- and its theme variables load, so every color falls back to a literal. */
+/* The toolbar is dev-only chrome, not part of the app being built: it keeps its
+ own palette instead of the instance theme, so it looks the same whatever the
+ app is themed as, and renders identically before the SDK bundle has loaded. */
.DevToolbar {
+ --toolbar-brand: #509ee3;
+ --toolbar-error: #e35050;
+ --toolbar-border: #eeecec;
+ --toolbar-surface: #fff;
+ --toolbar-surface-muted: #f9fbfc;
+ --toolbar-surface-error: hsl(0deg 76% 97%);
+ --toolbar-surface-warning: hsl(45deg 100% 96%);
+ --toolbar-text: #4c5773;
+ --toolbar-text-muted: #696e7b;
+ --toolbar-text-faint: #949aab;
+ --toolbar-text-on-brand: #fff;
+ --toolbar-shadow: rgb(0 0 0 / 13%);
+
position: fixed;
right: 16px;
bottom: 16px;
@@ -22,37 +36,58 @@
border: none;
border-radius: 8px;
cursor: pointer;
- color: #fff;
- background: var(--mb-color-brand, #509ee3);
- box-shadow: 0 2px 8px var(--mb-color-shadow, rgba(0, 0, 0, 0.13));
+ color: var(--toolbar-text-on-brand);
+ background: var(--toolbar-brand);
+ box-shadow: 0 2px 8px var(--toolbar-shadow);
font-weight: 700;
}
.ToggleHasErrors {
- background: var(--mb-color-error, #e35050);
+ background: var(--toolbar-error);
}
+/* Chrome-devtools-style bottom dock: full-width, drag the top edge to resize.
+ Height is set inline from component state (see `startResize`). */
.Panel {
- width: 380px;
- max-height: 60vh;
- margin-bottom: 8px;
+ position: fixed;
+ inset: auto 0 0 0;
display: flex;
flex-direction: column;
- background: var(--mb-color-background-primary, #fff);
- color: var(--mb-color-text-primary, #4c5773);
- border: 1px solid var(--mb-color-border, #eeecec);
- border-radius: 8px;
overflow: hidden;
- box-shadow: 0 8px 24px var(--mb-color-shadow, rgba(0, 0, 0, 0.13));
+ background: var(--toolbar-surface);
+ color: var(--toolbar-text);
+ border-top: 1px solid var(--toolbar-border);
+ box-shadow: 0 8px 24px var(--toolbar-shadow);
}
-.Header {
+/* The drag handle along the panel's top edge. */
+.ResizeHandle {
+ flex: 0 0 auto;
+ height: 6px;
+ cursor: ns-resize;
+ background: var(--toolbar-border);
+}
+
+.ResizeHandle:hover {
+ background: var(--toolbar-brand);
+}
+
+.Header,
+.Tabs {
display: flex;
+ background: var(--toolbar-surface-muted);
+ border-bottom: 1px solid var(--toolbar-border);
+}
+
+.Header {
align-items: center;
gap: 8px;
padding: 10px 12px;
- background: var(--mb-color-background-secondary, #f9fbfc);
- border-bottom: 1px solid var(--mb-color-border, #eeecec);
+}
+
+.Tabs {
+ gap: 2px;
+ padding: 0 8px;
}
.Title {
@@ -63,41 +98,151 @@
flex: 1;
}
-.Action {
+.Action,
+.Tab {
border: none;
background: none;
- color: var(--mb-color-brand, #509ee3);
cursor: pointer;
- padding: 0;
font-size: 13px;
font-weight: 600;
}
+.Action {
+ padding: 0;
+ color: var(--toolbar-brand);
+}
+
+.Tab {
+ padding: 8px 10px;
+ color: var(--toolbar-text-muted);
+ border-bottom: 2px solid transparent;
+}
+
+.TabActive {
+ color: var(--toolbar-brand);
+ border-bottom-color: var(--toolbar-brand);
+}
+
+/* After `.TabActive` so a selected tab holding problems still reads as such —
+ the underline keeps showing which tab is open. */
+.TabHasAlerts {
+ color: var(--toolbar-error);
+}
+
.Body {
+ flex: 1;
+ min-height: 0;
overflow-y: auto;
padding: 4px;
}
+.Note {
+ margin: 8px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: var(--toolbar-surface-muted);
+ color: var(--toolbar-text-muted);
+ font-size: 12px;
+}
+
+.StatusBody {
+ padding: 8px;
+}
+
+.StatusRow {
+ display: flex;
+ gap: 12px;
+ padding: 6px 4px;
+ border-bottom: 1px solid var(--toolbar-border);
+}
+
+.StatusLabel {
+ flex: 0 0 140px;
+ font-weight: 600;
+ color: var(--toolbar-text-muted);
+}
+
+.Problem,
+.Warning {
+ margin: 8px 4px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ font-size: 12px;
+}
+
+.Problem {
+ background: var(--toolbar-surface-error);
+ color: var(--toolbar-error);
+}
+
+.Warning {
+ background: var(--toolbar-surface-warning);
+ color: var(--toolbar-text);
+}
+
+/* Collapsed by default, like a DevTools console entry: the headline is always
+ visible, the stack frames only when asked for. */
+.EntrySummary {
+ cursor: pointer;
+}
+
+.StatusValue,
+.EntryMessage,
+.EntryDetail {
+ word-break: break-word;
+ font-family: Monaco, ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+}
+
+.EntryMessage {
+ white-space: pre-wrap;
+ color: var(--toolbar-text);
+}
+
+.EntryDetail {
+ margin-top: 4px;
+ padding-left: 10px;
+ border-left: 2px solid var(--toolbar-border);
+ white-space: pre-wrap;
+ font-size: 11px;
+ color: var(--toolbar-text-muted);
+}
+
+.EntryFailed {
+ border-left: 3px solid var(--toolbar-error);
+}
+
+.Filter {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0 8px 4px;
+ color: var(--toolbar-text-muted);
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.EntryHint,
+.Empty {
+ color: var(--toolbar-text-muted);
+}
+
+.EntryHint {
+ margin-top: 4px;
+ font-size: 12px;
+}
+
.Empty {
padding: 12px;
- color: var(--mb-color-text-secondary, #696e7b);
}
.Entry {
padding: 8px 10px;
- border-bottom: 1px solid var(--mb-color-border, #eeecec);
+ border-bottom: 1px solid var(--toolbar-border);
}
.EntryTime {
- color: var(--mb-color-text-tertiary, #949aab);
+ color: var(--toolbar-text-faint);
font-size: 11px;
margin-bottom: 2px;
}
-
-.EntryMessage {
- white-space: pre-wrap;
- word-break: break-word;
- font-family: Monaco, ui-monospace, SFMono-Regular, Menlo, monospace;
- font-size: 12px;
- color: var(--mb-color-text-primary, #4c5773);
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx
index a0904e2daf9..d482ac0acd3 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx
@@ -1,74 +1,125 @@
/* eslint-disable i18next/no-literal-string */
import cx from "classnames";
-import { useState, useSyncExternalStore } from "react";
+import { useState } from "react";
-import { formatDevDiagnostic, isAlert } from "../../lib/diagnostics-payload";
+import { DATA_APP_DIAGNOSTICS_URL } from "../../constants/diagnostics-channel";
+import {
+ type SubscribeToChanges,
+ useDiagnosticsFeed,
+} from "../../lib/use-diagnostics-feed";
+import { ConnectionTab } from "./ConnectionTab/ConnectionTab";
import S from "./DevToolbar.module.css";
-import { devDiagnostics } from "./diagnostics";
+import { DiagnosticsToggle } from "./DiagnosticsToggle/DiagnosticsToggle";
+import { EntryList } from "./EntryList/EntryList";
+import { FeedBanner } from "./FeedBanner/FeedBanner";
+import { ManifestTab } from "./ManifestTab/ManifestTab";
+import { QueriesTab } from "./QueriesTab/QueriesTab";
+import { ResizeHandle } from "./ResizeHandle/ResizeHandle";
+import { TABS, type TabId, getTabAlertCounts, isBlocked } from "./entries";
+import { usePanelResize } from "./use-panel-resize";
-export function DevToolbar() {
- const captured = useSyncExternalStore(
- devDiagnostics.subscribe,
- devDiagnostics.getEntries,
- );
+export interface DevToolbarProps {
+ /** Notifies that the dev server's feed changed, so it need not be polled. */
+ subscribe?: SubscribeToChanges;
+}
+
+export function DevToolbar({ subscribe }: DevToolbarProps = {}) {
+ const feed = useDiagnosticsFeed(DATA_APP_DIAGNOSTICS_URL, subscribe);
const [open, setOpen] = useState(false);
+ const [tab, setTab] = useState<TabId>("errors");
+ const { height, startResize } = usePanelResize();
+
+ const { entries } = feed;
+ const count = entries.filter((entry) => entry.alert).length;
- const entries = captured.filter(isAlert);
- const count = entries.length;
+ const tabEntries = {
+ errors: entries.filter((entry) => entry.kind === "error"),
+ blocked: entries.filter(isBlocked),
+ queries: entries.filter((entry) => entry.kind === "sdk-call"),
+ };
+
+ const tabAlerts = getTabAlertCounts({
+ entries,
+ manifest: feed.manifest,
+ connection: feed.connection,
+ });
+
+ if (!open) {
+ return (
+ <div className={S.DevToolbar}>
+ <DiagnosticsToggle count={count} onOpen={() => setOpen(true)} />
+ </div>
+ );
+ }
return (
<div className={S.DevToolbar}>
- {open && (
- <div className={S.Panel}>
- <div className={S.Header}>
- <span className={S.Title}>Data app diagnostics</span>
- <span className={S.Spacer} />
- <button
- type="button"
- className={S.Action}
- onClick={devDiagnostics.clear}
- >
- Clear
- </button>
+ <div
+ className={S.Panel}
+ style={{ height }}
+ data-testid="dev-toolbar-panel"
+ >
+ <ResizeHandle onMouseDown={startResize} />
+
+ <div className={S.Header}>
+ <span className={S.Title}>Data app diagnostics</span>
+ <span className={S.Spacer} />
+ <button type="button" className={S.Action} onClick={feed.clear}>
+ Clear
+ </button>
+ <button
+ type="button"
+ className={S.Action}
+ onClick={() => setOpen(false)}
+ >
+ Close
+ </button>
+ </div>
+
+ <div className={S.Tabs} role="tablist">
+ {TABS.map(({ id, label }) => (
<button
+ key={id}
type="button"
- className={S.Action}
- onClick={() => setOpen(false)}
+ role="tab"
+ aria-selected={tab === id}
+ className={cx(S.Tab, {
+ [S.TabActive]: tab === id,
+ [S.TabHasAlerts]: tabAlerts[id] > 0,
+ })}
+ onClick={() => setTab(id)}
>
- Close
+ {tabAlerts[id] > 0 ? `${label} (${tabAlerts[id]})` : label}
</button>
- </div>
- <div className={S.Body}>
- {count === 0 ? (
- <div className={S.Empty}>No errors captured.</div>
- ) : (
- entries
- .slice()
- .reverse()
- .map((entry) => (
- <div key={entry.id} className={S.Entry}>
- <div className={S.EntryTime}>
- {new Date(entry.time).toLocaleTimeString()}
- </div>
- <div className={S.EntryMessage}>
- {formatDevDiagnostic(entry)}
- </div>
- </div>
- ))
- )}
- </div>
+ ))}
</div>
- )}
- <button
- type="button"
- className={cx(S.Toggle, { [S.ToggleHasErrors]: count > 0 })}
- onClick={() => setOpen((value) => !value)}
- title="Data app diagnostics"
- >
- ⚠ Diagnostics{count > 0 ? ` (${count})` : ""}
- </button>
+ <div className={S.Body}>
+ <FeedBanner
+ problem={feed.problem}
+ loaded={feed.loaded}
+ clients={feed.clients}
+ />
+ {tab === "errors" && (
+ <EntryList
+ entries={tabEntries.errors}
+ emptyMessage="No errors captured."
+ />
+ )}
+ {tab === "blocked" && (
+ <EntryList
+ entries={tabEntries.blocked}
+ emptyMessage="Nothing blocked."
+ />
+ )}
+ {tab === "queries" && <QueriesTab entries={tabEntries.queries} />}
+ {tab === "manifest" && <ManifestTab manifest={feed.manifest} />}
+ {tab === "connection" && (
+ <ConnectionTab connection={feed.connection} />
+ )}
+ </div>
+ </div>
</div>
);
}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx
index bfe9d127f27..da84fe973bf 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx
@@ -1,125 +1,454 @@
import userEvent from "@testing-library/user-event";
-import { act, render, screen } from "__support__/ui";
+import { fireEvent, render, screen, waitFor } from "__support__/ui";
+
+import { DEV_SESSION_ID } from "../../lib/dev-session";
+import type {
+ DataAppDiagnosticPayload,
+ DataAppDiagnosticsReport,
+} from "../../types/diagnostics-channel";
import { DevToolbar } from "./DevToolbar";
-import { devDiagnostics } from "./diagnostics";
-const recordError = (message: string) => {
- act(() => {
- console.error(message);
- });
-};
+// The toolbar is a pure reader of the dev server's feed: collection lives in the
+// store + reporter, outside this component. So the tests drive it by serving
+// feed responses, exactly as the dev server would.
-let originalConsoleError: typeof console.error;
+let served: DataAppDiagnosticsReport;
+let deleted: number;
-beforeAll(() => {
- originalConsoleError = console.error;
- console.error = () => {};
- devDiagnostics.install();
+const entry = (
+ overrides: Partial<DataAppDiagnosticPayload> = {},
+): DataAppDiagnosticPayload => ({
+ eventId: 1,
+ sessionId: DEV_SESSION_ID,
+ time: Date.parse("2026-01-01T10:00:00Z"),
+ kind: "error",
+ summary: "boom",
+ detail: null,
+ hint: null,
+ alert: true,
+ ...overrides,
});
-afterAll(() => {
- console.error = originalConsoleError;
-});
+const serve = (
+ entries: DataAppDiagnosticPayload[],
+ overrides: Partial<DataAppDiagnosticsReport> = {},
+) => {
+ served = {
+ entries,
+ connection: null,
+ manifest: null,
+ clients: 1,
+ lastReportAt: 1,
+ lastRebuildAt: 1,
+ nextEventId: (entries.at(-1)?.eventId ?? 0) + 1,
+ sessionId: "page-1",
+ ...overrides,
+ };
+};
beforeEach(() => {
- devDiagnostics.clear();
+ deleted = 0;
+ serve([]);
+
+ jest.spyOn(globalThis, "fetch").mockImplementation((_url, init) => {
+ if (init?.method === "DELETE") {
+ deleted += 1;
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+ return Promise.resolve(
+ new Response(JSON.stringify(served), { status: 200 }),
+ );
+ });
});
+afterEach(() => jest.restoreAllMocks());
+
const getToggle = () => screen.getByRole("button", { name: /Diagnostics/ });
-describe("DevToolbar", () => {
- it("renders a collapsed diagnostics toggle with no count when there are no errors", () => {
- render(<DevToolbar />);
+/** Render and wait for the first poll to land. */
+const setup = async () => {
+ render(<DevToolbar />);
+ await waitFor(() => expect(globalThis.fetch).toHaveBeenCalled());
+};
+/** Open the full panel — a single click, no intermediate popover. */
+const open = async () => {
+ await userEvent.click(getToggle());
+};
+
+describe("DevToolbar closed", () => {
+ it("badges the count of entries the server marked as alerts", async () => {
+ serve([
+ entry({ eventId: 1, summary: "boom", alert: true }),
+ entry({
+ eventId: 2,
+ kind: "sdk-call",
+ summary: "GET /api/card/1 → 200",
+ alert: false,
+ }),
+ ]);
+ await setup();
+
+ await waitFor(() =>
+ expect(getToggle()).toHaveTextContent("⚠ Diagnostics (1)"),
+ );
+ });
+
+ it("shows no count when there are no alerts", async () => {
+ await setup();
expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);
- expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
});
+});
- it("opens the panel showing the empty state, then closes via the toggle", async () => {
- render(<DevToolbar />);
+describe("DevToolbar open", () => {
+ it("opens the full panel with tabs on a single click", async () => {
+ await setup();
+ await open();
- await userEvent.click(getToggle());
- expect(screen.getByText("Data app diagnostics")).toBeInTheDocument();
+ // No intermediate popover: the tabs are there immediately, and the toggle
+ // button is replaced by the panel.
+ expect(screen.getByRole("tab", { name: /^Errors/ })).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Diagnostics/ }),
+ ).not.toBeInTheDocument();
expect(screen.getByText("No errors captured.")).toBeInTheDocument();
+ });
+
+ it("counts the problems on each tab, so the toggle's badge points somewhere", async () => {
+ serve(
+ [
+ entry({ eventId: 1, kind: "blocked-network", summary: "Blocked x" }),
+ entry({
+ eventId: 2,
+ kind: "sdk-call",
+ summary: "POST /api/dataset → 400",
+ alert: true,
+ }),
+ entry({
+ eventId: 3,
+ kind: "sdk-call",
+ summary: "GET /api/card/1 → 200",
+ alert: false,
+ }),
+ ],
+ {
+ manifest: {
+ name: null,
+ bundlePath: "dist/index.js",
+ bundlePathExists: true,
+ allowedHosts: [],
+ errors: ['"name" is required.'],
+ warnings: ["a warning is not a problem"],
+ restartRequired: false,
+ },
+ connection: {
+ checkedAt: 1,
+ metabaseUrl: "http://localhost:3000",
+ reachable: false,
+ sdkVersion: null,
+ error: "Could not reach http://localhost:3000.",
+ },
+ },
+ );
+ await setup();
+ await open();
- await userEvent.click(getToggle());
- expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
+ // Every kind of problem is counted where it lives — entries, the manifest,
+ // and the connection check alike.
+ expect(screen.getByRole("tab", { name: "Blocked (1)" })).toBeVisible();
+ expect(screen.getByRole("tab", { name: "Queries (1)" })).toBeVisible();
+ expect(screen.getByRole("tab", { name: "Manifest (1)" })).toBeVisible();
+ expect(screen.getByRole("tab", { name: "Connection (1)" })).toBeVisible();
+
+ // A clean tab stays bare: no "(0)" to read past.
+ expect(screen.getByRole("tab", { name: "Errors" })).toBeVisible();
});
- it("shows the captured count and lists entries newest first", async () => {
- render(<DevToolbar />);
+ it("renders the server's summary, collapsed detail and hint", async () => {
+ serve([
+ entry({
+ eventId: 1,
+ summary: "TypeError: nope",
+ detail: " at App (src/App.tsx:1:1)",
+ hint: "Fix the thing.",
+ }),
+ ]);
+ await setup();
+ await open();
+
+ expect(screen.getByText("TypeError: nope")).toBeInTheDocument();
+ expect(screen.getByRole("group")).not.toHaveAttribute("open");
+ expect(
+ screen.getByText(/at App \(src\/App\.tsx:1:1\)/),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Fix the thing.")).toBeInTheDocument();
+ });
+
+ it("splits entries across their tabs by kind", async () => {
+ serve([
+ entry({ eventId: 1, kind: "error", summary: "plain error" }),
+ entry({
+ eventId: 2,
+ kind: "blocked-network",
+ summary: "Blocked fetch to evil.test",
+ }),
+ entry({
+ eventId: 3,
+ kind: "csp-violation",
+ summary: "Content Security Policy (connect-src) blocked https://x",
+ hint: "Add that URL's origin to allowed_hosts in data_app.yaml.",
+ }),
+ ]);
+ await setup();
+ await open();
+
+ expect(screen.getByText("plain error")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Blocked fetch to evil.test"),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("tab", { name: /^Blocked/ }));
+
+ expect(screen.getByText("Blocked fetch to evil.test")).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "Add that URL's origin to allowed_hosts in data_app.yaml.",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("plain error")).not.toBeInTheDocument();
+ });
+
+ it("filters the Queries tab to failed calls only", async () => {
+ serve([
+ entry({
+ eventId: 1,
+ kind: "sdk-call",
+ summary: "POST /api/card/1/query → 202 (45ms)",
+ alert: false,
+ }),
+ entry({
+ eventId: 2,
+ kind: "sdk-call",
+ summary: "POST /api/dataset → 400 (12ms)",
+ alert: true,
+ }),
+ ]);
+ await setup();
+ await open();
+ await userEvent.click(screen.getByRole("tab", { name: /^Queries/ }));
+
+ expect(screen.getByText(/api\/card\/1\/query/)).toBeInTheDocument();
+ expect(screen.getByText(/Dev runs with an API key/)).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("checkbox", { name: /Failed only/ }),
+ );
+
+ expect(screen.getByText(/api\/dataset/)).toBeInTheDocument();
+ expect(screen.queryByText(/api\/card\/1\/query/)).not.toBeInTheDocument();
+ });
- recordError("first error");
- recordError("second error");
+ it("renders the manifest status the feed carries", async () => {
+ serve([], {
+ manifest: {
+ name: "Demo",
+ bundlePath: "dist/index.js",
+ bundlePathExists: false,
+ allowedHosts: [],
+ errors: ["path is required"],
+ warnings: [],
+ restartRequired: true,
+ },
+ });
+ await setup();
+ await open();
+ await userEvent.click(screen.getByRole("tab", { name: /^Manifest/ }));
- expect(getToggle()).toHaveTextContent("⚠ Diagnostics (2)");
+ expect(screen.getByText("path is required")).toBeInTheDocument();
+ expect(screen.getByText(/allowed_hosts changed/)).toBeInTheDocument();
+ expect(screen.getByText(/file not found/)).toBeInTheDocument();
+ });
- await userEvent.click(getToggle());
+ it("renders the connection status the feed carries", async () => {
+ serve([], {
+ connection: {
+ checkedAt: 1,
+ metabaseUrl: "http://localhost:3000",
+ reachable: true,
+ sdkVersion: "0.64.0",
+ error: "Could not reach http://localhost:3000.",
+ },
+ });
+ await setup();
+ await open();
+ await userEvent.click(screen.getByRole("tab", { name: /^Connection/ }));
- const messages = screen.getAllByText(/error$/);
- expect(messages[0]).toHaveTextContent("second error");
- expect(messages[1]).toHaveTextContent("first error");
+ expect(screen.getByText("http://localhost:3000")).toBeInTheDocument();
+ expect(
+ screen.getByText("Could not reach http://localhost:3000."),
+ ).toBeInTheDocument();
});
- it("clears entries when Clear is clicked, leaving the panel open", async () => {
+ it("says so when the dev server is unreachable, rather than looking healthy", async () => {
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockRejectedValue(new Error("connection refused"));
+
render(<DevToolbar />);
- recordError("boom");
+ await open();
- await userEvent.click(getToggle());
+ expect(
+ await screen.findByText(/Can't reach the dev server/),
+ ).toBeInTheDocument();
+ });
+
+ it("says so when no preview tab is connected", async () => {
+ serve([], { clients: 0 });
+ await setup();
+ await open();
+
+ expect(screen.getByText(/No preview tab is connected/)).toBeInTheDocument();
+ });
+
+ it("clears through the endpoint so every reader is cleared", async () => {
+ serve([entry({ eventId: 1, summary: "boom" })]);
+ await setup();
+ await open();
+ expect(await screen.findByText("boom")).toBeInTheDocument();
+
+ serve([]);
await userEvent.click(screen.getByRole("button", { name: "Clear" }));
- expect(screen.getByText("No errors captured.")).toBeInTheDocument();
- expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);
+ await waitFor(() => expect(deleted).toBe(1));
+ expect(screen.queryByText("boom")).not.toBeInTheDocument();
});
- it("leaves successful requests off the badge and out of the panel", async () => {
- render(<DevToolbar />);
- act(() => {
- devDiagnostics.record({
- kind: "sdk-call",
- method: "GET",
- endpoint: "/api/card/1",
- status: 200,
- durationMs: 12,
- });
+ it("closes back to the toggle when Close is clicked", async () => {
+ await setup();
+ await open();
+ expect(screen.getByRole("tab", { name: /^Errors/ })).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Close" }));
+
+ expect(
+ screen.queryByRole("tab", { name: "Errors" }),
+ ).not.toBeInTheDocument();
+ expect(getToggle()).toBeInTheDocument();
+ });
+
+ it("resizes the panel by dragging its top edge", async () => {
+ await setup();
+ await open();
+
+ const handle = screen.getByRole("separator", {
+ name: /Resize diagnostics panel/,
});
+ const panel = screen.getByTestId("dev-toolbar-panel");
+ const before = parseInt(panel.style.height, 10);
- // Every request lands in the collector now. Counting them would warn about
- // a page that is working.
- expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);
+ // Drag the top edge up by 120px — the bottom-docked panel grows.
+ fireEvent.mouseDown(handle, { clientY: 400 });
+ fireEvent.mouseMove(window, { clientY: 280 });
+ fireEvent.mouseUp(window);
- await userEvent.click(getToggle());
- expect(screen.getByText("No errors captured.")).toBeInTheDocument();
+ expect(parseInt(panel.style.height, 10)).toBe(before + 120);
});
- it("still badges a request that failed", async () => {
- render(<DevToolbar />);
- act(() => {
- devDiagnostics.record({
- kind: "sdk-call",
- method: "POST",
- endpoint: "/api/dataset",
- status: 400,
- durationMs: 8,
- error: "Table does not exist",
- });
+ const resizeViewport = (innerHeight: number) => {
+ Object.defineProperty(window, "innerHeight", {
+ value: innerHeight,
+ configurable: true,
});
+ fireEvent(window, new Event("resize"));
+ };
+
+ it("follows the viewport until the author drags, then keeps their height", async () => {
+ const originalInnerHeight = window.innerHeight;
+
+ try {
+ await setup();
+ await open();
+
+ const panel = screen.getByTestId("dev-toolbar-panel");
- expect(getToggle()).toHaveTextContent("⚠ Diagnostics (1)");
+ resizeViewport(900);
+ expect(parseInt(panel.style.height, 10)).toBe(300);
- await userEvent.click(getToggle());
- expect(screen.getByText(/Table does not exist/)).toBeInTheDocument();
+ fireEvent.mouseDown(
+ screen.getByRole("separator", { name: /Resize diagnostics panel/ }),
+ { clientY: 600 },
+ );
+ fireEvent.mouseMove(window, { clientY: 400 });
+ fireEvent.mouseUp(window);
+ expect(parseInt(panel.style.height, 10)).toBe(500);
+
+ // A dragged height is kept across viewport changes, but never taller than
+ // the window — a shrunk window would otherwise leave the panel off-screen.
+ resizeViewport(1200);
+ expect(parseInt(panel.style.height, 10)).toBe(500);
+
+ // Shrunk below the kept height, it clamps to fit — the exact margin the
+ // hook leaves above the panel is its own business.
+ resizeViewport(300);
+ expect(parseInt(panel.style.height, 10)).toBeLessThan(300);
+ } finally {
+ Object.defineProperty(window, "innerHeight", {
+ value: originalInnerHeight,
+ configurable: true,
+ });
+ }
});
- it("closes the panel when Close is clicked", async () => {
- render(<DevToolbar />);
+ it("stops dragging when the panel unmounts mid-drag", async () => {
+ await setup();
+ await open();
- await userEvent.click(getToggle());
- expect(screen.getByText("Data app diagnostics")).toBeInTheDocument();
+ fireEvent.mouseDown(
+ screen.getByRole("separator", { name: /Resize diagnostics panel/ }),
+ { clientY: 400 },
+ );
+ // Close unmounts the panel; a drag whose listeners outlived it would keep
+ // setting state on an unmounted component with every mouse move.
await userEvent.click(screen.getByRole("button", { name: "Close" }));
- expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
+ fireEvent.mouseMove(window, { clientY: 200 });
+
+ expect(screen.queryByTestId("dev-toolbar-panel")).not.toBeInTheDocument();
+ });
+});
+
+// Guard the contract this refactor rests on: the panel must not reach into the
+// in-page store, or it would drift from what an external reader sees. The read
+// mechanics (mirror the report, drop stale/cleared reads) live in
+// `lib/use-diagnostics-feed.unit.spec.ts`.
+describe("DevToolbar data source", () => {
+ it("reads the diagnostics endpoint", async () => {
+ await setup();
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ expect.stringContaining("/__data-app/diagnostics"),
+ );
+ });
+
+ it("reads on a nudge rather than on a timer when the dev server can push", async () => {
+ const listeners = new Set<() => void>();
+ const subscribe = (onChange: () => void) => {
+ listeners.add(onChange);
+
+ return () => listeners.delete(onChange);
+ };
+
+ render(<DevToolbar subscribe={subscribe} />);
+ await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
+
+ // Left alone it must stay quiet: there is no timer, so a second read without
+ // a nudge would mean it is polling when it should only be pushed.
+ await new Promise((resolve) => setTimeout(resolve, 1200));
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+
+ listeners.forEach((listener) => listener());
+ await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(2));
});
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx
new file mode 100644
index 00000000000..68deea0716c
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx
@@ -0,0 +1,20 @@
+/* eslint-disable i18next/no-literal-string */
+import cx from "classnames";
+
+import S from "../DevToolbar.module.css";
+
+interface Props {
+ count: number;
+ onOpen: () => void;
+}
+
+export const DiagnosticsToggle = ({ count, onOpen }: Props) => (
+ <button
+ type="button"
+ className={cx(S.Toggle, { [S.ToggleHasErrors]: count > 0 })}
+ onClick={onOpen}
+ title="Data app diagnostics"
+ >
+ ⚠ Diagnostics{count > 0 ? ` (${count})` : ""}
+ </button>
+);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/EntryList/EntryList.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/EntryList/EntryList.tsx
new file mode 100644
index 00000000000..3f885572aaa
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/EntryList/EntryList.tsx
@@ -0,0 +1,46 @@
+import cx from "classnames";
+
+import type { DataAppDiagnosticPayload } from "../../../types/diagnostics-channel";
+import S from "../DevToolbar.module.css";
+import { isFailedCall } from "../entries";
+
+interface Props {
+ entries: readonly DataAppDiagnosticPayload[];
+ emptyMessage: string;
+}
+
+export const EntryList = ({ entries, emptyMessage }: Props) => {
+ if (entries.length === 0) {
+ return <div className={S.Empty}>{emptyMessage}</div>;
+ }
+
+ const displayedEntries = entries.slice().reverse();
+
+ return (
+ <>
+ {displayedEntries.map((entry) => (
+ <div
+ key={entry.eventId}
+ className={cx(S.Entry, { [S.EntryFailed]: isFailedCall(entry) })}
+ >
+ <div className={S.EntryTime}>
+ {new Date(entry.time).toLocaleTimeString()}
+ </div>
+
+ {entry.detail ? (
+ <details>
+ <summary className={cx(S.EntryMessage, S.EntrySummary)}>
+ {entry.summary}
+ </summary>
+ <div className={S.EntryDetail}>{entry.detail}</div>
+ </details>
+ ) : (
+ <div className={S.EntryMessage}>{entry.summary}</div>
+ )}
+
+ {entry.hint && <div className={S.EntryHint}>{entry.hint}</div>}
+ </div>
+ ))}
+ </>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/FeedBanner/FeedBanner.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/FeedBanner/FeedBanner.tsx
new file mode 100644
index 00000000000..5334b5809bf
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/FeedBanner/FeedBanner.tsx
@@ -0,0 +1,39 @@
+/* eslint-disable i18next/no-literal-string */
+import type { DiagnosticsFeedProblem } from "../../../lib/use-diagnostics-feed";
+import S from "../DevToolbar.module.css";
+
+interface Props {
+ problem: DiagnosticsFeedProblem | null;
+ loaded: boolean;
+ clients: number;
+}
+
+export const FeedBanner = ({ problem, loaded, clients }: Props) => {
+ if (problem?.kind === "unreachable") {
+ return (
+ <div className={S.Problem}>
+ Can&apos;t reach the dev server, so this is not up to date. Is `npm run
+ dev` still running?
+ </div>
+ );
+ }
+
+ if (problem?.kind === "http") {
+ return (
+ <div className={S.Problem}>
+ The dev server answered {problem.status} for the diagnostics feed, so
+ this is not up to date.
+ </div>
+ );
+ }
+
+ if (loaded && clients === 0) {
+ return (
+ <div className={S.Note}>
+ No preview tab is connected, so nothing has been captured yet.
+ </div>
+ );
+ }
+
+ return null;
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ManifestTab/ManifestTab.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ManifestTab/ManifestTab.tsx
new file mode 100644
index 00000000000..edf29c89c1d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ManifestTab/ManifestTab.tsx
@@ -0,0 +1,54 @@
+/* eslint-disable i18next/no-literal-string */
+import type { DataAppManifestStatus } from "../../../types/manifest-status";
+import S from "../DevToolbar.module.css";
+import { StatusRow } from "../StatusRow/StatusRow";
+
+type Props = {
+ manifest: DataAppManifestStatus | null;
+};
+
+export const ManifestTab = ({ manifest }: Props) => {
+ if (!manifest) {
+ return <div className={S.Empty}>Manifest has not been validated yet.</div>;
+ }
+
+ return (
+ <div className={S.StatusBody}>
+ {manifest.restartRequired && (
+ <div className={S.Problem}>
+ allowed_hosts changed since the dev server started — restart `npm run
+ dev` to apply it to the sandbox and CSP.
+ </div>
+ )}
+
+ {manifest.errors.map((error) => (
+ <div key={error} className={S.Problem}>
+ {error}
+ </div>
+ ))}
+
+ {manifest.warnings.map((warning) => (
+ <div key={warning} className={S.Warning}>
+ {warning}
+ </div>
+ ))}
+
+ {manifest.errors.length === 0 && manifest.warnings.length === 0 && (
+ <div className={S.Empty}>data_app.yaml is valid.</div>
+ )}
+
+ <StatusRow label="name">{manifest.name ?? "missing"}</StatusRow>
+ <StatusRow label="path">
+ {manifest.bundlePath ?? "missing"}
+ {manifest.bundlePath != null &&
+ !manifest.bundlePathExists &&
+ " (file not found)"}
+ </StatusRow>
+ <StatusRow label="allowed_hosts">
+ {manifest.allowedHosts.length > 0
+ ? manifest.allowedHosts.join(", ")
+ : "none (network egress is blocked)"}
+ </StatusRow>
+ </div>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/QueriesTab/QueriesTab.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/QueriesTab/QueriesTab.tsx
new file mode 100644
index 00000000000..5bc9d2c4146
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/QueriesTab/QueriesTab.tsx
@@ -0,0 +1,41 @@
+/* eslint-disable i18next/no-literal-string */
+/* eslint-disable metabase/no-literal-metabase-strings -- dev-only toolbar for data-app authors, not whitelabel-able product UI */
+import { useState } from "react";
+
+import type { DataAppDiagnosticPayload } from "../../../types/diagnostics-channel";
+import S from "../DevToolbar.module.css";
+import { EntryList } from "../EntryList/EntryList";
+import { isFailedCall } from "../entries";
+
+type Props = {
+ entries: readonly DataAppDiagnosticPayload[];
+};
+
+export const QueriesTab = ({ entries }: Props) => {
+ const [failedOnly, setFailedOnly] = useState(false);
+ const failedCount = entries.filter(isFailedCall).length;
+ const shown = failedOnly ? entries.filter(isFailedCall) : entries;
+
+ return (
+ <>
+ <div className={S.Note}>
+ Dev runs with an API key; in production the app runs as the viewing
+ user, whose data permissions may differ.
+ </div>
+ <label className={S.Filter}>
+ <input
+ type="checkbox"
+ checked={failedOnly}
+ onChange={(event) => setFailedOnly(event.target.checked)}
+ />
+ Failed only{failedCount > 0 ? ` (${failedCount})` : ""}
+ </label>
+ <EntryList
+ entries={shown}
+ emptyMessage={
+ failedOnly ? "No failed calls." : "No Metabase calls captured."
+ }
+ />
+ </>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ResizeHandle/ResizeHandle.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ResizeHandle/ResizeHandle.tsx
new file mode 100644
index 00000000000..eb24ef76a8b
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/ResizeHandle/ResizeHandle.tsx
@@ -0,0 +1,17 @@
+import type { MouseEvent as ReactMouseEvent } from "react";
+
+import S from "../DevToolbar.module.css";
+
+type Props = {
+ onMouseDown: (event: ReactMouseEvent) => void;
+};
+
+export const ResizeHandle = ({ onMouseDown }: Props) => (
+ <div
+ className={S.ResizeHandle}
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label="Resize diagnostics panel"
+ onMouseDown={onMouseDown}
+ />
+);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/StatusRow/StatusRow.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/StatusRow/StatusRow.tsx
new file mode 100644
index 00000000000..6f969f7f58f
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/StatusRow/StatusRow.tsx
@@ -0,0 +1,15 @@
+import type { ReactNode } from "react";
+
+import S from "../DevToolbar.module.css";
+
+type Props = {
+ label: string;
+ children: ReactNode;
+};
+
+export const StatusRow = ({ label, children }: Props) => (
+ <div className={S.StatusRow}>
+ <span className={S.StatusLabel}>{label}</span>
+ <span className={S.StatusValue}>{children}</span>
+ </div>
+);
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/entries.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/entries.ts
new file mode 100644
index 00000000000..21c21b6579c
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/entries.ts
@@ -0,0 +1,46 @@
+import type {
+ DataAppDiagnosticPayload,
+ InstanceConnectionStatus,
+} from "../../types/diagnostics-channel";
+import type { DataAppManifestStatus } from "../../types/manifest-status";
+
+export type TabId =
+ | "errors"
+ | "blocked"
+ | "queries"
+ | "manifest"
+ | "connection";
+
+export const TABS: { id: TabId; label: string }[] = [
+ { id: "errors", label: "Errors" },
+ { id: "blocked", label: "Blocked" },
+ { id: "queries", label: "Queries" },
+ { id: "manifest", label: "Manifest" },
+ { id: "connection", label: "Connection" },
+];
+
+const BLOCKED_KINDS = ["blocked-api", "blocked-network", "csp-violation"];
+
+export const isBlocked = (entry: DataAppDiagnosticPayload): boolean =>
+ BLOCKED_KINDS.includes(entry.kind);
+
+export const isFailedCall = (entry: DataAppDiagnosticPayload): boolean =>
+ entry.kind === "sdk-call" && entry.alert;
+
+export const getTabAlertCounts = ({
+ entries,
+ manifest,
+ connection,
+}: {
+ entries: DataAppDiagnosticPayload[];
+ manifest: DataAppManifestStatus | null;
+ connection: InstanceConnectionStatus | null;
+}): Record<TabId, number> => ({
+ errors: entries.filter((entry) => entry.kind === "error" && entry.alert)
+ .length,
+ blocked: entries.filter((entry) => isBlocked(entry) && entry.alert).length,
+ queries: entries.filter(isFailedCall).length,
+ manifest: manifest?.errors.length ?? 0,
+ connection:
+ connection && (!connection.reachable || connection.error != null) ? 1 : 0,
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/use-panel-resize.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/use-panel-resize.ts
new file mode 100644
index 00000000000..7185632caf9
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/use-panel-resize.ts
@@ -0,0 +1,87 @@
+import {
+ type MouseEvent as ReactMouseEvent,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+const MIN_PANEL_HEIGHT = 140;
+
+/** Keeps a part of the app visible above a panel dragged to full height. */
+const VIEWPORT_MARGIN = 100;
+
+const SSR_VIEWPORT_HEIGHT = 960;
+
+const getViewportHeight = () =>
+ typeof window !== "undefined" ? window.innerHeight : SSR_VIEWPORT_HEIGHT;
+
+const clampToViewport = (height: number, viewportHeight: number) =>
+ Math.min(
+ Math.max(height, MIN_PANEL_HEIGHT),
+ // A viewport shorter than the minimum would invert the bounds.
+ Math.max(viewportHeight - VIEWPORT_MARGIN, MIN_PANEL_HEIGHT),
+ );
+
+/**
+ * The bottom-docked panel's height, and the drag handler for its top edge.
+ *
+ * Until the author drags, the height follows the viewport (a third of it);
+ * after that their height is kept, clamped so a shrinking window can't leave
+ * the panel taller than the screen.
+ *
+ * A drag binds its listeners to `window`, since the pointer routinely leaves
+ * the handle mid-drag. They are removed on mouse-up, on `blur` (a release the
+ * page never sees — alt-tab, or the cursor over an iframe), and on unmount.
+ */
+export const usePanelResize = () => {
+ const [draggedHeight, setDraggedHeight] = useState<number | null>(null);
+ const [viewportHeight, setViewportHeight] = useState(getViewportHeight);
+ const stopResizeRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ const onViewportResize = () => setViewportHeight(getViewportHeight());
+
+ window.addEventListener("resize", onViewportResize);
+
+ return () => {
+ window.removeEventListener("resize", onViewportResize);
+ stopResizeRef.current?.();
+ };
+ }, []);
+
+ const height = clampToViewport(
+ draggedHeight ?? Math.round(viewportHeight / 3),
+ viewportHeight,
+ );
+
+ const startResize = (event: ReactMouseEvent) => {
+ event.preventDefault();
+
+ const startY = event.clientY;
+ const startHeight = height;
+
+ const onMove = (moveEvent: MouseEvent) => {
+ setDraggedHeight(
+ clampToViewport(
+ startHeight + (startY - moveEvent.clientY),
+ getViewportHeight(),
+ ),
+ );
+ };
+
+ const stopResize = () => {
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", stopResize);
+ window.removeEventListener("blur", stopResize);
+ stopResizeRef.current = null;
+ };
+
+ stopResizeRef.current = stopResize;
+
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", stopResize);
+ window.addEventListener("blur", stopResize);
+ };
+
+ return { height, startResize };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.tsx
new file mode 100644
index 00000000000..b5ee1b49061
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.tsx
@@ -0,0 +1,29 @@
+import type { PropsWithChildren } from "react";
+
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+import type { MetabaseEmbeddingTheme } from "metabase/embedding-sdk/theme";
+
+export const SdkThemeProviderWithStore = ({
+ theme,
+ children,
+}: PropsWithChildren<{ theme?: MetabaseEmbeddingTheme }>) => {
+ const {
+ state: {
+ internalProps: { reduxStore },
+ },
+ } = useMetabaseProviderPropsStore();
+
+ const BundleSdkThemeProviderWithStore =
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.SdkThemeProviderWithStore;
+
+ if (!BundleSdkThemeProviderWithStore || !reduxStore) {
+ return <>{children}</>;
+ }
+
+ return (
+ <BundleSdkThemeProviderWithStore store={reduxStore} theme={theme}>
+ {children}
+ </BundleSdkThemeProviderWithStore>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.unit.spec.tsx
new file mode 100644
index 00000000000..1a2a8195167
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/SdkThemeProviderWithStore/SdkThemeProviderWithStore.unit.spec.tsx
@@ -0,0 +1,103 @@
+import { act, render, screen } from "@testing-library/react";
+import type { PropsWithChildren } from "react";
+
+import type { MetabaseEmbeddingSdkBundleExports } from "embedding-sdk-bundle/types/sdk-bundle";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import type { MetabaseEmbeddingTheme } from "metabase/embedding-sdk/theme";
+
+import { SdkThemeProviderWithStore } from "./SdkThemeProviderWithStore";
+
+const FakeThemedProvider = ({
+ children,
+ theme,
+}: PropsWithChildren<{ store: unknown; theme?: MetabaseEmbeddingTheme }>) => (
+ <div data-testid="themed">
+ <div data-testid="theme-preset">
+ {(typeof theme === "object" && "preset" in theme && theme.preset) ||
+ "none"}
+ </div>
+ {children}
+ </div>
+);
+
+const setBundleGlobal = (withThemeProvider: boolean) => {
+ // The spec only needs the one export the wrapper reaches for; the full
+ // bundle contract is irrelevant here.
+ window.METABASE_EMBEDDING_SDK_BUNDLE = (
+ withThemeProvider ? { SdkThemeProviderWithStore: FakeThemedProvider } : {}
+ ) as MetabaseEmbeddingSdkBundleExports;
+};
+
+const setReduxStore = (store: unknown) => {
+ ensureMetabaseProviderPropsStore().updateInternalProps({
+ // A stand-in — the wrapper only passes the store through.
+ reduxStore: store as never,
+ });
+};
+
+afterEach(() => {
+ delete window.METABASE_EMBEDDING_SDK_BUNDLE;
+ ensureMetabaseProviderPropsStore().cleanup();
+});
+
+describe("package SdkThemeProviderWithStore", () => {
+ it("renders children untouched before the bundle is on the page", () => {
+ render(
+ <SdkThemeProviderWithStore>
+ <div>content</div>
+ </SdkThemeProviderWithStore>,
+ );
+
+ expect(screen.getByText("content")).toBeInTheDocument();
+ expect(screen.queryByTestId("themed")).not.toBeInTheDocument();
+ });
+
+ it("renders children untouched while the redux store is not initialized, even with the bundle present", () => {
+ // Regression: the data-app dev preview crashed on its second mount —
+ // the bundle global from the previous page lifecycle was already there, so
+ // the wrapper mounted the bundle's theme provider (which reads the redux
+ // store) without any store to read.
+ setBundleGlobal(true);
+
+ render(
+ <SdkThemeProviderWithStore>
+ <div>content</div>
+ </SdkThemeProviderWithStore>,
+ );
+
+ expect(screen.getByText("content")).toBeInTheDocument();
+ expect(screen.queryByTestId("themed")).not.toBeInTheDocument();
+ });
+
+ it("renders children untouched when the instance's bundle predates the with-store export", () => {
+ setBundleGlobal(false);
+ setReduxStore({});
+
+ render(
+ <SdkThemeProviderWithStore>
+ <div>content</div>
+ </SdkThemeProviderWithStore>,
+ );
+
+ expect(screen.getByText("content")).toBeInTheDocument();
+ expect(screen.queryByTestId("themed")).not.toBeInTheDocument();
+ });
+
+ it("mounts the bundle's themed provider once both the bundle and the store exist", () => {
+ setBundleGlobal(true);
+
+ render(
+ <SdkThemeProviderWithStore theme={{ preset: "dark" }}>
+ <div>content</div>
+ </SdkThemeProviderWithStore>,
+ );
+
+ act(() => {
+ setReduxStore({});
+ });
+
+ expect(screen.getByTestId("themed")).toBeInTheDocument();
+ expect(screen.getByTestId("theme-preset")).toHaveTextContent("dark");
+ expect(screen.getByText("content")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/validate-manifest.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/validate-manifest.ts
index 0cc4084c6a4..0fc57d76cf2 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/validate-manifest.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/validate-manifest.ts
@@ -45,7 +45,6 @@ export function validateDataAppManifest(
initialAllowedHosts: string[],
): DataAppManifestStatus {
const status: DataAppManifestStatus = {
- checkedAt: Date.now(),
name: null,
bundlePath: null,
bundlePathExists: false,
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/diagnostics-channel.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/diagnostics-channel.ts
index 26ef3bfa8c9..b82426c12d1 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/diagnostics-channel.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/diagnostics-channel.ts
@@ -1,5 +1,3 @@
-export const DATA_APP_DIAGNOSTICS_EVENT = "data-app:diagnostics";
-
// Server → page nudge. Carries no data: readers re-read the endpoint, so the
// toolbar and a shell agent never diverge on where the truth came from.
export const DATA_APP_DIAGNOSTICS_CHANGED_EVENT =
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts
index 5fcf8b3da7b..5268c097fc8 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts
@@ -2,7 +2,8 @@
// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
import * as dataAppVirtualModules from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
-const { DATA_APP_DEV_ENTRY_VIRTUAL_ID } = dataAppVirtualModules;
+const { DATA_APP_DEV_ENTRY_VIRTUAL_ID, DATA_APP_VIRTUAL_URL_PREFIX } =
+ dataAppVirtualModules;
/** The preview shell. There is no index.html on disk; the dev server serves this. */
export const INDEX_HTML = `<!doctype html>
@@ -14,9 +15,7 @@ export const INDEX_HTML = `<!doctype html>
</head>
<body>
<div id="root"></div>
- <script type="module">
- import ${JSON.stringify(DATA_APP_DEV_ENTRY_VIRTUAL_ID)};
- </script>
+ <script type="module" src="${DATA_APP_VIRTUAL_URL_PREFIX}${DATA_APP_DEV_ENTRY_VIRTUAL_ID}"></script>
</body>
</html>
`;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/timings.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/timings.ts
index 311b865b5e6..ac5083bde9c 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/timings.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/timings.ts
@@ -1,2 +1,8 @@
/** How long the reporter batches page events before pushing them to the server. */
export const DIAGNOSTICS_FLUSH_MS = 100;
+
+/** How long the reporter waits before re-attempting a failed push. */
+export const DIAGNOSTICS_RETRY_MS = 1000;
+
+/** How often feed readers re-read regardless of nudges. */
+export const DIAGNOSTICS_POLL_MS = 2000;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.ts
index a706890e843..f2a12213de1 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.ts
@@ -1,7 +1,4 @@
-import {
- trimDiagnosticEntries,
- truncateDiagnosticText,
-} from "../lib/diagnostics-limits";
+import { trimDiagnosticEntries } from "../lib/diagnostics-limits";
import type {
DataAppDiagnosticEntry,
DataAppDiagnosticPayload,
@@ -28,7 +25,10 @@ export class DiagnosticsStore {
const connectionChanged = this.applyConnection(message?.connection);
const sessionChanged = this.applySession(message?.sessionId);
- const entriesAdded = this.appendEntries(message?.entries);
+ const entriesAdded = this.appendEntries(
+ message?.entries,
+ message?.sessionId,
+ );
// Returns whether a reader would now see something different.
return connectionChanged || sessionChanged || entriesAdded;
@@ -83,6 +83,7 @@ export class DiagnosticsStore {
private appendEntries(
entries: DataAppDiagnosticEntry[] | undefined,
+ sessionId: string | undefined,
): boolean {
if (!Array.isArray(entries) || entries.length === 0) {
return false;
@@ -90,7 +91,7 @@ export class DiagnosticsStore {
this.entries = trimDiagnosticEntries([
...this.entries,
- ...entries.map((entry) => this.toStoredEntry(entry)),
+ ...entries.map((entry) => this.toStoredEntry(entry, sessionId)),
]);
return true;
@@ -98,13 +99,16 @@ export class DiagnosticsStore {
private toStoredEntry(
entry: DataAppDiagnosticEntry,
+ sessionId: string | undefined,
): DataAppDiagnosticPayload {
+ // The page already truncated every field in `toPayload` before sending, so
+ // there is nothing left to bound here. The session stamp is what lets the
+ // toolbar show only the current page's entries while the buffer — which a
+ // shell reader pages with `?startEventId=` — keeps every session's.
return {
...entry,
- summary: truncateDiagnosticText(entry.summary ?? ""),
- detail:
- entry.detail == null ? null : truncateDiagnosticText(entry.detail),
eventId: this.nextEntryId++,
+ sessionId: sessionId ?? "",
};
}
}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.unit.spec.ts
index e5443392cc2..ca01445713a 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/diagnostics-store.unit.spec.ts
@@ -1,7 +1,6 @@
import {
DATA_APP_DIAGNOSTICS_CALL_LIMIT,
DATA_APP_DIAGNOSTICS_LIMIT,
- DATA_APP_DIAGNOSTIC_MAX_CHARS,
} from "../constants/diagnostics-channel";
import type { DataAppDiagnosticEntry } from "../types/diagnostics-channel";
@@ -56,6 +55,22 @@ describe("DiagnosticsStore", () => {
expect(second.eventId).toBe(2);
});
+ it("stamps each entry with the page load that reported it", () => {
+ const store = new DiagnosticsStore();
+
+ store.applyMessage(message([entry({ summary: "old page" })], "page-1"));
+ store.applyMessage(message([entry({ summary: "new page" })], "page-2"));
+
+ // The toolbar shows only its own page's entries; the buffer keeps both, so
+ // a shell reader paging with `?startEventId=` still sees the older ones.
+ expect(
+ store.getReport(0).entries.map((e) => [e.sessionId, e.summary]),
+ ).toEqual([
+ ["page-1", "old page"],
+ ["page-2", "new page"],
+ ]);
+ });
+
it("keeps the previous page's events across a reload", () => {
const store = new DiagnosticsStore();
@@ -134,17 +149,6 @@ describe("DiagnosticsStore", () => {
expect(store.getReport(0).entries).toHaveLength(1);
});
- it("re-truncates oversized text, since the socket is just another local process", () => {
- const store = new DiagnosticsStore();
- const long = "x".repeat(DATA_APP_DIAGNOSTIC_MAX_CHARS + 100);
-
- store.applyMessage(message([entry({ summary: long, detail: long })]));
-
- const [only] = store.getReport(0).entries;
- expect(only.summary).toContain("truncated");
- expect(only.detail).toContain("truncated");
- });
-
it("holds the last connection status reported, ignoring messages without one", () => {
const store = new DiagnosticsStore();
const connection = {
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/middlewares/diagnostics-endpoint-middleware.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/middlewares/diagnostics-endpoint-middleware.ts
index 4e2db975051..02596ebb4dd 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/middlewares/diagnostics-endpoint-middleware.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/middlewares/diagnostics-endpoint-middleware.ts
@@ -4,7 +4,10 @@ import {
DATA_APP_DIAGNOSTICS_URL,
START_EVENT_ID_PARAM,
} from "../../constants/diagnostics-channel";
-import type { DataAppDiagnosticsReport } from "../../types/diagnostics-channel";
+import type {
+ DataAppDiagnosticsMessage,
+ DataAppDiagnosticsReport,
+} from "../../types/diagnostics-channel";
import type { DataAppManifestStatus } from "../../types/manifest-status";
import type { DiagnosticsStore } from "../diagnostics-store";
@@ -13,11 +16,28 @@ export interface DiagnosticsEndpointMiddlewareOptions {
getManifest: () => DataAppManifestStatus | null;
getClients: () => number;
getLastRebuildAt: () => number | null;
+ notifyChanged: () => void;
}
+const readJsonBody = async (req: Connect.IncomingMessage): Promise<unknown> => {
+ // The stream yields Buffers, but typing the array as `Uint8Array` (their
+ // base class) sidesteps `Buffer.concat`'s over-narrow generic signature.
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of req) {
+ chunks.push(chunk);
+ }
+
+ try {
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ } catch {
+ return null;
+ }
+};
+
/**
- * Adds the `DATA_APP_DIAGNOSTICS_URL` endpoint to the dev server: `GET` returns
- * the feed as JSON (from `?startEventId=` onward), `DELETE` empties it.
+ * The `DATA_APP_DIAGNOSTICS_URL` endpoint: `GET` serves the feed (from
+ * `?startEventId=` onward), `POST` takes the page reporter's batches, `DELETE`
+ * empties the feed. Mutations broadcast a changed-event so readers re-read.
*/
export const getDiagnosticsEndpointMiddleware =
({
@@ -25,8 +45,9 @@ export const getDiagnosticsEndpointMiddleware =
getManifest,
getClients,
getLastRebuildAt,
+ notifyChanged,
}: DiagnosticsEndpointMiddlewareOptions): Connect.NextHandleFunction =>
- (req, res, next) => {
+ async (req, res, next) => {
const [pathname, query] = (req.url ?? "").split("?");
if (pathname !== DATA_APP_DIAGNOSTICS_URL) {
@@ -35,9 +56,32 @@ export const getDiagnosticsEndpointMiddleware =
return;
}
+ if (req.method === "POST") {
+ const message = await readJsonBody(req);
+
+ if (typeof message !== "object" || message === null) {
+ res.statusCode = 400;
+ res.end();
+
+ return;
+ }
+
+ // Field-level guarding happens in `applyMessage`; the parse above only
+ // establishes that a JSON object arrived.
+ if (store.applyMessage(message as DataAppDiagnosticsMessage)) {
+ notifyChanged();
+ }
+
+ res.statusCode = 204;
+ res.end();
+
+ return;
+ }
+
// Clear diagnostics store on DELETE
if (req.method === "DELETE") {
store.clear();
+ notifyChanged();
res.statusCode = 204;
res.end();
@@ -46,7 +90,7 @@ export const getDiagnosticsEndpointMiddleware =
if (req.method !== "GET") {
res.statusCode = 405;
- res.setHeader("Allow", "GET, DELETE");
+ res.setHeader("Allow", "GET, POST, DELETE");
res.end();
return;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
index 28f4b9ef69f..62ecd93a361 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
@@ -4,12 +4,8 @@ import type { Plugin } from "vite";
import { validateDataAppManifest } from "../config/validate-manifest";
import { DATA_APP_REBUILT_EVENT } from "../constants/bundle";
-import {
- DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
- DATA_APP_DIAGNOSTICS_EVENT,
-} from "../constants/diagnostics-channel";
+import { DATA_APP_DIAGNOSTICS_CHANGED_EVENT } from "../constants/diagnostics-channel";
import { DATA_APP_MANIFEST_FILE_NAME } from "../constants/paths";
-import type { DataAppManifestStatus } from "../types/manifest-status";
import { createAppBundle } from "./app-bundle";
import { DiagnosticsStore } from "./diagnostics-store";
@@ -26,7 +22,6 @@ export function dataAppSandboxDevPlugin(
allowedHosts: string[],
): Plugin {
const diagnostics = new DiagnosticsStore();
- let manifestStatus: DataAppManifestStatus | null = null;
return {
name: "metabase-data-app-dev",
@@ -45,36 +40,29 @@ export function dataAppSandboxDevPlugin(
onError: (message) => server.config.logger.error(message),
});
- const refreshManifestStatus = () => {
- manifestStatus = validateDataAppManifest(root, allowedHosts);
- };
-
- refreshManifestStatus();
-
server.middlewares.use(getAppBundleMiddleware(bundle));
server.middlewares.use(
getDiagnosticsEndpointMiddleware({
store: diagnostics,
- getManifest: () => manifestStatus,
+ getManifest: () => validateDataAppManifest(root, allowedHosts),
getClients: () => server.ws.clients.size,
getLastRebuildAt: () => bundle.lastRebuildAt,
+ notifyChanged: () =>
+ server.ws.send({
+ type: "custom",
+ event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
+ }),
}),
);
- server.ws.on(DATA_APP_DIAGNOSTICS_EVENT, (message) => {
- if (diagnostics.applyMessage(message)) {
- server.ws.send({
- type: "custom",
- event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
- });
- }
- });
-
const srcDir = `${path.sep}src${path.sep}`;
server.watcher.on("all", async (_event, file) => {
if (path.basename(file) === DATA_APP_MANIFEST_FILE_NAME) {
- refreshManifestStatus();
+ server.ws.send({
+ type: "custom",
+ event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
+ });
return;
}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
index abb0f6e827c..6079d0dcca9 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
@@ -14,7 +14,6 @@ import {
} from "../constants/bundle";
import {
DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
- DATA_APP_DIAGNOSTICS_EVENT,
DATA_APP_DIAGNOSTICS_URL,
} from "../constants/diagnostics-channel";
@@ -36,6 +35,8 @@ type ConnectReq = {
url?: string;
method?: string;
headers?: Record<string, string>;
+ // The POST branch reads the body by async-iterating the request stream.
+ [Symbol.asyncIterator]?: () => AsyncIterator<Buffer>;
};
type ConnectRes = { statusCode: number; setHeader: jest.Mock; end: jest.Mock };
type ConnectHandler = (
@@ -110,9 +111,18 @@ class FakeDevServer {
async request(
url: string,
- { method = "GET", headers = {} }: RequestOptions = {},
+ { method = "GET", headers = {}, body }: RequestOptions = {},
): Promise<RequestResult> {
- const req: ConnectReq = { url, method, headers };
+ const req: ConnectReq = {
+ url,
+ method,
+ headers,
+ ...(body !== undefined && {
+ [Symbol.asyncIterator]: async function* () {
+ yield Buffer.from(JSON.stringify(body));
+ },
+ }),
+ };
const res: ConnectRes = {
statusCode: 0,
setHeader: jest.fn(),
@@ -140,6 +150,12 @@ class FakeDevServer {
await next();
+ // Middlewares follow connect's convention of calling `next()` without
+ // awaiting it, so an async handler further down the stack (the POST
+ // branch reads the body) may still be running — let it settle before
+ // reading the response.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
const [payload] = res.end.mock.calls[0] ?? [];
return {
@@ -154,7 +170,11 @@ class FakeDevServer {
}
}
-type RequestOptions = { method?: string; headers?: Record<string, string> };
+type RequestOptions = {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: unknown;
+};
type TestPlugin = {
name: string;
@@ -352,7 +372,27 @@ describe("dataAppSandboxDevPlugin", () => {
);
expect(mockedBuild).toHaveBeenCalledTimes(1);
- expect(server.ws.send).not.toHaveBeenCalled();
+ expect(server.ws.send).not.toHaveBeenCalledWith({
+ type: "custom",
+ event: DATA_APP_REBUILT_EVENT,
+ });
+ });
+
+ it("nudges clients to re-read the feed when data_app.yaml changes", async () => {
+ const { server } = await setup();
+
+ await server.watcher.emit(
+ "all",
+ "change",
+ path.join("/app", "data_app.yaml"),
+ );
+
+ // The manifest is served from the feed, so the toolbar's Manifest tab
+ // only refreshes when told to re-read — otherwise it lags the edit.
+ expect(server.ws.send).toHaveBeenCalledWith({
+ type: "custom",
+ event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
+ });
});
});
@@ -404,15 +444,20 @@ describe("dataAppSandboxDevPlugin", () => {
});
describe("diagnostics feed", () => {
+ // The page's reporter delivers over POST (see the middleware's note on
+ // why not the HMR socket).
const report = (
server: FakeDevServer,
entries: unknown[],
sessionId?: string,
) =>
- server.ws.emit(DATA_APP_DIAGNOSTICS_EVENT, {
- sessionId,
- entries,
- connection: { reachable: true },
+ server.request(DATA_APP_DIAGNOSTICS_URL, {
+ method: "POST",
+ body: {
+ sessionId,
+ entries,
+ connection: { reachable: true },
+ },
});
it("refuses a method it does not serve", async () => {
@@ -420,17 +465,39 @@ describe("dataAppSandboxDevPlugin", () => {
const { statusCode, res } = await server.request(
DATA_APP_DIAGNOSTICS_URL,
- { method: "POST" },
+ { method: "PUT" },
);
expect(statusCode).toBe(405);
- expect(res.setHeader).toHaveBeenCalledWith("Allow", "GET, DELETE");
+ expect(res.setHeader).toHaveBeenCalledWith(
+ "Allow",
+ "GET, POST, DELETE",
+ );
+ });
+
+ it("accepts a reporter batch on POST and rejects a non-JSON body", async () => {
+ const { server } = await setup();
+
+ const posted = await report(server, [{ summary: "boom" }], "page-1");
+ expect(posted.statusCode).toBe(204);
+
+ const { body } = await server.request(DATA_APP_DIAGNOSTICS_URL);
+ expect(
+ body.entries.map((entry: { summary: string }) => entry.summary),
+ ).toEqual(["boom"]);
+
+ const rejected = await server.request(DATA_APP_DIAGNOSTICS_URL, {
+ method: "POST",
+ // A raw string is valid JSON but not a message object.
+ body: "not-a-message",
+ });
+ expect(rejected.statusCode).toBe(400);
});
it("serves what the page reported, and passes other URLs through", async () => {
const { server } = await setup();
- report(server, [
+ await report(server, [
{ id: 1, kind: "error", summary: "boom", alert: true },
{ id: 2, kind: "sdk-call", summary: "POST /api/dataset → 400" },
]);
@@ -461,7 +528,7 @@ describe("dataAppSandboxDevPlugin", () => {
it("keeps the manifest even when the page reports without one", async () => {
const { server } = await setup();
- report(server, [{ eventId: 1, summary: "boom" }]);
+ await report(server, [{ eventId: 1, summary: "boom" }]);
const { body } = await server.request(DATA_APP_DIAGNOSTICS_URL);
@@ -470,7 +537,7 @@ describe("dataAppSandboxDevPlugin", () => {
it("returns only events from `startEventId` onward", async () => {
const { server } = await setup();
- report(server, [
+ await report(server, [
{ id: 1, summary: "old" },
{ id: 2, summary: "new" },
]);
@@ -495,7 +562,7 @@ describe("dataAppSandboxDevPlugin", () => {
});
server.ws.clients.add({});
- report(server, []);
+ await report(server, []);
const { body } = await server.request(DATA_APP_DIAGNOSTICS_URL);
expect(body.clients).toBe(1);
@@ -510,7 +577,7 @@ describe("dataAppSandboxDevPlugin", () => {
it("nudges readers when a report brings something new", async () => {
const { server } = await setup();
- report(server, [{ summary: "boom" }], "page-1");
+ await report(server, [{ summary: "boom" }], "page-1");
// The nudge carries no payload: readers re-read the endpoint, so the
// toolbar and a shell agent still see the same bytes.
@@ -524,14 +591,32 @@ describe("dataAppSandboxDevPlugin", () => {
it("stays quiet when a report brings nothing new", async () => {
const { server } = await setup();
- report(server, [{ summary: "boom" }], "page-1");
- report(server, [], "page-1");
- report(server, [], "page-1");
+ await report(server, [{ summary: "boom" }], "page-1");
+ await report(server, [], "page-1");
+ await report(server, [], "page-1");
// The reporter flushes on a timer whether or not anything happened.
// Nudging on those would rebuild the poll loop from the other side.
expect(changeNudges(server)).toBe(1);
});
+
+ it("clears on DELETE and nudges every reader, so Clear is global", async () => {
+ const { server } = await setup();
+ await report(server, [{ summary: "boom" }], "page-1");
+ const nudgesBefore = changeNudges(server);
+
+ const { statusCode } = await server.request(DATA_APP_DIAGNOSTICS_URL, {
+ method: "DELETE",
+ });
+
+ expect(statusCode).toBe(204);
+ // Other open toolbars only re-read on the nudge — without it they'd
+ // keep showing the entries that were just cleared.
+ expect(changeNudges(server)).toBe(nudgesBefore + 1);
+
+ const { body } = await server.request(DATA_APP_DIAGNOSTICS_URL);
+ expect(body.entries).toEqual([]);
+ });
});
});
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts
index ceb6209de4e..d3fe006501b 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts
@@ -18,11 +18,11 @@ import {
SDK_PACKAGE_NAME,
} from "../constants/paths";
-const { DATA_APP_DEV_CONFIG_VIRTUAL_ID, DATA_APP_DEV_ENTRY_VIRTUAL_ID } =
- dataAppVirtualModules;
-
-// Rollup's virtual-module marker: a leading NUL tells plugins the id is synthetic.
-const RESOLVED_PREFIX = "\0";
+const {
+ DATA_APP_DEV_CONFIG_VIRTUAL_ID,
+ DATA_APP_DEV_ENTRY_VIRTUAL_ID,
+ DATA_APP_VIRTUAL_RESOLVED_PREFIX: RESOLVED_PREFIX,
+} = dataAppVirtualModules;
const DEV_ENTRY_SOURCE_PATH = fileURLToPath(
new URL(DATA_APP_DEV_ENTRY_FILE_NAME, import.meta.url),
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/dev-session.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/dev-session.ts
new file mode 100644
index 00000000000..af4e99dfc2b
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/dev-session.ts
@@ -0,0 +1 @@
+export const DEV_SESSION_ID = `${Date.now()}-${performance.now()}`;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.ts
index 08a9488a1ca..d4e1c02d5bf 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.ts
@@ -1,74 +1,70 @@
import { devDiagnostics } from "../components/DevToolbar/diagnostics";
-import { DATA_APP_DIAGNOSTICS_EVENT } from "../constants/diagnostics-channel";
-import { DIAGNOSTICS_FLUSH_MS } from "../constants/timings";
-import type { DataAppDiagnosticsMessage } from "../types/diagnostics-channel";
+import { DATA_APP_DIAGNOSTICS_URL } from "../constants/diagnostics-channel";
+import {
+ DIAGNOSTICS_FLUSH_MS,
+ DIAGNOSTICS_RETRY_MS,
+} from "../constants/timings";
+import { DEV_SESSION_ID } from "./dev-session";
import { toPayload } from "./diagnostics-payload";
-export interface DiagnosticsReporterHot {
- send: (event: string, data: DataAppDiagnosticsMessage) => void;
-}
-
-const getNextSessionId = (): string => {
- if (typeof globalThis.crypto?.getRandomValues !== "function") {
- throw new Error(
- "The data-app dev preview needs Web Crypto to identify a session.",
- );
- }
-
- const random = globalThis.crypto.getRandomValues(new Uint8Array(8));
- const suffix = Array.from(random, (byte) =>
- byte.toString(16).padStart(2, "0"),
- ).join("");
-
- return `${Date.now()}-${suffix}`;
-};
-
/**
- * Mirrors the page's collector to the dev server over the HMR socket, so the
- * feed shows what the preview captured. Sends once on install to announce the
- * page, then a coalesced batch of whatever is new.
+ * Mirrors the page's collector to the dev server: POSTs coalesced batches to
+ * the diagnostics endpoint, retrying failures without losing entries. HTTP on
+ * purpose — the HMR socket silently drops anything sent before its handshake.
*/
export const installDiagnosticsReporter = (
- hot: DiagnosticsReporterHot,
-): (() => void) => {
- const sessionId = getNextSessionId();
-
+ url: string = DATA_APP_DIAGNOSTICS_URL,
+): void => {
let lastSentId = 0;
+ let inFlight = false;
let timer: ReturnType<typeof setTimeout> | null = null;
- const flush = () => {
- timer = null;
+ const scheduleIn = (delayMs: number) => {
+ timer ??= setTimeout(() => {
+ timer = null;
+ flush();
+ }, delayMs);
+ };
+
+ const flush = async () => {
+ if (inFlight) {
+ // A batch is on the wire; whatever prompted this call goes in the next.
+ scheduleIn(DIAGNOSTICS_FLUSH_MS);
+
+ return;
+ }
const fresh = devDiagnostics
.getEntries()
.filter((entry) => entry.id > lastSentId);
-
- if (fresh.length > 0) {
- lastSentId = fresh[fresh.length - 1].id;
+ const sentUpTo = fresh.length > 0 ? fresh[fresh.length - 1].id : lastSentId;
+
+ inFlight = true;
+ try {
+ const response = await fetch(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ sessionId: DEV_SESSION_ID,
+ entries: fresh.map(toPayload),
+ connection: devDiagnostics.getConnectionStatus(),
+ }),
+ });
+
+ if (response.ok) {
+ lastSentId = sentUpTo;
+ } else {
+ scheduleIn(DIAGNOSTICS_RETRY_MS);
+ }
+ } catch {
+ scheduleIn(DIAGNOSTICS_RETRY_MS);
+ } finally {
+ inFlight = false;
}
-
- hot.send(DATA_APP_DIAGNOSTICS_EVENT, {
- sessionId,
- entries: fresh.map(toPayload),
- connection: devDiagnostics.getConnectionStatus(),
- });
- };
-
- const schedule = () => {
- timer ??= setTimeout(flush, DIAGNOSTICS_FLUSH_MS);
};
flush();
- const unsubscribe = devDiagnostics.subscribe(schedule);
-
- return () => {
- unsubscribe();
-
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- };
+ devDiagnostics.subscribe(() => scheduleIn(DIAGNOSTICS_FLUSH_MS));
};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.unit.spec.ts
index ac7f6fbabb8..2d8e74c73a7 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/diagnostics-reporter.unit.spec.ts
@@ -1,58 +1,95 @@
-import { devDiagnostics } from "../components/DevToolbar/diagnostics";
-import { DATA_APP_DIAGNOSTICS_EVENT } from "../constants/diagnostics-channel";
+import type { devDiagnostics as DevDiagnostics } from "../components/DevToolbar/diagnostics";
+import { DATA_APP_DIAGNOSTICS_URL } from "../constants/diagnostics-channel";
import type { DataAppDiagnosticsMessage } from "../types/diagnostics-channel";
-import { installDiagnosticsReporter } from "./diagnostics-reporter";
+const originalFetch = global.fetch;
const setup = () => {
const sent: DataAppDiagnosticsMessage[] = [];
- const cleanup = installDiagnosticsReporter({
- send: (_event, data) => {
- sent.push(data);
+ const requests: { url: string; init: RequestInit | undefined }[] = [];
+ const fetchMock = jest.fn(
+ async (url: RequestInfo | URL, init?: RequestInit) => {
+ requests.push({ url: String(url), init });
+ // The body is authored by the reporter under test, so it is a message.
+ sent.push(JSON.parse(String(init?.body)) as DataAppDiagnosticsMessage);
+
+ // The reporter only reads `ok` off the response.
+ return { ok: true } as Response;
},
+ );
+
+ // The mock covers the one overload the reporter calls.
+ global.fetch = fetchMock as typeof fetch;
+
+ let devDiagnostics!: typeof DevDiagnostics;
+ jest.isolateModules(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- isolateModules offers no import() form
+ const reporter = require("./diagnostics-reporter") as {
+ installDiagnosticsReporter: () => void;
+ };
+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- isolateModules offers no import() form
+ const diagnostics = require("../components/DevToolbar/diagnostics") as {
+ devDiagnostics: typeof DevDiagnostics;
+ };
+ devDiagnostics = diagnostics.devDiagnostics;
+
+ reporter.installDiagnosticsReporter();
});
- return { sent, cleanup };
-};
-beforeEach(() => {
- jest.useFakeTimers();
- devDiagnostics.clear();
-});
+ return { sent, requests, fetchMock, devDiagnostics };
+};
-afterEach(() => {
- jest.useRealTimers();
-});
+const settle = () => jest.runOnlyPendingTimersAsync();
describe("installDiagnosticsReporter", () => {
- it("reports immediately on install, so the server knows a client is alive", () => {
- const { sent, cleanup } = setup();
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ jest.useRealTimers();
+ });
+
+ it("announces on install, so the server knows a client is alive", async () => {
+ const { sent } = setup();
+ await settle();
expect(sent).toHaveLength(1);
expect(sent[0].entries).toEqual([]);
+ });
+
+ it("POSTs JSON to the diagnostics endpoint", async () => {
+ const { requests } = setup();
+ await settle();
- cleanup();
+ expect(requests[0].url).toBe(DATA_APP_DIAGNOSTICS_URL);
+ expect(requests[0].init?.method).toBe("POST");
+ expect(requests[0].init?.headers).toEqual({
+ "content-type": "application/json",
+ });
});
- it("sends the toolbar's summary, detail and hint rather than raw fields", () => {
- const { sent, cleanup } = setup();
+ it("sends the toolbar's summary, detail and hint rather than raw fields", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({
kind: "csp-violation",
directive: "connect-src",
blockedUri: "https://api.example.com/v1",
});
- jest.runOnlyPendingTimers();
+ await settle();
const [entry] = sent[sent.length - 1].entries;
expect(entry.kind).toBe("csp-violation");
expect(entry.alert).toBe(true);
expect(entry.hint).toMatch(/allowed_hosts in data_app.yaml/);
-
- cleanup();
});
- it("carries the allowed_hosts hint for a blocked request", () => {
- const { sent, cleanup } = setup();
+ it("carries the allowed_hosts hint for a blocked request", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({
kind: "blocked-network",
@@ -60,34 +97,32 @@ describe("installDiagnosticsReporter", () => {
url: "https://api.example.com/v1/data",
reason: "api.example.com (not in allowed_hosts)",
});
- jest.runOnlyPendingTimers();
+ await settle();
const [entry] = sent[sent.length - 1].entries;
expect(entry.hint).toBe(
"Add https://api.example.com to allowed_hosts in data_app.yaml (dev server restart required).",
);
-
- cleanup();
});
- it("splits a stack into summary and detail", () => {
- const { sent, cleanup } = setup();
+ it("splits a stack into summary and detail", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({
kind: "error",
message: "TypeError: nope\n at App (src/App.tsx:1:1)",
});
- jest.runOnlyPendingTimers();
+ await settle();
const [entry] = sent[sent.length - 1].entries;
expect(entry.summary).toBe("TypeError: nope");
expect(entry.detail).toBe(" at App (src/App.tsx:1:1)");
-
- cleanup();
});
- it("marks a failed SDK call as an alert but not a successful one", () => {
- const { sent, cleanup } = setup();
+ it("marks a failed SDK call as an alert but not a successful one", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({
kind: "sdk-call",
@@ -103,20 +138,19 @@ describe("installDiagnosticsReporter", () => {
status: 200,
durationMs: 3,
});
- jest.runOnlyPendingTimers();
+ await settle();
const { entries } = sent[sent.length - 1];
expect(entries.map((entry) => entry.alert)).toEqual([true, false]);
-
- cleanup();
});
- it("batches a burst into one message and never re-sends an entry", () => {
- const { sent, cleanup } = setup();
+ it("batches a burst into one message and never re-sends an entry", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({ kind: "error", message: "one" });
devDiagnostics.record({ kind: "error", message: "two" });
- jest.runOnlyPendingTimers();
+ await settle();
expect(sent).toHaveLength(2);
expect(sent[1].entries.map((entry) => entry.summary)).toEqual([
@@ -125,62 +159,70 @@ describe("installDiagnosticsReporter", () => {
]);
devDiagnostics.record({ kind: "error", message: "three" });
- jest.runOnlyPendingTimers();
+ await settle();
expect(sent[2].entries.map((entry) => entry.summary)).toEqual(["three"]);
-
- cleanup();
});
- it("does not resend earlier entries after the toolbar's Clear", () => {
- const { sent, cleanup } = setup();
+ it("does not resend earlier entries after the toolbar's Clear", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
devDiagnostics.record({ kind: "error", message: "before clear" });
- jest.runOnlyPendingTimers();
+ await settle();
devDiagnostics.clear();
devDiagnostics.record({ kind: "error", message: "after clear" });
- jest.runOnlyPendingTimers();
+ await settle();
const summaries = sent.at(-1)?.entries.map((entry) => entry.summary);
expect(summaries).toEqual(["after clear"]);
+ });
+
+ it("keeps a batch the network dropped and delivers it on the retry", async () => {
+ const { sent, fetchMock, devDiagnostics } = setup();
+ await settle();
+ const sentBefore = sent.length;
+
+ // e.g. the dev server is restarting onto a changed .env.local
+ fetchMock.mockRejectedValueOnce(new Error("connection refused"));
+ devDiagnostics.record({ kind: "error", message: "kept" });
+ await settle();
- cleanup();
+ expect(sent).toHaveLength(sentBefore);
+
+ // The retry timer re-flushes; the cursor never moved, so nothing was lost.
+ await settle();
+ expect(sent.at(-1)?.entries.map((entry) => entry.summary)).toEqual([
+ "kept",
+ ]);
});
- it("stops sending once torn down", () => {
- const { sent, cleanup } = setup();
- cleanup();
+ it("treats a non-2xx response as undelivered and retries it", async () => {
+ const { sent, fetchMock, devDiagnostics } = setup();
+ await settle();
- devDiagnostics.record({ kind: "error", message: "ignored" });
- jest.runOnlyPendingTimers();
+ // The reporter only reads `ok` off the response.
+ fetchMock.mockResolvedValueOnce({ ok: false } as Response);
+ devDiagnostics.record({ kind: "error", message: "rejected then kept" });
+ await settle();
+ await settle();
- expect(sent).toHaveLength(1);
+ expect(sent.at(-1)?.entries.map((entry) => entry.summary)).toEqual([
+ "rejected then kept",
+ ]);
});
- it("tags every message with a stable per-install sessionId", () => {
- const { sent, cleanup } = setup();
+ it("tags every message with a stable per-install sessionId", async () => {
+ const { sent, devDiagnostics } = setup();
+ await settle();
+
devDiagnostics.record({ kind: "error", message: "one" });
- jest.runOnlyPendingTimers();
+ await settle();
expect(typeof sent[0].sessionId).toBe("string");
expect(sent[0].sessionId).not.toBe("");
// Same page load → same sessionId on every message.
expect(sent[sent.length - 1].sessionId).toBe(sent[0].sessionId);
-
- cleanup();
- });
-
- it("uses the agreed channel event name", () => {
- const events: string[] = [];
- const cleanup = installDiagnosticsReporter({
- send: (event) => {
- events.push(event);
- },
- });
-
- expect(events).toEqual([DATA_APP_DIAGNOSTICS_EVENT]);
-
- cleanup();
});
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.ts
new file mode 100644
index 00000000000..11e297fa1c5
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.ts
@@ -0,0 +1,144 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { DATA_APP_DIAGNOSTICS_URL } from "../constants/diagnostics-channel";
+import { DIAGNOSTICS_POLL_MS } from "../constants/timings";
+import type {
+ DataAppDiagnosticPayload,
+ DataAppDiagnosticsReport,
+ InstanceConnectionStatus,
+} from "../types/diagnostics-channel";
+import type { DataAppManifestStatus } from "../types/manifest-status";
+
+import { DEV_SESSION_ID } from "./dev-session";
+
+export type SubscribeToChanges = (onChange: () => void) => () => void;
+
+export type DiagnosticsFeedProblem =
+ | { kind: "unreachable" }
+ | { kind: "http"; status: number };
+
+export interface DiagnosticsFeed {
+ entries: DataAppDiagnosticPayload[];
+ connection: InstanceConnectionStatus | null;
+ manifest: DataAppManifestStatus | null;
+ clients: number;
+ lastReportAt: number | null;
+ lastRebuildAt: number | null;
+ problem: DiagnosticsFeedProblem | null;
+ loaded: boolean;
+ clear: () => void;
+}
+
+const EMPTY_ENTRIES: DataAppDiagnosticPayload[] = [];
+
+/**
+ * Mirrors the dev server's diagnostics report — what the preview page has
+ * captured, plus the connection and manifest status — for the toolbar to
+ * render, and exposes `clear` to empty it for every reader.
+ *
+ * The endpoint is the single source of truth: the hook never reads the page's
+ * in-memory collector, so the toolbar and a shell agent polling the same URL
+ * can't diverge. `subscribe` (the dev server's "feed changed" nudge over the
+ * HMR socket) makes updates immediate; the hook polls regardless, because a
+ * dev-server restart can leave that socket unconnectable.
+ */
+export const useDiagnosticsFeed = (
+ url: string = DATA_APP_DIAGNOSTICS_URL,
+ subscribe?: SubscribeToChanges,
+): DiagnosticsFeed => {
+ const [report, setReport] = useState<DataAppDiagnosticsReport | null>(null);
+ const [problem, setProblem] = useState<DiagnosticsFeedProblem | null>(null);
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ // Each read replaces state with the endpoint's whole report rather than
+ // fetching only what is new, so there is no cursor to keep or batch to stitch.
+ // Reads are numbered instead: only the newest issued may apply its result, so
+ // a slow read can't overwrite a fresher one, and `clear` can void reads still
+ // in flight.
+ const latestRead = useRef(0);
+ const pendingClear = useRef<Promise<void> | null>(null);
+
+ const readFeed = useCallback(async () => {
+ await pendingClear.current;
+
+ const readId = ++latestRead.current;
+
+ try {
+ const response = await fetch(url);
+
+ if (readId !== latestRead.current) {
+ return;
+ }
+
+ if (!response.ok) {
+ setProblem({ kind: "http", status: response.status });
+ return;
+ }
+
+ // `json()` returns `any`
+ const next = (await response.json()) as DataAppDiagnosticsReport;
+
+ if (readId !== latestRead.current) {
+ return;
+ }
+
+ setProblem(null);
+ setIsLoaded(true);
+ setReport(next);
+ } catch {
+ if (readId === latestRead.current) {
+ setProblem({ kind: "unreachable" });
+ }
+ }
+ }, [url]);
+
+ useEffect(() => {
+ readFeed();
+
+ const unsubscribe = subscribe?.(() => readFeed());
+
+ const pollId = setInterval(() => readFeed(), DIAGNOSTICS_POLL_MS);
+
+ return () => {
+ unsubscribe?.();
+ clearInterval(pollId);
+ };
+ }, [readFeed, subscribe]);
+
+ const clear = useCallback(() => {
+ // Void any read in flight, drop the entries locally, and tell the server —
+ // the DELETE empties every reader's buffer, this one included. Reads issued
+ // while it is in flight wait for it (see `readFeed`).
+ latestRead.current += 1;
+ setReport((current) => (current ? { ...current, entries: [] } : current));
+
+ const request: Promise<void> = fetch(url, { method: "DELETE" })
+ .then(() => undefined)
+ .catch(() => setProblem({ kind: "unreachable" }))
+ .finally(() => {
+ if (pendingClear.current === request) {
+ pendingClear.current = null;
+ }
+ });
+
+ pendingClear.current = request;
+ }, [url]);
+
+ return {
+ // Only this page load's entries: after a reload the author is looking at a
+ // fresh page, and a persistent error would otherwise stack up a copy per
+ // load. The server's buffer keeps every session — a shell reader paging it
+ // with `?startEventId=` still sees what previous pages reported.
+ entries:
+ report?.entries.filter((entry) => entry.sessionId === DEV_SESSION_ID) ??
+ EMPTY_ENTRIES,
+ connection: report?.connection ?? null,
+ manifest: report?.manifest ?? null,
+ clients: report?.clients ?? 0,
+ lastReportAt: report?.lastReportAt ?? null,
+ lastRebuildAt: report?.lastRebuildAt ?? null,
+ problem,
+ loaded: isLoaded,
+ clear,
+ };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.unit.spec.ts
new file mode 100644
index 00000000000..6607580c358
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/lib/use-diagnostics-feed.unit.spec.ts
@@ -0,0 +1,269 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+
+import type {
+ DataAppDiagnosticPayload,
+ DataAppDiagnosticsReport,
+} from "../types/diagnostics-channel";
+
+import { DEV_SESSION_ID } from "./dev-session";
+import { useDiagnosticsFeed } from "./use-diagnostics-feed";
+
+const entry = (
+ eventId: number,
+ sessionId: string = DEV_SESSION_ID,
+): DataAppDiagnosticPayload => ({
+ eventId,
+ sessionId,
+ time: 0,
+ kind: "error",
+ summary: `event ${eventId}`,
+ detail: null,
+ hint: null,
+ alert: true,
+});
+
+const report = (
+ entries: DataAppDiagnosticPayload[],
+): DataAppDiagnosticsReport => ({
+ entries,
+ connection: null,
+ manifest: null,
+ clients: 1,
+ lastReportAt: 1,
+ lastRebuildAt: 1,
+ nextEventId: (entries.at(-1)?.eventId ?? 0) + 1,
+ sessionId: "page-1",
+});
+
+const ok = (body: DataAppDiagnosticsReport) =>
+ new Response(JSON.stringify(body), { status: 200 });
+
+/** The dev server's "feed changed" socket, in the shape the hook subscribes to. */
+const makeSubscribe = () => {
+ const listeners = new Set<() => void>();
+
+ return {
+ subscribe: (onChange: () => void) => {
+ listeners.add(onChange);
+
+ return () => listeners.delete(onChange);
+ },
+ nudge: () => listeners.forEach((listener) => listener()),
+ get listenerCount() {
+ return listeners.size;
+ },
+ };
+};
+
+afterEach(() => jest.restoreAllMocks());
+
+describe("useDiagnosticsFeed", () => {
+ it("mirrors the endpoint's report on mount", async () => {
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(ok(report([entry(1), entry(2)])));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ await waitFor(() =>
+ expect(result.current.entries.map((e) => e.eventId)).toEqual([1, 2]),
+ );
+ });
+
+ it("re-reads and re-mirrors on a nudge", async () => {
+ const { subscribe, nudge } = makeSubscribe();
+ let current = report([entry(1)]);
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(() => Promise.resolve(ok(current)));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed", subscribe));
+ await waitFor(() => expect(result.current.entries).toHaveLength(1));
+
+ // The server buffer changed — a restart or a reload just means a different
+ // report, which the next read mirrors wholesale. No cursor, no stitching.
+ current = report([entry(1), entry(2)]);
+ await act(async () => nudge());
+
+ await waitFor(() =>
+ expect(result.current.entries.map((e) => e.eventId)).toEqual([1, 2]),
+ );
+ });
+
+ it("shows only this page load's entries, leaving earlier sessions to shell readers", async () => {
+ // The buffer outlives reloads on purpose (an agent pages it with
+ // `?startEventId=`), but a persistent error would otherwise stack up one
+ // copy per reload in the panel.
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(
+ ok(report([entry(1, "previous-page-load"), entry(2)])),
+ );
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ await waitFor(() =>
+ expect(result.current.entries.map((e) => e.eventId)).toEqual([2]),
+ );
+ });
+
+ it("converges by polling when there is no nudge channel", async () => {
+ // The nudge channel rides the HMR socket, which a dev-server restart can
+ // strand — the feed must keep converging without it.
+ jest.useFakeTimers();
+ try {
+ let current = report([entry(1)]);
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(() => Promise.resolve(ok(current)));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+ await act(() => jest.advanceTimersByTimeAsync(0));
+ expect(result.current.entries).toHaveLength(1);
+
+ current = report([entry(1), entry(2)]);
+ await act(() => jest.advanceTimersByTimeAsync(2100));
+
+ expect(result.current.entries.map((e) => e.eventId)).toEqual([1, 2]);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it("does not let a slow read overwrite a fresher one", async () => {
+ const { subscribe, nudge } = makeSubscribe();
+
+ let releaseStale: (value: Response) => void = () => undefined;
+ const stale = new Promise<Response>((resolve) => {
+ releaseStale = resolve;
+ });
+
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockReturnValueOnce(stale) // the mount read, left hanging
+ .mockResolvedValue(ok(report([entry(9)]))); // the nudge read, resolves first
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed", subscribe));
+ await act(async () => nudge());
+ await waitFor(() => expect(result.current.entries).toHaveLength(1));
+
+ // The mount read finally lands, carrying older data. It must be dropped, not
+ // painted over the newer report the nudge already delivered.
+ await act(async () => {
+ releaseStale(ok(report([entry(1), entry(2), entry(3)])));
+ await stale;
+ });
+
+ expect(result.current.entries.map((e) => e.eventId)).toEqual([9]);
+ });
+
+ it("discards a response that was in flight when the feed was cleared", async () => {
+ let release: (value: Response) => void = () => undefined;
+ const pending = new Promise<Response>((resolve) => {
+ release = resolve;
+ });
+
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockReturnValueOnce(pending)
+ .mockResolvedValue(ok(report([])));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ act(() => result.current.clear());
+
+ await act(async () => {
+ release(ok(report([entry(1), entry(2)])));
+ await pending;
+ });
+
+ // Those two were fetched before the clear; showing them would resurrect
+ // exactly what the user asked to remove.
+ expect(result.current.entries).toEqual([]);
+ });
+
+ it("holds reads issued while a clear is in flight", async () => {
+ const { subscribe, nudge } = makeSubscribe();
+ let completeDelete: (value: Response) => void = () => undefined;
+ const deleteRequest = new Promise<Response>((resolve) => {
+ completeDelete = resolve;
+ });
+
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockImplementation((_url, init) =>
+ init?.method === "DELETE"
+ ? deleteRequest
+ : Promise.resolve(ok(report([entry(1)]))),
+ );
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed", subscribe));
+ await waitFor(() => expect(result.current.entries).toHaveLength(1));
+
+ act(() => result.current.clear());
+ expect(result.current.entries).toEqual([]);
+
+ // A poll (or nudge) lands mid-DELETE. Reading now would mirror the entries
+ // the server is about to drop, flashing them back into the panel.
+ await act(async () => nudge());
+ expect(result.current.entries).toEqual([]);
+
+ // Once the DELETE completes, reads resume — against the emptied feed.
+ jest.mocked(globalThis.fetch).mockResolvedValue(ok(report([])));
+ await act(async () => {
+ completeDelete(new Response(null, { status: 204 }));
+ await deleteRequest;
+ });
+ await act(async () => nudge());
+
+ expect(result.current.entries).toEqual([]);
+ });
+
+ it("distinguishes a refused response from an unreachable server", async () => {
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response("nope", { status: 500 }));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ await waitFor(() =>
+ expect(result.current.problem).toEqual({ kind: "http", status: 500 }),
+ );
+
+ fetchSpy.mockRejectedValue(new Error("connection refused"));
+ const { result: offline } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ await waitFor(() =>
+ expect(offline.current.problem).toEqual({ kind: "unreachable" }),
+ );
+ });
+
+ it("reports `loaded` only once a response has landed", async () => {
+ jest.spyOn(globalThis, "fetch").mockResolvedValue(ok(report([])));
+
+ const { result } = renderHook(() => useDiagnosticsFeed("/feed"));
+
+ // Before the first response, `clients: 0` is an absence of data, not a fact.
+ expect(result.current.loaded).toBe(false);
+
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ });
+
+ it("stops listening when unmounted", () => {
+ const socket = makeSubscribe();
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(() => Promise.resolve(ok(report([]))));
+
+ const { unmount } = renderHook(() =>
+ useDiagnosticsFeed("/feed", socket.subscribe),
+ );
+ expect(socket.listenerCount).toBe(1);
+
+ unmount();
+
+ // A toolbar that unmounts without unsubscribing keeps re-reading the feed
+ // for the rest of the session, once per nudge, forever.
+ expect(socket.listenerCount).toBe(0);
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/diagnostics-channel.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/diagnostics-channel.ts
index 9d687259892..e6b4fd6c9d6 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/diagnostics-channel.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/diagnostics-channel.ts
@@ -19,6 +19,8 @@ export interface DataAppDiagnosticEntry {
export interface DataAppDiagnosticPayload extends DataAppDiagnosticEntry {
eventId: number;
+ /** The page load that reported this entry (see `lib/dev-session`). */
+ sessionId: string;
}
export interface DataAppDiagnosticsMessage {
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/manifest-status.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/manifest-status.ts
index 9c9e21d556c..75348c601d1 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/manifest-status.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/types/manifest-status.ts
@@ -1,5 +1,4 @@
export interface DataAppManifestStatus {
- checkedAt: number;
name: string | null;
bundlePath: string | null;
bundlePathExists: boolean;
diff --git a/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js b/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js
index 715a563b8ad..c4ed9f7709d 100644
--- a/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js
+++ b/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js
@@ -11,8 +11,6 @@
/**
* The dev entry the template's `index.html` imports; the dev plugin serves the
* prebuilt bundle for it.
- *
- * @type {"virtual:metabase-data-app-dev-entry"}
*/
module.exports.DATA_APP_DEV_ENTRY_VIRTUAL_ID =
"virtual:metabase-data-app-dev-entry";
@@ -20,8 +18,19 @@ module.exports.DATA_APP_DEV_ENTRY_VIRTUAL_ID =
/**
* The config module the dev plugin generates (the app's allowed hosts + the bundle
* URL/event); the dev entry imports it and the rspack build externalizes it.
- *
- * @type {"virtual:metabase-data-app-dev-config"}
*/
module.exports.DATA_APP_DEV_CONFIG_VIRTUAL_ID =
"virtual:metabase-data-app-dev-config";
+
+/**
+ * Rollup's virtual-module marker: a leading NUL tells plugins a resolved id is
+ * synthetic. The dev plugin prefixes it on resolve.
+ */
+module.exports.DATA_APP_VIRTUAL_RESOLVED_PREFIX = "\0";
+
+/**
+ * How the dev server addresses a resolved virtual id by URL: Vite's `/@id/`
+ * scheme, with the NUL marker encoded as `__x00__`. The preview shell loads the
+ * dev entry through this.
+ */
+module.exports.DATA_APP_VIRTUAL_URL_PREFIX = "/@id/__x00__";
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx
index 102c7a537b5..e6830d27771 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx
@@ -4,13 +4,14 @@ import { useContext, useId, useMemo } from "react";
import { DEFAULT_FONT } from "embedding-sdk-bundle/config";
import { useEmbeddingThemeOverride } from "embedding-sdk-bundle/hooks/private/use-embedding-theme-override";
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
import { EnsureSingleInstance } from "embedding-sdk-shared/components/EnsureSingleInstance/EnsureSingleInstance";
import { useSetting } from "metabase/common/hooks";
import {
type MetabaseEmbeddingTheme,
isEmbeddingThemeV1,
} from "metabase/embedding-sdk/theme";
-import { useSelector } from "metabase/redux";
+import { MetabaseReduxProvider, useSelector } from "metabase/redux";
import { getFont } from "metabase/styled-components/selectors";
import { getMetabaseSdkCssVariables } from "metabase/styled-components/theme/css-variables";
import { ThemeProvider, useMantineTheme } from "metabase/ui";
@@ -70,6 +71,23 @@ export const SdkThemeProvider = ({ theme, children }: Props) => {
);
};
+/**
+ * `SdkThemeProvider` reads whitelabel colors and the font from the SDK redux
+ * store, so it can only render under a redux provider. Hosts that sit outside
+ * the SDK component tree (the data-app dev preview reaches this through the
+ * bundle global) use this variant, which brings its own provider — the same
+ * pattern as `MetabotSubscriber`.
+ */
+export const SdkThemeProviderWithStore = ({
+ store,
+ theme,
+ children,
+}: Props & { store: SdkStore }) => (
+ <MetabaseReduxProvider store={store}>
+ <SdkThemeProvider theme={theme}>{children}</SdkThemeProvider>
+ </MetabaseReduxProvider>
+);
+
function GlobalSdkCssVariables() {
const theme = useMantineTheme();
const whitelabelColors = useSetting("application-colors");
diff --git a/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts
index 37d29911b85..bbe4363bcd6 100644
--- a/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts
+++ b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts
@@ -3,7 +3,7 @@
import type { MetabaseEmbeddingSdkBundleExports } from "./types/sdk-bundle";
import { MetabotSubscriber } from "./components/private/MetabotSubscriber/MetabotSubscriber";
-import { SdkThemeProvider } from "./components/private/SdkThemeProvider";
+import { SdkThemeProviderWithStore } from "./components/private/SdkThemeProvider";
import { CollectionBrowser } from "./components/public/CollectionBrowser";
import { CreateDashboardModal } from "./components/public/CreateDashboardModal";
import { CreateQuestion } from "./components/public/CreateQuestion";
@@ -68,7 +68,7 @@ export const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {
useLogVersionInfo,
validateFunctionSchema,
MetabotSubscriber,
- SdkThemeProvider,
+ SdkThemeProviderWithStore,
queryDataset,
queryQuestion,
dataAppRouting,
diff --git a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
index a0243c96b80..2fdbec9e45e 100644
--- a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
+++ b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
@@ -1,7 +1,7 @@
import type { JSXElementConstructor } from "react";
import type { MetabotSubscriber } from "embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber";
-import type { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkThemeProvider";
+import type { SdkThemeProviderWithStore } from "embedding-sdk-bundle/components/private/SdkThemeProvider";
import type { CollectionBrowser } from "embedding-sdk-bundle/components/public/CollectionBrowser";
import type { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
import type { CreateDashboardModal } from "embedding-sdk-bundle/components/public/CreateDashboardModal";
@@ -128,5 +128,5 @@ type SchemaValidationUtils = {
type InternalComponentExports = {
MetabotSubscriber: typeof MetabotSubscriber;
- SdkThemeProvider: typeof SdkThemeProvider;
+ SdkThemeProviderWithStore: typeof SdkThemeProviderWithStore;
};