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
Require defineQuery and defineAction exports in data-app hooks (#82489)
Timofey Kachalova367aac5d8f4
diff --git a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsxindex f1427aacd30..68e1b9990b9 100644--- a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx+++ b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/src/App.tsx@@ -1,9 +1,16 @@import { StaticQuestion } from "@metabase/embedding-sdk-react";-import { useMetabaseQueryObject } from "@metabase/embedding-sdk-react/data-app";+import {+ defineQuery,+ useMetabaseQueryObject,+} from "@metabase/embedding-sdk-react/data-app";import { useEffect } from "react";const ORDERS_TABLE_ID = 5;+const OrdersQuery = defineQuery({+ source: { type: "table", id: ORDERS_TABLE_ID },+});+const ALLOWED_URL = "https://allowed.data-app.test/ping";const BLOCKED_URL = "https://blocked.data-app.test/ping";@@ -17,9 +24,7 @@ function SandboxProbe() {}export default function App() {- const { query } = useMetabaseQueryObject({- source: { type: "table", id: ORDERS_TABLE_ID },- });+ const { query } = useMetabaseQueryObject(OrdersQuery);return (<div data-testid="dev-app-content" style={{ padding: 24 }}>diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsxindex 93c57b95508..9818e3577eb 100644--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx@@ -1,12 +1,14 @@import {InteractiveQuestion,StaticQuestion,- useAction,} from "@metabase/embedding-sdk-react";import {copy,DataAppLink,DataAppRouter,+ defineAction,+ defineQuery,+ useAction,useDataAppLocation,useMetabaseQuery,useMetabaseQueryObject,@@ -24,9 +26,9 @@ const PROBE_COLOR = "rgb(0, 128, 0)";function Overview() {const { scalarQuery, questionQuery } = getTestEnv();- const ordersCount = useMetabaseQuery(scalarQuery);+ const ordersCount = useMetabaseQuery(defineQuery(scalarQuery));const totalOrders = ordersCount.data?.rawRows?.[0]?.[0];- const ordersQuery = useMetabaseQueryObject(questionQuery);+ const ordersQuery = useMetabaseQueryObject(defineQuery(questionQuery));return (<div data-testid="data-app-content" style={{ padding: 24 }}>@@ -82,8 +84,8 @@ function Details() {function QueryStates() {const { scalarQuery, errorQuery } = getTestEnv();- const broken = useMetabaseQuery(errorQuery!);- const working = useMetabaseQuery(scalarQuery);+ const broken = useMetabaseQuery(defineQuery(errorQuery!));+ const working = useMetabaseQuery(defineQuery(scalarQuery));const count = working.data?.rawRows?.[0]?.[0];return (@@ -130,7 +132,7 @@ function DownloadQuestionPage() {// to a custom viz — the example `demo-viz` requires exactly one result column.function CustomVizPage() {const { scalarQuery } = getTestEnv();- const q = useMetabaseQueryObject(scalarQuery);+ const q = useMetabaseQueryObject(defineQuery(scalarQuery));return (<div data-testid="data-app-custom-viz" style={{ padding: 24 }}>@@ -148,7 +150,7 @@ function CustomVizPage() {function StaticQuestionPage() {const { questionQuery } = getTestEnv();- const q = useMetabaseQueryObject(questionQuery);+ const q = useMetabaseQueryObject(defineQuery(questionQuery));return (<div data-testid="data-app-static-question" style={{ padding: 24 }}>@@ -198,7 +200,10 @@ function Actions() {// the copy the definition points at is the authored action itself.const action = useAction(actionId- ? { action: { id: actionId, parameters: [] }, copiedActionId: actionId }+ ? defineAction({+ action: { id: actionId, parameters: [] },+ copiedActionId: actionId,+ }): null,);const [output, setOutput] = useState("idle");diff --git a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsxindex 83c64d6d1f1..65b5641499e 100644--- a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx+++ b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx@@ -1,6 +1,7 @@-import { useAction } from "@metabase/embedding-sdk-react";+import { useAction } from "@metabase/embedding-sdk-react/data-app";import { useState } from "react";+// @ts-expect-error generated at test timeimport { CreateScore } from "../actions/orders.action";/**diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsxindex ac65872d4b0..4269465c432 100644--- a/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsx@@ -1,8 +1,10 @@import { MetabaseProvider } from "@metabase/embedding-sdk-react";import {+ type DefinedQuery,type MetabaseQueryOptions,aggregations,breakout,+ defineQuery,filter,orderBy,useMetabaseQuery,@@ -55,6 +57,18 @@ const describeResult = (data &&`[${data.columns.map((column) => column.name).join(",")}] ${JSON.stringify(data.rawRows)}`;+type SourceQuery = MetabaseQueryOptions<undefined> & DefinedQuery;++const asCardQuery = (query: {+ source: { type: "card"; id: number };+ [clause: string]: unknown;+}) =>+ // The public query type admits only a table source until saved-question+ // sources ship, while the runtime this test exercises also accepts a card.+ // The cast keeps the card variant on the package API instead of reaching+ // the hook underneath.+ query as unknown as SourceQuery;+/*** Runs the same clauses against a table source and against a card of that table,* and reports whether they agree — so an assertion never has to encode@@ -64,8 +78,8 @@ function QueryComparison({tableQuery,cardQuery,}: {- tableQuery: MetabaseQueryOptions<undefined>;- cardQuery: MetabaseQueryOptions<undefined>;+ tableQuery: SourceQuery;+ cardQuery: SourceQuery;}) {const fromTable = useMetabaseQuery(tableQuery);const fromCard = useMetabaseQuery(cardQuery);@@ -115,8 +129,8 @@ describe("scenarios > embedding-sdk > query sources", () => {const compare = (build: (source: { type: "card"; id: number }) => {- tableQuery: MetabaseQueryOptions<undefined>;- cardQuery: MetabaseQueryOptions<undefined>;+ tableQuery: SourceQuery;+ cardQuery: SourceQuery;},) =>cy.get<{ type: "card"; id: number }>("@cardSource").then((cardSource) => {@@ -142,56 +156,59 @@ describe("scenarios > embedding-sdk > query sources", () => {it("returns the same rows from a table and from a card of that table", () => {compare((source) => ({- tableQuery: { source: tableSource, aggregations: [aggregations.count()] },- cardQuery: { source, aggregations: [aggregations.count()] },+ tableQuery: defineQuery({+ source: tableSource,+ aggregations: [aggregations.count()],+ }),+ cardQuery: asCardQuery({ source, aggregations: [aggregations.count()] }),}));});it("applies filters the same way on either source", () => {compare((source) => ({- tableQuery: {+ tableQuery: defineQuery({source: tableSource,filters: [filter(totalField, ">", 50)],aggregations: [aggregations.count()],- },- cardQuery: {+ }),+ cardQuery: asCardQuery({source,filters: [filter(totalColumn, ">", 50)],aggregations: [aggregations.count()],- },+ }),}));});it("applies aggregations the same way on either source", () => {compare((source) => ({- tableQuery: {+ tableQuery: defineQuery({source: tableSource,aggregations: [aggregations.count(), aggregations.sum(totalField)],- },- cardQuery: {+ }),+ cardQuery: asCardQuery({source,aggregations: [aggregations.count(), aggregations.sum(totalColumn)],- },+ }),}));});// The combinators the query builder exposes, on both source kinds at once.it("applies breakouts and orderBys the same way on either source", () => {compare((source) => ({- tableQuery: {+ tableQuery: defineQuery({source: tableSource,filters: [filter(totalField, ">", 50)],aggregations: [aggregations.count()],breakouts: [breakout(productField)],orderBys: [orderBy(productField, "asc")],- },- cardQuery: {+ }),+ cardQuery: asCardQuery({source,filters: [filter(totalColumn, ">", 50)],aggregations: [aggregations.count()],breakouts: [breakout(productColumn)],orderBys: [orderBy(productColumn, "asc")],- },+ }),}));});});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.tsindex 46ab149e8a2..9e27fec16a2 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts@@ -43,6 +43,7 @@ export {} from "./hooks/public/use-data-app-location";export { defineQuery } from "./hooks/public/use-metabase-query/define-query";export { defineAction } from "./hooks/public/use-action/define-action";+export { useDataAppAction as useAction } from "./hooks/public/use-action";export {aggregations,breakout,@@ -52,6 +53,7 @@ export {useMetabaseQueryObject,} from "./hooks/public/use-metabase-query";export type {+ DefinedQuery,LocalFieldReference,MetabaseBreakout,MetabaseDynamicColumn,@@ -66,6 +68,7 @@ export type {export type {ActionKindFromDataAppSchema,ActionParametersFromDataAppSchema,+ DefinedAction,} from "./hooks/public/use-action";export type {DataAppFactory,diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.tsindex 44b5a9ca3b7..dec06cfb971 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts@@ -1,3 +1,5 @@+import type { DefinedAction } from "./types";+/*** Defines a source-controlled data app action. `action` names the generated* action the app runs. `copiedActionId` is generated state — synchronization@@ -8,6 +10,8 @@ export function defineAction<action: { id: number; parameters: readonly unknown[] };copiedActionId?: number;},->(definition: TDefinition): TDefinition {- return definition;+>(definition: TDefinition): TDefinition & DefinedAction {+ // `DefinedAction` has no runtime member, so the object is returned as is; the+ // cast only adds the mark that a data app's `useAction` requires.+ return definition as TDefinition & DefinedAction;}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.tsindex 7690a93b7b6..c9f91d45214 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts@@ -1,4 +1,4 @@-export { useAction } from "./use-action";+export { useAction, useDataAppAction } from "./use-action";export type {ActionExecuteError,ActionImplicitKind,@@ -14,5 +14,6 @@ export type {ActionResultForUpdate,ActionSchema,AnyActionResult,+ DefinedAction,UseActionResult,} from "./types";diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.tsindex 1a68da3dbdf..84312d01acb 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts@@ -287,8 +287,20 @@ export type UseActionResult<reset: () => void;};+/**+ * Marks an action as declared through `defineAction`. A data app's `useAction`+ * accepts only marked definitions, so an inline definition object is a+ * compile-time error.+ *+ * @category useAction+ */+export declare class DefinedAction {+ private readonly definedWithDefineAction: true;+}++/** The SDK's `useAction`: a definition object, or an id. */export interface UseAction {- /** A `defineAction(...)` export, which types `execute` and `result` itself. */+ /** A definition, which types `execute` and `result` itself. */<TDefinition extends { action: ActionSchema }>(action: TDefinition | null,): UseActionResult<@@ -304,3 +316,15 @@ export interface UseAction {actionId: SdkActionId | null,): UseActionResult<TParameters, TKind>;}++/**+ * A data app's `useAction`: only a `defineAction(...)` export from `actions/`.+ */+export interface UseDataAppAction {+ <TDefinition extends DefinedAction & { action: ActionSchema }>(+ action: TDefinition | null,+ ): UseActionResult<+ ActionParametersFromDataAppSchema<TDefinition["action"]>,+ ActionKindFromDataAppSchema<TDefinition["action"]>+ >;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.tsindex 888de656413..2942d629e96 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts@@ -12,6 +12,7 @@ import type {ActionResultForKind,UseAction,UseActionResult,+ UseDataAppAction,} from "./types";/**@@ -92,3 +93,6 @@ const useActionImpl = </** @notExported UseAction */export const useAction: UseAction = useActionImpl;++/** @notExported UseDataAppAction */+export const useDataAppAction: UseDataAppAction = useActionImpl;diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.tsindex 5a1e12c3ad0..e851685f6f3 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts@@ -1,6 +1,7 @@import type { TableSchema } from "../data-schema";import type {+ DefinedQuery,MetabaseQueryOptions,RequireAggregationsForBreakouts,} from "./types";@@ -25,6 +26,8 @@ export function defineQuery<? RequireAggregationsForBreakouts<TQuery>: unknown: MetabaseQueryOptions<TEntity, TSchema>),-): TQuery {- return query;+): TQuery & DefinedQuery {+ // `DefinedQuery` has no runtime member, so the object is returned as is; the+ // cast only adds the mark that the query hooks require.+ return query as TQuery & DefinedQuery;}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.tsindex cede3cccba1..2f0862d9f41 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts@@ -12,6 +12,7 @@ export { breakout, filter, orderBy } from "./query-helpers";export { useMetabaseQuery } from "./use-metabase-query";export { useMetabaseQueryObject } from "./use-metabase-query-object";export type {+ DefinedQuery,LocalFieldReference,MetabaseBreakout,MetabaseDynamicColumn,diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.tsindex 4dd2803e965..ea01a750079 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts@@ -5,8 +5,14 @@ import { TEST_SCHEMA } from "./fixtures";import type { MetabaseCard } from "metabase/embedding-sdk/types/question";import type { MetabaseQueryOptions, UseMetabaseQueryObjectResult } from "..";-import { breakout, count, sum, useMetabaseQuery } from "..";-import { useAction } from "../../use-action";+import {+ breakout,+ count,+ sum,+ useMetabaseQuery,+ useMetabaseQueryObject,+} from "..";+import { useAction, useDataAppAction } from "../../use-action";import { defineAction, defineQuery } from "../../../../data-app";type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];@@ -115,10 +121,49 @@ const _invalidMetricSourceQuery = {breakout(TEST_SCHEMA.tables.orders.fields.status, { unit: "month" });function InvalidTypeFixtures() {+ const staticQuery = defineQuery({+ source: TEST_SCHEMA.tables.orders,+ savedQuestionSourceId: 41,+ });++ // @ts-expect-error a query is a `defineQuery` export from `queries/`, never an inline object+ useMetabaseQuery({ source: TEST_SCHEMA.tables.orders });++ // @ts-expect-error a query is a `defineQuery` export from `queries/`, never an inline object+ useMetabaseQueryObject({ source: TEST_SCHEMA.tables.orders });++ const plainQuery = {+ source: TEST_SCHEMA.tables.orders,+ } satisfies MetabaseQueryOptions<OrdersTable>;++ // @ts-expect-error a typed query object is still not a `defineQuery` export+ useMetabaseQuery(plainQuery);++ // @ts-expect-error a typed query object is still not a `defineQuery` export+ useMetabaseQueryObject(plainQuery);+// @ts-expect-error saved-question metadata cannot be passed to querying hooks- useMetabaseQuery({ source: TEST_SCHEMA.questions.ordersQuestion });+ defineQuery({ source: TEST_SCHEMA.questions.ordersQuestion });++ // @ts-expect-error a copy of a definition is not the definition+ useMetabaseQuery({ ...staticQuery, limit: 10 });++ // @ts-expect-error a copy of a definition is not the definition+ useMetabaseQueryObject({ ...staticQuery, limit: 10 });++ // @ts-expect-error a data app's action is a `defineAction` export from `actions/`, never an inline object+ useDataAppAction({ action: TEST_SCHEMA.models.orders.actions.create });++ // @ts-expect-error a copy of a definition is not the definition+ useDataAppAction({ ...CreateOrder });++ // @ts-expect-error a data app never names an action by id+ useDataAppAction(51);// @ts-expect-error pass the `defineAction` export, not the schema entry+ useDataAppAction(TEST_SCHEMA.models.orders.actions.create);++ // @ts-expect-error the SDK hook takes a definition object or an id, not the schema entryuseAction(TEST_SCHEMA.models.orders.actions.create);// @ts-expect-error the definition's parameter slugs are the only keys@@ -133,48 +178,41 @@ function InvalidTypeFixtures() {// @ts-expect-error `result` is discriminated by the action's kindvoid useAction(CreateOrder).result?.["rows-updated"];- const scalarAggregationResult = useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],- });+ const scalarAggregationResult = useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],+ }),+ );// @ts-expect-error aggregation result rows should not include source fieldsvoid scalarAggregationResult.data?.rows[0]?.amount;- const metricResult = useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- aggregations: [TEST_SCHEMA.metrics.revenue],- });+ const metricResult = useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ aggregations: [TEST_SCHEMA.metrics.revenue],+ }),+ );// @ts-expect-error aggregation result rows should not include source fieldsvoid metricResult.data?.rows[0]?.status;- const groupedMetricResult = useMetabaseQuery<OrdersTable>({- source: TEST_SCHEMA.tables.orders,- aggregations: [TEST_SCHEMA.metrics.revenue],- breakouts: [- breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {- unit: "month",- }),- ],- });+ const groupedMetricResult = useMetabaseQuery(+ defineQuery<OrdersTable>({+ source: TEST_SCHEMA.tables.orders,+ aggregations: [TEST_SCHEMA.metrics.revenue],+ breakouts: [+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {+ unit: "month",+ }),+ ],+ }),+ );// @ts-expect-error result row keys use returned column names, not schema object keysvoid groupedMetricResult.data?.rows[0]?.createdAt;- // @ts-expect-error grouped queries must include an explicit aggregation- useMetabaseQuery<OrdersTable>({- source: TEST_SCHEMA.tables.orders,- breakouts: [- breakout(TEST_SCHEMA.tables.orders.fields.createdAt, { unit: "month" }),- ],- });-- const staticQuery = {- source: TEST_SCHEMA.tables.orders,- savedQuestionSourceId: 41,- } satisfies MetabaseQueryOptions<OrdersTable>;-useMetabaseQuery(staticQuery, {// @ts-expect-error Segments belong to a table source, so the dynamic stage// cannot resolve one. Filter the static query with it instead.diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.tsindex b445fc7b80f..d4e6eca0d7c 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts@@ -6,7 +6,7 @@ import type { RowValue } from "../../data-schema";import type { MetabaseCard } from "metabase/embedding-sdk/types/question";-import type { MetabaseQueryOptions, UseMetabaseQueryObjectResult } from "..";+import type { UseMetabaseQueryObjectResult } from "..";import {breakout,count,@@ -16,7 +16,7 @@ import {useMetabaseQuery,useMetabaseQueryObject,} from "..";-import { useAction } from "../../use-action";+import { useAction, useDataAppAction } from "../../use-action";import { defineAction, defineQuery } from "../../../../data-app";type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];@@ -69,7 +69,7 @@ const _validHookResultCard = {function ValidTypeFixtures() {// A definition types `execute` and `result` on its own, no generics written.- const createOrder = useAction(CreateOrder);+ const createOrder = useDataAppAction(CreateOrder);void createOrder.execute({ status: "shipped" });@@ -78,10 +78,18 @@ function ValidTypeFixtures() {void createdRow;- const updateOrder = useAction(UpdateOrder);+ const updateOrder = useDataAppAction(UpdateOrder);void updateOrder.execute({ id: 1 });+ // The SDK hook takes a plain definition object, and a `defineAction` export too.+ const sdkCreateOrder = useAction({+ action: TEST_SCHEMA.models.orders.actions.create,+ });++ void sdkCreateOrder.execute({ status: "shipped" });+ void useAction(CreateOrder).execute({ status: "shipped" });+const updatedRows: readonly RowValue[] | undefined =updateOrder.result?.["rows-updated"];@@ -92,23 +100,25 @@ function ValidTypeFixtures() {void rawAction.execute({ status: "shipped" });- const selectedFieldsResult = useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- fields: [TEST_SCHEMA.tables.orders.fields.id],- });+ const selectedFieldsResult = useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ fields: [TEST_SCHEMA.tables.orders.fields.id],+ }),+ );const selectedFieldValue: number | null | undefined =selectedFieldsResult.data?.rows[0]?.ID;void selectedFieldValue;- const selectedFieldsQuery = {+ const selectedFieldsQuery = defineQuery({source: TEST_SCHEMA.tables.orders,fields: [TEST_SCHEMA.tables.orders.fields.id,TEST_SCHEMA.tables.orders.fields.status,],- } satisfies MetabaseQueryOptions<OrdersTable>;+ });const selectedFieldsQueryResult = useMetabaseQuery(selectedFieldsQuery);@@ -117,25 +127,29 @@ function ValidTypeFixtures() {void selectedQueryFieldValue;- const scalarAggregationResult = useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],- });+ const scalarAggregationResult = useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],+ }),+ );const scalarAggregationValue: RowValue | undefined =scalarAggregationResult.data?.rows[0]?.sum;void scalarAggregationValue;- const groupedMetricResult = useMetabaseQuery<OrdersTable>({- source: TEST_SCHEMA.tables.orders,- aggregations: [TEST_SCHEMA.metrics.revenue],- breakouts: [- breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {- unit: "month",- }),- ],- });+ const groupedMetricResult = useMetabaseQuery(+ defineQuery<OrdersTable>({+ source: TEST_SCHEMA.tables.orders,+ aggregations: [TEST_SCHEMA.metrics.revenue],+ breakouts: [+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {+ unit: "month",+ }),+ ],+ }),+ );const groupedMetricBreakoutValue: string | Date | null | undefined =groupedMetricResult.data?.rows[0]?.CREATED_AT;@@ -152,16 +166,18 @@ function ValidTypeFixtures() {createdAt: TEST_SCHEMA.tables.orders.fields.createdAt,} satisfies Record<string, OrdersField>;- useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- orderBys: [orderBy(sortFields[sortKey], "desc")],- });+ useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ orderBys: [orderBy(sortFields[sortKey], "desc")],+ }),+ );// A static query published as a card, with dynamic clauses layered on top.- const staticQuery = {+ const staticQuery = defineQuery({source: TEST_SCHEMA.tables.orders,savedQuestionSourceId: 41,- } satisfies MetabaseQueryOptions<OrdersTable>;+ });const dynamicResult = useMetabaseQuery(staticQuery, {filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid")],diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsxindex aa00d320975..7b293ba9972 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx@@ -17,14 +17,15 @@ import type { QueryInput } from "embedding-sdk-shared/lib/create-metabase-query/import type { DatasetQuery } from "metabase-types/api";import { filter, useMetabaseQuery, useMetabaseQueryObject } from "..";+import { defineQuery } from "../define-query";beforeEach(resetTestState);describe("useMetabaseQueryObject", () => {- const query = {+ const query = defineQuery({source: TEST_SCHEMA.tables.orders,limit: 10,- };+ });it("returns a loading state until async query creation resolves", async () => {const deferred = createDeferred<DatasetQuery>();@@ -102,15 +103,15 @@ describe("useMetabaseQueryObject", () => {const firstDeferred = createDeferred<DatasetQuery>();const secondDeferred = createDeferred<DatasetQuery>();- const firstQuery = {+ const firstQuery = defineQuery({source: TEST_SCHEMA.tables.orders,limit: 10,- };+ });- const secondQuery = {+ const secondQuery = defineQuery({source: TEST_SCHEMA.tables.orders,limit: 20,- };+ });const secondDatasetQuery = createMockDatasetQuery([{ "source-table": 1, limit: 20 },@@ -126,9 +127,13 @@ describe("useMetabaseQueryObject", () => {stubSdkBundle({ resolveDatasetQuery });+ const initialProps: {+ currentQuery: typeof firstQuery | typeof secondQuery;+ } = { currentQuery: firstQuery };+const { result, rerender } = renderHook(({ currentQuery }) => useMetabaseQueryObject(currentQuery),- { initialProps: { currentQuery: firstQuery } },+ { initialProps },);rerender({ currentQuery: secondQuery });@@ -174,7 +179,7 @@ describe("useMetabaseQueryObject", () => {const { result, rerender } = renderHook(({ queryEnabled, dynamicEnabled }) =>useMetabaseQueryObject(- { ...query, enabled: queryEnabled },+ defineQuery({ ...query, enabled: queryEnabled }),{ enabled: dynamicEnabled },),{ initialProps: disabledProps },@@ -214,7 +219,8 @@ describe("useMetabaseQueryObject", () => {});const { result, rerender } = renderHook(- ({ enabled }) => useMetabaseQueryObject({ ...query, enabled }),+ ({ enabled }) =>+ useMetabaseQueryObject(defineQuery({ ...query, enabled })),{ initialProps: { enabled: true } },);@@ -235,15 +241,15 @@ describe("useMetabaseQueryObject", () => {describe("useMetabaseQuery", () => {it("ignores a stale response after the query changes", async () => {- const firstQuery = {+ const firstQuery = defineQuery({source: TEST_SCHEMA.tables.orders,limit: 10,- };+ });- const secondQuery = {+ const secondQuery = defineQuery({source: TEST_SCHEMA.tables.orders,limit: 20,- };+ });const firstDatasetQuery = createMockDatasetQuery([{ "source-table": 1, limit: 10 },@@ -277,9 +283,13 @@ describe("useMetabaseQuery", () => {queryDataset: jest.fn(() => runDatasetQuery),});+ const initialProps: {+ currentQuery: typeof firstQuery | typeof secondQuery;+ } = { currentQuery: firstQuery };+const { result, rerender } = renderHook(({ currentQuery }) => useMetabaseQuery(currentQuery),- { initialProps: { currentQuery: firstQuery } },+ { initialProps },);await waitFor(() => expect(runDatasetQuery).toHaveBeenCalledTimes(1));@@ -341,10 +351,12 @@ describe("useMetabaseQuery", () => {});renderHook(() =>- useMetabaseQuery({- source: TEST_SCHEMA.tables.orders,- limit: 10,- }),+ useMetabaseQuery(+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ limit: 10,+ }),+ ),);expect(queryDataset).not.toHaveBeenCalled();@@ -360,7 +372,7 @@ describe("useMetabaseQuery", () => {});describe("dynamic query clauses", () => {- const staticQuery = { source: TEST_SCHEMA.tables.orders };+ const staticQuery = defineQuery({ source: TEST_SCHEMA.tables.orders });it("re-resolves when only the dynamic part changes", async () => {const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));@@ -415,7 +427,10 @@ describe("dynamic query clauses", () => {// builds them inline. The hooks key on content, so this must not refetch.const { rerender } = renderHook(() =>useMetabaseQuery(- { source: TEST_SCHEMA.tables.orders, savedQuestionSourceId: 41 },+ defineQuery({+ source: TEST_SCHEMA.tables.orders,+ savedQuestionSourceId: 41,+ }),{filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "x")],},diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.tsindex 89c6308ef20..de14fcaad60 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts@@ -554,13 +554,24 @@ export type UseMetabaseQueryResult<refetch: () => Promise<void>;};+/**+ * Marks a query as declared through `defineQuery`. The query hooks accept only+ * marked queries, so an inline query object is a compile-time error.+ *+ * @category useMetabaseQuery+ */+export declare class DefinedQuery {+ private readonly definedWithDefineQuery: true;+}+export type UseMetabaseQuery = <TEntity extends TableSchema | undefined = undefined,TSchema = unknown,- const TQuery = MetabaseQueryOptions<TEntity, TSchema>,+ const TQuery = MetabaseQueryOptions<TEntity, TSchema> & DefinedQuery,const TDynamic = undefined,>(query: TQuery &+ DefinedQuery &(TQuery extends MetabaseQueryOptions<TEntity, TSchema>? TQuery extends { source: unknown }? RequireAggregationsForBreakouts<TQuery>diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.tsindex 75eea5cb15b..c072b8a9d70 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts@@ -11,7 +11,11 @@ import {getResolveDatasetQueryFromBundle,} from "./bundle";import { stableStringifyQuery } from "./stable-query-key";-import type { MetabaseDynamicQuery, MetabaseQueryOptions } from "./types";+import type {+ DefinedQuery,+ MetabaseDynamicQuery,+ MetabaseQueryOptions,+} from "./types";export type UseMetabaseQueryObjectResult = {query: MetabaseQueryObject | null;@@ -28,7 +32,7 @@ type QueryObjectState = {* Resolves a data app query into a query object that can be passed to SDK question components.*/export function useMetabaseQueryObject(- query: MetabaseQueryOptions<undefined>,+ query: MetabaseQueryOptions<undefined> & DefinedQuery,dynamicQuery?: MetabaseDynamicQuery,): UseMetabaseQueryObjectResult {const { loadingState } = useSdkLoadingState();diff --git a/skills/metabase-data-app-actions/SKILL.md b/skills/metabase-data-app-actions/SKILL.mdindex ad21d21c40e..55360089819 100644--- a/skills/metabase-data-app-actions/SKILL.md+++ b/skills/metabase-data-app-actions/SKILL.md@@ -27,13 +27,14 @@ Before writing any action-invoking code, look at the schema and enumerate what's## The hook```ts-import { useAction } from "@metabase/embedding-sdk-react";+import { useAction } from "@metabase/embedding-sdk-react/data-app";const { execute, isExecuting, result, error, reset } = useAction(MyAction);```-- **The argument** is the `defineAction(...)` export itself — pass `MyAction`, not `MyAction.copiedActionId`. A production build then runs the synchronized copy, whose model sits in the app's own collection; the dev preview keeps running the authored action, so an app works before it has ever been synchronized. Do **not** pass `schema.models.<model>.actions.<action>` or its `.id`: the entry is a compile error, and the raw id belongs to the original model, which the app's users cannot read, so the call fails on permissions in production. Outside a data app the hook also accepts a raw numeric id or an `entity_id` string.-- **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 `implicitKind` / `type` become the kind (`"row/create"` → `"create"`, `"row/update"` → `"update"`, `"row/delete"` → `"delete"`, any `"bulk/*"` → `"bulk"`, `type === "query"` → `"sql"`). Only the raw-id form still needs them spelled out — `useAction<TParameters, TKind>(42)` — since an id describes nothing.+- **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; a data app that imports it from the main entry compiles with an unsynchronized action and fails in production.+- **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.copiedActionId`. 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 is never synchronized. A production build then runs the synchronized copy, whose model sits in the app's own collection; the dev preview keeps running the authored action, so an app works before it has ever been synchronized. Do **not** pass `schema.models.<model>.actions.<action>` or its `.id`: the entry is a compile error, and the raw id belongs to the original model, which the app's users cannot read, so the call fails on permissions in production.+- **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 `implicitKind` / `type` become the kind (`"row/create"` → `"create"`, `"row/update"` → `"update"`, `"row/delete"` → `"delete"`, any `"bulk/*"` → `"bulk"`, `type === "query"` → `"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@@ -52,7 +53,7 @@ const { execute, isExecuting, result, error, reset } = useAction(MyAction);## Canonical usage — a form that creates a row```tsx-import { useAction } from "@metabase/embedding-sdk-react";+import { useAction } from "@metabase/embedding-sdk-react/data-app";import { CreatePerson } from "../../actions/people.action";@@ -186,7 +187,7 @@ No hand-rolled `!name || !email` checks.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. Passing the schema entry is a compile error; passing its `.id` compiles but leaves `execute` untyped and 403s in production, since the authored action is not the one an app's users can run.+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 403s in production, since the authored action is not the one an app's users can run. Calling `defineAction(...)` inside the component compiles too, but `sync-resources` scans only `actions/`, so that action is never copied and also 403s.3. Log the object passed to `execute({ ... })`. Every key must match a parameter `slug` from `schema.models.<model>.actions.<action>.parameters`; every value must match its declared `jsType`.4. List every data view on the screen that reads from the mutated model. 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`).@@ -195,6 +196,8 @@ When an action appears to succeed but the screen doesn't update, or a call fails## 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 `actions/` is synchronized.- Passing `schema.models.<model>.actions.<action>.id` to `useAction` instead of the `defineAction(...)` export. `execute` then accepts any `Record<string, unknown>`, typos like `{ wrongKey: 1 }` slip through, and production 403s because the authored action is not the one an app's users can run.- 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*.diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.mdindex 0f64f6f1148..a83dd361d9e 100644--- a/skills/metabase-data-app-semantic-layer/SKILL.md+++ b/skills/metabase-data-app-semantic-layer/SKILL.md@@ -12,6 +12,7 @@ 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`.- 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.- Never remove, edit, or copy a generated `savedQuestionSourceId` or `copiedActionId`, even if it appears unused. Preserve it during refactors; use `npm run sync-resources` to repair or replace generated IDs.- 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.@@ -34,7 +35,7 @@ Keep the semantic layer and presentation layer separate.- 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]`. That erases the generated table/metric validation. Use `useMetabaseQuery<typeof table>(...)`, or type a reusable query object with `satisfies MetabaseQueryOptions<typeof table>`.+- 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.@@ -139,7 +140,7 @@ const { data } = useMetabaseQuery(RevenueQuery, {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, `savedQuestionSourceId`, `copiedActionId`, 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, and `schema.models.<model>.actions.<action>` is a type error. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — synchronization bakes them 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`.+Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, `savedQuestionSourceId`, `copiedActionId`, 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.models.<model>.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 leaves the query unsynchronized. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — synchronization bakes them 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 `"sync-resources": "embedding-sdk-react data-apps sync-resources"` and `"build": "npm run sync-resources && vite build"`, then run `npm run build` after adding, changing, renaming, or removing any definition; run `sync-resources` directly only to inspect generated state before a build. It reads `DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` from the repo-root `.env.local`.@@ -149,20 +150,22 @@ If synchronization fails, surface the exact error and stop. Fix local shape, ser## Standard pattern+Two files per query: the definition in `queries/`, the hook call in the component.+```ts+// queries/orders.query.tsimport {aggregations,breakout,+ defineQuery,filter,orderBy,- useMetabaseQuery,- useMetabaseQueryObject,} from "@metabase/embedding-sdk-react/data-app";-import schema from "../metabase.data";+import schema from "../src/metabase.data";const ordersTable = schema.tables.orders;-const { data, isLoading, error } = useMetabaseQuery({+export const PaidRevenueByMonth = defineQuery({source: ordersTable,filters: [ordersTable.segments.completed,@@ -175,7 +178,15 @@ const { data, isLoading, error } = useMetabaseQuery({});```-For direct row access, prefer letting `useMetabaseQuery(...)` infer the query shape from the inline query object. If you need a reusable query object and table ownership checks, type the object with `satisfies MetabaseQueryOptions<OrdersTable>`, then pass it to `useMetabaseQuery(query)`. Avoid forcing the hook generic on selected-field queries when you need precise row keys from `data.rows`.+```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.@@ -244,9 +255,10 @@ Do not remove or hand-edit `savedQuestionSourceId` if you find it on a query objFor a table query, pass the generated table object as `source`:```ts+// queries/records.query.tsconst recordsTable = schema.tables.records;-const { data } = useMetabaseQuery({+export const RecordStatuses = defineQuery({source: recordsTable,fields: [recordsTable.fields.id, recordsTable.fields.status],});@@ -255,7 +267,7 @@ const { data } = useMetabaseQuery({For grouped table summaries, include at least one aggregation:```ts-useMetabaseQuery({+export const ActiveAmountByMonth = defineQuery({source: recordsTable,filters: [recordsTable.segments.activeRecords,@@ -270,7 +282,7 @@ useMetabaseQuery({For basic aggregations without a curated measure, use the `aggregations` helpers:```ts-useMetabaseQuery({+export const AmountByCategory = defineQuery({source: recordsTable,aggregations: [aggregations.count(),@@ -282,17 +294,18 @@ useMetabaseQuery({When using the same helper more than once, Metabase may return numbered runtime keys such as `sum`, `sum_2`, and `sum_3`. TypeScript only models the base helper key today. For custom KPI code that intentionally uses repeated same-kind aggregations, read through `data.columns` or cast the row to `Record<string, unknown>` before accessing numbered keys. Prefer curated measures or separate queries when that is clearer.-Table fields, segments, measures, filters, breakouts, and orderBys must come from the queried table. For reusable query objects, use `satisfies MetabaseQueryOptions<RecordsTable>` so TypeScript can validate the query while preserving precise row keys.+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 recipesFor a metric-backed query, pass the generated table object as `source` and the generated metric object in `aggregations`:```ts+// queries/revenue.query.tsconst ordersTable = schema.tables.orders;const revenueMetric = schema.metrics.revenue;-const { data } = useMetabaseQuery({+export const Revenue = defineQuery({source: ordersTable,aggregations: [revenueMetric],});@@ -301,7 +314,7 @@ const { data } = useMetabaseQuery({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-useMetabaseQuery({+export const PaidRevenueByMonthAndFranchise = defineQuery({source: ordersTable,aggregations: [revenueMetric],filters: [filter(revenueMetric.dimensions.orders.status, "=", "paid")],@@ -326,7 +339,7 @@ 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-useMetabaseQuery({+export const CompletedRevenueByStatus = defineQuery({source: ordersTable,filters: [schema.tables.orders.segments.completed],aggregations: [@@ -338,16 +351,16 @@ useMetabaseQuery({});```-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. For reusable query objects, use `satisfies MetabaseQueryOptions<typeof ordersTable>` so TypeScript can validate the query while preserving precise row keys.+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 viewsTable 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`, prefer inline inference or a reusable query object with `satisfies MetabaseQueryOptions<typeof recordsTable>` so TypeScript can validate the query without losing precise result-row keys.+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: build a semantic query with `useMetabaseQueryObject`, then pass it through the SDK question component's `card` prop.+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.@@ -358,18 +371,19 @@ When wrapping `useMetabaseQueryObject` in a reusable chart/card component, destrWrong/right pattern:```tsx-const trendQuery = useMetabaseQueryObject(querySpec);+const trendQuery = useMetabaseQueryObject(TrendQuery);<InteractiveQuestion card={{ query: trendQuery }} />; // wrong-const { query: trendQuery } = useMetabaseQueryObject(querySpec);+const { query: trendQuery } = useMetabaseQueryObject(TrendQuery);<InteractiveQuestion card={{ query: trendQuery }} />; // right```Hook typing:-- `useMetabaseQuery(...)` infers typed row data from the generated `source` and query object. For reusable query objects, use `satisfies MetabaseQueryOptions<...>` on the object instead of forcing the hook generic.-- `useMetabaseQueryObject(...)` accepts no generic and returns `{ query, error, isLoading }`. Pass the `query` property to `card={{ query }}`.-- Do not use `as Parameters<typeof useMetabaseQuery>[0]` to quiet query typing errors. It hides invalid table fields, metric aggregations, and breakouts. Prefer `useMetabaseQuery<typeof table>(query)` or `const query = { ... } satisfies MetabaseQueryOptions<typeof table>`.+- 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 an unsynchronized query that fails in production.The basic prop contract is:@@ -410,19 +424,11 @@ import {type MetabaseCard,} from "@metabase/embedding-sdk-react";-import {- aggregations,- breakout,- useMetabaseQueryObject,-} from "@metabase/embedding-sdk-react/data-app";+import { useMetabaseQueryObject } from "@metabase/embedding-sdk-react/data-app";-const eventsTable = schema.tables.events;+import { AmountByMonth } from "../../queries/events.query";-const { query, isLoading, error } = useMetabaseQueryObject({- source: eventsTable,- aggregations: [aggregations.sum(eventsTable.fields.amount)],- breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],-});+const { query, isLoading, error } = useMetabaseQueryObject(AmountByMonth);if (error) {return null;@@ -442,12 +448,16 @@ return (Configured SDK visualization:```tsx-const { query, isLoading, error } = useMetabaseQueryObject({+// 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;}@@ -496,9 +506,10 @@ Do not hand-write `orderBys` object literals such as `{ field, direction }` or `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.tsconst avgQuantity = aggregations.avg(inventoryTable.fields.quantityOnHand);-const { query, error, isLoading } = useMetabaseQueryObject({+export const TopIngredientsByQuantity = defineQuery({source: inventoryTable,aggregations: [avgQuantity],breakouts: [breakout(inventoryTable.fields.ingredient)],@@ -507,11 +518,9 @@ const { query, error, isLoading } = useMetabaseQueryObject({});```-For user-selectable sorting, build a typed map of allowed generated fields instead of indexing the whole `fields` object:+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-import type { MetabaseQueryOptions } from "@metabase/embedding-sdk-react/data-app";-type SortKey = "revenue" | "orders";type ScorecardTable = typeof scorecardTable;@@ -522,12 +531,13 @@ const sortFields = {orders: scorecardTable.fields.orders,} satisfies Record<SortKey, ScorecardField>;-const query = {- source: scorecardTable,+const { data } = useMetabaseQuery(Scorecard, {orderBys: [orderBy(sortFields[sortKey], "desc")],-} satisfies MetabaseQueryOptions<ScorecardTable>;+});```+`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@@ -655,7 +665,9 @@ If no curated schema entry supports the intended UI, leave the section out or as## Final Checks-- Run `npm run typecheck`.+- 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.- Run `npm run build`; it synchronizes queries before producing the bundle.- 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.@@ -667,6 +679,9 @@ If no curated schema entry supports the intended UI, leave the section out or as## Common Mistakes- Creating or searching for Metabase content during app building.+- 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 `sync-resources` never sees it, so it is refused in production.+- Putting definitions under `src/queries/` or `src/actions/`, where `sync-resources` 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 }`.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.mdindex 29f043dcb28..6e25107896e 100644--- a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md+++ b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md@@ -27,7 +27,7 @@ Before rendering a filter, answer:Query options from Metabase at runtime with a breakout on the same generated table field or compatible Metric dimension used by the filter.-- Run a `useMetabaseQuery` breakout on the same table field or Metric dimension used by `filter(...)`, then derive a deduped option list from returned rows.+- 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.@@ -35,16 +35,20 @@ Query options from Metabase at runtime with a breakout on the same generated tabFor 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.tsconst ordersTable = schema.tables.orders;const revenueMetric = schema.metrics.revenue;const franchiseDimension = revenueMetric.dimensions.orders.franchiseId;-const { data: optionData } = useMetabaseQuery<typeof ordersTable>({+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"? []diff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.mdindex 44b65bc1d1d..00d79d02831 100644--- a/skills/metabase-data-app-setup/SKILL.md+++ b/skills/metabase-data-app-setup/SKILL.md@@ -70,6 +70,8 @@ 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 — CustomizeOnce the template is in `<repo>/data_apps/<slug>/` (run everything below from that directory):@@ -295,16 +297,21 @@ export default function CustomerCard({ customer }: { customer: Customer }) {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 — see the semantic-layer skill)├── pages/ (one file per screen)│ ├── Overview.tsx│ └── CustomerDetail.tsx├── components/ (shared UI)│ └── Card.tsx-├── hooks/ (data-fetching wrappers, custom hooks)+├── hooks/ (custom hooks that wrap a query export, never the query itself)│ └── useCustomers.ts├── lib/ (pure helpers / derivations)│ └── format.ts@@ -312,7 +319,7 @@ src/└── customer.ts```-Vite bundles everything reachable from `src/index.tsx` into a single `dist/index.js` IIFE — the folder layout is purely for your own readability.+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: `npm run build` synchronizes exactly those two root-level directories to Metabase, 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:@@ -534,6 +541,7 @@ Data apps are delivered by Git, not uploaded — you commit the app directory an| 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 synchronized. || 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`. |diff --git a/skills/metabase-data-app-setup/template/README.md b/skills/metabase-data-app-setup/template/README.mdindex 8a601330a94..b06357b3241 100644--- a/skills/metabase-data-app-setup/template/README.md+++ b/skills/metabase-data-app-setup/template/README.md@@ -42,6 +42,10 @@ import (manual "Pull changes", auto-import, or startup).├── package.json ← @metabase/embedding-sdk-react + react/react-dom + Vite toolchain├── vite.config.ts ← one-liner: `export default dataAppConfig()`├── tsconfig.json+├── queries/ ← every query, as `defineQuery(...)` exports (see its README)+│ └── README.md+├── actions/ ← every action, as `defineAction(...)` exports (see its README)+│ └── README.md├── src/│ ├── index.tsx ← entry — default-exports a factory returning { component, providerProps }│ ├── App.tsx ← edit this; pure content, no <MetabaseProvider> wrap@@ -50,6 +54,11 @@ import (manual "Pull changes", auto-import, or startup).└── .gitignore```+`queries/` and `actions/` are not optional: the query hooks accept only a+`defineQuery(...)` export and `useAction` only a `defineAction(...)` export, and+`npm run build` synchronizes exactly those two directories to Metabase. Read+their READMEs before the first hook call.+The build, dev server, Near-Membrane sandbox, and bundle contract all live inthe SDK behind `dataAppConfig()` — there's no `index.html` or separate dev entryto edit. Keep `<MetabaseProvider>` out of `App.tsx`: the production host and thediff --git a/skills/metabase-data-app-setup/template/actions/README.md b/skills/metabase-data-app-setup/template/actions/README.mdnew file mode 100644index 00000000000..8d9532a3fa4--- /dev/null+++ b/skills/metabase-data-app-setup/template/actions/README.md@@ -0,0 +1,66 @@+# 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({+ action: schema.models.orders.actions.create,+});+```++```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/`. Synchronization+ (`npm run sync-resources`, run by `npm run build`) scans only `queries/` and+ `actions/`, so a definition anywhere else is never synchronized, and the+ authored action is refused for the app's viewers in production.+- Actions exist only when the generated schema includes models+ (`include-models=true`). Synchronization copies actions; it never creates+ them.+- Pass the export itself to `useAction`. Never pass+ `schema.models.<model>.actions.<action>` or its `.id`.+- `copiedActionId` is written by synchronization. Never add, edit, or remove it+ by hand; commit it together with `resources_metadata.json`.+- After `execute` resolves, refresh every query on screen the action could have+ changed.diff --git a/skills/metabase-data-app-setup/template/queries/README.md b/skills/metabase-data-app-setup/template/queries/README.mdnew file mode 100644index 00000000000..1b7ffc88ca2--- /dev/null+++ b/skills/metabase-data-app-setup/template/queries/README.md@@ -0,0 +1,66 @@+# 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({ source: orders, limit: 100 });++export const OrdersByMonth = defineQuery({+ 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/`. `npm run+sync-resources` (run by `npm run build`) scans only `queries/` and `actions/`,+ so a definition anywhere else is never synchronized 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.+- `savedQuestionSourceId` is written by synchronization. Never add, edit, or+ remove it by hand; commit it together with `resources_metadata.json`.diff --git a/skills/metabase-data-app-setup/template/tsconfig.json b/skills/metabase-data-app-setup/template/tsconfig.jsonindex ae9cdb14735..3ab6c4c2d30 100644--- a/skills/metabase-data-app-setup/template/tsconfig.json+++ b/skills/metabase-data-app-setup/template/tsconfig.json@@ -21,5 +21,5 @@"noFallthroughCasesInSwitch": true,"types": ["vite/client"]},- "include": ["src", "vite.config.ts"]+ "include": ["src", "queries", "actions", "vite.config.ts"]}