The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Moved the data-app skills to metabase/agent-skills (#84030)
Timofey Kachalov6352149685dd
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/schema_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/schema_test.cljindex 836897e6441..d655a00ade7 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/schema_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/schema_test.clj@@ -1,6 +1,5 @@(ns metabase-enterprise.data-apps.schema-test(:require- [clojure.java.io :as io][clojure.test :refer :all][metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.schema :as data-apps.schema]@@ -37,15 +36,6 @@(doseq [bad [0 -1 1.5 "1" "one" [1]]](is (not (valid? ::data-apps.schema/version bad)) (str "should reject: " (pr-str bad))))))-(deftest migration-upgrade-guides-cover-every-version-test- (testing "the migrate skill ships one guide per upgrade up to the supported version, so an app at any older version has a path"- (let [upgrades (->> (.listFiles (io/file "skills/metabase-data-app-migrate/references/upgrades"))- (keep #(re-matches #"v(\d+)-to-v(\d+)\.md" (.getName ^java.io.File %)))- (map (fn [[_ from to]] [(parse-long from) (parse-long to)]))- sort)]- (is (= (map (fn [n] [n (inc n)]) (range 1 data-app.config/supported-app-version))- upgrades)))))-(deftest outdated-test(testing "an app below the supported version is outdated; one at it is not"(with-redefs [data-app.config/supported-app-version 2]diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsxindex ff12558c491..e8cf30997b6 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx@@ -79,10 +79,9 @@ describe("ManageDataAppsPage", () => {screen.getByRole("link", { name: "Go to Git sync settings" }),).toHaveAttribute("href", "/admin/settings/remote-sync");expect(- screen.getByText(/npx skills add metabase\/metabase/),- ).toBeInTheDocument();- expect(- screen.getByText(/--skill metabase-data-app-setup/),+ screen.getByText(+ /npx skills add metabase\/agent-skills\/skills\/metabase-data-apps\/v1/,+ ),).toBeInTheDocument();});});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsxindex 8e5364fde9a..7f3a8ef4df2 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx@@ -1,67 +1,27 @@import { t } from "ttag";import { CopyTextArea } from "metabase/common/components/CopyTextArea";-import { useSetting } from "metabase/settings";import { Stack, Text, Title } from "metabase/ui";-import {- isLocalOrSnapshotVersion,- versionToNumericComponents,-} from "metabase/utils/version";-const REPOSITORY_NAME = "metabase/metabase";-const MAIN_BRANCH_NAME = "master";-const RELEASE_BRANCH_PREFIX = "release";-const PUBLIC_SKILLS_PATH = "/skills";--// The data-app skills to install. `skills add metabase/metabase` alone would-// discover *every* skill in the repo, so each is selected explicitly.-const DATA_APP_SKILLS = [- "metabase-data-app-setup",- "metabase-data-app-routing",- "metabase-data-app-actions",- "metabase-data-app-semantic-layer",- "metabase-data-app-migrate",-];--// Writes the YAML an app's resources are committed as. It lives in another-// repository, which has no release branches to pin to.-const REPRESENTATION_SKILL_COMMAND =- "npx skills add metabase/agent-skills/skills --skill metabase-representation-format";--export const DataAppSkillsSection = () => {- // Pin the data-app skills (and the template bundled inside `metabase-data-app-setup`)- // to the branch matching this instance: `release-x.<major>.x`, or `master` for- // local/dev builds that have no release branch.- const { tag } = useSetting("version");- const majorVersion = tag ? versionToNumericComponents(tag)?.[1] : undefined;- const skillBranch =- tag && !isLocalOrSnapshotVersion(tag) && majorVersion != null- ? `${RELEASE_BRANCH_PREFIX}-x.${majorVersion}.x`- : MAIN_BRANCH_NAME;-- const skillCommandBase = `npx skills add ${REPOSITORY_NAME}${PUBLIC_SKILLS_PATH}#${skillBranch}`;- const skillSelectors = DATA_APP_SKILLS.map((skill) => `--skill ${skill}`);- // Joined with shell line-continuations (` \` + newline) so each `--skill` is on- // its own line for readability, while the copied text is still one runnable- // command when pasted.- const installSkillCommand = [- [skillCommandBase, ...skillSelectors].join(" \\\n"),- REPRESENTATION_SKILL_COMMAND,- ].join(" && \\\n");-- return (- <Stack gap="sm">- <Title order={3}>{t`AI skills`}</Title>-- {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}- <Text>{t`Install Metabase Data App skills in your project, then ask your AI agent to create a data app.`}</Text>-- <CopyTextArea- value={installSkillCommand}- aria-label={t`Install command`}- autosize- ff="monospace"- />- </Stack>- );-};+// metabase/agent-skills keeps one folder per breaking version of the skill, at+// `skills/metabase-data-apps/<version>`. The skill is marked internal, so the+// install also names it.+const INSTALL_SKILL_COMMAND =+ "npx skills add metabase/agent-skills/skills/metabase-data-apps/v1 \\\n --skill metabase-data-apps";++export const DataAppSkillsSection = () => (+ <Stack gap="sm">+ <Title order={3}>{t`AI skills`}</Title>++ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}+ <Text>{t`Install the Metabase Data Apps skill in your project, then ask your AI agent to create a data app.`}</Text>++ <CopyTextArea+ value={INSTALL_SKILL_COMMAND}+ aria-label={t`Install command`}+ autosize+ // `ff` styles the field's wrapper, not the textarea that holds the text.+ styles={{ input: { fontFamily: "var(--mantine-font-family-monospace)" } }}+ />+ </Stack>+);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsxindex 0ac019a8df3..37bdb26fd60 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx@@ -1,19 +1,11 @@import userEvent from "@testing-library/user-event";-import { createMockSettingsState, createMockState } from "__support__/state";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { createMockVersion } from "metabase-types/api/mocks";import { DataAppSkillsSection } from "./DataAppSkillsSection";-const setup = (tag?: string) => {- renderWithProviders(<DataAppSkillsSection />, {- storeInitialState: createMockState({- settings: createMockSettingsState({- version: createMockVersion({ tag }),- }),- }),- });+const setup = () => {+ renderWithProviders(<DataAppSkillsSection />);};const copyCommand = async () => {@@ -26,56 +18,20 @@ const copyCommand = async () => {return writeText.mock.calls[0][0];};-const DATA_APP_SKILLS = [- "metabase-data-app-setup",- "metabase-data-app-routing",- "metabase-data-app-actions",- "metabase-data-app-semantic-layer",- "metabase-data-app-migrate",-];-describe("DataAppSkillsSection", () => {- it("shows the command in a copy field, split across lines with shell continuations", async () => {- setup("v0.64.0");+ it("shows the command in a copy field exactly as it is copied", async () => {+ setup();const command = await copyCommand();- // The command is shown in a copy field (textarea) exactly as it is copied.expect(screen.getByRole("textbox")).toHaveValue(command);-- // Each --skill sits on its own line, joined by ` \` line-continuations, so- // the pasted command is still one runnable invocation.- expect(command).toContain("npx skills add metabase/metabase/skills#");- expect(command).toContain(" \\\n--skill metabase-data-app-setup");});- it.each(DATA_APP_SKILLS)(- "includes the %s skill in the copied command",- async (skill) => {- setup("v0.64.0");-- expect(await copyCommand()).toContain(`--skill ${skill}`);- },- );+ it("installs the data apps skill from its v1 folder, naming it because it's internal", async () => {+ setup();- it("also installs the skill for writing Metabase YAML, in the same copied command", async () => {- setup("v0.64.0");-- expect(await copyCommand()).toContain(- " && \\\nnpx skills add metabase/agent-skills/skills --skill metabase-representation-format",+ expect(await copyCommand()).toBe(+ "npx skills add metabase/agent-skills/skills/metabase-data-apps/v1 \\\n --skill metabase-data-apps",);});-- // Release builds pin to their `release-x.<major>.x` branch; local, snapshot,- // and unknown builds fall back to `master`.- it.each<[tag: string | undefined, branch: string]>([- ["v0.64.0", "release-x.64.x"],- ["vLOCAL_DEV", "master"],- ["v0.53.0-SNAPSHOT", "master"],- [undefined, "master"],- ])("pins the skills for version '%s' to #%s", async (tag, branch) => {- setup(tag);-- expect(await copyCommand()).toContain(`/skills#${branch}`);- });});diff --git a/skills/metabase-data-app-actions/SKILL.md b/skills/metabase-data-app-actions/SKILL.mddeleted file mode 100644index 989a9793736..00000000000--- a/skills/metabase-data-app-actions/SKILL.md+++ /dev/null@@ -1,204 +0,0 @@-----name: metabase-data-app-actions-description: Use when a Metabase data app needs to trigger a write or mutation — submitting a form, updating a row, deleting an entry, running a saved action, or any "do something" interaction. Covers invoking an existing action via `useAction`, parameter typing, response handling, and the critical post-action refresh of any UI data the action may have changed.-metadata:- version: master------# Triggering actions from a Metabase data app--A Metabase **action** is a saved, parameterized SQL write against the data warehouse — an `INSERT`, `UPDATE`, or `DELETE`. Actions are configured ahead of time on the Metabase instance, with their parameters and permissions already set. A data app's job is to **invoke** an action with the right parameters when the user does something — clicking a button, submitting a form, confirming a destructive prompt.--## The mental model--- Every action the app can run appears in the schema as `schema.actions.<actionName>`, with `type: "query"`.-- Each action publishes a `parameters` list. Each parameter has a `slug` (the key the Data App sends), a `jsType` (`"string"` / `"number"` / `"Date"` / `"boolean"` / `"unknown"`), and an optional `required` flag.-- Use `action.parameters` to know which fields to render and submit. The result reports `result["rows-affected"]`; use it for lightweight confirmation, then refresh the table/question/query data the page already shows.--## What's in the schema (and what isn't)--Before writing any action-invoking code, enumerate what's available under `schema.actions`. The schema is your **complete** catalog of the actions the app can run. Anything not present doesn't exist as far as the Data App is concerned: when the app needs a write the schema lacks, ask the user to create it as a query action without a model (`POST /api/action` with `type: "query"` and no `model_id`; actions created in the Metabase UI belong to a model and are never listed), on a database with actions enabled, then regenerate the schema.--## The hook--```ts-import { useAction } from "@metabase/embedding-sdk-react/data-app";--const { execute, isExecuting, result, error, reset } = useAction(MyAction);-```--- **Import it from `@metabase/embedding-sdk-react/data-app`.** That entry's `useAction` is the data-app form: it accepts a `defineAction(...)` export or `null` and nothing else. The main entry's `useAction` is the general SDK hook, which also takes plain objects and raw ids, so it cannot enforce the definition at compile time; in a data app, a raw id still fails at runtime with "was passed to `useAction` as a raw id".-- **The argument** is the `defineAction(...)` export itself, declared in the app's root-level `actions/` directory (one `<topic>.action.ts` file per topic, beside `package.json`, never under `src/`) — pass `MyAction`, not `MyAction.copiedActionEntityId`. The hook accepts nothing else in a data app: an inline `{ action: ... }` object, the schema entry, or a spread copy of a definition fails to compile with `Property 'definedWithDefineAction' is missing`. Fix that by adding the export to `actions/`, not with a cast and not by calling `defineAction(...)` at the hook, which compiles but never gets a copy. A production build then runs the copy its `copiedActionEntityId` names in the app's own collection, under the repo's `collections/data_apps/`; the dev preview keeps running the authored action, so an app works before its resources exist. Writing those copies is covered by the data-app guidance on writing the files of an app's collection (use skill discovery). Do **not** pass `schema.actions.<action>` or its `.id`: the entry is a compile error, and a data app refuses the raw id at runtime with "was passed to `useAction` as a raw id".-- **Don't write the generics.** The definition carries its schema entry, so the hook infers both the parameters object and the discriminated `result` from it: `parameters[]` becomes a keyed object (`required: true` entries are required keys, each value typed from its `jsType`), and `type: "query"` makes the kind `"sql"`. The raw-id form exists only on the SDK's `useAction` from the main entry, where `useAction<TParameters, TKind>(42)` needs them spelled out since an id describes nothing; a data app never names an action by id.-- **`execute(parameters)`** — triggers the action. Parameters object is keyed by parameter `slug`; parameters declared `required: true` are required keys, everything else optional. Returns the response body on success AND throws on failure (the error is also written to `error` state for render-time consumers). Resolves to `null` (without making a request) when `actionId` is `null` or the SDK is not yet initialized — guard the call site if those cases are reachable.-- **No `enabled` / `options` argument.** The hook only ever runs when `execute(...)` is called, so a gate option would be redundant. Skip the action by branching in the event handler:- ```ts- const onClick = async () => {- if (!user.canEdit) return;- await execute({ id: orderId, discount });- };- ```-- **`isExecuting`** — `true` between the call and its resolution. Drive button `disabled` from this so the user can't double-click into duplicate requests.-- **`result`** — the response body, discriminated by `TKind` (or the `AnyActionResult` union when `TKind` is omitted). `null` before the first call and after `reset()`. Use it for lightweight confirmation (`result?.["rows-affected"]`), then refresh surrounding data — see *After an action runs*.-- **`error`** — the last thrown error, typed `ActionExecuteError | null`. Read fields directly with no cast: `error?.data?.message`, `error?.status`, `error?.isCancelled`.-- **`reset()`** — clears `result` and `error` back to `null`. Useful after the user acknowledges success or dismisses an error.--**The hook does NOT auto-fire on mount.** Actions only run when the Data App calls `execute(...)` explicitly.--## Canonical usage — a form that creates a row--```tsx-import { useAction } from "@metabase/embedding-sdk-react/data-app";--import { CreatePerson } from "../../actions/people.action";--function AddPersonForm({ onCreated }: { onCreated: () => void }) {- const { useState } = React;- const { execute, isExecuting, error, reset } = useAction(CreatePerson);-- const [name, setName] = useState("");- const [email, setEmail] = useState("");-- async function onSubmit(e: React.FormEvent) {- e.preventDefault();- try {- await execute({ name, email }); // typed: keys match parameter slugs- setName("");- setEmail("");- onCreated(); // ← let the parent refresh dependent data- } catch {- // error is captured into hook state for render-time display- }- }-- return (- <form onSubmit={onSubmit}>- <input value={name} onChange={(e) => setName(e.target.value)} />- <input value={email} onChange={(e) => setEmail(e.target.value)} />- <button type="submit" disabled={isExecuting || !name || !email}>- {isExecuting ? "Saving…" : "Add"}- </button>- </form>- );-}-```--## Showing the error message--When `execute(...)` fails, surface both error layers. The hook's `error` is typed `ActionExecuteError | null` — shape `{ status?, data: { message?, errors? }, isCancelled }`. `error.data.message` is the whole-request failure. `error.data.errors` is a per-field validation map keyed by parameter slug (`{ <slug>: <message> }`), or `{}` for whole-request failures — which is every failure of the SQL itself. Read both directly, no cast:--```tsx-const fieldErrors = error?.data.errors ?? {};--{error ? (- <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>- {error.data.message ?? "Action failed."}- </pre>-) : null}--{action.parameters.map((parameter) => {- const fieldError = fieldErrors[parameter.slug];- return (- <label key={parameter.slug}>- {parameter.displayName}- <input- aria-invalid={Boolean(fieldError)}- style={{ borderColor: fieldError ? "#dc2626" : undefined }}- />- {fieldError ? <div role="alert">{fieldError}</div> : null}- </label>- );-})}-```--Use `<pre>` (or any element with `white-space: pre-wrap`) — the messages contain newlines that matter (driver errors include the SQL on its own line). A `<span>` collapses them into one wall of text.--Example: submitting a 9-character value into a `CHARACTER(2)` column produces--```-Value too long for column "STATE CHARACTER(2)": "'dadasdasd' (9)";-SQL statement:-UPDATE "PUBLIC"."PEOPLE" SET … WHERE "PUBLIC"."PEOPLE"."ID" = 1 [22001-214]-```--That whole string is `error.data.message`. Render it as-is.--**Don't:**--- Render `"Failed"` / `"Something went wrong"` / `String(error)` instead of `error.data.message` — the user loses the only fix-it info they have.-- Render only `error.data.message` for validation failures — `error.data.errors[parameter.slug]` is often the actionable "which field and why" detail.-- Paraphrase the message into a "friendlier" version. The raw H2/Postgres/SQL error is more actionable than any rewrite.--## After an action runs — keeping the UI honest--When an action succeeds, the data the user sees may be stale. Without an explicit refresh, the list still shows the old rows; the stat tile still shows the old count; the row the user just edited still shows its old values. The action worked, but the UI lies — and there is no warning.--The rule is simple and absolute: **after an action resolves successfully, every piece of data on the screen that the action could have changed must be refreshed.**--## Mapping parameters--Each `parameters[]` entry on a schema action exposes `slug`, `displayName`, `jsType`, and optionally `required`. The Data App's job:--- **Object keys in `execute({ … })` match the parameter `slug` strings.** Use them as literal string keys — the shape the hook derives from the definition rejects typos at compile time, but only when the argument is the `defineAction(...)` export (not a bare id).-- **Pick the right input `type` from `jsType`** so the browser provides the correct UX and built-in coercion. The agent never invents the input type from the slug name (a slug called `"phone"` is still `jsType: "string"` → `type="text"`).-- | `jsType` | Input element |- | --- | --- |- | `"string"` | `<input type="text" …>` |- | `"number"` | `<input type="number" …>` |- | `"boolean"` | `<input type="checkbox" …>` (or a Mantine `Switch`/`Checkbox`) |- | `"Date"` | `<input type="date" …>` (or `"datetime-local"` if a time component is expected) |- | `"unknown"` | `<input type="text" …>` — best effort, coerce at the call site |--- **Value types in `execute({ … })` match `jsType`.** A `jsType: "number"` parameter wants a `number`, not a string. With `type="number"` the input emits a number for `.valueAsNumber`, but `<input>.value` is still a string — coerce at the call site (`Number(input)`) if you're reading the latter.-- **`required: true` parameters cannot be omitted.** Reflected in the TS type: required keys are required.-- **`displayName`** is for labels; never use it as a key.--Slugs are whatever the action's author named the SQL parameters in Metabase; the schema is the source of truth.--## Form-side validation — match the main app--The schema exposes `parameter.required` (and `jsType` for type coercion). That's the full validation contract today, matching Metabase's built-in action-execute form. **No length checks, no min/max, no format checks** — anything more granular comes back as a BE error after submit (see *Showing the error message*).--**Schema is the ONLY source of truth.** Read `parameter.required` and wire it — nothing else. Don't add `required` because a field is named `"email"`, don't cap a "name" at 100 chars on a hunch, don't set `type="email"` from the slug. If the schema is silent, the field is unconstrained.--**Disable the submit button while the form is invalid.** Drive it from the browser's native verdict so `required` is the only rule in play:--```tsx-const [isFormValid, setIsFormValid] = useState(false);-const onFormChange = (e: React.FormEvent<HTMLFormElement>) =>- setIsFormValid(e.currentTarget.checkValidity());--<form onSubmit={...} onChange={onFormChange}>- <input required={parameter.required} />- <button type="submit" disabled={isExecuting || !isFormValid}>Create</button>-</form>-```--No hand-rolled `!name || !email` checks.--## Debugging Checklist--When an action appears to succeed but the screen doesn't update, or a call fails with a 400:--1. Log `result`, `error`, and `isExecuting` after `await execute(...)` to confirm the request actually went through and succeeded.-2. Confirm `useAction` was called with the `defineAction(...)` export imported from `actions/`. Passing the schema entry, an inline object, or a spread copy is a compile error; passing its `.id` compiles but leaves `execute` untyped and fails at runtime with "was passed to `useAction` as a raw id". Calling `defineAction(...)` inside the component compiles too, but it has no copy in the app's collection, so a deployed app throws "This action has no copy". The same error means a definition in `actions/` lacks its `copiedActionEntityId`.-3. Log the object passed to `execute({ ... })`. Every key must match a parameter `slug` from `schema.actions.<action>.parameters`; every value must match its declared `jsType`.-4. List every data view on the screen that reads the rows the action writes. Confirm each one's data hook is mounted ABOVE the action trigger so its refresh callback can be passed down.-5. Confirm the refresh callback is called AFTER `await execute(...)` AND that the refresh itself is awaited. When multiple refreshes apply, confirm they're awaited together (`Promise.all`).-6. If the schema doesn't list an action you expect, the action isn't defined on the instance or the schema file is stale. Regenerate the schema.--## Common Mistakes--- Importing `useAction` from `@metabase/embedding-sdk-react` instead of `@metabase/embedding-sdk-react/data-app`. The main entry's hook is the general SDK one and accepts anything, so the definition check never runs.-- Declaring the action anywhere but root-level `actions/`: inline at the hook, wrapped in `defineAction(...)` inside a component, or under `src/actions/`. Only definitions in `actions/` are checked against the app's collection files.-- Passing `schema.actions.<action>.id` to `useAction` instead of the `defineAction(...)` export. `execute` then accepts any `Record<string, unknown>`, typos like `{ wrongKey: 1 }` slip through, and a data app refuses the raw id at runtime with "was passed to `useAction` as a raw id".-- Forgetting to refresh after a successful action. The UI keeps rendering stale data with no error or warning.-- Rendering `"Failed"` / `"Something went wrong"` / `String(error)` instead of the real backend message. Always extract `error.data.message` / `error.data.errors` (the diagnostic the user needs is in there) and render it verbatim — see *Showing the error message*.-- Calling the refresh callback without `await`ing it. The modal dismisses or the form clears before fresh data arrives, leaving the user staring at the stale view for a beat.-- Loading data INSIDE the same component that triggers the action. The hook is below the trigger, so its refresh callback can't be wired up. Lift the data hook to a parent and hand its refresh callback down to the trigger.-- Passing raw `<input>` strings as parameter values when the slug's `jsType` is `"number"` or `"boolean"`. Coerce at the call site.-- Letting the trigger fire while a previous request is in flight. Drive `disabled={isExecuting}` from the hook.-- Prepending the action's `result` directly to a local list to skip the refresh. Server-filled defaults (auto-IDs, timestamps, computed columns, derived join columns) diverge from any client-side guess.-- Inventing an action because the user asked for behavior the instance doesn't expose. The schema is the catalog of what exists; surface the gap, don't fake the call.-- Reaching for `fetch("/api/action/...")` directly. The sandbox blocks raw network calls to the Metabase origin (raw `fetch`/XHR work only for external `allowed_hosts` declared in `data_app.yaml`); the only path to actions is `useAction`.diff --git a/skills/metabase-data-app-migrate/SKILL.md b/skills/metabase-data-app-migrate/SKILL.mddeleted file mode 100644index f117a55747f..00000000000--- a/skills/metabase-data-app-migrate/SKILL.md+++ /dev/null@@ -1,191 +0,0 @@-----name: metabase-data-app-migrate-description: Migrate an existing Metabase data app that Metabase marks Outdated (its `data_app.yaml` `version` is below the data-app contract version the installed skills and SDK target) to the current version, one upgrade at a time, with a resumable procedure. Use when Metabase shows an app as Outdated, `npm run typecheck` or `npm run build` fails after an SDK upgrade, or an existing app's `version` is behind the one the installed skills target. Not for creating an app.-metadata:- version: master------# Migrate a data app to the current contract version--A data app declares the contract version its code targets in `data_app.yaml`-(`version: N`; a manifest without the field is version 1). Metabase bumps the-version it serves only on a breaking change to that contract: the-`@metabase/embedding-sdk-react/data-app` API, the bundle factory, the manifest,-the `queries/` and `actions/` conventions, or what an app may declare. An app on-an older version is marked _Outdated_ in the admin list, hidden from every other-user, and refuses to open until it is migrated.--Migration is a walk over **upgrades**: `N -> N+1 -> ... -> M`, one upgrade at a time,-each described by a guide in `references/upgrades/`. Nothing is skipped and nothing-is remembered between sessions: the app's own files and git history carry all-the state.--## Four invariants--Every step below follows from these. Never break them.--1. **`version` is written last.** An upgrade's `version: N+1` goes into- `data_app.yaml` only after every check of that upgrade passes.-2. **One commit per upgrade, locally.** Push only after the final gates at the- target version pass. The version line never moves by more than one per commit.-3. **Compiler and build gates run only at the target version.** The installed- SDK is the target, so an app halfway through several upgrades cannot type-check- or build. Do not run them earlier and do not "fix" their failures earlier.-4. **Nothing generated is edited by hand.** `dist/` is written by- `npm run build` and `src/metabase.data.ts` by the typed-schema export, never- by you. The files of the app's collection under `collections/data_apps/`- and the entity IDs its definitions name (`savedQuestionEntityId`,- `copiedActionEntityId`) change only where an upgrade guide says so,- following the data-app guidance on writing the files of an app's- collection (use skill discovery).--## Step 0 - Locate the app and read its state--Work from the app directory, `<repo>/data_apps/<slug>/`. Resolve the repo root-with `ROOT="$(git rev-parse --show-toplevel)"`. The instance checks need the-repo-root `.env.local` credentials (`DATA_APP_MB_URL`, `DATA_APP_MB_API_KEY`).-Check them by sourcing the file in a subshell and printing only whether both are-set; never print the file or its variables. The key must belong to an admin:-the API returns `version` and `outdated` only to admins and refuses an outdated-app's metadata to everyone else, so a non-admin key cannot prove anything here.--`npm` below stands for the app's own package manager, the one whose lockfile is-committed (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`).-Never introduce a second lockfile.--Read three numbers:--```bash-# version committed at HEAD (absent line means 1)-git show HEAD:data_apps/<slug>/data_app.yaml | grep -E '^version:' || echo "version: 1"-# version in the working tree-grep -E '^version:' data_app.yaml || echo "version: 1"-# target: the highest upgrade guide shipped with this skill (no guides means 1)-ls <skill-dir>/references/upgrades/ | sed -nE 's/^v[0-9]+-to-v([0-9]+)\.md$/\1/p' | sort -n | tail -1 | grep . || echo 1-```--`<skill-dir>` is the directory this SKILL.md was loaded from.--Then decide:--| HEAD version | working tree | do |-| ------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| equals target | clean | Nothing to migrate. Say so; run the final gates only if the user asked to verify. |-| above target | any | **Stop.** There is no downgrade. Either Metabase, the SDK, and the skills are older than the app, or a bump was committed against the wrong instance (`git log -- data_apps/<slug>/data_app.yaml` shows it). Wait for the answer. |-| below target | clean | Start at _Step 1_. |-| any | dirty under `data_apps/<slug>` | A previous session was interrupted. Go to _Resuming_ first. |--## Step 1 - Preflight, once--1. Install the SDK that matches the target Metabase release with the app's- package manager (`npm install @metabase/embedding-sdk-react@<tag>` or its- equivalent); each upgrade guide names the dist-tag it was written against.- The lockfile change is committed with the final upgrade.-2. Confirm the app is template-shaped at its current version: `vite.config.ts`- is the one-liner `export default dataAppConfig()` and `src/index.tsx`- default-exports a `DataAppFactory`. If not, **Stop**: this is not a version- migration but structural drift. Offer to scaffold a fresh app under the same- slug (a separate task: use skill discovery for creating a data app) and port- `src/`, `queries/`, and `actions/` over, or to proceed at the user's risk.- Wait for the answer.-3. Read every upgrade guide from the current version to the target before editing- anything, so a later upgrade cannot surprise you halfway through an earlier one.--## Step 2 - The upgrade loop--For each `N` from the HEAD version up to `target - 1`:--1. Open `references/upgrades/v<N>-to-v<N+1>.md` and run its _Preconditions_.-2. Apply the guide's _Steps_ in order. Each step is mechanical and ends with a- **Done when** command. Run the command first: if it already passes, skip the- step; if not, apply the edit and run it again. A step's command is the only- proof it happened; never mark a step done by reading.-3. Apply the _Instance steps_, if any. Their **Done when** is an API response- from the connected Metabase, fetched with the credentials from `.env.local`:- ```bash- ( source "$ROOT/.env.local"; curl -s -H "x-api-key: $DATA_APP_MB_API_KEY" "$DATA_APP_MB_URL/api/apps/<slug>" )- ```-4. Run the guide's _Done-check summary_. Every line must print `ok`.-5. Only now set `version: N+1` in `data_app.yaml`. This is the one edit to that line.-6. If `N+1 < target`: from the repo root,- `git add data_apps/<slug> collections/data_apps && git commit -m "Migrate <slug> data app to data-app version N+1" -- data_apps/<slug> collections/data_apps`.- The pathspec keeps anything staged outside the app out of the commit.- No push, no typecheck, no build. If the user asks why, say the app cannot- compile until the last upgrade.-7. If `N+1 == target`: run _Step 3_ before committing.--Do not batch steps across upgrades. Do not touch `version` before item 5.--## Step 3 - Final gates, at the target version only--1. `npm run typecheck`. Fix failures inside the app's own source. A failure that- names an SDK symbol no upgrade guide mentions is a gap in the guides, not a user- problem: surface the exact error, say which guide should have covered it, and- stop. Otherwise, at most three fix rounds, then stop and ask.-2. `npm run check-resources`, then `npm run build`, which refuses to bundle- when the app's collection files don't back the definitions. Follow their messages;- neither calls Metabase.-3. `npm run dev`, then take the preview URL from the `Local:` line Vite prints.- The template asks for port 5174, but Vite moves to the next free port when- that one is taken, so never assume it. Open that URL, then read the- diagnostics feed once from the same origin:- ```bash- curl -s "<preview-url>/__data-app/diagnostics?startEventId=0"- ```- Expect `clients: 1` and no entry with `"alert": true`. `clients: 0` means no- preview tab is open, so an empty feed proves nothing.-4. `git status` from the repo root must show only: the upgrade edits,- `data_app.yaml`, the built bundle, the app's collection files if an upgrade changed them,- and the package lockfile if the SDK was re-pinned. Anything else inside the- app directory is a user edit; say so before committing.-5. From the repo root,- `git add data_apps/<slug> collections/data_apps && git commit -m "Migrate <slug> data app to data-app version M" -- data_apps/<slug> collections/data_apps`,- push, and tell the user to **Pull changes** under Admin > Data apps.-6. Prove it. After the pull:- ```bash- ( source "$ROOT/.env.local"; curl -s -H "x-api-key: $DATA_APP_MB_API_KEY" "$DATA_APP_MB_URL/api/apps/<slug>" )- ```- must show `"version": M` and `"outdated": false`.- A response holding only `name` and `display_name` means the key is not an- admin's: ask for one, or ask the user to read the admin list, and say the- proof is still pending. Report the command and the result. Do not claim the- migration is done without it.--## Resuming an interrupted migration--A fresh session has no memory of the previous one and needs none. Read the-three numbers from _Step 0_ and `git status --porcelain -- data_apps/<slug>`,-then:--| tree | working-tree version | meaning | do |-| ----- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| clean | equals HEAD | every finished upgrade is a commit; nothing half done | continue the loop from the HEAD version |-| dirty | equals HEAD | upgrade `HEAD -> HEAD+1` was in progress and its checks had not all passed | re-run every **Done when** of that upgrade; apply only the steps whose command fails; continue from loop item 4 |-| dirty | equals HEAD + 1 | all checks passed and the bump was written, but the commit is missing (or the final gates failed after the bump) | re-run that upgrade's _Done-check summary_ (all `ok`, or someone edited after the bump: stop and show `git diff`); if it is the target, run the final gates; commit |-| any | more than HEAD + 1, or below HEAD | an invariant was broken | **Stop.** Show `git diff -- data_apps/<slug>/data_app.yaml` and ask whether to take that one file back to HEAD and re-derive, or to stash the tree. Wait for the answer. |--Files dirty outside `data_apps/<slug>` are not yours: never `git add` them.--## Reporting--One line per upgrade, in order: `v1 -> v2: done (commit abc1234)` or-`v2 -> v3: blocked - <the exact Done-when command that fails and its output>`.-Never soften a failing check. Keep `tsc` output grouped by root cause with a-few representative diagnostics rather than pasting it whole.--## Never do--- Set or edit `version` before the upgrade's checks pass, or by more than one at a time.-- Skip an upgrade, or apply two upgrades' steps at once.-- Run `npm run typecheck` or `npm run build` before the last upgrade, or push before the final gates pass.-- Hand-edit `dist/` or `src/metabase.data.ts`, or change the app's collection files or a definition's entity ID beyond what an upgrade guide says.-- Copy a step's outcome from the previous session's chat instead of re-running its **Done when**.-- Migrate with a checklist of your own when an upgrade guide exists; when one does not exist for an upgrade you need, stop and say so.--## Upgrade guides--Guides live in `references/upgrades/`, one per upgrade, named `v<N>-to-v<N+1>.md`. They-are written by Metabase when the contract version is bumped, from the template-in `references/upgrade-guide-template.md`; `references/maintainer-checklist.md`-describes that process. A missing guide for an upgrade you need is a bug in the-skill install, not something to improvise around.diff --git a/skills/metabase-data-app-migrate/references/maintainer-checklist.md b/skills/metabase-data-app-migrate/references/maintainer-checklist.mddeleted file mode 100644index 9ad81fe3572..00000000000--- a/skills/metabase-data-app-migrate/references/maintainer-checklist.md+++ /dev/null@@ -1,42 +0,0 @@-# Maintainer checklist: bumping the data-app contract version--For Metabase engineers, not for agents migrating an app. The version is bumped-only for a change an app author must act on. Decide the category first:--| Change | Bump? | Proven by | What the upgrade guide contains |-| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------ |-| `@metabase/embedding-sdk-react/data-app` API: components, hooks, types, the bundle factory, `providerProps` | yes, after one deprecation release | `npm run typecheck` | the symbol table from the `.d.ts` diff, with replacements |-| `data_app.yaml` fields, `queries/` and `actions/` conventions, entity-ID keys, the layout of the app's collection files | yes | `npm run check-resources` and `npm run build` | mechanical steps, including every edit to the app's collection files |-| What an app may declare or run under the permission model | yes | the instance API, read by the agent with the app's API key | instance steps whose _Done when_ is an API response |-| Instance-only changes: the app group's grants, collection layout, provisioning | **no** | nothing app-side | none; ship a backend migration and make provisioning converge on the next pull |--Deprecation policy for `/data-app` exports: a rename keeps the old name for one-release as a `@deprecated` alias, wired at the fallback point in-`enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts`-(the `dataAppExports` spread), so old bundles keep running. The release that-deletes the alias bumps the contract version and ships the upgrade.--## In the bump PR--1. `enterprise/backend/src/metabase_enterprise/data_apps/config.clj`:- `supported-app-version` to `N+1`. `initial-app-version` stays 1.-2. Update `skills/metabase-data-app-setup/template/` if the contract change touches it.-3. Every e2e fixture manifest that declares a version- (`e2e/support/assets/data-apps/*/data_app.yaml`,- `e2e/support/assets/example_synced_data_apps/data_apps/*/data_app.yaml`,- `e2e/embedding-sdk-host-apps/*/data_app.yaml`): `version: N+1`.-4. `skills/metabase-data-app-migrate/references/upgrades/v<N>-to-v<N+1>.md` from- `upgrade-guide-template.md`, every section filled. Build the symbol table from- `git diff <previous-release-tag> -- resources/embedding-sdk/dist/data-app.d.ts`- after regenerating the declarations (`bun run embedding-sdk:dts:generate`).-5. Verify the guide by hand: take a fresh copy of the _previous_ release's- template, apply the guide, confirm every _Done when_ prints `ok`, then- `npm run typecheck && npm run build` pass at `N+1`. Confirm every _Done when_- also passes unchanged on the new template.-6. Remove any `@deprecated` alias kept for the previous release at the- `sandbox.ts` fallback point; that removal is the breaking change.-7. `enterprise/frontend/src/embedding-sdk-package/CHANGELOG.md`: a "Data apps- contract v<N+1>" entry linking the upgrade guide.-8. Run `./bin/test-agent :only '[metabase-enterprise.data-apps.schema-test]'`.- It fails until steps 1 and 4 agree: the upgrade guides must cover every- version from 1 up to the supported one.diff --git a/skills/metabase-data-app-migrate/references/upgrade-guide-template.md b/skills/metabase-data-app-migrate/references/upgrade-guide-template.mddeleted file mode 100644index 3ee873345bb..00000000000--- a/skills/metabase-data-app-migrate/references/upgrade-guide-template.md+++ /dev/null@@ -1,110 +0,0 @@-# Upgrade guide template--Copy this file to `upgrades/v<N>-to-v<N+1>.md` and fill every section. Delete the-guidance in angle brackets. Rules the template encodes:--- Every step is mechanical and idempotent: applying it twice is a no-op, and its- **Done when** command decides whether it is still needed.-- A **Done when** for a code step inspects the app's own tree (grep, file- presence), never compiler output: the app cannot compile until the last upgrade.- A **Done when** for an instance step is an API response.-- The symbol table is complete, types included. Derive it from the diff of- `resources/embedding-sdk/dist/data-app.d.ts` (and `index.d.ts` for main-entry- components apps use) between the two releases.-- Every command in the guide must pass unchanged on a fresh copy of the new- template, and the whole guide must take a fresh copy of the previous template- to a passing `npm run typecheck && npm run build`.--````markdown-# Data app contract v<N> -> v<N+1>--Metabase release: <x.YY> SDK tag: <YY-alpha | YY-stable> PR: <#>--## Why this is a breaking change--<One paragraph: what an app built for v<N> does on a v<N+1> Metabase without-these edits, e.g. "the bundle refuses to load because `useFoo` no longer exists-on the endowed `/data-app` export".>--## Preconditions--Run from the app directory. Every command must print `ok`.--```bash-grep -q 'export default dataAppConfig()' vite.config.ts && echo ok-grep -q 'DataAppFactory' src/index.tsx && echo ok-<upgrade-specific precondition, if any>-```--If one fails, stop: the app is not template-shaped at v<N>. See SKILL.md, Step 1.--## Removed and renamed symbols--| Symbol | Entry point | Change | Replacement |-| ---------- | ---------------------------------------- | ------------ | --------------------- |-| `oldName` | `@metabase/embedding-sdk-react/data-app` | renamed | `newName` |-| `gone` | `@metabase/embedding-sdk-react/data-app` | removed | <what to use instead> |-| `OldProps` | `@metabase/embedding-sdk-react/data-app` | type removed | `NewProps` |--Every row is a `tsc` error at v<N+1>. List types as well as values.--## Other contract changes--<Manifest fields, `queries/` and `actions/` layout, entity-ID keys, the layout of the app's collection files, factory-shape, `providerProps`, sandbox rules, what an app may declare, or "none".>--## Steps--### Step 1 - <imperative title>--Files: `src/**/*.tsx`--Before:--```tsx-import { oldName } from "@metabase/embedding-sdk-react/data-app";-```--After:--```tsx-import { newName } from "@metabase/embedding-sdk-react/data-app";-```--Notes: <edge cases; what NOT to touch>--Done when:--```bash-! grep -rqE '\boldName\b' src queries actions && echo ok-```--### Step 2 - <imperative title>--<same shape>--## Instance steps--<Steps whose effect lives in Metabase rather than in the repo, or "none". Each-ends with a **Done when** that reads the API:>--Done when:--```bash-( source "$ROOT/.env.local"; curl -s -H "x-api-key: $DATA_APP_MB_API_KEY" "$DATA_APP_MB_URL/api/apps/<slug>" ) | grep -q '"outdated":false' && echo ok-```--## Done-check summary--All of this upgrade's **Done when** commands in one block. Every line must print `ok`.--```bash-( ! grep -rqE '\boldName\b' src queries actions && echo ok )-( <step 2 command> && echo ok )-```--## After this upgrade--<Follow-ups with their exact commands, e.g. "regenerate `src/metabase.data.ts`:-<curl command>", or "nothing". If this is not the final upgrade, nothing is built.>-````diff --git a/skills/metabase-data-app-migrate/references/upgrades/README.md b/skills/metabase-data-app-migrate/references/upgrades/README.mddeleted file mode 100644index 12149d6872c..00000000000--- a/skills/metabase-data-app-migrate/references/upgrades/README.md+++ /dev/null@@ -1,9 +0,0 @@-# Upgrade guides--One file per contract-version upgrade, named `v<N>-to-v<N+1>.md`, written from-`../upgrade-guide-template.md` when Metabase bumps the data-app contract version.--The highest `<N+1>` here is the version this skill migrates to. No files means-the current version is 1 and there is nothing to migrate yet. Upgrades are never-skipped: an app at version 1 migrating to version 4 applies `v1-to-v2.md`,-`v2-to-v3.md`, then `v3-to-v4.md`, in that order, with one commit each.diff --git a/skills/metabase-data-app-routing/SKILL.md b/skills/metabase-data-app-routing/SKILL.mddeleted file mode 100644index 545aaa35da8..00000000000--- a/skills/metabase-data-app-routing/SKILL.md+++ /dev/null@@ -1,186 +0,0 @@-----name: metabase-data-app-routing-description: Add client-side routing (multiple pages) to an existing Metabase data-app project using the host-provided `DataAppRouter`, `DataAppLink`, and `useDataAppLocation` primitives. Use when the user has an existing data-app project and wants more than one page.-metadata:- version: master------# Add routing to a data-app--A Metabase data-app bundle doesn't bundle a router library — it imports three small primitives from `@metabase/embedding-sdk-react/data-app`:--| API | Purpose |-|---|---|-| `<DataAppRouter>` | Wrap the app once. Tracks the current sub-path. Auto-detects the iframe's URL prefix; bundle author writes no basename. |-| `<DataAppLink to="/customers/42">` | Internal navigation link. Renders a real `<a href>` so middle-click / cmd-click open in a new tab. |-| `useDataAppLocation()` | Returns `{ pathname, navigate }`. Use `pathname` for match-by-equality / `startsWith` rendering; use `navigate(to)` for programmatic nav. |--That's the entire surface. **No `react-router` of any version, no `<BrowserRouter>`, no `<HashRouter>`.** The API is deliberately decoupled from any router library so a future Metabase version can swap the underlying implementation without touching bundle code.--## When to use this skill--- The user has a working data-app project — scaffolded from the data-app template, so a one-liner `vite.config.ts` (`dataAppConfig()`) and an `src/index.tsx` that exports a factory already exist. The dev preview has no in-project entry: the SDK's dev preset serves it.-- The user wants the bundle to render different content at different URLs (`/overview`, `/customers/:id`).-- **Do not use this skill** to scaffold a project from scratch — it only patches an existing data-app project. If there is no project yet, stop and tell the user to start with a new data-app scaffold before adding routing.--`dataAppConfig()` already externalizes `@metabase/embedding-sdk-react/data-app`. You do NOT need to edit `vite.config.ts` to add routing — just edit `src/App.tsx` (and add more component files as needed) per the step below.--## Step 1 — Wrap `App.tsx` with `<DataAppRouter>`--Import the routing primitives normally. `<DataAppRouter>` does NOT take a `basename` prop — it auto-detects the iframe's URL prefix (`/embed/apps/<name>`) in production and resolves to no prefix in the Vite dev preview.--`App.tsx` is pure content — no `<MetabaseProvider>` here. The SDK's dev preview entry (`DataAppDevProvider`) and the production host (`DataAppProvider`) each wrap the tree in their own realm.--```tsx-import { StaticQuestion } from "@metabase/embedding-sdk-react";-import {- DataAppRouter,- DataAppLink,- useDataAppLocation,-} from "@metabase/embedding-sdk-react/data-app";--function Nav() {- return (- <nav style={{ padding: 16, borderBottom: "1px solid #e5e7eb" }}>- <DataAppLink to="/" style={{ marginRight: 16 }}>Overview</DataAppLink>- <DataAppLink to="/customers/42">Customer 42</DataAppLink>- </nav>- );-}--function Page() {- const { pathname } = useDataAppLocation();-- if (pathname === "/") {- return (- <div style={{ padding: 24 }}>- <h1>Overview</h1>- <StaticQuestion questionId={1} height={360} />- </div>- );- }-- const customerMatch = pathname.match(/^\/customers\/(\d+)$/);- if (customerMatch) {- const id = Number(customerMatch[1]);- return (- <div style={{ padding: 24 }}>- <h1>Customer #{id}</h1>- <StaticQuestion questionId={id} height={360} />- </div>- );- }-- return <div style={{ padding: 24 }}>Not found: {pathname}</div>;-}--export default function App() {- return (- <DataAppRouter>- <Nav />- <Page />- </DataAppRouter>- );-}-```--Run `yarn dev`, click the links, watch the URL bar change. Reload at `http://localhost:5174/customers/42` and the dev preview lands on the customer route directly.--## Always preselect the default (leftmost) tab on load--**If the app presents multiple tabs (or any top-level page switcher), the base path `/` MUST render the default — leftmost / first — tab's content, never a blank page, a "Not found", or an empty shell.** This is the single most common mistake: the app boots at `/`, no branch matches, and the user sees nothing until they click a tab. Don't rely on the user (or a later navigation) to select the first tab — the default tab is the initial state.--Two equivalent ways to guarantee it, depending on whether tabs are route-backed:--- **Route-backed tabs** — give `/` an explicit branch that renders the first tab, so an unmatched/base path resolves to it:-- ```tsx- const TABS = [- { path: "/", label: "Overview", render: () => <Overview /> },- { path: "/customers", label: "Customers", render: () => <Customers /> },- { path: "/reports", label: "Reports", render: () => <Reports /> },- ];-- function Page() {- const { pathname } = useDataAppLocation();- // Exact-or-prefix match; fall back to the FIRST tab so `/` (and any- // unknown sub-path) always shows the default tab, never a blank page.- const active =- TABS.find((t) => t.path !== "/" && pathname.startsWith(t.path)) ?? TABS[0];- return active.render();- }- ```--- **Local-state tabs (no routing)** — initialize the active-tab state to the first tab, so the very first render shows it:-- ```tsx- const [active, setActive] = useState(TABS[0].id); // default = leftmost tab- ```--Verify by reloading the app at its base path (`/`) with a fresh load: the leftmost tab's content must be visible immediately, and that tab must read as selected in the tab bar.--## How navigation translates to the parent URL--You don't need to do anything for this. For context:--- Bundle calls `<DataAppLink to="/customers/42">` → host's `navigate` runs `pushState` with `/embed/apps/<name>/customers/42`.-- The parent's `AppView` observes the iframe URL change and mirrors it to the parent's URL bar as `/apps/<name>/customers/42` — the `/embed` prefix is stripped because the parent's React Router route is `/apps/:name/*`, not `/embed/...`.-- Reload works because the BE serves the same `data-app.html` for every `/embed/apps/:name/*` sub-path; the iframe boots, `<DataAppRouter>` reads `window.location.pathname`, auto-detects the prefix, and starts at the right sub-path.--## What NOT to do--- **Don't add `react-router-dom`** (or any router library) to the project. The bundle doesn't need it.-- **Don't use `<BrowserRouter>` or `<HashRouter>`** inside the bundle. They run their own `setState` flow that hits the Near Membrane batching bug.-- **Don't call `window.history.pushState` directly** from inside the bundle. Use `<DataAppLink>` or `navigate` from `useDataAppLocation`.-- **Don't try to read or write the parent's URL.** The iframe's sandbox attribute blocks it by design.--## Common patterns--### Conditional render based on path--```tsx-const { pathname } = useDataAppLocation();-if (pathname === "/") return <Home />;-if (pathname.startsWith("/customers/")) return <Customer />;-return <NotFound />;-```--### Programmatic navigation (e.g. from a `<button>`)--```tsx-function OpenCustomerButton({ id }: { id: number }) {- const { navigate } = useDataAppLocation();- return <button onClick={() => navigate(`/customers/${id}`)}>Open #{id}</button>;-}-```--### Parsing path params manually--There's no built-in `useParams`. Match yourself:--```tsx-const { pathname } = useDataAppLocation();-const match = pathname.match(/^\/customers\/(\d+)$/);-if (match) {- const id = Number(match[1]);- // ...-}-```--If you find yourself doing this often, factor it into your own helper inside the bundle:--```tsx-function useCustomerIdFromPath(): number | null {- const { pathname } = useDataAppLocation();- const m = pathname.match(/^\/customers\/(\d+)$/);- return m ? Number(m[1]) : null;-}-```--## Troubleshooting--| Symptom | Fix |-|---|---|-| `<DataAppLink>` renders as plain text (no clickable link) on initial load. | The bundle hasn't finished loading and the fallback path is showing. The provider wrap is supplied automatically (the SDK dev preview's `DataAppDevProvider`, or the host's `DataAppProvider`) — don't add `<MetabaseProvider>` inside the app. The fallback resolves to a real link once the bundle is up. |-| URL changes but UI doesn't. | A `<BrowserRouter>`/`<HashRouter>` is still in the tree. Strip the router library out and use `<DataAppRouter>` / `<DataAppLink>` instead — the Near Membrane interaction with React-18 batching breaks every router that runs its own `setState` inside the bundle. |-| Middle-click on a `<DataAppLink>` does nothing. | The link uses `event.button !== 0` to skip non-left clicks; check you haven't wrapped it in another component that swallows the event. |diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.mddeleted file mode 100644index e899fc9e119..00000000000--- a/skills/metabase-data-app-semantic-layer/SKILL.md+++ /dev/null@@ -1,743 +0,0 @@-----name: metabase-data-app-semantic-layer-description: Use when building, creating, or editing data apps that should query Metabase tables and metrics through generated schema files like metabase.data.ts or *.metabase.data.ts.-metadata:- version: master------# Metabase Data App Semantic Layer--## Core Rules--Keep the semantic layer and presentation layer separate.--- All Metabase context must come from the generated schema file, usually `src/metabase.data.ts` or `src/*.metabase.data.ts` (its runtime object and the `/* metadata: {...} */` block an entry opens with when it has context to give), and the files of the app's collection must come from `npm run write-resources`. Never from Metabase YAML in the repository, and never from your own API calls.-- Do not discover data through MCP tools, create Metabase content, create tables, or edit the semantic layer while building the React UI.-- Import data app query helpers from `@metabase/embedding-sdk-react/data-app`.-- Every query is a `defineQuery(...)` named export in the root-level `queries/` directory, and every action a `defineAction(...)` named export in the root-level `actions/` directory, both beside `package.json`. Create both directories before writing the first hook call; the template ships them, each with a README. The hooks enforce this at compile time: `useMetabaseQuery`, `useMetabaseQueryObject`, and `useAction` reject an inline object, a `satisfies MetabaseQueryOptions` object, and a spread copy of a definition. The error reads `Property 'definedWithDefineQuery' is missing` (or `'definedWithDefineAction'`); the fix is always to move the object into `queries/` or `actions/` as a definition and import it, never a cast.-- Every `savedQuestionEntityId` and `copiedActionEntityId` names a file in the app's collection (see *Write every query and action into the app's collection*). Keep it through refactors and renames, never copy it to another definition, and never remove it while its file exists.-- Prefer generated schema objects over raw IDs or strings. Extract local constants for top-level table objects.-- Never hand-write `DatasetQuery`/MBQL objects in app code. Do not pass inline query objects like `{ type: "query", query: { "source-table": table.id } }`, raw `source-table` clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, `useMetabaseQuery`, or `useMetabaseQueryObject`. Prefer generated table and metric schema objects; for simple table-source queries, an explicit source reference like `{ type: "table", id: table.id }` is also valid.-- Build queries with `source: schema.tables.<name>`, generated `fields`, generated `segments`, generated `measures`, generated metrics in `aggregations`, generated metric `dimensions`, `filter(...)`, `breakout(...)`, `orderBy(...)`, and `aggregations` helpers such as `aggregations.count()` and `aggregations.sum(...)`. Do not use `source: schema.metrics.<name>`; metrics are aggregation expressions, not query sources.-- Do not use existing saved questions as `useMetabaseQuery` or `useMetabaseQueryObject` sources. Typed schemas do not expose `schema.questions` or support `question-collections`, since an app's resources can't copy existing saved questions.-- Prefer semantically rich table queries over shallow table dumps. Use curated table measures, segments, filters, and breakouts when they make the generated app more useful.-- Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows. Both belong to the static query only — the dynamic second argument cannot take them, see *Static and dynamic query parts*.-- Filter UI must default to showing data. Empty controls, "All" options, and incomplete custom ranges should produce no filter instead of blocking queries or showing a blank dashboard.-- Do not hardcode categorical filter option values. A generated schema field only proves the field exists, not which values exist; query options from Metabase at runtime using the same generated schema field that the filter applies.-- Dashboard-level filters should visibly affect every compatible card, table, KPI, and trend. If a filter can only apply to one query, make that scope obvious in the UI; do not show duplicate or no-op date controls.-- Entity filters, where the stored value is an id/key and the UI shows a label, must use a single searchable combobox. Click/focus must open the option list immediately, before typing. Query options at runtime, search labels, and store the raw value. Never render entity filters as `<select>`; plain selects are only for short closed enums explicitly provided by the user.-- Use `DateRangePopover` from `@metabase/embedding-sdk-react/data-app` for custom date ranges: it wraps the app's own trigger element and opens a Metabase-styled range calendar under it. The trigger stays the app's — style it like the other filter controls — and `useDateFormatter()` from the same entry produces its label. It ships with the SDK and needs no dependency and no CSS import. `DateRangeCalendar` is the same calendar inline, for when the app already has a container. Do not install a date picker library for a range — not `react-datepicker`, `react-day-picker`, `flatpickr`, or a UI suite's picker (`@mui/x-date-pickers`, `antd`, `rsuite`, …). Do not use native `<input type="date">` either: its placeholder and calendar popover are browser-controlled, often show `mm/dd/yyyy`, and cannot be reliably themed.-- Never build a date label with `new Date("YYYY-MM-DD")` — a date-only string parses as UTC and shows the previous day west of Greenwich. Use `formatDateRange` / `formatDate` from `useDateFormatter()`, which parse in local time and format in the instance's locale.-- Reach for a third-party date picker only for what the SDK calendar does not cover, such as single-date or date-time selection; `react-datepicker` is the default pick. Then import its stylesheet (`react-datepicker/dist/react-datepicker.css`), add small CSS overrides for the app's visual style if needed, and pass `Date | null` — never `new Date("")` or another invalid date for incomplete ranges; type strict callback parameters explicitly, such as `onChange={(date: Date | null) => ...}`.-- Date bars must include Custom last by default: duration presets, All time, then Custom. Omit Custom only when the user explicitly asks for fixed presets only or no date range control.-- Never invent aggregation or measure objects such as `{ name: "count" }` or `{ name: "sum", field: ... }`. Use generated table measures or exported aggregation helpers.-- Only render values returned by Metabase or deterministic transforms of returned values. Do not invent KPI values, trends, labels, statuses, ratings, timestamps, rankings, insights, segments, or chart series.-- Do not custom-render ambiguous business fields such as `margin`, `rate`, `score`, `percent`, `health`, `risk`, or `efficiency`. Do not add `%`, multiply by 100, color-code, or render stars unless semantic-layer units explicitly support it; use an SDK table/chart, omit the field, or ask for curation.-- Visualization data must come from Metabase through `useMetabaseQuery` or `useMetabaseQueryObject` with `InteractiveQuestion`/`StaticQuestion`. Do not hardcode chart-ready arrays, sample data, demo values, or schema-shaped mock values.-- Render charts with `InteractiveQuestion`/`StaticQuestion`. When a custom visualization is allowed instead, and which of the two to use, is decided by the setup skill's *Rendering a chart: Metabase first*.-- `useMetabaseQueryObject(...)` returns `{ query, error, isLoading }`. Pass only the `query` property as `card={{ query }}` to `InteractiveQuestion` or `StaticQuestion`; never pass the whole hook result as `card.query`.-- `useMetabaseQuery().rows` are keyed objects, not tuple arrays. Never read `row[0]` / `row[1]`, and never silence this with `as unknown as [string, number][]`, `DisplayRow`, or another tuple cast. If TypeScript says property `0` does not exist, it is catching a real bug. For typed `data.rows`, use literal keys such as `row.count` or generated field names such as `row[ordersTable.fields.createdAt.name]`. Use `data.columns` with `rawRows` or after explicitly narrowing a key; do not index typed rows with arbitrary `string` values from `data.columns`.-- Do not cast query objects to `Parameters<typeof useMetabaseQuery>[0]` or to `DefinedQuery`. That erases the generated table/metric validation and the definition contract. Validate table ownership at the definition with `defineQuery<typeof table>(...)`; the hooks take the export with no generics.-- Do not build shared filter arrays with `ReturnType<typeof filter>[]` or `push(...)`; this can collapse overload inference. Pass raw filter state between components and build each query's `filters: [...]` inline with spreads.-- Keep runtime state out of the base query in `queries/`. A clause whose value comes from a control — a selected plan, a date range, a search box — belongs in the second argument to `useMetabaseQuery`/`useMetabaseQueryObject`, not in the query. See "Static and dynamic query parts".-- Do not include `fields` in queries with `aggregations` and `breakouts`; breakouts determine grouped result columns. Use `fields` only for row-selection queries.-- Before rendering a field, verify it exists in the generated schema object and is returned by the query. Do not guess table keys, field keys, or column names from the Metabase API, business intuition, or old mock data; only use entries actually emitted in `src/metabase.data.ts`.-- Avoid unsupported freshness or operational claims such as "real-time", "live", "understaffed", or "risk" unless the returned data or curated semantic-layer definition supports them.-- Before claiming the work is done or preparing a final handoff, run a TypeScript type-only check and report the command/result. If the check fails, fix the type errors before any final summary.--## Generate Schema--If the schema file already exists and covers what the app needs, use it. Otherwise generate it.--The schema always covers the same content: the published tables of the `Library / Data` tree, the metrics of the `Library / Metrics` tree (with the tables they map), and every query action that belongs to no model, under `schema.actions`. There is no scope to choose. When the app needs a table, metric, or action the schema lacks, ask the user to publish the table to the Data library, move the metric into the Metrics library, or create the action as a query action without a model, then regenerate.--The Metabase URL and API key live in the **repo-root** `.env.local` as-`DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` (one file per repo, usually two levels up-from the app dir, not in the app dir). The key must be one in the Administrators group:-the schema answers only an admin, and any other key gets a `403`. The command below `source`s that file so-the shell substitutes the values straight into `curl` — you never read, extract,-or handle the credentials yourself.--> **Never ask the user to paste the API key into the chat, and never `cat` /-> `echo` `.env.local`** — it's git-ignored and may hold other secrets, so its-> contents must stay out of the conversation. `source` it so the shell uses the-> values without exposing them. If `$DATA_APP_MB_API_KEY` or `$DATA_APP_MB_URL` is empty-> or still set to the default `mb_replace_me` placeholder after sourcing, ask-> the user to add real values themselves, then continue.--Source the credentials from the repo-root `.env.local` and generate the schema:--```bash-ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"-if [ -z "$ROOT" ]; then- echo "Not inside the connected git repo — cd into it first." >&2- exit 1-fi--(- source "$ROOT/.env.local" 2>/dev/null- # Fail early (before curl) if either var is missing or placeholder-only.- if [ -z "$DATA_APP_MB_URL" ] || [ "$DATA_APP_MB_URL" = "mb_replace_me" ] ||- [ -z "$DATA_APP_MB_API_KEY" ] || [ "$DATA_APP_MB_API_KEY" = "mb_replace_me" ]; then- echo "Set real DATA_APP_MB_URL / DATA_APP_MB_API_KEY in repo-root .env.local" >&2- exit 1- fi- curl \- -o src/metabase.data.ts \- -H "x-api-key: $DATA_APP_MB_API_KEY" \- -H "Accept: text/typescript" \- "$DATA_APP_MB_URL/api/apps/generate/schemas"-)-```--An entry in the generated file opens with a `/* metadata: {...} */` block of JSON, before its runtime properties, when it has context to give for writing the app: such as a field's display name, description, and semantic type, a table's database, schema, and real name, and a metric's description, filters, and whether it's verified. It is a comment, so it never reaches the bundle and the app never imports it; read it, and never edit or reformat the file.--After a successful export, verify that the schema contains every entity needed for the requested app. If any are missing, tell the user what to publish to the library before building the UI.--If schema generation fails, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing ids, names, and message when present.--## Write every query and action into the app's collection--Every query and action a data app runs goes through a copy in the app's own collection: read access to that collection lets viewers run the app's cards, but they see data only from tables they can already read, since the app grants the collection, not the tables. Declare each one as a named export in a root-level directory beside `package.json` — `queries/` for `defineQuery(...)`, `actions/` for `defineAction(...)`. The CLI scans only those two directories, so a definition under `src/queries/`, `src/actions/`, or any other source directory is never seen. Discovery covers `.js`, `.jsx`, `.ts`, `.tsx`, `.cjs`, `.cts`, `.mjs`, and `.mts`.--```ts-import { defineAction, defineQuery } from "@metabase/embedding-sdk-react/data-app";-import schema from "../src/metabase.data";--// queries/revenue.query.ts-export const RevenueQuery = defineQuery({- savedQuestionEntityId: "<entity ID of its saved question>",- source: schema.tables.orders,-});--// actions/orders.action.ts-export const CreateOrder = defineAction({- copiedActionEntityId: "<entity ID of its copied action>",- action: schema.actions.createOrder,-});-```--Each definition is backed by serialized Metabase YAML that `npm run write-resources` writes into the repository's `collections/data_apps/` directory, where the collections of the `data-apps` namespace live, as Metabase exports them. Nothing changes in Metabase until the repository is pulled; the pull loads the files into the app's collection as serialized content, like everything else the repository holds, so write the files instead of creating anything in that collection by hand. From the app's directory, `data_apps/<slug>/`, that directory is `../../collections/data_apps/`.--```-data_apps/<slug>/data_app.yaml collection: <entity ID of the app's collection>-collections/data_apps/<collection>.yaml the app's collection, a root collection of the data-apps namespace-collections/data_apps/<collection>/<name>.yaml a saved question per query, copies of the metrics they use, and a copy of each action the app runs-```--`<collection>` is the collection's name as Metabase slugs it: `data_app__sales` for `Data App: Sales`. The pull and the CLI find the app's files by content, not by path: the collection whose `entity_id` the manifest names, and the cards and actions whose `collection_id` is it.--Metabase writes every file of the app's collection: setting up the app writes the collection's own file, and `npm run write-resources` the rest. Never write or edit one yourself. Generate every new entity ID with `npx representations generate-entity-id` (`--count <n>` for several), from the app's own dev dependencies; never invent one, reuse one from another app, or keep a source entity's ID on its copy.--1. **Collection.** Setting up the app writes the collection's file under `collections/data_apps/` and names it in `data_app.yaml` as `collection: <id>`, through `POST /api/apps/generate/app` (see the setup skill). The pull refuses a manifest without `collection:`, and one whose collection has no file in the repository.--2. **Entity IDs.** Every `defineQuery` carries a `savedQuestionEntityId`, the entity ID of its saved question, and every `defineAction` a `copiedActionEntityId`, the entity ID of its copy, generated with `npx representations generate-entity-id`. The command refuses a definition without one and names it.--3. **Write the files.** `npm run write-resources` sends the app's definitions to Metabase, using `DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` from the repo-root `.env.local`, and regenerates the app's collection folder (`collections/data_apps/<collection>/`): it deletes the cards and actions the collection held and writes what comes back, each file with the text a Metabase export writes. No pull is needed first. It writes: a saved question per query (named after the export, in the app's collection, with its `savedQuestionEntityId`, holding the query the dev preview runs), a copy of each action the app runs, and a copy of each metric a query aggregates, which the question already references. It prints a `Wrote <path>` line per file.-- The command answers only an admin, so the API key must be one in the Administrators group. With any other key it fails with `403`: stop and tell the user, and never write the files another way.-- An item that can't be built or copied fails the whole command with its error, and nothing is written or deleted (for example a field the query names that doesn't exist, an action that belongs to a model, or a metric or action that reads another card); stop and tell the user. Run it again after any definition changes; it regenerates the folder.--Never write or edit a saved question, an action copy or a metric copy yourself, never copy one from YAML (not the repository's exported collections or its top-level `actions/`, not another app's collection, not git history), and never from your own API calls: a hand-written file differs from what Metabase serializes, and the query is what the dev preview ran, so any difference changes what production runs.--If a source the app needs isn't in `src/metabase.data.ts`, stop and tell the user; never write a replacement from scratch. After a source changes in Metabase, run `npm run write-resources` again.--Run `npm run check-resources`, and fix what it reports by changing the definitions or `data_app.yaml` and running `npm run write-resources` again, never by editing a generated file. It fails, listing every problem, when the definitions and the files of the app's collection disagree: a manifest naming no collection or one without a file, a definition without its entity ID or naming one no file holds, a query naming a card that isn't a question, or a question or action no definition names; then it validates every Metabase YAML file in the repository, the app's collection files included, against the format's schema. `npm run build` runs the first check. `write-resources` removes a metric copy once nothing uses it. `check-resources` never calls Metabase. The next pull validates everything again, and refuses the app's resources with a message naming the file, shown on the Data apps admin page. Fix the definition or source it names, run `npm run write-resources`, and push again.--Pass the definition itself to the hook and let the SDK resolve what runs — a production build runs the copy, while the dev preview runs the authored table or action, so an app works before its resources exist:--```ts-const { data } = useMetabaseQuery(RevenueQuery, {- filters: [filter(RevenueQuery.source.fields.status, "=", selectedStatus)],-});--const { execute, isExecuting, error } = useAction(CreateOrder);-```--Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, `savedQuestionEntityId`, `copiedActionEntityId`, or a hand-built `{ source: { type: "card", id } }`, and never spread a definition into a new object. Each defeats the swap; the authored ids also bypass the permission boundary. TypeScript rejects most of these: the hooks accept only what `defineQuery`/`defineAction` returned, so an inline object, a `satisfies`-typed object, a spread copy, and `schema.actions.<action>` all fail to compile. When `tsc` reports `Property 'definedWithDefineQuery' is missing` or `Property 'definedWithDefineAction' is missing`, the argument is not a definition: move it into `queries/` or `actions/` and import the export. Do not silence it with a cast or by wrapping the inline object in `defineQuery(...)` at the call site, which compiles but is never backed by a saved question. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — they are baked into the saved question, so don't apply them again outside it, and put runtime clauses in the hook's second argument (see *Static and dynamic query parts*). `useAction` needs no generics: the definition types `execute`'s parameters and `result`.--Wire `package.json` with `"write-resources": "embedding-sdk-react data-apps write-resources"`, `"check-resources": "embedding-sdk-react data-apps check-resources && representations validate-schema --folder ../.."` (with `@metabase/representations` as a dev dependency), and `"build": "vite build"`. After adding, changing, renaming, or removing any definition, run `npm run write-resources`, then `npm run check-resources` and `npm run build`. Do not test or hand off the app until `npm run build` succeeds. Commit `data_app.yaml`, the app's files under `collections/data_apps/`, and the definitions together; the app picks them up when Metabase pulls the repository.--## Standard pattern--Two files per query: the definition in `queries/`, the hook call in the component. The examples from here on leave out `savedQuestionEntityId` to stay short; every real definition carries it (see *Write every query and action into the app's collection*).--```ts-// queries/orders.query.ts-import {- aggregations,- breakout,- defineQuery,- filter,- orderBy,-} from "@metabase/embedding-sdk-react/data-app";-import schema from "../src/metabase.data";--const ordersTable = schema.tables.orders;--export const PaidRevenueByMonth = defineQuery({- source: ordersTable,- filters: [- ordersTable.segments.completed,- filter(ordersTable.fields.status, "=", "paid"),- ],- aggregations: [aggregations.sum(ordersTable.fields.amount)],- breakouts: [breakout(ordersTable.fields.createdAt, { unit: "month" })],- orderBys: [orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" })],- limit: 100,-});-```--```tsx-// src/pages/Overview.tsx-import { useMetabaseQuery } from "@metabase/embedding-sdk-react/data-app";-import { PaidRevenueByMonth } from "../../queries/orders.query";--const { data, isLoading, error } = useMetabaseQuery(PaidRevenueByMonth);-```--`useMetabaseQuery(...)` infers typed row data from the definition, so write no generics on the hook. To check table ownership of fields, segments, and measures, put the generic on the definition: `defineQuery<typeof ordersTable>({ ... })`. Leave it off selected-field queries when you need precise row keys from `data.rows`. The recipes below show the object passed to `defineQuery`; each one is an export in `queries/`, never an argument written at the hook.--**Call each schema entry at most once per render tree.** Multiple `useMetabaseQuery` calls on the same `questionId` (or same `tableId` + identical filters/measures/breakouts) mount independent subscriptions, fire duplicate queries, and let consumers disagree mid-load. Lift the call to the highest component that needs the data; pass `data` / `isLoading` / `error` down as props. Different ids — or the same id with different filters / breakouts — are different data sources; call them separately.--Use keyed schema objects:--- Tables: `source: schema.tables.<table>`-- metrics: `schema.metrics.<metric>` inside `aggregations`-- Fields: `schema.tables.<table>.fields.<field>`-- Segments: `schema.tables.<table>.segments.<segment>`-- Measures: `schema.tables.<table>.measures.<measure>`-- metric dimensions: `schema.metrics.<metric>.dimensions.<group>.<dimension>`--Do not pass raw dimension strings like `"created_at"` or `"segment"`.--## Static and dynamic query parts--Both query hooks take an optional second argument: the clauses that change while the app runs.--```ts-// revenue.query.ts — static, and identical on every render-const orders = schema.tables.orders;--export const RevenueQuery = defineQuery({- source: orders,- aggregations: [aggregations.sum(orders.fields.total)],- breakouts: [- breakout(orders.fields.createdAt, { unit: "month" }),- breakout(orders.fields.plan),- ],-});--// the component supplies only what the UI changes-const { data } = useMetabaseQuery(RevenueQuery, {- filters: plan === null ? [] : [filter(orders.fields.plan, "=", plan)],-});-```--Split them this way even when nothing appears to depend on it: the first argument must be identical on every render, and only the second may vary with runtime state.--The dynamic clauses run as their own stage, so they see the **result columns** of the static query, not its source table. That is why `plan` is a breakout above: a control that filters on a source column only works if that column survives into the result. If it does not, add it as a breakout, or leave the static query unaggregated. Likewise, filter an aggregated static query on `count`/`sum`, not on the fields behind them.--**Segments and measures belong to the static part only.** They are defined against a table, and the dynamic stage has no table — so `filters: [orders.segments.completed]` and `aggregations: [orders.measures.revenue]` are rejected, at compile time and again at runtime. This is the one place the usual "prefer the curated definition" rule does not apply.--Put the curated definition in the static query where it resolves, and let the dynamic clause work on what came out:--```ts-export const CompletedOrders = defineQuery({- source: orders,- filters: [orders.segments.completed], // the segment resolves here- aggregations: [orders.measures.revenue],- breakouts: [breakout(orders.fields.plan)],-});--const { data } = useMetabaseQuery(CompletedOrders, {- // a result column, not a segment or measure- filters: plan === null ? [] : [filter({ type: "column", name: "PLAN" }, "=", plan)],-});-```--If a control must switch a segment on and off, that is a choice between static queries, not a dynamic clause: define one query per state and pick the query, or express the same condition as a filter on a result column.--Do not remove `savedQuestionEntityId` if you find it on a query object, or `copiedActionEntityId` on an action definition. Each names the definition's file in the app's collection — see *Write every query and action into the app's collection*.--## Table query recipes--For a table query, pass the generated table object as `source`:--```ts-// queries/records.query.ts-const recordsTable = schema.tables.records;--export const RecordStatuses = defineQuery({- source: recordsTable,- fields: [recordsTable.fields.id, recordsTable.fields.status],-});-```--For grouped table summaries, include at least one aggregation:--```ts-export const ActiveAmountByMonth = defineQuery({- source: recordsTable,- filters: [- recordsTable.segments.activeRecords,- filter(recordsTable.fields.amount, ">", 100),- ],- aggregations: [recordsTable.measures.totalAmount],- breakouts: [breakout(recordsTable.fields.createdAt, { unit: "month" })],- orderBys: [orderBy(recordsTable.fields.createdAt, "desc", { unit: "month" })],-});-```--For basic aggregations without a curated measure, use the `aggregations` helpers:--```ts-export const AmountByCategory = defineQuery({- source: recordsTable,- aggregations: [- aggregations.count(),- aggregations.sum(recordsTable.fields.amount),- ],- breakouts: [breakout(recordsTable.fields.category)],-});-```--When a query uses the same helper more than once, give each one a `name`. The name becomes the result column's name and the row key, it is typed, and it is how `orderBy(...)` and runtime clauses refer to that aggregation. Without names, the columns come back as `sum`, `sum_2`, and so on, and sorting or filtering by one of them fails:--```ts-const totalAmount = aggregations.sum(recordsTable.fields.amount, {- name: "total_amount",-});-const totalTax = aggregations.sum(recordsTable.fields.tax, {- name: "total_tax",-});--export const TaxByCategory = defineQuery({- source: recordsTable,- aggregations: [totalAmount, totalTax],- breakouts: [breakout(recordsTable.fields.category)],- orderBys: [orderBy(totalTax, "desc")],-});-// Rows are keyed `total_amount` and `total_tax`.-```--Table fields, segments, measures, filters, breakouts, and orderBys must come from the queried table. Use `defineQuery<RecordsTable>({ ... })` when you want TypeScript to validate that ownership at the definition.--## metric aggregation recipes--For a metric-backed query, pass the generated table object as `source` and the generated metric object in `aggregations`:--```ts-// queries/revenue.query.ts-const ordersTable = schema.tables.orders;-const revenueMetric = schema.metrics.revenue;--export const Revenue = defineQuery({- source: ordersTable,- aggregations: [revenueMetric],-});-```--Use generated metric dimensions for filters and breakouts in queries that aggregate the owning metric. Dimensions from the metric's source table work directly. Dimensions from related tables also work when the generated field includes `sourceFieldId`; prefer those related-table dimensions for readable labels instead of grouping by raw foreign key IDs:--```ts-export const PaidRevenueByMonthAndFranchise = defineQuery({- source: ordersTable,- aggregations: [revenueMetric],- filters: [filter(revenueMetric.dimensions.orders.status, "=", "paid")],- breakouts: [- breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" }),- breakout(revenueMetric.dimensions.franchises.name),- ],- orderBys: [- orderBy(revenueMetric.dimensions.orders.createdAt, "desc", {- unit: "month",- }),- ],-});--// Prefer readable related-table dimensions when available.-breakout(revenueMetric.dimensions.franchises.name);--// Avoid raw FK IDs when the related-table dimension exists.-breakout(revenueMetric.dimensions.orders.franchiseId);-```--Queries backed by metrics can include helper aggregations over generated metric dimensions. They can also use compatible saved Segments and Measures from the table source when the generated schema exposes them:--```ts-export const CompletedRevenueByStatus = defineQuery({- source: ordersTable,- filters: [schema.tables.orders.segments.completed],- aggregations: [- revenueMetric,- schema.tables.orders.measures.totalRevenue,- aggregations.sum(revenueMetric.dimensions.orders.amount),- ],- breakouts: [breakout(revenueMetric.dimensions.orders.status)],-});-```--A metric aggregation must belong to the table source. Do not use source-card metrics in table-source queries. Generated metric dimensions are scoped to their owning metric: if a query uses `revenueMetric.dimensions.*` in filters, helper aggregations, breakouts, or orderBys, it must also include `revenueMetric` in `aggregations`. Do not use metric dimensions as standalone table fields for unrelated `count()` or table-measure queries. Generated metric dimensions must also resolve to the table source. Use `defineQuery<typeof ordersTable>({ ... })` when you want TypeScript to validate that at the definition.--## SDK-rendered views--Table fields, segments, measure aggregations, and metric aggregations must come from the queried table. Generated metric dimensions used in filters, helper aggregations, breakouts, and orderBys must resolve to the queried table and belong to a metric included in the same query's `aggregations`.-When table queries use `fields`, `segments`, `aggregations`, `breakouts`, or `orderBys`, let `defineQuery` infer the shape, or write `defineQuery<typeof recordsTable>` when ownership validation matters more than precise result-row keys.--## Interactive Metabase Views--Whether an element is an SDK question at all — and whether it is `StaticQuestion` or `InteractiveQuestion` — is decided in the data-app setup skill (*Rendering a chart: Metabase first*). Once it is: declare the query in `queries/`, resolve it with `useMetabaseQueryObject(TheQuery)`, then pass the result through the SDK question component's `card` prop.--`useMetabaseQueryObject` supports generated table queries, including metric aggregations. Use `useMetabaseQuery` when custom React needs direct row data; use `useMetabaseQueryObject` when Metabase should render or manage the visualization. Do not pass generics to `useMetabaseQueryObject`; it returns `{ query, error, isLoading }`, not query result rows.--The examples under *Rendering With SDK Components* use `return null` for minimal loading and error handling. In a real app, render the app's existing loading or error UI there. Passing `card={{ query }}` is safe while `query` is `null`; do not pass the full `{ query, error, isLoading }` hook result as `card.query`.--When wrapping `useMetabaseQueryObject` in a reusable chart/card component, destructure and render `error`; do not read only `{ query }`, because query-construction failures otherwise look like endless loading. Calling the hook inside that child component is valid React. Do not call hooks directly inside loops, conditions, or callbacks in the parent component.--Wrong/right pattern:--```tsx-const trendQuery = useMetabaseQueryObject(TrendQuery);-<InteractiveQuestion card={{ query: trendQuery }} />; // wrong--const { query: trendQuery } = useMetabaseQueryObject(TrendQuery);-<InteractiveQuestion card={{ query: trendQuery }} />; // right-```--Hook typing:--- Both hooks take a `defineQuery` export imported from `queries/` and nothing else; an inline object is a compile error. Write no generics on the hooks.-- `useMetabaseQuery(...)` infers typed row data from the definition. Put `defineQuery<typeof table>` on the definition when ownership validation matters.-- `useMetabaseQueryObject(...)` returns `{ query, error, isLoading }`. Pass the `query` property to `card={{ query }}`.-- Do not use `as Parameters<typeof useMetabaseQuery>[0]` or `as DefinedQuery` to quiet query typing errors. The first hides invalid table fields, metric aggregations, and breakouts; the second hides a query without a saved question, which fails in production.--The basic prop contract is:--- Generated table query, including metric aggregations: `<StaticQuestion card={{ query }} />`-- Full interactive question: `<InteractiveQuestion card={{ query }} />`--When you need the set of SDK-supported question displays, do not copy a local list. In generated apps, search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for the exact declaration `declare const cardDisplayTypes: readonly [...]` and use that tuple as the source of truth. Do not read the whole declaration file into context.--Always pass SDK-rendered ad hoc questions with a `card` object. Start with `card={{ query }}` when the user has not asked for a specific chart type and Metabase defaults can infer a reasonable display from the query. Use `card={{ query, visualization }}` when the user request or design calls for a specific chart type, such as a pie chart for a distribution, but does not ask for setting-level customization. Add `visualizationSettings` only when the user explicitly asks for a setting-level presentation change, such as hiding or renaming an axis label, showing value labels, stacking bars, adding a goal line, ordering table columns, showing pie totals/labels, or controlling series/slice order. Search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for `export declare type MetabaseCard`, the relevant `*VisualizationSettings` type, and any setting key you plan to use. Read the JSDoc comments attached to those declarations, then use the TypeScript declarations as the source of truth for legal `visualization` and `visualizationSettings` combinations. Build the query with `useMetabaseQueryObject`; do not call internal query resolution helpers, cast through `any`, or hardcode settings from memory.--For lightweight descriptions of the exposed settings and when to use them, read [references/visualization-settings.md](references/visualization-settings.md). Treat that file as guidance only; the installed SDK declaration decides what is legal.--Before writing a `card`, check `node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts` for the `useMetabaseQueryObject` return type. Destructure the returned `query` and use that value in `card.query`; for configured cards, type the object with `satisfies MetabaseCard`. If TypeScript reports duplicate opaque `DatasetQuery` symbols, do not force a cast; update the SDK package before using `card`.--Do not invent alternate prop names for generated queries or visualization settings. If the SDK type says a prop does not exist, believe it and use the documented `card` prop shape.--When `useMetabaseQuery` is needed, map typed rows into an explicit local view model using named properties before rendering:--```ts-const orderedAtKey = ordersTable.fields.orderedAt.name;--const chartRows = (data?.rows ?? []).map((row) => ({- label: String(row[orderedAtKey] ?? "Unknown"),- value: row.count,-}));-```--If the result key only comes from `data.columns` at runtime, use `rawRows` with the matching column position, or narrow the key to a literal before indexing `data.rows`.--### Rendering With SDK Components--Chart only, without the toolbar:--```tsx-import {- InteractiveQuestion,- StaticQuestion,- type MetabaseCard,-} from "@metabase/embedding-sdk-react";--import { useMetabaseQueryObject } from "@metabase/embedding-sdk-react/data-app";--import { AmountByMonth } from "../../queries/events.query";--const { query, isLoading, error } = useMetabaseQueryObject(AmountByMonth);--if (error) {- return null;-}--if (isLoading || !query) {- return null;-}--return (- <InteractiveQuestion card={{ query }}>- <InteractiveQuestion.QuestionVisualization height="500px" />- </InteractiveQuestion>-);-```--Configured SDK visualization:--```tsx-// queries/events.query.ts-export const TotalAmountByMonth = defineQuery({- source: eventsTable,- aggregations: [eventsTable.measures.totalAmount],- breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],-});--// the component-const { query, isLoading, error } = useMetabaseQueryObject(TotalAmountByMonth);--if (error) {- return null;-}--if (isLoading || !query) {- return null;-}--const trendCard = {- query,- visualization: "bar",- visualizationSettings: {- "graph.show_values": true,- "graph.y_axis.title_text": "Total amount",- },-} satisfies MetabaseCard;--return (- <InteractiveQuestion card={trendCard}>- <InteractiveQuestion.QuestionVisualization height="500px" />- </InteractiveQuestion>-);-```--## Filters And Breakouts--Use helpers because they give better autocomplete and shorter errors.--```ts-filter(ordersTable.fields.quantity, ">", 0);-filter(ordersTable.fields.status, "contains", "paid");-filter(ordersTable.fields.quantity, "between", [10, 20]);-filter(ordersTable.fields.status, "not-empty");--breakout(ordersTable.fields.createdAt, { unit: "month" });-breakout(ordersTable.fields.amount, {- binning: { strategy: "num-bins", numBins: 10 },-});-breakout(ordersTable.fields.state);--orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" });-```--Do not hand-write `orderBys` object literals such as `{ field, direction }` or `{ fieldId, direction }`; use `orderBy(...)`. When ordering the same date field used by a date breakout, pass the same `unit` to both `breakout(...)` and `orderBy(...)`.--For top-N grouped summaries, order by the aggregation result, not the raw source field. Store the aggregation helper in a local constant and pass that same constant to both `aggregations` and `orderBy(...)`:--```ts-// queries/inventory.query.ts-const avgQuantity = aggregations.avg(inventoryTable.fields.quantityOnHand);--export const TopIngredientsByQuantity = defineQuery({- source: inventoryTable,- aggregations: [avgQuantity],- breakouts: [breakout(inventoryTable.fields.ingredient)],- orderBys: [orderBy(avgQuantity, "desc")],- limit: 15,-});-```--For user-selectable sorting, the sort is runtime state, so it belongs in the hook's second argument. Build a typed map of allowed generated fields instead of indexing the whole `fields` object:--```ts-type SortKey = "revenue" | "orders";-type ScorecardTable = typeof scorecardTable;--type ScorecardField = ScorecardTable["fields"][keyof ScorecardTable["fields"]];--const sortFields = {- revenue: scorecardTable.fields.netRevenue,- orders: scorecardTable.fields.orders,-} satisfies Record<SortKey, ScorecardField>;--const { data } = useMetabaseQuery(Scorecard, {- orderBys: [orderBy(sortFields[sortKey], "desc")],-});-```--`Scorecard` is the unaggregated `defineQuery({ source: scorecardTable })` export in `queries/`; its source fields survive into the result, so the dynamic stage can order by them.--For metric queries, pass generated metric dimensions to `filter(...)` and `breakout(...)`:--```ts-filter(revenueMetric.dimensions.orders.status, "=", "paid");-breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" });-```--Filter operator rules:--- string: `=`, `!=`, `contains`, `does-not-contain`, `starts-with`, `ends-with`, `is-empty`, `not-empty`, `is-null`, `not-null`-- number: `=`, `!=`, `>`, `>=`, `<`, `<=`, `between`, `is-null`, `not-null`-- date: `=`, `!=`, `>`, `>=`, `<`, `<=`, `between`, `time-interval`, `is-null`, `not-null`-- boolean: `=`, `is-null`, `not-null`--Only date dimensions can use `unit`. Non-date dimensions can be used as breakouts without `unit`; numeric dimensions can use `binning`.--Segments are already filters:--```ts-filters: [- schema.tables.records.segments.activeRecords,- filter(schema.tables.records.fields.amount, ">", 100),-];-```--Use curated segments first when they exactly match the product intent. Use `filter(...)` when the UI needs a threshold, category, date range, text match, boolean condition, or other narrowing that is not already represented by a curated segment.--## Filter UI Patterns--When the user asks for custom filters, build normal React controls that feed semantic query filters.--Before implementing filters, create a filter contract for the visible dashboard. At minimum, identify:--- For each filter, name the runtime query that provides its options.-- For each filter, name the raw value used in `filter(...)`.-- For each card, table, KPI, and trend, name the generated table field or metric dimension that can receive that filter.-- If a filter only applies to one section, keep it section-scoped or omit it from the global filter bar.-- If a page needs a different date field such as `snapshotDate`, use one visible date control for that page.-- KPI/detail pairs that describe the same concept should use the same relevant filters.--Use the detailed checklist in `references/filter-ui-patterns.md` for filter state rules, runtime categorical options, stale option reset, searchable controls, and custom date-picker implementation.--For the common memoized date/category filter shape:--```tsx-type DatePreset = "30d" | "90d" | "custom" | "all";--const [datePreset, setDatePreset] = useState<DatePreset>("all");-const [customRange, setCustomRange] = useState<[string | null, string | null]>([- null,- null,-]);-const [status, setStatus] = useState("all");--const dateRange = useMemo((): readonly [string, string] | null => {- if (datePreset === "all") {- return null;- }-- if (datePreset === "custom") {- const [start, end] = customRange;- return start && end ? [start, end] : null;- }-- return getPresetDateRange(datePreset);-}, [datePreset, customRange]);--const orderFilters = useMemo(- () => [- ...(dateRange- ? [filter(ordersTable.fields.createdAt, "between", dateRange)]- : []),- ...(status === "all"- ? []- : [filter(ordersTable.fields.status, "=", status)]),- ],- [dateRange, status],-);-```--`customRange` above is what `<DateRangePopover value={customRange} onChange={setCustomRange}>` stores, so there is nothing to convert. When a fallback picker's state uses `Date | null`, convert selected dates with a local `YYYY-MM-DD` formatter before passing them to `filter(..., "between", range)`. Do not use `date.toISOString().split("T")[0]` for local date filters.--## Result Shape And Charts--- Prefer keyed `data.rows`.-- Never treat `data.rows` as positional arrays. Do not use `row[0]`, `row[1]`, `DisplayRow`, or tuple casts for `useMetabaseQuery` row objects.-- Inspect `data.columns` before mapping low-level `rawRows`, but do not use arbitrary `data.columns[].name` strings to index typed `data.rows`.-- Runtime row objects are keyed by returned Metabase column names, usually `column.name` such as `total_amount` or `average_score`. Do not assume generated schema keys like `totalAmount` or `averageScore` are runtime row keys.-- For generated field references, the React property path and runtime result key can differ: `schema.tables.orders.fields.orderedAt.name` might be `ordered_at`. Use `row[ordersTable.fields.orderedAt.name]`, `row.count`, or `data.columns` metadata instead of guessing `row.orderedAt`.-- Treat row values as nullable. Guard before calling number/string methods such as `toFixed`, `toLocaleString`, or string transforms.-- Use `rawRows` only for known positional shapes.-- Aggregation columns may be named `count`, `sum`, or `avg`; match metadata when needed.-- If a query has several helper aggregations of the same kind, such as multiple `aggregations.sum(...)` calls, name each one (`{ name: "..." }`) and read the rows by those names. Never depend on generated names like `sum_2`.-- Grouped queries can include a `null` breakout bucket. Render it as `"Unknown"` or filter it out deliberately.-- Time-series charts need multiple ordered buckets. Do not fake sparklines for scalar or one-point results.-- Multi-series charts with different units or magnitudes need separate axes or normalization.-- Format user-facing values: currency to at most 2 decimals, counts as whole numbers, dates as readable labels.-- Do not render ambiguous derived business values unless the semantic layer description or inspected sample values make the meaning and units obvious.-- Empty results are distinct from loading. After `isLoading` is false, render a clear empty state instead of leaving a skeleton or blank KPI.--## Presentation Guidance--Prefer Metabase-rendered panels for chart-shaped and table-shaped data. The React app may group, sort, format, and derive display-only values from `data.rows` when a custom panel is justified, but do not make custom panels the default.--Good transforms:--- Group rows for summaries.-- Sort and slice rows for ranked lists only when a custom list is clearly better than a Metabase row/bar/table visualization.-- Pick chart types from actual data shape, and prefer Metabase `bar`, `line`, `area`, `row`, `combo`, `pivot`, and `table` displays before writing custom chart code.-- Show loading, error, and empty states.-- Bound dense result displays. Tables, alert lists, logs, and ranked lists should use a top-N slice, grouping, pagination, or a fixed/max-height scroll area so a large result set cannot stretch the entire page.--When a page feels like a raw table browser, look for schema-backed ways to enrich it:--- Use segments for curated subsets like active, completed, overdue, high-priority, or needs-attention records.-- Use measures for curated aggregations instead of recalculating everything ad hoc in React.-- Use metrics when the schema exposes a curated metric aggregation for the page's core business question.-- Use filters to focus the query on the UI's intent.-- Use breakouts to create trends, category comparisons, and grouped summaries.-- If the enriched result is still a sortable/drillable table, render it with SDK visualization components instead of rebuilding table behavior in React.--Avoid manual classification when the semantic layer already has the concept. Prefer curated segments, fields, or measures over string matching, threshold heuristics, or category reconstruction in React.--If no curated schema entry supports the intended UI, leave the section out or ask for semantic-layer curation. Do not keep mock data or placeholder analytics in the finished app.--## Final Checks--- Run `npm run typecheck`. `Property 'definedWithDefineQuery' is missing` or `Property 'definedWithDefineAction' is missing` means a hook received something other than a `queries/` or `actions/` export; move the object there and import it.-- Search touched files for `useMetabaseQuery(`, `useMetabaseQueryObject(`, and `useAction(`. The first argument must be an identifier imported from `queries/` or `actions/`; a `{`, a `defineQuery(`, a `defineAction(`, or a spread there is wrong even when it compiles. The second argument of the query hooks is the dynamic object and is written inline.-- Confirm `queries/` and `actions/` sit beside `package.json`, not under `src/`, and that every definition the app renders lives there.-- Confirm every definition has its entity ID, and run `npm run write-resources`, then `npm run check-resources` and `npm run build`; both fail when the app's collection files no longer back the definitions.-- Keep TypeScript diagnostics compact in the chat or handoff. Use the full output locally to fix the app, but report grouped root causes and only a few representative diagnostics instead of pasting the entire `tsc` output.-- Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.-- Search touched files for `row[0]`, `row[1]`, `row.orderedAt`, `row.orderDate`, `as unknown as`, `DisplayRow`, `<select`, `margin`, `rate`, `score`, `percent`, `%`, `* 100`, and `.toFixed`; fix positional rows, result-key guesses, entity `<select>` filters, and unsupported business-field interpretations.-- Verify every date preset bar includes Custom last unless explicitly omitted, every visible date filter affects the current page, and no page shows duplicate date filters for one scope.-- Verify `data_app.yaml` points at the built bundle path and that the bundle path is tracked by git.-- For every visible filter, verify "All" maps to no filter, selected values come from runtime query results, and each non-All option changes every card it claims to affect.--## Common Mistakes--- Creating or searching for Metabase content during app building. The files of the app's collection are written by `npm run write-resources`, never created in Metabase.-- Copying a metric or action from Metabase YAML in the repository (its exports, its top-level `actions/`, or git history), or from your own API calls, instead of letting `npm run write-resources` write it.-- Writing or editing a saved question, action copy or metric copy yourself instead of running `npm run write-resources`.-- Writing the query object at the hook call instead of exporting it from `queries/` with `defineQuery`, or the action at `useAction` instead of from `actions/` with `defineAction`. Both are compile errors now; the fix is the directory, not a cast.-- Wrapping the inline object in `defineQuery(...)` or `defineAction(...)` at the call site. It compiles, but it is never backed by a saved question, so it is refused in production.-- Putting definitions under `src/queries/` or `src/actions/`, where the CLI never looks.-- Importing older hooks instead of `useMetabaseQuery`.-- Copying raw numeric IDs into constants instead of using generated schema objects.-- Inventing ad hoc measure objects such as `{ name: "count" }` or `{ name: "sum", field: fieldId }`.-- Passing raw strings for table fields.-- Adding lookup helpers instead of using keyed generated schema objects.-- Inventing SDK component prop names instead of using `query` for generated table queries.-- Mixing fields, segments, or measures from unrelated tables.-- Passing a segment or measure to the dynamic second argument, where only result columns resolve.-- Adding a filter UI that sends empty values instead of omitting the filter.-- Hardcoding categorical filter values instead of querying the runtime values from Metabase.-- Displaying entity names but filtering by those names when a stable ID is available.-- Applying a dashboard-level filter to only one KPI while related charts and tables ignore it.-- Showing a global Date Range plus a page-specific Snapshot Date where one date filter has no effect.-- Letting a KPI and its detail table use different date or category filters without explaining the difference.-- Rendering `Margin`/`Rate`/`Score`/`Health` with invented `%`, stars, colors, or thresholds.-- Shipping a date preset bar with no Custom range option, or Custom before All time.-- Charting opaque IDs such as `franchise_id` when a user-facing name is available.-- Rendering an entity filter in a plain `<select>`, even if the current runtime option list is short.-- Reaching for native `<input type="date">` or any date picker dependency (`react-datepicker`, `react-day-picker`, a UI suite's picker) for a date range instead of `DateRangePopover`, and shipping browser-controlled `mm/dd/yyyy` placeholders or unthemed calendar popovers.-- Labelling a date trigger with `new Date("YYYY-MM-DD").toLocaleDateString()` instead of `useDateFormatter()`, so the label is a day early for users west of Greenwich.-- Assuming `filter(...)` fully validates value types.-- Letting a `null` bucket become the latest time-series point.-- Hardcoding business values, labels, timestamps, or rankings.-- Creating chart-ready arrays by hand instead of deriving them from queried `data.rows`.-- Casting typed SDK rows to generic tuple rows such as `[string, number]`.-- Reading generated object property names such as `row.orderedAt` when Metabase returns column names such as `ordered_at`.-- Rendering fields that are not present in the schema or returned query result.-- Rendering `No data` while the SDK is still authenticating or loading.-- Creating nested `MetabaseProvider` instances instead of sharing one provider at the app boundary.diff --git a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.mddeleted file mode 100644index 6e25107896e..00000000000--- a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md+++ /dev/null@@ -1,189 +0,0 @@-# Filter UI Checklist--Use these patterns when building custom filter bars for data apps.--## Filter Contract--Before writing controls, map each filter to the dashboard. Keep this contract small and concrete:--| Filter | Runtime options query | Raw value | Applies to | Unsupported sections |-| --------- | ----------------------------- | ------------ | --------------------------------- | -------------------- |-| Franchise | breakout on franchise id/name | franchise id | orders, revenue Metric, inventory | none |-| Plan | breakout on plan | plan text | orders | revenue, inventory |--If a filter has unsupported sections, either make it section-scoped or do not render it as a global dashboard filter. Do not show duplicate date controls for the same page unless both visibly affect different labeled sections.--For every rendered card or table, build filters from that query source's generated table fields or compatible Metric dimensions. Do not reuse a filter array built for a different table.--Before rendering a filter, answer:--- What query provides runtime options?-- What raw value is stored?-- Which cards can accept that value?-- Which cards cannot?-- Does `All` produce no filter?--## Runtime Categorical Options--Query options from Metabase at runtime with a breakout on the same generated table field or compatible Metric dimension used by the filter.--- Declare an options query in `queries/` with a breakout on the same table field or Metric dimension used by `filter(...)`, run it with `useMetabaseQuery`, then derive a deduped option list from returned rows. An options query is a query like any other: it needs its own `defineQuery` export, never an inline object.-- Prefer querying options from the same source used by the charts so the option list stays compatible with the filter.-- Treat categorical labels as runtime values unless the user explicitly provides a closed enum. Field names in the generated schema are not value lists.-- Use a searchable picker/combobox for entity filters and long runtime option lists.--For Metric-backed cards, use the table source plus generated Metric aggregation. Use the generated Metric dimension in both the options query and the visible card query when the dimension belongs to that table source:--```ts-// queries/revenue.query.ts-const ordersTable = schema.tables.orders;-const revenueMetric = schema.metrics.revenue;-const franchiseDimension = revenueMetric.dimensions.orders.franchiseId;--export const RevenueByFranchise = defineQuery<typeof ordersTable>({- source: ordersTable,- aggregations: [revenueMetric],- breakouts: [breakout(franchiseDimension)],-});--// the filter bar-const { data: optionData } = useMetabaseQuery(RevenueByFranchise);--const revenueFilters =- selectedFranchise === "all"- ? []- : [filter(franchiseDimension, "=", selectedFranchise)];-```--Do not use source-card Metrics in table-source filter queries. Wait for saved-question source support, then pair those Metrics with `source: schema.questions.<question>` instead.--For entity filters, keep display labels and raw values separate:--```ts-type Option = { label: string; value: string };--const franchiseOptions = rows.map((row) => ({- label: row.franchise_name ?? row.franchise_id,- value: row.franchise_id,-}));-```--Use the raw `value` in `filter(...)`. Never filter by display labels when a stable id is available.--Do not render a free-text input that writes directly to an exact id filter. If the filter is searchable, search option labels and store the selected raw value.--## Reset Missing Runtime Values--Runtime option sets can change. If the selected value disappears, reset to `all` so the app does not stay filtered to no rows.--```tsx-useEffect(() => {- if (- selectedValue !== "all" &&- !options.some((option) => option.value === selectedValue)- ) {- setSelectedValue("all");- }-}, [options, selectedValue]);-```--Keep the `All` option selectable even while options are loading, empty, or errored.--## Filter State Rules--- Default every filter to `all` or empty, and run the unfiltered query.-- Convert `all`, `""`, `null`, and `undefined` to `[]`.-- Keep `All` options selectable even while runtime option queries are loading, empty, or errored.-- Do not disable the whole control while loading options; keep `All` enabled and show a loading/empty option for dynamic values.-- If a selected runtime option disappears from the latest option query, reset that filter to `all` so stale values do not keep filtering the dashboard to no rows.-- For custom date ranges, apply the filter only when both dates are valid.-- Never fill half-selected ranges with sentinel dates like `2000-01-01` or `2100-01-01`.-- Keep one filter array per queried table when charts use different date fields.-- Memoize filter arrays so SDK query keys stay stable.-- For boolean Yes/No/All filters, map both `true` and `false` explicitly; only All maps to no filter.--## Searchable Runtime Filters--Entity filters are filters where the selected value is an id/key but users need a label. They always use one searchable combobox, never a native `<select>` or a search input paired with `<select>`. Plain `<select>` is only for short closed enums explicitly provided by the user.--If no component exists:--- Prefer a small established combobox/listbox dependency for keyboard/focus behavior.-- Hand-roll only a small picker: input, capped list, mouse selection, Escape/blur close, and clear button.--Minimum behavior:--- Click or focus opens the option list immediately, even before the user types.-- Search filters labels, not raw ids.-- The `All` option is always available.-- Selecting an option stores the raw `value`.-- The list is capped or scrollable so it cannot stretch the page.--Do not close the list from an `onBlur` handler on the trigger button when the-popover contains an auto-focused input. Moving focus from the button to the-input blurs the button and immediately closes the list. If hand-rolling a-combobox, keep focus inside one wrapper and close only when focus leaves the-whole wrapper, or close from explicit selection, Escape, and outside clicks.--Style this to match the app. If accessibility, keyboard behavior, or popover positioning becomes non-trivial, prefer a small established combobox component or the app's component library instead of hand-rolling more behavior.--## Date Range Filters--Date ranges should use ISO `YYYY-MM-DD` strings for query values. Never use `type="date"`.--Include a Custom range option in date preset bars by default. Omit it only when the user explicitly asks for fixed presets only or no date range control. Order presets as durations first, then All time, then Custom last.--### Use the built-in `DateRangePopover`--`DateRangePopover` wraps the app's own trigger and opens a Metabase-styled range calendar under it. The trigger is yours — a button styled exactly like the preset buttons beside it — and the SDK owns the calendar, the popover positioning, outside-click and Escape. No dependency to install, no CSS to import.--```tsx-import {- DateRangePopover,- useDateFormatter,-} from "@metabase/embedding-sdk-react/data-app";--const { formatDateRange } = useDateFormatter();-const [range, setRange] = useState<[string | null, string | null]>([- null,- null,-]);-const [start, end] = range;--const dateFilters =- start && end- ? [filter(ordersTable.fields.createdAt, "between", [start, end])]- : [];--<DateRangePopover value={range} onChange={setRange}>- <button className="filter-button">- {formatDateRange(range) || "Custom"}- </button>-</DateRangePopover>;-```--Both ends are `YYYY-MM-DD` strings — the same shape `filter(...)` takes, so there is no `Date` conversion and no time zone to get wrong.--- The trigger must be a single DOM element or a `forwardRef` component; the popover attaches a ref and a click handler to it. Give it the same class as the other filter controls so it matches them.-- Label the trigger with `formatDateRange(range)` from `useDateFormatter()`. It is the same formatter Mantine's date input draws its own label with, in the instance's locale, so the trigger reads exactly as the built-in input would; it returns `""` until the SDK bundle has loaded and re-renders the trigger when it has. Never use `new Date("YYYY-MM-DD")` — a date-only string parses as UTC and shows the previous day west of Greenwich. The three states are `""`, `"September 1, 2026 – "`, and `"September 1, 2026 – September 10, 2026"`; `formatDate` does one end. Options: `format` (a dayjs format) and `separator`.-- `onChange` fires on every calendar click, so it reports half-picked ranges as `[start, null]`. Build the filter only when both ends are set; a half-picked range means no date filter, not a sentinel date.-- The popover closes itself once both ends are picked (`closeOnSelect`, default true). Pass `opened` / `onOpenedChange` to drive it yourself.-- Other props: `defaultValue`, `minDate`, `maxDate` (`YYYY-MM-DD`), `numberOfColumns` (months side by side, default 2), `position` (default `bottom-start`).-- `DateRangeCalendar` is the same calendar with no popover, for rendering inline in a container the app already has. Same value props, plus `className` / `style`.--### Falling back to a third-party picker--Only for what the SDK calendar does not cover, such as single-date or date-time selection. Nothing else justifies a picker dependency — `react-datepicker`, `react-day-picker`, `flatpickr`, `@mui/x-date-pickers`, `antd` and `rsuite` are all the same mistake for a plain date range. The default data-app template ships React, React DOM, and the Metabase SDK, so this adds a dependency:--```bash-npm install react-datepicker-```--`react-datepicker` is the default pick; the rest of this section assumes it.--- Do not install a large UI suite just for one data-app date filter.-- Import `react-datepicker/dist/react-datepicker.css`, then add small CSS overrides for the app's visual style if needed.-- Type strict `react-datepicker` callbacks explicitly, for example `onChange={(date: Date | null) => ...}` for single-date pickers.-- Convert selected dates to ISO `YYYY-MM-DD` strings with local date getters (`getFullYear`, `getMonth`, `getDate`) rather than `toISOString()`.-- For date-picker `selected` props, parse saved strings defensively and pass `null` for empty or invalid values. Never pass `new Date("")`.-- Recent `react-datepicker` packages include their own TypeScript types; do not add `@types/react-datepicker` unless the installed version actually needs it.diff --git a/skills/metabase-data-app-semantic-layer/references/visualization-settings.md b/skills/metabase-data-app-semantic-layer/references/visualization-settings.mddeleted file mode 100644index 771b479ffaf..00000000000--- a/skills/metabase-data-app-semantic-layer/references/visualization-settings.md+++ /dev/null@@ -1,46 +0,0 @@-# SDK Visualization Settings--Use this as a quick orientation guide. The installed SDK types are always the source of truth: search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for `MetabaseCard`, the relevant `*VisualizationSettings` type, and any setting key before writing settings. The SDK declaration includes lightweight descriptions for the supported setting families and keys.--## How To Choose Settings--- Start with `card={{ query }}` when the user has not asked for a specific chart type and Metabase defaults can infer a reasonable display from the query.-- Use `card={{ query, visualization }}` when the user request or design calls for a specific chart type, such as a pie chart for a distribution, but does not ask for setting-level customization.-- Use `card={{ query, visualization, visualizationSettings }}` only when the user explicitly asks for a setting-level presentation change, such as hiding or renaming an axis label, showing value labels, stacking bars, adding a goal line, ordering table columns, showing pie totals/labels, or controlling series/slice order.-- Use `useMetabaseQueryObject` to build the query. Do not call internal query resolution helpers directly.-- Set only the few settings that express the requested setting-level change. Let Metabase choose defaults for dimensions, metrics, colors, and formatting when the query shape is obvious.-- Use result column names in settings such as `graph.dimensions`, `graph.metrics`, `pie.dimension`, `pie.metric`, `scalar.field`, `sankey.source`, and `scatter.bubble`. If you are not sure what column names the query will produce, avoid those keys and use safer presentation settings instead.-- Keep `column_settings`, `series_settings`, row ordering, and per-slice colors minimal. They depend on exact result keys and can break when the query changes.--## Source Lookup--Use targeted searches instead of reading the whole declaration file:--```bash-rg -n "export declare type MetabaseCard|declare interface MetabaseCardBase|declare type .*VisualizationSettings|declare type VisualizationSettings" node_modules/@metabase/embedding-sdk-react/dist/index.d.ts-```--When the app has an older SDK package, also check:--```bash-rg -n "useMetabaseQueryObject|UseMetabaseQueryObjectResult" node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts-```--If `useMetabaseQueryObject` and `MetabaseCard` expose incompatible opaque `DatasetQuery` symbols, do not cast through `any`; update the SDK package before using `card`.--## Setting Families--Read the setting-family docstrings from the installed SDK declaration:--- `CartesianVisualizationSettings`: bar, line, area, combo, row-- `ScatterVisualizationSettings`: scatter plots-- `WaterfallVisualizationSettings`: waterfall charts-- `TableVisualizationSettings`: table, pivot, object detail, list-- `PieVisualizationSettings`: pie and donut charts-- `ScalarVisualizationSettings`: scalar, smartscalar, gauge, progress-- `FunnelVisualizationSettings`: funnel charts-- `SankeyVisualizationSettings`: Sankey charts-- `BoxplotVisualizationSettings`: box plots-- `MapVisualizationSettings`: pin and region maps--For individual setting behavior, search the same declaration for the key, such as `graph.dimensions`, `pie.dimension`, `sankey.source`, or `boxplot.whisker_type`. Do not invent settings that are not exposed by the installed SDK type. Custom `custom:*` visualizations accept `Record<string, unknown>` settings only when the app has a known custom visualization contract.diff --git a/skills/metabase-data-app-setup/.gitignore b/skills/metabase-data-app-setup/.gitignoredeleted file mode 100644index 4487a70e91b..00000000000--- a/skills/metabase-data-app-setup/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-template/dist-template/package-lock.json-template/yarn.lock-template/pnpm-lock.yaml-template/bun.lock-template/bun.lockbdiff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.mddeleted file mode 100644index 6ba4f89cec0..00000000000--- a/skills/metabase-data-app-setup/SKILL.md+++ /dev/null@@ -1,618 +0,0 @@-----name: metabase-data-app-setup-description: Scaffold a new Metabase data-app into the connected remote-sync repository's `data_apps/<app>/` directory from the `data-app-template`. Use when the user asks to start, create, scaffold, or set up a data-app from scratch, or to remove one.-metadata:- version: master------# Create a Metabase Data App--A Metabase **data-app** is a single JS bundle that the host loads inside a Near Membrane sandbox and renders inside its own React tree. The scaffold is a Vite + React + TypeScript project: source under `src/`, a dev server that previews the app against a real Metabase **through the same Near Membrane sandbox + distortion rules Metabase uses in production** — so `npm run dev` behaves like production, including for third-party libraries the app bundles — and `npm run build` producing a single `dist/index.js`. (Because the sandbox runs a built bundle, a change rebuilds it and does a *soft reload* — re-evaluates the bundle in the sandbox and remounts the app, keeping auth/SDK loaded — rather than hot-swapping modules; component state resets, but there's no full browser refresh.) The dev preview also shows a corner **⚠ Diagnostics** toolbar that captures runtime errors — including the sandbox's otherwise-opaque blocked-API messages — so failures surface instead of being swallowed. The same data is served as JSON at `http://localhost:5174/__data-app/diagnostics`, which is how *you* read it (see "Reading the diagnostics feed" below) — you have a shell, not a browser, and these failures are invisible from the terminal otherwise.--**Data apps are served from Git** (they can also be created and updated through `/api/apps`). A single repository is connected to Metabase via remote-sync (Admin → Settings → Remote sync). Each app lives in its own directory `data_apps/<slug>/` inside that repo — its source, a `data_app.yaml` (slug/name/path/collection), and the committed built bundle at the `path` its `data_app.yaml` declares (`dist/index.js` by default). Its collection, with its saved questions and the copies of the metrics and actions it uses, is YAML under the repo's `collections/data_apps/`, like every collection of the `data-apps` namespace. On each remote-sync import Metabase materializes each app and serves it at `/apps/<slug>`, where the slug is the `slug` its `data_app.yaml` declares. So this skill always scaffolds **into the connected repo's `data_apps/<slug>/` directory**, never as a standalone project.--**The scaffold ships inside this skill at `./template/`** — a Vite + React + TypeScript project that was installed alongside the skill. Step 3 just copies it into the app directory; the skill then guides you through the customization + first-app-content steps — it never generates project files from scratch. If you find yourself writing `package.json`, `vite.config.ts`, `tsconfig.json`, or `src/index.tsx` by hand, stop — copy the template instead.--## When to invoke this skill--- "scaffold a new data app" / "create a Metabase data app" / "set up a data-app project"-- "I want to build a data app" / any vague intent to author a data app-- Starting a fresh agent task that will produce a data-app bundle.-- "remove the <slug> data app" / "delete a data app" — only *Removing an app* below applies.-- Do **not** use this skill for an existing data-app project when the task is to- build screens, use Metabase data, generate or refresh schema files, wire saved- questions / tables / metrics / actions, add filters, or author data hooks.- Treat those as existing-data-app editing tasks and use the agent's normal- skill-discovery flow from the user's wording.--## Step 1 — Locate the remote-sync repository--Data apps live inside the Git repository connected to Metabase via remote-sync. Find it before scaffolding:--- Ask: **"Do you already have a Git repository connected to this Metabase via remote-sync?"**- - **Yes** → ask for its local path.- - **No** → ask the user to **create one** (a plain Git repo they will connect under Admin → Settings → Remote sync) and share its path. The skill does **not** create or connect the repo — the user owns that.-- Verify the path exists and is a Git working tree (it has a `.git`). This repo is the working directory for every step below.--## Step 2 — Name the app and create its directory--1. Settle on the app's **slug** before scaffolding — the `/apps/<slug>` URL — so it **must be dash-cased**: lowercase letters, numbers, and single dashes (`[a-z0-9]+(?:-[a-z0-9]+)*`), e.g. `sales-overview`. Anything else (uppercase, spaces, underscores) is rejected on sync. If the purpose isn't clear yet, ask a one-line "what's this app for?" and propose a slug; confirm it.-2. Ensure `<repo>/data_apps/` exists; create it if missing.-3. Create `<repo>/data_apps/<slug>/`. **If it already exists**, treat it as an existing project (see below) — never overwrite without confirmation.--### Detecting an existing app--If `<repo>/data_apps/<slug>/` already holds a project, verify it matches the current `data-app-template`. Check **all** of:--1. `vite.config.ts` is a one-liner: `export default dataAppConfig()`- (from `@metabase/embedding-sdk-react/data-app-dev/config`). There is **no**- local `config/` directory: the whole bundle contract (externals/globals, the- dev sandbox entry, CSS/SVG handling) lives inside that SDK config, not the- scaffold. `dataAppConfig` takes only a curated set of overrides (currently just- `port`); the contract plugin is always applied and can't be overridden.-2. `src/index.tsx` default-exports a `DataAppFactory` (type from- `@metabase/embedding-sdk-react/data-app`) returning `{ component, providerProps? }`- (no args).-3. `data_app.yaml` declares the `version:` Metabase serves (a manifest without- the line is version 1). Print the version Metabase serves without writing- anything (never reuse the Step 4 snippet here: it writes files):-- ```bash- ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"- (- source "$ROOT/.env.local" 2>/dev/null- curl -sS -X POST \- -H "x-api-key: $DATA_APP_MB_API_KEY" \- -H "Content-Type: application/json" \- -d '{"name": "Version check"}' \- "$DATA_APP_MB_URL/api/apps/generate/app" |- node -e 'let s="";process.stdin.on("data",(d)=>(s+=d)).on("end",()=>{const r=JSON.parse(s);if(!r.files){console.error(s);process.exit(1)}console.log(r.files[0].yaml.match(/^version: (\d+)/m)[1])})'- )- ```-- A lower version is not drift but an outdated app: **Stop.** Migrating it is a- separate task; use the agent's normal skill-discovery flow for migrating an- outdated data app before extending it.--**All checks pass** → template-shaped. Ask: "Extend this app, or scaffold a new one under a different slug?" If extend → skip the copy step, edit `src/`. If new → pick a different slug and restart at Step 2.--**Any check fails** → not template-shaped (older scaffold or drift). **Stop.** Tell the user the structure differs from the current template, extending it risks breaking the bundle contract, and ask whether to (1) migrate it (a separate task; use skill discovery for migrating an outdated data app), (2) scaffold fresh under a new slug and port the code over, or (3) proceed anyway at their risk. Wait for the answer.--Never overwrite existing files without explicit confirmation.--## Step 3 — Copy the template into the app directory--The template ships **inside this skill** at `./template/` (installed alongside the skill via `skills add metabase/metabase/skills#release-x.<major>.x`). Copy it into the app directory:--```bash-APP_DIR="<repo>/data_apps/<slug>"-# `<skill-dir>` = the directory this SKILL.md was loaded from-# (e.g. `.claude/skills/metabase-data-app-setup`); the template is its `template/` subfolder.-cp -R "<skill-dir>/template/." "$APP_DIR/"-```--A data app is a *subdirectory* of the remote-sync repo, not its own repository — so this is a plain copy, never a nested `git clone` / `git init`. Everything below runs **inside `$APP_DIR`**.--The copy includes two root-level directories, `queries/` and `actions/`, each holding only a `README.md`. Keep both, even while empty: every query the app runs is a `defineQuery(...)` export in `queries/`, every action a `defineAction(...)` export in `actions/`, and the hooks refuse anything else at compile time. Read both READMEs before writing the first `useMetabaseQuery` / `useMetabaseQueryObject` / `useAction` call.--## Step 4 — Customize--Once the template is in `<repo>/data_apps/<slug>/` (run everything below from that directory):--1. Edit `package.json` `name` to match the slug.-2. Pin `@metabase/embedding-sdk-react` to the published data-apps tag (the template ships with `*`):-- ```bash- npm install @metabase/embedding-sdk-react@64-alpha- ```-- This resolves to the current internal-testing SDK build with the `@metabase/embedding-sdk-react/data-app` entrypoint (the app's APIs) and the `@metabase/embedding-sdk-react/data-app-dev/config` entrypoint `vite.config.ts` uses (the dev/build preset, which serves the sandbox entry). Do not use `latest` or `64-stable` as data apps are not yet released.-3. **Ensure the repo-root `.gitignore` ignores `.env.local`** — do this *before* creating any credentials file so the secret can never be committed. Create the `.gitignore` if the repo doesn't have one, then add the entry if it's missing:-- ```bash- ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"- if [ -z "$ROOT" ]; then- echo "MISSING (run this from inside the connected git repo)"- else- GITIGNORE="$ROOT/.gitignore"- # Create the repo-root .gitignore if absent, then ensure `.env.local` is- # ignored so the credentials file (next step) can never be committed.- [ -f "$GITIGNORE" ] || : > "$GITIGNORE"- grep -qxF ".env.local" "$GITIGNORE" || echo ".env.local" >> "$GITIGNORE"- fi- ```-4. Set up the Metabase credentials at the **repository root** — `<repo>/.env.local` (usually two levels up from the app dir), **not** the app dir. One `.env.local` there serves every data app in the repo.-- Create it from the example if absent, then verify the two vars are set **without printing the file** (it may hold other secrets) — `source` it and echo only a pass/fail signal, never the values:-- ```bash- # Resolve the repo root first; an unguarded $(git ...) would expand to- # "/.env.local" outside a repo and touch a system-level file.- ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"- if [ -z "$ROOT" ]; then- echo "MISSING (run this from inside the connected git repo)"- else- ENV_FILE="$ROOT/.env.local"- [ -f "$ENV_FILE" ] || cp .env.local.example "$ENV_FILE"- # Source inside a subshell so the vars never leak into your environment.- ( source "$ENV_FILE" 2>/dev/null- [ -n "$DATA_APP_MB_URL" ] && [ "$DATA_APP_MB_URL" != "mb_replace_me" ] &&- [ -n "$DATA_APP_MB_API_KEY" ] && [ "$DATA_APP_MB_API_KEY" != "mb_replace_me" ]- ) && echo "creds present" || echo "MISSING"- fi- ```-- If it prints `MISSING`, **ask the user to fill `DATA_APP_MB_URL` (the running Metabase instance) and `DATA_APP_MB_API_KEY` (Admin → Authentication → API keys, a key in the Administrators group, since the typed schema answers only an admin) in `<repo>/.env.local` themselves** — up front, before anything needs the key.-- > **Never ask the user to paste the API key into the chat, and never `cat` / `echo` / print `.env.local` or its variables.** It's git-ignored and may hold *other* secrets — the file's contents and the key must never enter the conversation or your context. Every command that needs the key `source`s the file (as above) so the shell uses the value directly; you only ever see the `creds present` / `MISSING` signal, never the secret itself. (`creds present` only means both vars are filled and not the default `mb_replace_me` placeholder — not that the URL or key are valid; a bad key surfaces later when a request fails.)-5. **Generate `data_app.yaml` and the app's collection.** Metabase writes both, with new entity IDs: `POST /api/apps/generate/app` answers the app's `data_app.yaml` (at `data_apps/<slug>/data_app.yaml`) and its collection's file under `collections/data_apps/`, each at its path from the repo root. Run it from the repo, with the app's display name, its `/apps/<slug>` slug, and an optional one-line description:-- ```bash- ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"- (- source "$ROOT/.env.local" 2>/dev/null- curl -sS -X POST \- -H "x-api-key: $DATA_APP_MB_API_KEY" \- -H "Content-Type: application/json" \- -d '{"name": "Sales App", "slug": "sales-app", "description": "Pipeline health and quota attainment by region"}' \- "$DATA_APP_MB_URL/api/apps/generate/app" |- node -e 'let s="";process.stdin.on("data",(d)=>(s+=d)).on("end",()=>{const r=JSON.parse(s);if(!r.files){console.error(s);process.exit(1)}for(const f of r.files){const p=require("path").join(process.argv[1],f.path);require("fs").mkdirSync(require("path").dirname(p),{recursive:true});require("fs").writeFileSync(p,f.yaml);console.log("Wrote "+f.path)}})' "$ROOT"- )- ```-- Run it once per app: a second run writes a new collection with new entity IDs. Never copy `data_app.yaml` or its `collection:` line from another app. Edit the generated `data_app.yaml` only to add `allowed_hosts` (below).-- **`description`** — optional: a single short sentence saying what the app- does, shown under its name in the admin UI so admins can tell apps apart at a- glance. Sync folds any whitespace into single spaces and rejects anything over- 255 characters; the admin list wraps what is left rather than cutting it off,- so a sentence reads well there and a paragraph crowds out the rows around it.- Pass a real sentence about *this* app, or leave `description` out of the- request if it adds nothing beyond the name.-- **`version`** — the data app contract version this app's code targets, a- whole number. Metabase writes the version it serves; do not change it by- hand. Metabase bumps the version it serves only on a breaking- change to the contract. An app on an older version is marked *Outdated* in- the admin list, hidden from every other user, and refuses to open until it- is migrated to the current contract, its `version` raised to match, rebuilt,- and synced. That migration is a separate, instructed procedure, one version- at a time; reach it through skill discovery and never do it ad hoc.-- **`allowed_hosts`** — only needed if the app calls an **external** API directly- with `fetch`/`XHR`. The sandbox blocks all network egress by default; listing an- origin here (exact or a `*.` subdomain wildcard) opens it in both `npm run dev`- (dev-server CSP) and Metabase (iframe CSP + sandbox). Do **not** list the- Metabase instance — Metabase data is read via the `useMetabaseQuery` data hooks- and written via `useAction` (the SDK handles auth), never raw `fetch`. Leave- `allowed_hosts` out entirely when the app only talks to Metabase.-- Native `<form action="…">` submissions and `<iframe src="…">`/navigations obey- the **same** allowlist. Prefer a client-side `<form onSubmit>` that- `preventDefault`s and writes via `useAction`/`fetch`: a native submit- *navigates the sandboxed iframe away* from the app. If you do use one, the- target host must be in `allowed_hosts` or it's blocked (`form-action` for- submits, `frame-src` for embeds/navigations). A host you navigate to or embed- must also permit framing (`X-Frame-Options`/`frame-ancestors`) — many public- sites don't.--6. `npm install` (or whichever package manager the user prefers — the template ships with no lockfile, so `npm` / `yarn` / `pnpm` / `bun` all work; use the project's existing lockfile if one appears post-clone).-7. **The lockfile and the built bundle must both be committed.** Metabase serves the file at the `path` declared in `data_app.yaml` (the template builds to `dist/index.js`) straight from the committed Git tree, and the lockfile keeps installs reproducible. **Verify with `git status`** after `npm install` and a build: both must appear as committable files.-8. `npm run dev` and confirm the preview at http://localhost:5174 renders the starter "Hello, data app" message.-9. If the preview hits CORS, add `http://localhost:5174` under Admin → Embedding → Embedded analytics SDK → CORS.--### The order of the app's files--An app's YAML is written in this order, and each step needs the one before it:--1. `data_app.yaml` and the collection's file under `collections/data_apps/`,- both generated at item 5.-2. The files in the collection's directory: a saved question per query and- copies of the metrics and actions they use, which `npm run write-resources`- regenerates once the app has definitions in `queries/` or `actions/`. It- writes into the collection `data_app.yaml` names, so it refuses to run until- the manifest names one whose file exists.--Scaffolding ends after the first. The second is part of building the app's-data layer; use skill discovery for that.--## Step 5 — Verify the starter app--At this point the data app exists. Keep this workflow focused on creating the-project scaffold and proving the starter bundle works.--1. Run `npm run typecheck`.-2. Run `npm run check-resources`. It fails when `data_app.yaml` names no- collection or one without a file, and it validates the repository's YAML- against the format. It changes nothing in Metabase.-3. Run `npm run build`.-4. Confirm `git status` shows the app source, lockfile, `data_app.yaml`, the- collection's file under `collections/data_apps/`, and the built bundle- (`dist/index.js` by default) as committable files.-5. If the user asked for a live preview, run `npm run dev` and confirm the- starter "Hello, data app" screen renders through the sandbox preview.-6. With the preview open, check the diagnostics feed once — it is the only place- runtime failures appear to you (see *Reading the diagnostics feed*):-- ```bash- curl -s "http://localhost:5174/__data-app/diagnostics?startEventId=0"- ```-- Expect `clients: 1` and no entries with `"alert": true`. `clients: 0` means no- preview tab is open, so an empty feed proves nothing.--Stop here if the user only asked to create, scaffold, or set up a data app.--If the next task is to build or iterate on the actual app UI — especially if it-mentions an existing data app, Metabase data, generated schema files, saved-questions, tables, metrics, actions, filters, semantic-layer entities, or data-hooks — treat it as a separate existing-data-app editing task. Use the agent's-normal skill-discovery flow from those terms. Do not expand this scaffold skill-with data-layer authoring rules.--**Do not modify `src/index.tsx` or `tsconfig.json` unless the change is genuinely required.** The whole build/dev setup lives in the SDK behind `dataAppConfig()` (which also serves the dev HTML shell — there's no `index.html` to edit), so `vite.config.ts` is just:--```ts-import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";--export default dataAppConfig();-```--`dataAppConfig` exposes only a curated set of overrides (currently just `port`). The whole contract — factory shape, externals/globals, the dev sandbox entry, CSS inlining, and SVG-as-component support — is baked in and **can't** be overridden; that's deliberate, so a data app can't drift from what Metabase loads. There's no local build config to touch (and no `index.html` — the SDK's dev server serves the HTML shell), and tweaks to `src/index.tsx` still risk breaking the factory shape and silently break drill popups and routing.--There is intentionally **no escape hatch** for extra Vite plugins, aliases, or `define`s — `port` is the only knob. If you think you need more, you almost certainly don't; solve it in `src/` instead.--**After every meaningful round of edits, run `npm run typecheck`.** It runs `tsc --noEmit` over `src/` and `vite.config.ts` — catches wrong prop shapes against the SDK types, broken refactors, missing imports, etc. The Vite dev server does NOT typecheck (it only transpiles), so errors that would fail a production CI run can sit invisibly in a passing `npm run dev` session. Run it before declaring a task complete.--**Before handoff, re-check package hygiene.** `@metabase/embedding-sdk-react` should use the expected data-app SDK source/tag for the target environment. No date picker dependency should be installed when the app only needs date ranges — not `react-datepicker`, `react-day-picker`, `flatpickr`, or a UI suite's picker (`@mui/x-date-pickers`, `antd`, `rsuite`, …); that is `DateRangePopover` from `@metabase/embedding-sdk-react/data-app`. `@types/react-datepicker` should not be installed unless the chosen `react-datepicker` version actually needs it.--## Reading the diagnostics feed--`npm run dev` serves everything the toolbar shows as JSON — the only way *you*-see runtime failures, since sandbox blocks, CSP refusals, failed queries and-uncaught errors reach neither the terminal nor `npm run typecheck`. Check it-after any change you can't verify by reading the code.--**Loop:** note `nextEventId` before editing → make the change (rebuilds-automatically) → re-read. `startEventId` is inclusive and survives page reloads.--```bash-curl -s "http://localhost:5174/__data-app/diagnostics?startEventId=0"-```--```jsonc-{- "entries": [{- "eventId": 31, "kind": "blocked-network", "alert": true,- "summary": "Blocked fetch to api.example.com (not in allowed_hosts)",- "detail": null, // stack frames, when any- "hint": "Add https://api.example.com to allowed_hosts in data_app.yaml …",- "buildId": 7 // the bundle generation that reported it- }],- "clients": 1, // connected preview tabs — 0 means nothing ran- "buildId": 7, // the generation running now- "staleEntries": 164, // held back, reported by an older build — see below- "nextEventId": 32 // pass back as ?startEventId=-}-```--**`clients: 0` does not mean healthy** — it means no preview tab is open, so an-empty `entries` proves nothing. Open `http://localhost:5174` first.--**The feed answers for the bundle that is running, not for everything that ever-happened.** Every save rebuilds and remounts the app, so a multi-step edit runs-through builds that don't compile or don't render — errors from those describe-code the preview has already replaced. They're withheld and counted in-`staleEntries`; read mid-edit and you see the current build's failures, not a-pile of them. Nothing is lost: the rebuild re-runs the app from scratch, so-anything still broken reports itself again under the new `buildId`, and-`?includeStale=true` hands back the withheld entries when comparing builds is-the point. A *failed* build doesn't advance `buildId` — the preview keeps-running the last good bundle, so its entries stay current.--Triage by `kind` (always read `hint` — it names the exact fix; never soften a-`summary` when reporting it):--| `kind` | Fix |-|---|---|-| `blocked-network` / `csp-violation` | add the origin to `allowed_hosts` in `data_app.yaml`, then **restart** `npm run dev` (allowlist + CSP are read at boot) |-| `blocked-api` | blocked in production too — use an SDK API or drop the call, don't work around it |-| `sdk-call` + `alert: true` | a Metabase request failed; fix the query — `summary` has the endpoint and status |-| `error` | a real bug; `detail` has the stack |--Text is truncated and the buffer holds the last 200 events. `curl -X DELETE-.../__data-app/diagnostics` clears it for every reader.--## Source conventions--### 1. Write TSX--Plain ESM + TSX, normal package imports:--```tsx-// src/components/CustomerCard.tsx-import { StaticQuestion } from "@metabase/embedding-sdk-react";--type Customer = { name: string; questionId: number };--export default function CustomerCard({ customer }: { customer: Customer }) {- return (- <article>- <h3>{customer.name}</h3>- <StaticQuestion questionId={customer.questionId} height={300} width="100%" />- </article>- );-}-```--### 2. Structure from the start--Default project layout once the starter app is extended:--```-queries/ (root level, beside package.json — NOT under src/)-│ └── orders.query.ts (defineQuery exports; one file per topic)-actions/ (root level, beside package.json — NOT under src/)-│ └── orders.action.ts (defineAction exports; one file per topic)-src/-├── index.tsx (template — the factory; don't edit)-├── App.tsx (routing + composition only)-├── theme.ts-├── metabase.data.ts (generated schema — use skill discovery for the data-app semantic layer)-├── pages/ (one file per screen)-│ ├── Overview.tsx-│ └── CustomerDetail.tsx-├── components/ (shared UI)-│ └── Card.tsx-├── hooks/ (custom hooks that wrap a query export, never the query itself)-│ └── useCustomers.ts-├── lib/ (pure helpers / derivations)-│ └── format.ts-└── types/ (shared TS types)- └── customer.ts-```--Vite bundles everything reachable from `src/index.tsx` into a single `dist/index.js` IIFE — the `src/` layout is purely for your own readability. `queries/` and `actions/` are not: each definition in those two root-level directories is backed by a file in the app's collection under the repo's `collections/data_apps/`, `npm run build` fails until they match, and the query and action hooks accept only the `defineQuery` / `defineAction` exports declared there. A query object written at a hook call, under `src/`, or spread from a definition does not compile (`Property 'definedWithDefineQuery' is missing`); the fix is to move it into `queries/` and import it, never a cast.--**If the app has multiple tabs (or any top-level screen switcher), the default — leftmost / first — tab MUST be selected on initial load.** The app should never boot to a blank page, an empty shell, or a "nothing selected" state that waits for the user to click. Agents repeatedly forget this. For local-state tabs, initialize the active tab to the first one so the very first render shows it:--```tsx-const [active, setActive] = useState(TABS[0].id); // default = leftmost tab-```--If the tabs are instead backed by URL routes (multiple pages), the same rule applies via the router — use skill discovery for data-app routing to make the base path `/` resolve to the default tab. Either way, verify by loading the app fresh: the leftmost tab's content is visible immediately and reads as selected.--**The build output is one self-contained `.js` file — nothing else.** The backend serves a single bundle, so there are no sidecar files: CSS is inlined into the JS, and every imported asset (images, fonts, SVGs-as-URLs) is base64-inlined as a data URI. So `import logo from "./logo.png"` / `import iconUrl from "./icon.svg"` give you a ready-to-use data-URI string, and SVGs can also be imported as React components with the **`?react`** suffix (built-in `svgr`): `import Icon from "./icon.svg?react"`. Everything gets baked into `dist/index.js` — just keep large binaries out, since inlining inflates the bundle. (If your editor doesn't recognize a `?react` import, add `declare module "*.svg?react";` to a `.d.ts` in `src/`.)--### 3. Import SDK values from the correct SDK entrypoint--The build externalizes React, the JSX runtimes, `@metabase/embedding-sdk-react`, and `@metabase/embedding-sdk-react/data-app` to sandbox globals in **both** production and `npm run dev` — in dev the sandbox entry endows them from the npm package, so the bundle runs identically in both. Just import from the entrypoints normally:--```tsx-// ✅ correct-import { StaticQuestion } from "@metabase/embedding-sdk-react";-import {- DataAppRouter,- DataAppLink,- useMetabaseQuery,-} from "@metabase/embedding-sdk-react/data-app";--// ❌ wrong — no globalThis pattern; you'd be reading nothing-const { MetabaseProvider, StaticQuestion } = globalThis;-```--**Do NOT render `<MetabaseProvider>` in `App.tsx`.** The dev entry (served by the SDK's dev preset) and the production host both wrap your tree in a provider that lives in their own realm — wrapping inside the bundle would route the SDK's `setState`-via-listener paths through the Near Membrane sandbox and silently break drill popups, plugin init, and similar.--### 4. Import `react` normally too--The build externalizes `react` and `react-dom`, so plain imports resolve the same way in both modes — the production host and the dev sandbox both endow them as sandbox globals:--```tsx-import { useState, useEffect, useMemo } from "react";-```--**No `import React from "react"` needed in TSX files** — the template uses the automatic JSX runtime (`jsx: "react-jsx"` in `tsconfig.json`; `dataAppConfig()` includes the React plugin). The compiler injects the JSX-runtime imports it needs (`react/jsx-runtime` in production, `react/jsx-dev-runtime` in dev — both externalized and endowed by the sandbox). Just write JSX and named imports — that's it.--For React *types* (e.g. `ComponentType`, `ReactNode`, `RefObject`), use named type imports rather than the `React.` namespace:--```ts-import type { ComponentType, ReactNode } from "react";-```--## Theme rules--`MetabaseProvider`'s `theme` (defined in `src/theme.ts`) is the only way SDK component appearance changes. It is NOT a stylesheet for the bundle's own chrome.--| Field | Purpose | Notes |-|---|---|---|-| `colors.brand` | Accent for SDK widgets | Use the data app's primary color. |-| `colors.brand-hover`, `colors.brand-hover-light` | Hover/accent backgrounds for SDK widgets | Use a subtle surface tint that contrasts with hover text. Do not use the same saturated color as `brand`. |-| `colors.charts` | Chart palette | Array of strings. Use vivid brand-shade colors only; **never pale tints** — palette index 1+ may render labels and pale-on-white is invisible. |-| `colors.positive` / `colors.negative` | Semantic indicators | |-| `colors.background`, `colors.background-secondary` | SDK component surface | **MUST match the immediate parent container of the SDK component.** If the chart sits inside a white card, use `"white"`. If it sits on a tinted page, use that tint. |-| `colors.text-primary`, `text-secondary`, `text-tertiary` | Text on SDK surfaces | **MUST contrast with `background`.** For white bg: use `#1f2937` or similar dark color. The SDK's default `text-primary` resolves to ~white, so leaving it unset on a white surface produces invisible white text. **Always pair `background` and `text-primary` when overriding.** |-| `fontFamily` | SDK widget typography | |--Hover colors are a contrast pair. If you set `colors.text-hover`, verify it-contrasts with `colors.brand-hover` / `colors.brand-hover-light` in open menus,-chart type selectors, and visualization settings dropdowns. For a blue `brand`,-use a pale hover surface like `#EAF4FF`, not the brand blue itself.--**The theme only styles SDK widgets — never your own UI.** For your page background, headers, card wrappers, etc., use inline `style={{ background: "#f5f5f7" }}` or CSS modules on your own elements.--**Don't expect per-subtree theming.** Multiple `<MetabaseProvider>`s on the page fight for the single CSS-variable slot. If the look needs to change with state, recompute `sdkTheme` at the App level and re-render — the whole tree re-themes.--## Custom error UI (optional)--When an embedded question or dashboard can't load — its `questionId` was removed, the user lacks access, or a request fails — the host renders a **neutral built-in error state** in place of that component (a muted icon + the SDK's message). This needs no setup; leave it alone unless the app has a strong reason to restyle it.--To match the app's look, return your own `errorComponent` in the factory's `providerProps` (the same object that carries `theme`). It's an ordinary `providerProps` key, not a change to the factory shape — safe to add:--```tsx-// src/components/AppError.tsx-import type { SdkErrorComponentProps } from "@metabase/embedding-sdk-react";--export default function AppError({ message }: SdkErrorComponentProps) {- return (- <div style={{ padding: 16, textAlign: "center", color: "#6b7280" }}>- {message}- </div>- );-}-```--```tsx-// src/index.tsx — add the key alongside `theme`-import AppError from "./components/AppError";--const factory: DataAppFactory = () => ({- component: App,- providerProps: { theme: sdkTheme, errorComponent: AppError },-});-```--Rules:--- **It replaces the error UI for *every* SDK component in the app**, not just not-found — so keep the copy generic. Render `message` (or your own wording), not an assumption about which error occurred.-- `message` is a `ReactNode` — render it as-is; don't call `.toString()` or index into it.-- Keep it a small **presentational** component. It renders inside the host's provider, but treat it as leaf UI — no data hooks, no `useMetabaseQuery`.-- Omit `errorComponent` entirely to keep the neutral default. There's no need to re-implement it.--## Available SDK surface--The bundle imports React hooks/JSX, SDK components from `@metabase/embedding-sdk-react`, and data-app-specific routing/query APIs from `@metabase/embedding-sdk-react/data-app`. `dataAppConfig()` externalizes these packages at build time, so production references the host's copies at runtime (`globalThis.__metabase_sdk__` / `globalThis.__metabase_data_app__` for SDK packages), and the Vite dev sandbox endows the same globals from the installed npm package.--`<MetabaseProvider>` is **not** rendered by the bundle's `App.tsx` — the dev entry and the host wrap it for their respective modes. Bundle author only renders the **content** below.--| Import | Purpose |-|---|---|-| `React` (from `"react"`) | Hooks (`useState`, `useEffect`, etc.), JSX runtime. Externalized to the host's React via `react: "React"`. |-| `StaticQuestion` | Non-drillable question. Props include `questionId`, `card`, `withChartTypeSelector`, `height`, `width`. |-| `InteractiveQuestion` | Drillable question. Same props as StaticQuestion plus drill behaviors. Use `card={{ query }}` for ad hoc SDK-rendered questions. See *Rendering a chart: Metabase first* for choosing between the two and for `visualization` / `visualizationSettings`. |-| `MetabaseCard` | Type-only import from `@metabase/embedding-sdk-react` for ad hoc SDK-rendered cards with `visualization` or `visualizationSettings`; use skill discovery for the full generated-query card contract before authoring data-layer code. |-| `CreateQuestion`, `MetabotQuestion` | More question variants. |-| `StaticDashboard`, `InteractiveDashboard`, `EditableDashboard` | Dashboard variants. |-| `CreateDashboardModal` | Modal for new-dashboard flow. |-| `CollectionBrowser` | Collection picker. |-| `@metabase/embedding-sdk-react/data-app` exports | Data-app-only helpers for routing, schema-backed data reads, actions, clipboard, and sandbox-safe integration. Treat schema-backed queries, generated schema files, filters, metrics, actions, and other data-layer behavior as existing-data-app editing work; use skill discovery before authoring that code. |-| `DateRangePopover`, `DateRangeCalendar`, `useDateFormatter` (from `@metabase/embedding-sdk-react/data-app`) | Date range selection for filter bars. `DateRangePopover` wraps the app's own trigger element and opens a Metabase-styled range calendar under it; `DateRangeCalendar` is that calendar inline. `value`/`onChange` are `[start, end]` pairs of `YYYY-MM-DD` strings, `null` on either end while half-picked. `useDateFormatter().formatDateRange(value)` makes the trigger's label in the instance's locale, without the UTC-parsing bug of `new Date("YYYY-MM-DD")`. Use these instead of `<input type="date">` or a third-party picker — no dependency, no CSS import. |--### Blocked APIs--The Near Membrane sandbox throws at runtime on these globals. Use the endowed replacement instead:--| Blocked | Use instead |-|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-| **Network** — `fetch`, `XMLHttpRequest`, `WebSocket` | Use the SDK/data-app APIs for Metabase reads and writes — never raw `fetch`. Raw `fetch`/`XHR` reach **only** the external origins listed in `data_app.yaml`'s `allowed_hosts` (Step 4); everything else (including the Metabase origin) throws. `WebSocket` is always blocked. |-| **UI dialogs** — `alert`, `confirm`, `prompt` | Render a React modal in your own tree. |-| **Storage** — `localStorage`, `sessionStorage`, `indexedDB`, `document.cookie` | Treat the data app as stateless across reloads; persist via a Metabase action. |-| **Window / history navigation** — `window.open`, `history.pushState`, `history.replaceState` | `useDataAppLocation().navigate` for in-app; `<a target="_blank" rel="noopener">` for external. |-| **Clipboard** — `document.execCommand("copy")`, `navigator.clipboard` | `copy` (write-only): `import { copy } from "@metabase/embedding-sdk-react/data-app"`, then `await copy(text)` from a user event. There is **no** read/paste API — that would let a bundle exfiltrate whatever the user copied. |-| **Other `navigator.*` device APIs** — `geolocation`, etc. | Not available. |-| **Global `document`/`window` listeners** for typing/clipboard events — `keydown`, `keyup`, `keypress`, `beforeinput`, `input`, `paste`, `copy`, `cut`, `before*paste/copy/cut`, `compositionstart/update/end`, `storage` | Attach the listener to your own element, or use the React handler (`onKeyDown`, `onPaste`, …) on the specific input/container. The same listener on a script-owned element still works. |--**Rule of thumb:** if you're about to touch `window.X`, `document.X`, `navigator.X`, `history.X`, or any storage global, stop and pick the endowed replacement above. The endowed surface (React + React DOM + SDK components + data hooks + `useAction` + DataAppRouter + `DateRangePopover` + `copy`) covers every routine need; anything outside it is intentionally unreachable.--### Rendering a chart: Metabase first--This is a per-element decision, not one taken once for a row, a section, or the app. One tile that needs custom code makes a row with one custom tile in it, not a row of them — the rest stay SDK components and keep their formatting, theming and drill-through. Consistent heights and card chrome come from the container each tile sits in, so "the others should match it" is not a reason to hand-build the others.--A built-in visualization carries the instance's theming, accessibility, tooltips, formatting and drill-through. A chart built in React carries none of that, and drifts from every other chart in the app as soon as either changes. So the question is never "which looks closer to my design" — it is **can Metabase display this at all?**--- **Yes → `useMetabaseQueryObject` + `StaticQuestion` / `InteractiveQuestion`.** Bar, line, area, combo, row, trend, **pie/donut**, scalar/smartscalar, gauge, progress, funnel, scatter, waterfall, boxplot, sankey, pivot, map, object/list views, sortable table, and anything else in the chart-type list. Also whenever visualization settings can carry the presentation — axes, labels, stacking, goals, trendlines, split panels, series, formatting, table/pie/pivot/list settings — or the user benefits from sorting, column inspection, drill-through, or downloading. Build the semantic query from generated schema objects, destructure the returned `query`, and pass only that value in a card object — `<StaticQuestion card={{ query }} visualization="pie" ... />`. Never pass the whole `{ query, error, isLoading }` hook result as `card.query`.-- **No → `useMetabaseQuery` and your own component.** Only when the user asked for a custom visualization, or nothing Metabase renders can express the request: bespoke scorecards, alert panels, narrative layouts or mixed-content cards, custom interactions its chart/table chrome cannot express, unusual forms such as calendar grids, timelines, heat strips, radial views, custom maps or domain-specific diagrams, and elements combining several queries into one visual unit. Keep the row handling typed. Use a charting dependency the app already has; otherwise SVG is fine.--**`StaticQuestion` is the default of the two.** It renders the visualization and nothing else — no query bar, no editor, no save — and takes `withChartTypeSelector`, `withDownloads`, `title` and the sizing props. Use `InteractiveQuestion` when the element is meant to be explored: drill-through, filtering, switching the chart type, or the notebook editor. It shows a Save button unless you turn it off — `isSaveEnabled` defaults to `true` — which offers viewers a save-to-collection flow that belongs in Metabase, not in an app, so pass `isSaveEnabled={false}` unless the app is deliberately an editing surface. That applies to the default layout; giving `InteractiveQuestion` its own children replaces the layout, so a composed `<InteractiveQuestion.QuestionVisualization />` renders no toolbar and no Save button.--**Pass `title={false}` when the question sits in a card or section that already carries a heading.** `InteractiveQuestion`'s default layout shows the question's own title, so you get two; `StaticQuestion` hides it already.--"It has to match our styling" is not a reason to hand-build one: pass `visualization` for the chart type, `visualizationSettings` for setting-level changes, and theme the SDK for the rest. A pie chart in a data app is a Metabase pie chart — unless the user asked for a custom one, which is their call to make, not one to infer from a design reference, brand colours, or a screenshot of something bespoke.--**A single-value KPI is a scalar** — or smartscalar, gauge, progress. If the tile wants a number plus something Metabase does not draw, such as a star row, a caption, or a total from a second query, render the scalar for the number and put the extra beside it. Hand-build it only when the number itself cannot come from one.--**Always render a spinner (or skeleton) while `isLoading` is `true`** — never an empty slot or stale value, which causes layout shift when the data arrives. Same rule for lifted / derived queries (pass `isLoading` down) and for `useAction`'s `isExecuting` (spinner in the button + `disabled={isExecuting}`).--For the hook contract itself — generics, table sources, segments, measures, breakouts, sorting, and debugging — use skill discovery before authoring schema-backed data-layer code.--## App layout — fill the frame height--Metabase and `npm run dev` both give the bundle a full-height frame, but nothing between it and your root element sets a height — so an app shorter than the frame ends where its content ends, leaving its background, sidebar and footer in a short strip over bare white.--So the app's outermost element carries `minHeight: "100vh"` (plus `boxSizing: "border-box"` when it has padding) and paints the page background. `minHeight`, never `height` — taller content must still scroll. Regions that should reach the bottom (sidebar, sticky footer) go in a flex-column root with `flex: 1`. Check the emptiest screen — loading, empty state, a lone KPI — those are the ones that render short.--## SDK component sizing--SDK components do NOT auto-fit their parent — without `height`/`width` they render at their intrinsic size and overflow. Setting only the outer container or card height is not enough either; the height goes on the SDK component that owns the visualization:--- Chart only: pass `height` to `InteractiveQuestion.QuestionVisualization`.-- Default question layout with query bar: pass `height` to `InteractiveQuestion`.-- Static question: pass `height` to `StaticQuestion`.--Use the actual body height available to the chart. For example, if a card is 560px tall and has a 60px header, pass `height="500px"`.--```tsx-<div style={{ height: 360 }}>- <StaticQuestion- questionId={1}- height="100%"- width="100%"- withChartTypeSelector={false}- />-</div>-```--Do not wrap `InteractiveQuestion` or `StaticQuestion` in containers that clip or move on hover. Avoid `overflow: hidden`, hover transforms, and hover-driven layout shifts around embedded Metabase UI; popovers, menus, and chart tooltips need stable geometry and visible overflow.--## Sync to Metabase--Data apps are delivered by Git — you commit the app directory and Metabase pulls it on its next remote-sync import.--1. After any change to `queries/` or `actions/`, run `npm run write-resources` (regenerating `src/metabase.data.ts` first if it doesn't cover what the definitions use), then `npm run check-resources`. Nothing reaches Metabase until the pull in step 4 applies it.-2. `npm run build` produces the bundle at your `data_app.yaml` `path` (the template builds to `dist/index.js`). It fails when the app's collection files don't match the definitions; run `npm run write-resources` and rebuild.-3. From the **repo root**, commit the app directory — its `data_app.yaml`, the built bundle (the file `path` points at), the source, and the lockfile — together with the app's collection files, and **push**:- ```bash- git add data_apps/<slug> collections/data_apps- git commit -m "Add <slug> data app"- git push- ```-4. The app appears in Metabase on the next remote-sync import — a manual **Pull changes** (Admin > Data apps / Remote sync), the auto-import poll, or a restart — reachable at `/apps/<slug>`.--> **Don't offer to "deploy" the app or ask how the bundle reaches a staging environment** — there is no separate deploy step, and the question only confuses users: Metabase imports the committed bundle straight from the connected repo on its next sync. Once the change is on the branch Metabase syncs from — however the user gets it there (a merged PR, or a push straight to that branch) — just tell them to pull it in and open the app in Metabase at `/apps/<slug>`.--- **To update:** run `npm run write-resources` if the definitions changed, commit a new build, and pull again.-- **To remove:** see *Removing an app* below.--## Removing an app--When the user asks to remove or delete a data app, delete its directory **and** its collection's files in one commit, from the repo root, and push:--```bash-git rm -r data_apps/<slug> collections/data_apps/<collection>.yaml collections/data_apps/<collection>-git commit -m "Remove <slug> data app"-git push-```--`<collection>` is the collection `data_app.yaml` names as `collection`: the file under `collections/data_apps/` whose `entity_id` is that value, and the directory of the same name beside it (`data_app__order_desk` for `Data App: Order Desk`). The next pull removes the app, and with it its collection, saved questions, metric copies and action copies.--A directory deleted without its collection's files still removes the app on the next pull, and with it the collection; the next push from Metabase then deletes those files from the repository. Delete both anyway: until that push, a pull that reloads every file brings the collection back as one no app owns, and the push would then keep it. The other way round is refused: an app whose directory stays while its collection file is gone fails the pull.--## Common pitfalls--| Symptom | Fix |-|---|---|-| "Failed to fetch the user, the session might be invalid." | Bad API key or CORS — check `( ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"; [ -n "$ROOT" ] && source "$ROOT/.env.local" 2>/dev/null; [ -n "$DATA_APP_MB_URL" ] && [ "$DATA_APP_MB_URL" != "mb_replace_me" ] && [ -n "$DATA_APP_MB_API_KEY" ] && [ "$DATA_APP_MB_API_KEY" != "mb_replace_me" ] && curl -H "x-api-key: $DATA_APP_MB_API_KEY" "$DATA_APP_MB_URL/api/user/current" || echo "set real DATA_APP_MB_URL / DATA_APP_MB_API_KEY in the repo-root .env.local" )` (uses the repo-root `.env.local`), add `http://localhost:5174` to SDK CORS origins. |-| Invisible chart labels. | Set `text-primary` in the theme (see *Theme rules*). |-| A chart looks unlike the rest of the instance, ignores the theme, or has no tooltips, formatting or drill-through. | It was built in React. Render it with `StaticQuestion`/`InteractiveQuestion` and a `visualization` instead (see *Rendering a chart: Metabase first*). |-| Chart overflows its container. | Pass `height` / `width` to the SDK component (see *SDK component sizing*). |-| App background stops partway down, bare white below short content. | Give the root `minHeight: 100vh` (see *App layout*). |-| "Invalid hook call" at runtime. | Two React copies. `dataAppConfig()` externalizes `react` — ensure `react`/`react-dom` are installed and you haven't added a second React or a mismatched version. |-| Bundle is multi-MB. | React/the SDK should be externalized by the contract plugin — confirm `vite.config.ts` still uses `dataAppConfig()` and the pinned data-apps SDK tag is installed. (A large but not multi-MB bundle can also be inlined assets — see the single-file note above.) |-| `dist/index.js` doesn't assign to `__dataAppFactory__`. | `src/index.tsx` must `export default` the `DataAppFactory` — the preset wires that into the IIFE global. |-| `Cannot find module '@metabase/embedding-sdk-react'`. | Run `npm install` (or the equivalent for your package manager). Types come from the package directly. |-| `Property 'definedWithDefineQuery' is missing` / `Property 'definedWithDefineAction' is missing` on a hook call. | The hook got an inline object, a `satisfies`-typed object, or a spread copy instead of a definition. Export it with `defineQuery` from root-level `queries/` (or `defineAction` from `actions/`) and pass the import. Do not cast, and do not wrap the object in `defineQuery(...)` at the call site: that compiles but is never backed by a saved question. |-| Drill popups don't open / SDK components show empty / "MetabaseProvider not found" at runtime in dev. | `App.tsx` is rendering its own `<MetabaseProvider>` — remove it. The dev entry (SDK) and the production host provide the provider; wrapping it inside the bundle routes the SDK's state paths through the sandbox and breaks them. |-| Dev preview blank / `Bundle did not assign a function to __dataAppFactory__` / sandbox errors in dev. | `src/index.tsx` isn't default-exporting the factory, or your app code throws while the sandbox evaluates the bundle. Read the real error from the diagnostics feed (`curl -s "http://localhost:5174/__data-app/diagnostics?startEventId=0"`), or the dev toolbar's **Diagnostics** panel. |-| A network call works in `npm run dev` but is blocked after syncing to Metabase. | It was never allowed — you edited `allowed_hosts` without restarting the dev server, so the running sandbox and CSP still use the boot-time list. Restart `npm run dev`; the feed's `manifest` section flags this as `restartRequired`. |-| The SDK was rebuilt or reinstalled but the preview still behaves like the old version. | Vite pre-bundles the SDK into `node_modules/.vite` and keys that cache on the package version, so an in-place rebuild doesn't invalidate it. Stop the dev server, delete the `node_modules/.vite` directory, and start it again (or run `npx vite --force`). |-| Component state resets on every edit. | Expected: dev rebuilds the bundle and does a *soft reload* — re-evaluates it in the sandbox and remounts the app (auth/SDK stay loaded, no browser refresh). There's no module-level HMR / Fast Refresh because the app is an evaluated bundle in an isolated realm, so local component state resets. |-| URL changes but UI doesn't update in production (works in dev). | Import the routing primitives from `@metabase/embedding-sdk-react/data-app` (not the main entry) and keep using `dataAppConfig()` — it externalizes `/data-app` so its routing isn't inlined (inlining triggers the React-state-batching-through-Near-Membrane bug). |diff --git a/skills/metabase-data-app-setup/template/.env.local.example b/skills/metabase-data-app-setup/template/.env.local.exampledeleted file mode 100644index 32cdccb3828..00000000000--- a/skills/metabase-data-app-setup/template/.env.local.example+++ /dev/null@@ -1,2 +0,0 @@-DATA_APP_MB_URL=http://localhost:3000-DATA_APP_MB_API_KEY=mb_replace_mediff --git a/skills/metabase-data-app-setup/template/.gitignore b/skills/metabase-data-app-setup/template/.gitignoredeleted file mode 100644index 38028ade26b..00000000000--- a/skills/metabase-data-app-setup/template/.gitignore+++ /dev/null@@ -1,4 +0,0 @@-node_modules-.env.local-.vite-.ideadiff --git a/skills/metabase-data-app-setup/template/LICENSE b/skills/metabase-data-app-setup/template/LICENSEdeleted file mode 100644index 5f9c0a626d2..00000000000--- a/skills/metabase-data-app-setup/template/LICENSE+++ /dev/null@@ -1,21 +0,0 @@-MIT License--Copyright (c) 2026 Metabase--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.diff --git a/skills/metabase-data-app-setup/template/README.md b/skills/metabase-data-app-setup/template/README.mddeleted file mode 100644index db225f13abe..00000000000--- a/skills/metabase-data-app-setup/template/README.md+++ /dev/null@@ -1,20 +0,0 @@-# data-app-template--A Metabase data app: a single-bundle React app, built with the Embedding SDK,-that Metabase serves at `/apps/<slug>` from the Git repository it syncs. This-directory is `data_apps/<slug>/` in that repository. Build and change it with a-coding agent and the Metabase data-app skills.--## Commands--```bash-npm run dev # preview at http://localhost:5174, in the sandbox Metabase runs apps in-npm run typecheck # type-checks src/ and vite.config.ts-npm run write-resources # has Metabase regenerate the app's collection files under collections/data_apps/-npm run check-resources # checks the app's collection files against its definitions, then validates the repository's Metabase YAML-npm run build # builds dist/index.js, the bundle data_app.yaml's path names-```--`npm run dev` and `npm run write-resources` read `DATA_APP_MB_URL` and-`DATA_APP_MB_API_KEY` from the `.env.local` at the repository root;-`.env.local.example` lists them.diff --git a/skills/metabase-data-app-setup/template/actions/README.md b/skills/metabase-data-app-setup/template/actions/README.mddeleted file mode 100644index 107e5c1f2ee..00000000000--- a/skills/metabase-data-app-setup/template/actions/README.md+++ /dev/null@@ -1,72 +0,0 @@-# actions/--Every Metabase action this app triggers is declared here: one-`defineAction(...)` named export per action, in a file named-`<topic>.action.ts`. The data-app `useAction`, imported from-`@metabase/embedding-sdk-react/data-app`, takes a `defineAction` export only, so-an inline `{ action: ... }` object, an id, the schema entry itself, or a spread-copy of a definition fails to compile. The main entry's `useAction` is the SDK's-own hook and skips this check; do not import it in a data app.--```ts-// actions/orders.action.ts-import { defineAction } from "@metabase/embedding-sdk-react/data-app";-import schema from "../src/metabase.data";--export const CreateOrder = defineAction({- copiedActionEntityId: "<entity ID of the copy in the app's collection>",- action: schema.actions.createOrder,-});-```--```tsx-// src/components/CreateOrderForm.tsx-import { useAction } from "@metabase/embedding-sdk-react/data-app";-import type { FormEvent } from "react";-import { CreateOrder } from "../../actions/orders.action";--export function CreateOrderForm({ onCreated }: { onCreated: () => void }) {- const { execute, isExecuting, error } = useAction(CreateOrder);-- const onSubmit = async (event: FormEvent<HTMLFormElement>) => {- event.preventDefault();- try {- // keys and value types come from the action's parameters- await execute({ status: "paid" });- onCreated();- } catch {- // the failure is also in `error`, rendered below- }- };-- return (- <form onSubmit={onSubmit}>- <button type="submit" disabled={isExecuting}>- Create order- </button>- {error && <p>{error.data.message}</p>}- </form>- );-}-```--Rules:--- This directory sits beside `package.json`, not under `src/`. The CLI scans- only `queries/` and `actions/`, so a definition anywhere else never gets a- copy, and the authored action is refused for the app's viewers in production.-- The generated schema lists every query action that belongs to no model.- The app runs a copy of each action, written by- `npm run write-resources`; it never creates actions.-- Pass the export itself to `useAction`. Never pass- `schema.actions.<action>` or its `.id`.-- `copiedActionEntityId` is the entity ID of the action's copy in the app's- collection, under the repo's `collections/data_apps/`. After adding a- definition, run `npm run write-resources` to write the copy there, then- `npm run check-resources`, and commit- the definitions and the collection files together. `npm run build` fails- until they match.-- Never copy a `copiedActionEntityId` to another definition, or remove it while- its copy exists.-- After `execute` resolves, refresh every query on screen the action could have- changed.diff --git a/skills/metabase-data-app-setup/template/package.json b/skills/metabase-data-app-setup/template/package.jsondeleted file mode 100644index 26a7f09a530..00000000000--- a/skills/metabase-data-app-setup/template/package.json+++ /dev/null@@ -1,28 +0,0 @@-{- "name": "data-app-template",- "version": "0.1.0",- "private": true,- "type": "module",- "scripts": {- "dev": "vite --port 5174",- "build": "vite build",- "write-resources": "embedding-sdk-react data-apps write-resources",- "check-resources": "embedding-sdk-react data-apps check-resources && representations validate-schema --folder ../..",- "typecheck": "tsc --noEmit"- },- "dependencies": {- "@metabase/embedding-sdk-react": "*",- "react": "^18.3.1",- "react-dom": "^18.3.1"- },- "devDependencies": {- "@metabase/representations": "^1.5.1",- "@types/react": "^18.3.12",- "@types/react-dom": "^18.3.1",- "@vitejs/plugin-react": "^6.0.2",- "typescript": "^6.0.3",- "vite": "^8.0.16",- "vite-plugin-css-injected-by-js": "^3.5.2",- "vite-plugin-svgr": "^5.2.0"- }-}diff --git a/skills/metabase-data-app-setup/template/queries/README.md b/skills/metabase-data-app-setup/template/queries/README.mddeleted file mode 100644index f6a91b43602..00000000000--- a/skills/metabase-data-app-setup/template/queries/README.md+++ /dev/null@@ -1,77 +0,0 @@-# queries/--Every Metabase query this app runs is declared here: one `defineQuery(...)`-named export per query, in a file named `<topic>.query.ts`. The query hooks-accept nothing else. `useMetabaseQuery` and `useMetabaseQueryObject` take a-`defineQuery` export only, so an inline query object, a `satisfies-MetabaseQueryOptions` object, or a spread copy of a definition fails to compile-with `Property 'definedWithDefineQuery' is missing`.--```ts-// queries/orders.query.ts-import {- aggregations,- breakout,- defineQuery,-} from "@metabase/embedding-sdk-react/data-app";-import schema from "../src/metabase.data";--const orders = schema.tables.orders;--export const OrdersList = defineQuery({- savedQuestionEntityId: "<entity ID of its saved question>",- source: orders,- limit: 100,-});--export const OrdersByMonth = defineQuery({- savedQuestionEntityId: "<entity ID of its saved question>",- source: orders,- aggregations: [aggregations.count()],- breakouts: [breakout(orders.fields.createdAt, { unit: "month" })],-});-```--```tsx-// src/pages/Overview.tsx-import {- filter,- useMetabaseQuery,-} from "@metabase/embedding-sdk-react/data-app";-import { useState } from "react";-import { OrdersList } from "../../queries/orders.query";--export function Overview() {- const [status, setStatus] = useState("all");-- // runtime state goes in the second argument, never into the definition- const { data, isLoading, error } = useMetabaseQuery(OrdersList, {- filters:- status === "all"- ? []- : [filter(OrdersList.source.fields.status, "=", status)],- });-- // ...render a status control that calls setStatus, then data-}-```--Rules:--- This directory sits beside `package.json`, not under `src/`. The CLI scans- only `queries/` and `actions/`, so a definition anywhere else never gets a- saved question and fails in production.-- Keep a definition static. A clause whose value comes from a control (a- selected filter, a date range, a search box) goes in the hook's second- argument, never inside `defineQuery`.-- One export per query the app renders. Filter-option queries, KPI queries, and- helper queries are queries too.-- Pass the export itself to the hook. Never spread or copy it.-- Each definition carries `savedQuestionEntityId`, the entity ID of its saved- question in the app's collection, under the repo's `collections/data_apps/`.- After adding or changing a definition, run `npm run write-resources` to- write that card. A metric it aggregates is copied into the app's collection- too, by the same command. Then run `npm run check-resources`, and commit the definitions and- the collection files together. `npm run build` fails until they match.-- Never copy a `savedQuestionEntityId` to another definition, or remove it while- its card exists.diff --git a/skills/metabase-data-app-setup/template/src/App.tsx b/skills/metabase-data-app-setup/template/src/App.tsxdeleted file mode 100644index 3437719d2ac..00000000000--- a/skills/metabase-data-app-setup/template/src/App.tsx+++ /dev/null@@ -1,9 +0,0 @@-export default function App() {- return (- <div style={{ minHeight: "100vh", boxSizing: "border-box", padding: 24 }}>- <h1 style={{ margin: 0 }}>Hello, data app</h1>-- <p style={{ color: "#555" }}>Edit src/App.tsx to begin.</p>- </div>- );-}diff --git a/skills/metabase-data-app-setup/template/src/index.tsx b/skills/metabase-data-app-setup/template/src/index.tsxdeleted file mode 100644index 73299f764a7..00000000000--- a/skills/metabase-data-app-setup/template/src/index.tsx+++ /dev/null@@ -1,14 +0,0 @@-import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";--import App from "./App";-import { sdkTheme } from "./theme";--// The data app's entry point. Return the root component plus any `providerProps`-// the host should apply to `MetabaseProvider` (e.g. `theme`,-// `allowedCustomVisualizations`).-const factory: DataAppFactory = () => ({- component: App,- providerProps: { theme: sdkTheme },-});--export default factory;diff --git a/skills/metabase-data-app-setup/template/src/theme.ts b/skills/metabase-data-app-setup/template/src/theme.tsdeleted file mode 100644index 2d9b6ee0b0b..00000000000--- a/skills/metabase-data-app-setup/template/src/theme.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { MetabaseTheme } from "@metabase/embedding-sdk-react";--export const sdkTheme: MetabaseTheme = {- colors: {- brand: "#4D96FF",- "brand-hover": "#EAF4FF",- positive: "#4D96FF",- charts: ["#4D96FF"],- background: "white",- "background-secondary": "white",- "text-primary": "#1f2937",- "text-secondary": "#4b5563",- "text-tertiary": "#6b7280",- },- fontFamily: "system-ui, -apple-system, Segoe UI, sans-serif",-};diff --git a/skills/metabase-data-app-setup/template/tsconfig.json b/skills/metabase-data-app-setup/template/tsconfig.jsondeleted file mode 100644index 3ab6c4c2d30..00000000000--- a/skills/metabase-data-app-setup/template/tsconfig.json+++ /dev/null@@ -1,25 +0,0 @@-{- "compilerOptions": {- "target": "ES2020",- "lib": ["ES2020", "DOM", "DOM.Iterable"],- "module": "ESNext",- "moduleResolution": "bundler",- "jsx": "react-jsx",- "esModuleInterop": true,- "resolveJsonModule": true,- "isolatedModules": true,- "skipLibCheck": true,- "noEmit": true,- "strict": true,- "allowJs": false,- "checkJs": false,- "noImplicitAny": true,- "strictNullChecks": true,- "forceConsistentCasingInFileNames": true,- "noUnusedLocals": false,- "noUnusedParameters": false,- "noFallthroughCasesInSwitch": true,- "types": ["vite/client"]- },- "include": ["src", "queries", "actions", "vite.config.ts"]-}diff --git a/skills/metabase-data-app-setup/template/vite.config.ts b/skills/metabase-data-app-setup/template/vite.config.tsdeleted file mode 100644index 3e1520458f2..00000000000--- a/skills/metabase-data-app-setup/template/vite.config.ts+++ /dev/null@@ -1,3 +0,0 @@-import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";--export default dataAppConfig();