Skip to content

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

feat(sdk): Add use-action hook for SDK (#75327)

Timofey Kachalov1a9b0c7520f4
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 48694371c6a..e68cfdd72b0 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -128,6 +128,7 @@
analytics
api
collections
+ eid-translation
lib
permissions
public-sharing
diff --git a/docs/embedding/sdk/actions.md b/docs/embedding/sdk/actions.md
new file mode 100644
index 00000000000..6ee6a626fa0
--- /dev/null
+++ b/docs/embedding/sdk/actions.md
@@ -0,0 +1,164 @@
+---
+title: "Modular embedding SDK - actions"
+summary: Trigger Metabase actions from your embedded application with the `useAction` hook.
+---
+
+# Modular embedding SDK - actions
+
+{% include plans-blockquote.html feature="Modular embedding SDK" sdk=true %}
+
+With the `useAction` hook, you can trigger an [action](../../actions/introduction.md) when someone clicks a button or submits a form in your app.
+
+The hook handles the HTTP request, exposes loading and error state as React state, and types the parameters the action expects. Basic CRUD and custom SQL actions are supported; HTTP-type actions are not. Always trigger actions through `useAction` — calling `POST /api/action/:id/execute` directly with `fetch` may be blocked in sandboxed embedding contexts.
+
+## Triggering an action with `useAction`
+
+```ts
+const { execute, isExecuting, result, error, reset } = useAction<
+ TParameters,
+ TKind // optional — drives the typed `result` shape
+>(actionId);
+```
+
+- `actionId` — the action's numeric id, its `entity_id` string, or `null`. Find the numeric id in Metabase by opening the action editor and copying it from the URL.
+- `TParameters` — a TypeScript type describing the parameters object that will be passed to `execute`. Keys are the action's parameter slugs (the names shown in the action editor).
+- `TKind` (optional) — the action's kind literal. Pass one of `"create"`, `"update"`, `"delete"`, `"bulk"`, or `"sql"` to get a typed `result` for that single shape. If you omit `TKind`, `result` defaults to a union of every possible response body (`AnyActionResult`), which you can narrow with `"<key>" in result`. See [Typing the response](#typing-the-response).
+- `execute(parameters)` — call `execute` from an event handler to trigger the action. The hook doesn't auto-fire on mount. Resolves to the response body on success, throws on failure, or resolves to `null` if `actionId` is `null`, or the SDK isn't yet initialized. You can `await execute(parameters)` or fire and forget. The same error is written to `error` state either way, so a render-time error message will appear even without a `try`/`catch`.
+- `isExecuting` — `true` between the call and its resolution. Use `isExecuting` to disable the trigger and prevent double-clicks.
+- `result` — the response body, or `null` before the first call and after `reset()`.
+- `error` — the last thrown error, or `null`. See [Error handling](#error-handling).
+- `reset()` — clears `result` and `error`.
+
+#### API Reference
+
+- [Hook](./api/useAction.html)
+- [Return type](./api/UseActionResult.html)
+
+## Example button to trigger an action
+
+This button calls a custom SQL action to apply a discount to an order:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/basic.tsx" %}
+```
+
+## Parameter keys
+
+**Send parameters keyed by `slug`**. The parameter's display `name` (e.g. `"Discount"`) won't work; you must use the slug (e.g., `"discount"`).
+
+### Parameter value types
+
+You can pass strings, number, and boolean parameters. For dates, pass an ISO 8601 string. Examples:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/parameter-values.tsx" snippet="primitives-and-dates" %}
+```
+
+#### Dates and timezones
+
+When the target column is `TIMESTAMP` without timezone, send the ISO value either _without a timezone offset_, or with the `Z` suffix:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/date-picker.tsx" snippet="timestamp-utc" %}
+```
+
+A timezone-offset value like `"2024-01-15T10:00:00+05:00"` is typically converted to UTC by the database driver, so the stored wall-clock shifts (the example above would store `05:00:00`). Exact behavior varies by warehouse — check your driver if precise timezone handling matters. For `TIMESTAMP WITH TIME ZONE` columns the offset is preserved as the same instant; for `DATE` columns timezone is irrelevant.
+
+When the value comes from a browser-local date picker (which often returns the user's local TZ), normalize before sending:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/date-picker.tsx" snippet="normalize-date" %}
+```
+
+If the string can't be parsed, the database driver throws and the message surfaces via `error.data.message` (see [Error handling](#error-handling)).
+
+## Typing the response
+
+The action's **kind** drives the shape of `result`. Pass it as the second generic to `useAction` and `result` gets typed automatically:
+
+{% include_file "{{ dirname }}/api/snippets/ActionKind.md" %}
+
+| Action kind | What it covers | `result` shape |
+| ------------------ | ------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
+| `"create"` | Single-row insert (basic action) | `{ "created-row": Record<string, RowValue> }` |
+| `"update"` | Single-row update | `{ "rows-updated": readonly RowValue[] }` |
+| `"delete"` | Single-row delete | `{ "rows-deleted": readonly RowValue[] }` |
+| `"bulk"` | Any bulk variant (bulk create / update / delete) | `{ success: boolean; "rows-created"?: number; "rows-updated"?: number; "rows-deleted"?: number }` |
+| `"sql"` | Custom SQL action | `{ "rows-affected": number }` |
+
+#### API Reference
+
+- [ActionKind](./api/ActionKind.html)
+- [AnyActionResult](./api/AnyActionResult.html)
+- [ActionResultForKind](./api/ActionResultForKind.html)
+- [ActionResultForCreate](./api/ActionResultForCreate.html)
+- [ActionResultForUpdate](./api/ActionResultForUpdate.html)
+- [ActionResultForDelete](./api/ActionResultForDelete.html)
+- [ActionResultForBulk](./api/ActionResultForBulk.html)
+- [ActionResultForSql](./api/ActionResultForSql.html)
+
+Example with a known kind:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/typed-response.tsx" snippet="known-kind" %}
+```
+
+### Reading the result
+
+It's common not to read the result at all (see [After an action succeeds, you must refresh the data](#after-an-action-succeeds-you-must-refresh-the-data)).
+
+But if you do read the result, specify `TKind` if you know the action's result up front.
+
+If you don't supply `TKind`, the `result` defaults to `AnyActionResult`, which is the union of every possible response body. TypeScript knows the result is one of the five known shapes, just not which one. You can then narrow with the `in` operator:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/typed-response.tsx" snippet="narrow-result" %}
+```
+
+The union default catches mistyped reads: if the type system can't prove `result` has a key, it'll error.
+
+## After an action succeeds, you must refresh the data
+
+When an action succeeds, you'll need to refresh any data in the UI that the action could have changed, otherwise the data on screen may be stale. There is no automatic refresh.
+
+After `execute` resolves successfully, refresh a question by remounting it: keep a `refreshKey` in state, use it as the question's `key`, and bump it after the action. The new `key` gives the question a fresh mount, which re-runs its query.
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/with-refresh.tsx" %}
+```
+
+If a single action invalidates more than one view, drive every dependent question off the same `refreshKey` so one state bump remounts them all and they re-query together:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/parallel-refresh.tsx" snippet="parallel-refresh" %}
+```
+
+Don't try to drive the state from `result` directly. The response body is for confirmation (a row count, the inserted row's primary key, etc.). You can use the `result` for toasts or detail-view navigation, but you still need to re-read the source to update the data on screen.
+
+## Error handling
+
+The hook normalizes whatever the underlying network client throws into a clean, public-facing shape and types `error` accordingly:
+
+{% include_file "{{ dirname }}/api/snippets/ActionExecuteError.md" snippet="properties" %}
+
+`error.status` is **optional**: present for HTTP-level failures (4xx / 5xx), absent for transport-layer failures (offline, aborted) where no HTTP response was received. The actionable diagnostic for end users lives at `error.data.message`.
+
+`error.data.errors` is a per-field map (`{ <slug>: <message> }`) when the backend reports parameter-level validation failures, keyed by the same parameter slugs you pass to `execute`. For whole-request failures (like a foreign-key constraint), it's an empty `{}` and the message lives in `error.data.message`.
+
+#### API Reference
+
+- [ActionExecuteError](./api/ActionExecuteError.html)
+
+For SQL or driver errors, `error.data.message` often includes a newline and the failing SQL statement on the next line, so render the error message inside an element with `white-space: pre-wrap` (a `<pre>` is fine). A `<span>` collapses the newlines into one wall of text.
+
+The basic example above renders `error.data.message` with a static fallback when no message was provided:
+
+```typescript
+{% include_file "{{ dirname }}/snippets/actions/basic.tsx" snippet="error-render" %}
+```
+
+Display the error message verbatim. Don't replace the message with a generic "Something went wrong". The raw SQL / validation / permission error is what tells the person how to fix their input.
+
+## Related
+
+- [Actions documentation](../../actions/introduction.md)
diff --git a/docs/embedding/sdk/introduction.md b/docs/embedding/sdk/introduction.md
index 84ebc14e3cc..c1049e48d4f 100644
--- a/docs/embedding/sdk/introduction.md
+++ b/docs/embedding/sdk/introduction.md
@@ -107,6 +107,7 @@ Start with one of the quickstarts, then see these pages for more info on compone
- [Questions](./questions.md)
- [AI chat](./ai-chat.md)
- [Dashboards](./dashboards.md)
+- [Actions](./actions.md)
- [Appearance](../appearance.md)
- [Collections](./collections.md)
- [Plugins](./plugins.md)
diff --git a/docs/embedding/sdk/snippets/actions/basic.tsx b/docs/embedding/sdk/snippets/actions/basic.tsx
new file mode 100644
index 00000000000..4906aa3ce67
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/basic.tsx
@@ -0,0 +1,73 @@
+import { useState } from "react";
+
+import {
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+// A Metabase action's numeric id (an `entity_id` string also works).
+// To get the id, open the action editor and copy it from the URL,
+// or fetch it via `GET /api/action`.
+const SET_DISCOUNT_ACTION_ID = 42;
+
+// Declare the parameter shape the action expects. Keys are the parameter
+// slugs (the names shown in Metabase's action editor), not internal UUIDs.
+type SetDiscountParameters = {
+ id: number;
+ discount: number;
+};
+
+function SetDiscountButton({ orderId }: { orderId: number }) {
+ const { execute, isExecuting, result, error } =
+ useAction<SetDiscountParameters>(SET_DISCOUNT_ACTION_ID);
+ const [discount, setDiscount] = useState(0.1);
+
+ const onClick = async () => {
+ try {
+ await execute({ id: orderId, discount });
+ } catch {
+ // The thrown error is also captured into `error` state, below.
+ }
+ };
+
+ return (
+ <div>
+ <label>
+ Discount:&nbsp;
+ <input
+ type="number"
+ step="0.05"
+ value={discount}
+ onChange={(e) => setDiscount(Number(e.target.value))}
+ />
+ </label>
+
+ <button onClick={onClick} disabled={isExecuting}>
+ {isExecuting ? "Applying…" : "Apply discount"}
+ </button>
+
+ {result ? <span>Done.</span> : null}
+
+ {/* [<snippet error-render>] */}
+ {error ? (
+ <pre style={{ whiteSpace: "pre-wrap" }}>
+ {error.data.message ?? "Action failed."}
+ </pre>
+ ) : null}
+ {/* [<endsnippet error-render>] */}
+ </div>
+ );
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <SetDiscountButton orderId={1} />
+ </MetabaseProvider>
+ );
+}
diff --git a/docs/embedding/sdk/snippets/actions/date-picker.tsx b/docs/embedding/sdk/snippets/actions/date-picker.tsx
new file mode 100644
index 00000000000..e272404ce6d
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/date-picker.tsx
@@ -0,0 +1,53 @@
+import { useState } from "react";
+
+import {
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+const CREATE_EVENT_ACTION_ID = 99;
+
+type CreateEventParameters = { created_at: string };
+
+function CreateEventButton() {
+ const { execute } = useAction<CreateEventParameters>(CREATE_EVENT_ACTION_ID);
+ const [datePickerValue, setDatePickerValue] = useState("2024-01-15T10:00");
+
+ const onUtcClick = async () => {
+ // [<snippet timestamp-utc>]
+ await execute({ created_at: "2024-01-15T10:00:00Z" }); // 10:00 UTC — stored as 10:00
+ // [<endsnippet timestamp-utc>]
+ };
+
+ const onClick = async () => {
+ // [<snippet normalize-date>]
+ const picked = new Date(datePickerValue);
+ await execute({ created_at: picked.toISOString() }); // always Z-suffixed
+ // [<endsnippet normalize-date>]
+ };
+
+ return (
+ <div>
+ <input
+ type="datetime-local"
+ value={datePickerValue}
+ onChange={(e) => setDatePickerValue(e.target.value)}
+ />
+ <button onClick={onClick}>Create event from picker</button>
+ <button onClick={onUtcClick}>Create event at fixed UTC</button>
+ </div>
+ );
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <CreateEventButton />
+ </MetabaseProvider>
+ );
+}
diff --git a/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx b/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx
new file mode 100644
index 00000000000..6f73a5ce5d2
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/parallel-refresh.tsx
@@ -0,0 +1,58 @@
+import { useState } from "react";
+
+import {
+ InteractiveQuestion,
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+const ORDERS_LIST_QUESTION_ID = 1;
+const ORDERS_STATS_QUESTION_ID = 2;
+const MARK_SHIPPED_ACTION_ID = 42;
+
+type MarkShippedParameters = { id: number };
+
+function OrdersScreen({ orderId }: { orderId: number }) {
+ const [refreshKey, setRefreshKey] = useState(0);
+
+ const { execute, isExecuting } = useAction<MarkShippedParameters>(
+ MARK_SHIPPED_ACTION_ID,
+ );
+
+ const onClick = async () => {
+ // [<snippet parallel-refresh>]
+ await execute({ id: orderId });
+ // One state bump remounts every dependent view, refreshing them together.
+ setRefreshKey((key) => key + 1);
+ // [<endsnippet parallel-refresh>]
+ };
+
+ return (
+ <div>
+ <InteractiveQuestion
+ key={`list-${refreshKey}`}
+ questionId={ORDERS_LIST_QUESTION_ID}
+ />
+ <InteractiveQuestion
+ key={`stats-${refreshKey}`}
+ questionId={ORDERS_STATS_QUESTION_ID}
+ />
+ <button onClick={onClick} disabled={isExecuting}>
+ {isExecuting ? "Shipping…" : "Mark order as shipped"}
+ </button>
+ </div>
+ );
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <OrdersScreen orderId={1} />
+ </MetabaseProvider>
+ );
+}
diff --git a/docs/embedding/sdk/snippets/actions/parameter-values.tsx b/docs/embedding/sdk/snippets/actions/parameter-values.tsx
new file mode 100644
index 00000000000..161a45dfdc1
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/parameter-values.tsx
@@ -0,0 +1,46 @@
+import {
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+const CREATE_PERSON_ACTION_ID = 1;
+
+type CreatePersonParameters = {
+ name: string;
+ age: number;
+ is_active: boolean;
+ birth_date: string;
+ created_at: string;
+};
+
+function CreatePersonButton() {
+ const { execute } =
+ useAction<CreatePersonParameters>(CREATE_PERSON_ACTION_ID);
+
+ const onClick = async () => {
+ // [<snippet primitives-and-dates>]
+ await execute({
+ name: "Jane", // string parameter
+ age: 30, // number parameter
+ is_active: true, // boolean parameter
+ birth_date: "1995-04-22", // date parameter, ISO format
+ created_at: "2024-01-15T10:00:00Z", // timestamp parameter, ISO with `Z` for UTC
+ });
+ // [<endsnippet primitives-and-dates>]
+ };
+
+ return <button onClick={onClick}>Create person</button>;
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <CreatePersonButton />
+ </MetabaseProvider>
+ );
+}
diff --git a/docs/embedding/sdk/snippets/actions/typed-response.tsx b/docs/embedding/sdk/snippets/actions/typed-response.tsx
new file mode 100644
index 00000000000..d2531097569
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/typed-response.tsx
@@ -0,0 +1,66 @@
+import {
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+// [<snippet known-kind>]
+const SET_DISCOUNT_ACTION_ID = 42;
+
+type SetDiscountParameters = { id: number; discount: number };
+
+function SetDiscountButton({ orderId }: { orderId: number }) {
+ const { execute, result } = useAction<SetDiscountParameters, "sql">(
+ SET_DISCOUNT_ACTION_ID,
+ );
+
+ const onClick = async () => {
+ await execute({ id: orderId, discount: 0.1 });
+ };
+
+ // result is typed `{ "rows-affected": number } | null` — no cast.
+ const affected = result?.["rows-affected"];
+
+ return (
+ <button onClick={onClick}>
+ Apply 10% discount{affected != null ? ` (${affected} rows)` : ""}
+ </button>
+ );
+}
+// [<endsnippet known-kind>]
+
+function SetDiscountButtonWithoutKind({ orderId }: { orderId: number }) {
+ // [<snippet narrow-result>]
+ const { execute, result } = useAction<SetDiscountParameters>(
+ SET_DISCOUNT_ACTION_ID,
+ );
+
+ const onClick = async () => {
+ await execute({ id: orderId, discount: 0.1 });
+ };
+
+ let summary = "Apply discount";
+ if (result && "rows-affected" in result) {
+ // `result["rows-affected"]` is typed `number` here
+ summary = `${result["rows-affected"]} rows affected`;
+ } else if (result && "created-row" in result) {
+ // `result["created-row"]` is typed `Record<string, RowValue>` here
+ summary = "Row created";
+ }
+ // [<endsnippet narrow-result>]
+
+ return <button onClick={onClick}>{summary}</button>;
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <SetDiscountButton orderId={1} />
+ <SetDiscountButtonWithoutKind orderId={1} />
+ </MetabaseProvider>
+ );
+}
diff --git a/docs/embedding/sdk/snippets/actions/with-refresh.tsx b/docs/embedding/sdk/snippets/actions/with-refresh.tsx
new file mode 100644
index 00000000000..8d70ece2cb9
--- /dev/null
+++ b/docs/embedding/sdk/snippets/actions/with-refresh.tsx
@@ -0,0 +1,58 @@
+import { useState } from "react";
+
+import {
+ InteractiveQuestion,
+ MetabaseProvider,
+ defineMetabaseAuthConfig,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+
+const authConfig = defineMetabaseAuthConfig({
+ metabaseInstanceUrl: "https://your-metabase.example.com",
+});
+
+// IDs of a saved question that lists orders and a "Mark shipped" action.
+const ORDERS_QUESTION_ID = 1;
+const MARK_SHIPPED_ACTION_ID = 42;
+
+type MarkShippedParameters = {
+ id: number;
+};
+
+function OrdersScreen() {
+ const [refreshKey, setRefreshKey] = useState(0);
+
+ return (
+ <div>
+ <InteractiveQuestion key={refreshKey} questionId={ORDERS_QUESTION_ID} />
+ <MarkAllShippedButton onShipped={() => setRefreshKey((key) => key + 1)} />
+ </div>
+ );
+}
+
+function MarkAllShippedButton({ onShipped }: { onShipped: () => void }) {
+ const { execute, isExecuting } = useAction<MarkShippedParameters>(
+ MARK_SHIPPED_ACTION_ID,
+ );
+
+ const onClick = async () => {
+ await execute({ id: 1 });
+ // Only refresh once the action has succeeded, so the question re-queries
+ // against the mutated rows.
+ onShipped();
+ };
+
+ return (
+ <button onClick={onClick} disabled={isExecuting}>
+ {isExecuting ? "Shipping…" : "Mark order as shipped"}
+ </button>
+ );
+}
+
+export default function App() {
+ return (
+ <MetabaseProvider authConfig={authConfig}>
+ <OrdersScreen />
+ </MetabaseProvider>
+ );
+}
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx
index 54a7f89f691..75aa30c6caf 100644
--- a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx
@@ -2,6 +2,7 @@ import {
InteractiveQuestion,
type MetabaseDashboard,
MetabaseProvider,
+ useAction,
useApplicationName,
useAvailableFonts,
useCreateDashboardApi,
@@ -10,7 +11,14 @@ import {
} from "@metabase/embedding-sdk-react";
import { useEffect, useState } from "react";
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import {
+ createImplicitAction,
+ createQuestion,
+ setActionsEnabledForDB,
+} from "e2e/support/helpers";
import {
DEFAULT_SDK_AUTH_PROVIDER_CONFIG,
mountSdk,
@@ -19,6 +27,9 @@ import {
mockAuthProviderAndJwtSignIn,
signInAsAdminAndEnableEmbeddingSdk,
} from "e2e/support/helpers/embedding-sdk-testing";
+import type { SdkActionId } from "embedding-sdk-bundle/types/action";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
describe("scenarios > embedding-sdk > sdk-bundle public hooks", () => {
beforeEach(() => {
@@ -250,6 +261,242 @@ describe("scenarios > embedding-sdk > sdk-bundle public hooks", () => {
});
});
+ describe("useAction", () => {
+ // Pre-create a real model + implicit action in the app DB so each test
+ // has a real numeric id to hand to the hook — not a made-up stub id
+ // that never round-trips through the backend. The outer `beforeEach`
+ // signed us out and switched to JWT-mocked auth for the SDK; we re-sign
+ // in as admin to bootstrap resources, then restore the JWT-mocked state.
+ beforeEach(() => {
+ cy.signInAsAdmin();
+ setActionsEnabledForDB(SAMPLE_DB_ID, true);
+ createQuestion({
+ name: "useAction test model",
+ type: "model",
+ // Root collection so the JWT-authed SDK user (not admin) can see
+ // the model and the action's read-check passes during execute.
+ collection_id: null,
+ query: { "source-table": ORDERS_ID },
+ }).then(({ body: model }) => {
+ createImplicitAction({
+ kind: "update",
+ model_id: model.id,
+ }).then(() => {
+ // Re-fetch the action list scoped to the model we just created
+ // rather than trusting the create response, which was flaky on CI:
+ // the create path goes through `t2/insert-returning-instances!`
+ // (see `actions/models.clj`) and intermittently yielded an id that
+ // 404'd from `eid-translation/->id-or-404` at execute time. Scoping
+ // the GET by `model-id` is unambiguous because we created exactly
+ // one action for this model.
+ cy.request("GET", `/api/action?model-id=${model.id}`).then(
+ ({ body: actions }) => {
+ const action = actions[0];
+ cy.wrap(action.id).as("actionId");
+ },
+ );
+ });
+ });
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ // Parameters match the Orders model: `id` is the PK that the
+ // `row/update` implicit action expects, plus one updatable column.
+ const ACTION_PARAMS = { id: 1, quantity: 99 } as const;
+
+ const ComponentWithHook = ({
+ actionId,
+ }: {
+ actionId: SdkActionId | null;
+ }) => {
+ // Wait for the SDK's auth flow to complete before firing the action —
+ // otherwise the legacy-client POST goes out without credentials and
+ // the backend rejects with a 401.
+ const authStatus = useMetabaseAuthStatus();
+ const { execute, result, error, isExecuting } = useAction<{
+ id: number;
+ quantity: number;
+ }>(actionId);
+
+ useEffect(() => {
+ if (authStatus?.status !== "success") {
+ return;
+ }
+ execute(ACTION_PARAMS).catch(() => {
+ // error is captured into hook state; ignore the rethrow
+ });
+ }, [execute, authStatus?.status]);
+
+ return (
+ <>
+ <div data-testid="action-result">
+ {result
+ ? JSON.stringify(result)
+ : isExecuting
+ ? "executing"
+ : "idle"}
+ </div>
+ <div data-testid="action-error">
+ {error ? (error.data.message ?? "") : ""}
+ </div>
+ </>
+ );
+ };
+
+ it("should execute the action when called inside MetabaseProvider", () => {
+ cy.get<number>("@actionId").then((actionId) => {
+ // Observe-only intercept (no reply) — the BE actually runs the
+ // implicit `row/update` against Orders and returns its real shape.
+ cy.intercept("POST", `/api/action/${actionId}/execute`).as(
+ "executeAction",
+ );
+
+ mountSdk(
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <ComponentWithHook actionId={actionId} />
+
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>,
+ );
+
+ cy.wait("@executeAction").then(({ request, response }) => {
+ expect(request.body).to.deep.equal({ parameters: ACTION_PARAMS });
+ expect(response?.statusCode).to.eq(200);
+ });
+
+ // `row/update` returns the affected primary keys under `rows-updated`.
+ cy.findByTestId("action-result").should(
+ "contain.text",
+ '"rows-updated":',
+ );
+ });
+ });
+
+ it("should execute the action when called outside MetabaseProvider", () => {
+ cy.get<number>("@actionId").then((actionId) => {
+ cy.intercept("POST", `/api/action/${actionId}/execute`).as(
+ "executeAction",
+ );
+
+ mountSdk(
+ <>
+ <ComponentWithHook actionId={actionId} />
+
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>
+ </>,
+ );
+
+ cy.wait("@executeAction").its("response.statusCode").should("eq", 200);
+
+ cy.findByTestId("action-result").should(
+ "contain.text",
+ '"rows-updated":',
+ );
+ });
+ });
+
+ it("should surface a permission-denied error from the execute endpoint", () => {
+ // This is the one test where we stub the response: the focus is on
+ // how the hook surfaces a non-2xx body via `error.data.message`,
+ // and creating a real auth scenario where the admin user lacks
+ // permission to execute their own action would require setting up a
+ // separate role + sandbox, which is out of scope for this hook test.
+ cy.get<number>("@actionId").then((actionId) => {
+ cy.intercept("POST", `/api/action/${actionId}/execute`, {
+ statusCode: 403,
+ body: { message: "You don't have permissions to do that." },
+ }).as("executeActionForbidden");
+
+ mountSdk(
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <ComponentWithHook actionId={actionId} />
+
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>,
+ );
+
+ cy.wait("@executeActionForbidden")
+ .its("response.statusCode")
+ .should("eq", 403);
+
+ cy.findByTestId("action-error").should(
+ "contain.text",
+ "You don't have permissions to do that.",
+ );
+
+ // result stays idle because execute threw before setResult.
+ cy.findByTestId("action-result").should("have.text", "idle");
+ });
+ });
+
+ it("should clear result and error when reset() is called", () => {
+ cy.get<number>("@actionId").then((actionId) => {
+ cy.intercept("POST", `/api/action/${actionId}/execute`).as(
+ "executeAction",
+ );
+
+ const ComponentWithResetButton = () => {
+ const authStatus = useMetabaseAuthStatus();
+ const { execute, result, error, isExecuting, reset } = useAction<{
+ id: number;
+ quantity: number;
+ }>(actionId);
+
+ useEffect(() => {
+ if (authStatus?.status !== "success") {
+ return;
+ }
+ execute(ACTION_PARAMS).catch(() => {
+ // error is captured into hook state; ignore the rethrow
+ });
+ }, [execute, authStatus?.status]);
+
+ return (
+ <>
+ <div data-testid="action-result">
+ {result
+ ? JSON.stringify(result)
+ : isExecuting
+ ? "executing"
+ : "idle"}
+ </div>
+ <div data-testid="action-error">
+ {error ? (error.data.message ?? "") : ""}
+ </div>
+ <button data-testid="action-reset" onClick={() => reset()}>
+ reset
+ </button>
+ </>
+ );
+ };
+
+ mountSdk(
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <ComponentWithResetButton />
+
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>,
+ );
+
+ cy.wait("@executeAction");
+ cy.findByTestId("action-result").should(
+ "contain.text",
+ '"rows-updated":',
+ );
+
+ cy.findByTestId("action-reset").click();
+
+ // The execute succeeded, so `result` was set and `error` never was —
+ // asserting `result` returns to "idle" is what proves reset() cleared
+ // the populated state.
+ cy.findByTestId("action-result").should("have.text", "idle");
+ });
+ });
+ });
+
describe("useCurrentUser", () => {
const ComponentWithHook = () => {
const user = useCurrentUser();
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.ts
new file mode 100644
index 00000000000..5e5a2be3628
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts
@@ -0,0 +1,13 @@
+export { useAction } from "./use-action";
+export type { UseActionResult } from "./use-action";
+export type {
+ ActionExecuteError,
+ ActionKind,
+ ActionResultForBulk,
+ ActionResultForCreate,
+ ActionResultForDelete,
+ ActionResultForKind,
+ ActionResultForSql,
+ ActionResultForUpdate,
+ AnyActionResult,
+} from "./types";
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts
new file mode 100644
index 00000000000..db265a97490
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts
@@ -0,0 +1,59 @@
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code -- reuse the shared abort/status error helpers rather than re-implementing them
+import { getErrorStatus, isAbortError } from "metabase/api/client/errors";
+
+import type { ActionExecuteError } from "../types";
+
+/**
+ * Adapter at the public-API boundary: takes whatever the underlying network
+ * client throws (legacy-client's wrapped response body, a native `Error`
+ * from a transport failure, anything else) and produces a clean
+ * `ActionExecuteError`. The public type must NOT leak the internal shape
+ * (`via`, `cause`, `trace`, etc.) — this helper drops it.
+ *
+ * `status` is omitted when no HTTP response was received (transport-layer
+ * failure, native `Error`, or anything that doesn't carry a numeric
+ * `status` field). `isCancelled` is `true` for `AbortError`/`DOMException`
+ * aborts so consumers can ignore user-cancelled actions without inspecting
+ * the message.
+ */
+export const toActionExecuteError = (error: unknown): ActionExecuteError => {
+ const isAbort = isAbortError(error);
+ const status = getErrorStatus(error);
+
+ if (status !== undefined) {
+ const { data, isCancelled } = error as {
+ data?: unknown;
+ isCancelled?: unknown;
+ };
+ // Most JSON error bodies are `{ message: "..." }`, but some endpoints
+ // (e.g. Metabase's "Not found.") return a plain string body — fall back
+ // to that so consumers always have a human-readable diagnostic.
+ const message =
+ typeof data === "string"
+ ? data
+ : typeof (data as { message?: unknown })?.message === "string"
+ ? (data as { message: string }).message
+ : undefined;
+ // The execute endpoint may also include an `errors` map keyed by
+ // parameter slug (`{ <slug>: <message> }`), or an empty `{}` for
+ // whole-request failures. Pass it through when present and well-shaped.
+ const rawErrors = (data as { errors?: unknown })?.errors;
+ const errors =
+ rawErrors != null &&
+ typeof rawErrors === "object" &&
+ !Array.isArray(rawErrors)
+ ? (rawErrors as Record<string, string>)
+ : undefined;
+
+ return {
+ status,
+ data: { message, ...(errors ? { errors } : {}) },
+ isCancelled: isAbort || Boolean(isCancelled),
+ };
+ }
+
+ return {
+ data: { message: error instanceof Error ? error.message : String(error) },
+ isCancelled: isAbort,
+ };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts
new file mode 100644
index 00000000000..254ca65182b
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts
@@ -0,0 +1,268 @@
+import { toActionExecuteError } from "./to-action-execute-error";
+
+describe("toActionExecuteError", () => {
+ describe("HTTP-shaped input (legacy-client throw)", () => {
+ it("normalizes a typical 4xx response", () => {
+ const result = toActionExecuteError({
+ status: 403,
+ data: { message: "denied" },
+ isCancelled: false,
+ });
+
+ expect(result).toEqual({
+ status: 403,
+ data: { message: "denied" },
+ isCancelled: false,
+ });
+ });
+
+ it("preserves a 5xx status", () => {
+ const result = toActionExecuteError({
+ status: 500,
+ data: { message: "internal" },
+ isCancelled: false,
+ });
+
+ expect(result.status).toBe(500);
+ });
+
+ it("passes through the per-field `errors` map but drops internal fields (via / cause / trace)", () => {
+ const result = toActionExecuteError({
+ status: 400,
+ data: {
+ message: "bad input",
+ errors: { discount: "must be positive" },
+ via: [{ type: ":db-error" }],
+ cause: { foo: "bar" },
+ trace: ["frame-1", "frame-2"],
+ },
+ isCancelled: false,
+ // an unrelated top-level field a future legacy-client could add
+ diagnostic: "raw",
+ });
+
+ expect(result).toEqual({
+ status: 400,
+ data: {
+ message: "bad input",
+ errors: { discount: "must be positive" },
+ },
+ isCancelled: false,
+ });
+ expect(result.data).not.toHaveProperty("via");
+ expect(result.data).not.toHaveProperty("cause");
+ expect(result.data).not.toHaveProperty("trace");
+ expect(result).not.toHaveProperty("diagnostic");
+ });
+
+ it("extracts the message from a raw driver error (via / trace / cause / nested data dropped)", () => {
+ const sqlMessage =
+ 'Value too long for column "STATE CHARACTER(2)": "\'dasddasd\' (8)"; SQL statement:\n' +
+ 'INSERT INTO "PUBLIC"."PEOPLE" ("STATE", "NAME", "EMAIL") VALUES (CAST(? AS VARCHAR), CAST(? AS VARCHAR), CAST(? AS VARCHAR)) [22001-214]';
+
+ const result = toActionExecuteError({
+ status: 400,
+ data: {
+ via: [{ type: "clojure.lang.ExceptionInfo", message: sqlMessage }],
+ trace: [
+ ["metabase.driver.sql_jdbc.actions", "invoke", "actions.clj", 71],
+ ],
+ cause: sqlMessage,
+ data: { message: sqlMessage, "status-code": 400 },
+ message: sqlMessage,
+ },
+ });
+
+ // message preserved verbatim (incl. the SQL statement + newline); no errors key
+ expect(result).toEqual({
+ status: 400,
+ data: { message: sqlMessage },
+ isCancelled: false,
+ });
+ expect(result.data).not.toHaveProperty("via");
+ expect(result.data).not.toHaveProperty("trace");
+ expect(result.data).not.toHaveProperty("cause");
+ expect(result.data).not.toHaveProperty("errors");
+ // the nested internal `data` block must not leak through
+ expect(result.data).not.toHaveProperty("status-code");
+ });
+
+ it("surfaces a whole-request failure with an empty `errors` map (e.g. FK constraint)", () => {
+ const result = toActionExecuteError({
+ status: 400,
+ data: {
+ message: "Other rows refer to this row so it cannot be deleted.",
+ errors: {},
+ },
+ isCancelled: false,
+ });
+
+ expect(result).toEqual({
+ status: 400,
+ data: {
+ message: "Other rows refer to this row so it cannot be deleted.",
+ errors: {},
+ },
+ isCancelled: false,
+ });
+ });
+
+ it("keeps `errors` even when there is no string message", () => {
+ const result = toActionExecuteError({
+ status: 403,
+ data: { errors: { id: "required" } },
+ isCancelled: false,
+ });
+
+ expect(result).toEqual({
+ status: 403,
+ data: { message: undefined, errors: { id: "required" } },
+ isCancelled: false,
+ });
+ });
+
+ it("omits `errors` when the body has none", () => {
+ const result = toActionExecuteError({
+ status: 403,
+ data: { message: "denied" },
+ isCancelled: false,
+ });
+
+ expect(result.data).not.toHaveProperty("errors");
+ });
+
+ it("ignores a non-object `errors` value", () => {
+ const result = toActionExecuteError({
+ status: 400,
+ data: { message: "x", errors: "not-a-map" },
+ isCancelled: false,
+ });
+
+ expect(result.data).not.toHaveProperty("errors");
+ });
+
+ it("coerces a truthy isCancelled to true", () => {
+ const result = toActionExecuteError({
+ status: 0,
+ data: { message: "aborted" },
+ isCancelled: 1,
+ });
+
+ expect(result.isCancelled).toBe(true);
+ });
+
+ it("defaults missing isCancelled to false", () => {
+ const result = toActionExecuteError({
+ status: 500,
+ data: { message: "x" },
+ });
+
+ expect(result.isCancelled).toBe(false);
+ });
+ });
+
+ describe("non-HTTP input (transport / unknown)", () => {
+ it("normalizes a native Error using its message and omits status", () => {
+ const result = toActionExecuteError(new Error("boom"));
+
+ expect(result).toEqual({
+ data: { message: "boom" },
+ isCancelled: false,
+ });
+ expect(result.status).toBeUndefined();
+ });
+
+ it("normalizes a string by using it as the message", () => {
+ const result = toActionExecuteError("oops");
+
+ expect(result).toEqual({
+ data: { message: "oops" },
+ isCancelled: false,
+ });
+ });
+
+ it("normalizes null with a 'null' message", () => {
+ const result = toActionExecuteError(null);
+
+ expect(result).toEqual({
+ data: { message: "null" },
+ isCancelled: false,
+ });
+ });
+
+ it("normalizes undefined with an 'undefined' message", () => {
+ const result = toActionExecuteError(undefined);
+
+ expect(result).toEqual({
+ data: { message: "undefined" },
+ isCancelled: false,
+ });
+ });
+
+ it("falls back when status is non-numeric (e.g. stringly-typed)", () => {
+ const result = toActionExecuteError({
+ status: "403",
+ data: { message: "denied" },
+ });
+
+ // Non-numeric status → treated as unknown shape, no status emitted.
+ expect(result.status).toBeUndefined();
+ expect(result.data.message).toBe("[object Object]");
+ });
+
+ it("falls back when there is no status field at all", () => {
+ const result = toActionExecuteError({
+ data: { message: "denied" },
+ });
+
+ expect(result.status).toBeUndefined();
+ });
+
+ it("marks AbortError-shaped errors as cancelled", () => {
+ const abort = Object.assign(new Error("Aborted"), {
+ name: "AbortError" as const,
+ });
+
+ const result = toActionExecuteError(abort);
+
+ expect(result.isCancelled).toBe(true);
+ expect(result.data.message).toBe("Aborted");
+ });
+
+ it("marks a DOMException AbortError as cancelled", () => {
+ const result = toActionExecuteError(
+ new DOMException("Aborted", "AbortError"),
+ );
+
+ expect(result.isCancelled).toBe(true);
+ });
+ });
+
+ describe("plain-string body", () => {
+ it("uses the body string as the message when data is a string", () => {
+ const result = toActionExecuteError({
+ status: 404,
+ data: "Not found.",
+ });
+
+ expect(result).toEqual({
+ status: 404,
+ data: { message: "Not found." },
+ isCancelled: false,
+ });
+ });
+ });
+
+ it("never leaks the original reference — output is always a fresh object", () => {
+ const input = {
+ status: 400,
+ data: { message: "x" },
+ isCancelled: false,
+ };
+
+ const result = toActionExecuteError(input);
+
+ expect(result).not.toBe(input);
+ expect(result.data).not.toBe(input.data);
+ });
+});
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.ts
new file mode 100644
index 00000000000..b420d570f47
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts
@@ -0,0 +1,130 @@
+/**
+ * Public types for the `useAction` hook surface.
+ *
+ * The hook is schema-agnostic — these types describe just the action kind
+ * union and the discriminated `result` shape it drives. A future Data App
+ * integration will layer schema-derived helpers (`ActionParametersFromDataAppSchema`,
+ * `ActionKindFromDataAppSchema`) on top; they are NOT shipped from this
+ * branch.
+ */
+
+import type { RowValue } from "metabase-types/api";
+
+/**
+ * Flat public kind union. Maps onto the backend's namespaced
+ * `row/*` + `bulk/*` `implicitKind` and the `query` `type` value, but
+ * exposes a simpler five-value surface to callers: `create` / `update` /
+ * `delete` always refer to a single row, `bulk` covers any bulk variant,
+ * and `sql` covers custom SQL actions (the backend's `query`-type action).
+ *
+ * @category useAction
+ */
+export type ActionKind = "create" | "update" | "delete" | "bulk" | "sql";
+
+/**
+ * Response from a single-row create — the inserted row.
+ *
+ * @category useAction
+ */
+export type ActionResultForCreate = {
+ "created-row": Record<string, RowValue>;
+};
+
+/**
+ * Response from a single-row update — the affected primary keys.
+ *
+ * @category useAction
+ */
+export type ActionResultForUpdate = {
+ "rows-updated": readonly RowValue[];
+};
+
+/**
+ * Response from a single-row delete — the affected primary keys.
+ *
+ * @category useAction
+ */
+export type ActionResultForDelete = {
+ "rows-deleted": readonly RowValue[];
+};
+
+/**
+ * Response from any bulk variant — a success flag plus optional counts.
+ *
+ * @category useAction
+ */
+export type ActionResultForBulk = {
+ success: boolean;
+ "rows-created"?: number;
+ "rows-updated"?: number;
+ "rows-deleted"?: number;
+};
+
+/**
+ * Response from a custom SQL action — the affected row count.
+ *
+ * @category useAction
+ */
+export type ActionResultForSql = {
+ "rows-affected": number;
+};
+
+/**
+ * Union of every possible response body. Used as the `result` default when
+ * `TKind` is omitted, so authors who don't know the action's kind upfront
+ * still get TS-narrowable shapes (via `"<key>" in result`) instead of a
+ * permissive `Record<string, unknown>` that swallows mistyped reads.
+ *
+ * @category useAction
+ */
+export type AnyActionResult =
+ | ActionResultForCreate
+ | ActionResultForUpdate
+ | ActionResultForDelete
+ | ActionResultForBulk
+ | ActionResultForSql;
+
+/**
+ * Shape of the thrown error captured into the hook's `error` state on a
+ * non-2xx response. The hook types `error` as `ActionExecuteError | null`,
+ * so consumers read its fields directly — no cast needed:
+ *
+ * const message = error?.data?.message;
+ *
+ * `error.data.message` is the actionable diagnostic for end users.
+ * `error.data.errors` is a per-field map (`{ <slug>: <message> }`) when the
+ * backend reports parameter-level validation failures; it is `{}` for
+ * whole-request failures (e.g. a foreign-key constraint:
+ * `{ message: "Other rows refer to this row…", errors: {} }`).
+ * `status` is absent for transport-layer failures (offline, aborted) where
+ * no HTTP response was received.
+ *
+ * @category useAction
+ */
+export type ActionExecuteError = {
+ status?: number;
+ data: {
+ message?: string;
+ errors?: Record<string, string>;
+ };
+ isCancelled: boolean;
+};
+
+/**
+ * Maps an `ActionKind` literal to the discriminated `result` shape. Omit
+ * `TKind` (`undefined`) to fall back to the `AnyActionResult` union.
+ *
+ * @category useAction
+ */
+export type ActionResultForKind<TKind extends ActionKind | undefined> =
+ TKind extends "create"
+ ? ActionResultForCreate
+ : TKind extends "update"
+ ? ActionResultForUpdate
+ : TKind extends "delete"
+ ? ActionResultForDelete
+ : TKind extends "bulk"
+ ? ActionResultForBulk
+ : TKind extends "sql"
+ ? ActionResultForSql
+ : AnyActionResult;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.stories.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.stories.tsx
new file mode 100644
index 00000000000..0524dca48c2
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.stories.tsx
@@ -0,0 +1,80 @@
+import type { StoryFn } from "@storybook/react";
+import type { JSXElementConstructor } from "react";
+
+import { getStorybookSdkAuthConfigForUser } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";
+import { MetabaseProvider } from "embedding-sdk-package/components/public/MetabaseProvider";
+import { getHostedBundleStoryDecorator } from "embedding-sdk-package/test/getHostedBundleStoryDecorator";
+import { Box, Button, Stack, Text } from "metabase/ui";
+
+import { useAction } from "./use-action";
+
+const config = getStorybookSdkAuthConfigForUser("admin");
+
+const ACTION_ID = 1;
+
+type SetDiscountParameters = {
+ id: string;
+ discount: number;
+};
+
+export default {
+ title: "EmbeddingSDK/use-action",
+ decorators: [getHostedBundleStoryDecorator()],
+};
+
+const HookTemplate: StoryFn<
+ JSXElementConstructor<Record<string, never>>
+> = () => {
+ const { execute, isExecuting, result, error, reset } =
+ useAction<SetDiscountParameters>(ACTION_ID);
+
+ const handleExecute = async () => {
+ try {
+ await execute({ id: "1", discount: 0.1 });
+ } catch {
+ // error is captured in hook state for render-time display
+ }
+ };
+
+ return (
+ <MetabaseProvider authConfig={config}>
+ <Box p="md">
+ <Stack gap="md">
+ <Button disabled={isExecuting} onClick={handleExecute}>
+ {isExecuting ? "Executing…" : `Execute action ${ACTION_ID}`}
+ </Button>
+
+ {result ? (
+ <Box>
+ <Text fw="bold">Result</Text>
+ <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
+ {JSON.stringify(result, null, 2)}
+ </pre>
+ <Button mt="xs" variant="subtle" onClick={reset}>
+ Reset
+ </Button>
+ </Box>
+ ) : null}
+
+ {error ? (
+ <Box>
+ <Text c="error" fw="bold">
+ Error
+ </Text>
+ <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
+ {error.data.message ?? "Action failed."}
+ </pre>
+ <Button mt="xs" variant="subtle" onClick={reset}>
+ Dismiss
+ </Button>
+ </Box>
+ ) : null}
+ </Stack>
+ </Box>
+ </MetabaseProvider>
+ );
+};
+
+export const Default = {
+ render: HookTemplate,
+};
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.ts
new file mode 100644
index 00000000000..a4f6f538fb1
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts
@@ -0,0 +1,130 @@
+import { useCallback, useState } from "react";
+
+import type { ExecuteActionResult } from "embedding-sdk-bundle/lib/execute-action";
+import type { SdkActionId } from "embedding-sdk-bundle/types/action";
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+
+import { toActionExecuteError } from "./lib/to-action-execute-error";
+import type {
+ ActionExecuteError,
+ ActionKind,
+ ActionResultForKind,
+} from "./types";
+
+/**
+ * @interface
+ * @expand
+ * @category useAction
+ */
+export type UseActionResult<
+ TParameters extends Record<string, unknown> = Record<string, unknown>,
+ TKind extends ActionKind | undefined = undefined,
+> = {
+ /**
+ * Trigger the action with the given parameters. Returns the response body
+ * on success AND throws on failure — the same error is stored in `error`
+ * for render-time consumers. Resolves to the discriminated `result` shape
+ * (see `ActionResultForKind<TKind>`); when `TKind` is omitted it resolves
+ * to `AnyActionResult`, narrowable via `"<key>" in r`.
+ *
+ * Resolves to `null` (without making a request) when `actionId` is `null`
+ * or the SDK is not yet initialized — guard the host-side caller with
+ * `if (!actionId) return;` if these cases are reachable.
+ */
+ execute: (
+ parameters: TParameters,
+ ) => Promise<ActionResultForKind<TKind> | null>;
+ isExecuting: boolean;
+ /** Last response, or `null` before first call and after `reset()`. */
+ result: ActionResultForKind<TKind> | null;
+ /** Last thrown error, normalized to the public `ActionExecuteError` shape, or `null`. */
+ error: ActionExecuteError | null;
+ /** Clear `result` and `error`. */
+ reset: () => void;
+};
+
+/**
+ * Triggers a pre-existing Metabase action. The first arg is the action's
+ * numeric id or its `entity_id` string; supply `TParameters` as the first
+ * generic to type the `execute` argument, and optionally `TKind` as the
+ * second generic to type the discriminated `result` shape.
+ *
+ * Without `TKind`, `result` defaults to a union of every possible response
+ * body (`AnyActionResult`) — authors who don't know the kind upfront can
+ * narrow with `"<key>" in result` instead of casting from
+ * `Record<string, unknown>`.
+ *
+ * useAction<{ name: string; email: string }, "create">(42);
+ *
+ * Unlike the query hooks, this does NOT run on mount — the caller invokes
+ * `execute` explicitly from an event handler. To gate execution
+ * conditionally, branch in the event handler (e.g.
+ * `if (!user.canEdit) return;`) before calling `execute`.
+ *
+ * @function
+ * @category useAction
+ */
+export const useAction = <
+ TParameters extends Record<string, unknown> = Record<string, unknown>,
+ TKind extends ActionKind | undefined = undefined,
+>(
+ actionId: SdkActionId | null,
+): UseActionResult<TParameters, TKind> => {
+ const {
+ state: {
+ internalProps: { reduxStore },
+ },
+ } = useMetabaseProviderPropsStore();
+
+ const executeAction =
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.executeAction;
+
+ const [result, setResult] = useState<ActionResultForKind<TKind> | null>(null);
+ const [isExecuting, setIsExecuting] = useState(false);
+ const [error, setError] = useState<ActionExecuteError | null>(null);
+
+ const reset = useCallback(() => {
+ setResult(null);
+ setError(null);
+ }, []);
+
+ const execute = useCallback(
+ async (
+ parameters: TParameters,
+ ): Promise<ActionResultForKind<TKind> | null> => {
+ if (actionId == null || !reduxStore || !executeAction) {
+ return null;
+ }
+
+ setIsExecuting(true);
+ setError(null);
+
+ try {
+ const raw: ExecuteActionResult = await executeAction(reduxStore)({
+ actionId,
+ parameters,
+ });
+ const next = raw as ActionResultForKind<TKind>;
+ setResult(next);
+ return next;
+ } catch (err) {
+ const adapted = toActionExecuteError(err);
+ setError(adapted);
+ setResult(null);
+ throw adapted;
+ } finally {
+ setIsExecuting(false);
+ }
+ },
+ [actionId, executeAction, reduxStore],
+ );
+
+ return {
+ execute,
+ isExecuting,
+ result,
+ error,
+ reset,
+ };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.unit.spec.tsx
new file mode 100644
index 00000000000..e5d19fa8a2a
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.unit.spec.tsx
@@ -0,0 +1,169 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { screen, waitFor } from "__support__/ui";
+import { executeAction } from "embedding-sdk-bundle/lib/execute-action";
+import { getLoginStatus } from "embedding-sdk-bundle/store/selectors";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import type { SdkActionId } from "embedding-sdk-bundle/types/action";
+
+import { useAction } from "./use-action";
+
+const TEST_ACTION_ID = 42;
+const EXECUTE_PATH = `path:/api/action/${TEST_ACTION_ID}/execute`;
+
+describe("useAction", () => {
+ it("exposes the hook surface in its initial idle state", () => {
+ setup();
+
+ expect(screen.getByTestId("status")).toHaveTextContent("idle");
+ expect(screen.getByTestId("result")).toHaveTextContent("null");
+ expect(screen.getByTestId("error")).toHaveTextContent("null");
+ });
+
+ it("populates result on a successful execute", async () => {
+ const { onResolved } = setup({ body: { "rows-affected": 7 } });
+
+ await userEvent.click(screen.getByText("execute"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("result")).toHaveTextContent(
+ '"rows-affected":7',
+ ),
+ );
+ expect(screen.getByTestId("status")).toHaveTextContent("idle");
+ expect(screen.getByTestId("error")).toHaveTextContent("null");
+ expect(onResolved).toHaveBeenCalledWith({ "rows-affected": 7 });
+ expect(fetchMock.callHistory.calls(EXECUTE_PATH)).toHaveLength(1);
+ });
+
+ it("populates error and leaves result null on failure", async () => {
+ setup({ status: 403, body: { message: "denied" } });
+
+ await userEvent.click(screen.getByText("execute"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("error")).toHaveTextContent("denied"),
+ );
+ expect(screen.getByTestId("result")).toHaveTextContent("null");
+ expect(screen.getByTestId("status")).toHaveTextContent("idle");
+ });
+
+ it("clears result and error when reset is called", async () => {
+ setup({ body: { "rows-affected": 7 } });
+
+ await userEvent.click(screen.getByText("execute"));
+ await waitFor(() =>
+ expect(screen.getByTestId("result")).toHaveTextContent(
+ '"rows-affected":7',
+ ),
+ );
+
+ await userEvent.click(screen.getByText("reset"));
+
+ expect(screen.getByTestId("result")).toHaveTextContent("null");
+ expect(screen.getByTestId("error")).toHaveTextContent("null");
+ });
+
+ it("resolves to null and skips the request when actionId is null", async () => {
+ const { onResolved } = setup({ actionId: null });
+
+ await userEvent.click(screen.getByText("execute"));
+
+ await waitFor(() => expect(onResolved).toHaveBeenCalledWith(null));
+ expect(fetchMock.callHistory.calls(EXECUTE_PATH)).toHaveLength(0);
+ });
+
+ it("resolves to null when the SDK bundle has not loaded", async () => {
+ const { onResolved } = setup({ bundleLoaded: false });
+
+ await userEvent.click(screen.getByText("execute"));
+
+ await waitFor(() => expect(onResolved).toHaveBeenCalledWith(null));
+ expect(fetchMock.callHistory.calls(EXECUTE_PATH)).toHaveLength(0);
+ });
+
+ it("accepts an entity_id string as actionId and routes the call to /api/action/:eid/execute", async () => {
+ const ENTITY_ID = "abc123def456abc123def";
+ const eidPath = `path:/api/action/${ENTITY_ID}/execute`;
+ fetchMock.post(eidPath, { status: 200, body: { "rows-affected": 1 } });
+
+ const { onResolved } = setup({ actionId: ENTITY_ID });
+
+ await userEvent.click(screen.getByText("execute"));
+
+ await waitFor(() =>
+ expect(onResolved).toHaveBeenCalledWith({ "rows-affected": 1 }),
+ );
+ expect(fetchMock.callHistory.calls(eidPath)).toHaveLength(1);
+ expect(fetchMock.callHistory.calls(EXECUTE_PATH)).toHaveLength(0);
+ });
+});
+
+type SetupProps = {
+ actionId?: SdkActionId | null;
+ status?: number;
+ body?: Record<string, unknown>;
+ bundleLoaded?: boolean;
+};
+
+function setup({
+ actionId = TEST_ACTION_ID,
+ status = 200,
+ body = { "rows-affected": 7 },
+ bundleLoaded = true,
+}: SetupProps = {}) {
+ fetchMock.post(EXECUTE_PATH, { status, body });
+
+ const onResolved = jest.fn();
+ const { state } = setupSdkState();
+
+ renderWithSDKProviders(
+ <TestComponent actionId={actionId} onResolved={onResolved} />,
+ {
+ metabaseEmbeddingSdkBundleExports: bundleLoaded
+ ? { executeAction, getLoginStatus }
+ : undefined,
+ storeInitialState: state,
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ },
+ );
+
+ return { onResolved };
+}
+
+const TestComponent = ({
+ actionId,
+ onResolved,
+}: {
+ actionId: SdkActionId | null;
+ onResolved: (value: unknown) => void;
+}) => {
+ const { execute, isExecuting, result, error, reset } = useAction<{
+ amount: number;
+ }>(actionId);
+
+ const onExecute = async () => {
+ try {
+ onResolved(await execute({ amount: 1 }));
+ } catch {
+ // captured into error state; the test reads from there
+ }
+ };
+
+ return (
+ <div>
+ <button onClick={onExecute}>execute</button>
+ <button onClick={reset}>reset</button>
+ <div data-testid="status">{isExecuting ? "executing" : "idle"}</div>
+ <div data-testid="result">{result ? JSON.stringify(result) : "null"}</div>
+ <div data-testid="error">
+ {error ? (error.data.message ?? "") : "null"}
+ </div>
+ </div>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.ts
index 66423f4d738..9a21f49dad8 100644
--- a/enterprise/frontend/src/embedding-sdk-package/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts
@@ -29,6 +29,19 @@ export { useCurrentUser } from "./hooks/public/use-current-user";
export { useMetabot } from "./hooks/public/use-metabot";
export { useCreateDashboardApi } from "./hooks/public/use-create-dashboard-api";
export { useMetabaseAuthStatus } from "./hooks/public/use-metabase-auth-status";
+export { useAction } from "./hooks/public/use-action";
+export type {
+ ActionExecuteError,
+ ActionKind,
+ ActionResultForBulk,
+ ActionResultForCreate,
+ ActionResultForDelete,
+ ActionResultForKind,
+ ActionResultForSql,
+ ActionResultForUpdate,
+ AnyActionResult,
+ UseActionResult,
+} from "./hooks/public/use-action";
export { defineMetabaseAuthConfig } from "./lib/public/define-metabase-auth-config";
export { defineMetabaseTheme } from "./lib/public/define-metabase-theme";
@@ -145,6 +158,7 @@ export type {
SqlParameterChangePayload,
SdkUserId,
SqlParameterValues,
+ SdkActionId,
} from "embedding-sdk-bundle/types";
export type {
diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.ts
index 01336c04104..9ba96c2a529 100644
--- a/frontend/src/embedding-sdk-bundle/index.ts
+++ b/frontend/src/embedding-sdk-bundle/index.ts
@@ -43,6 +43,7 @@ import { getUser } from "metabase/selectors/user";
import { useInitData } from "./hooks/private/use-init-data";
import { useLogVersionInfo } from "embedding-sdk-bundle/hooks/private/use-log-version-info";
import { createDashboard } from "embedding-sdk-bundle/lib/create-dashboard";
+import { executeAction } from "embedding-sdk-bundle/lib/execute-action";
import { defineBuildInfo } from "metabase/embedding-sdk/lib/define-build-info";
import { validateFunctionSchema } from "embedding-sdk-bundle/lib/validate-function-schema";
@@ -75,6 +76,7 @@ const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {
useLogVersionInfo,
validateFunctionSchema,
MetabotSubscriber,
+ executeAction,
};
// Define a global export METABASE_EMBEDDING_SDK_BUNDLE for SDK package
diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
new file mode 100644
index 00000000000..3b08c16cf3a
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
@@ -0,0 +1,37 @@
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import type { SdkActionId } from "embedding-sdk-bundle/types/action";
+import { POST } from "metabase/api/legacy-client";
+
+type ActionParametersPayload = Record<string, unknown>;
+
+export type ExecuteActionParams = {
+ actionId: SdkActionId;
+ parameters?: ActionParametersPayload;
+};
+
+/**
+ * Loose response shape from `POST /api/action/:id/execute`. The body varies
+ * by action kind (created-row / rows-updated / rows-deleted / rows-affected
+ * / success+counts). Per-kind discrimination happens in the package hook
+ * via the generated `ActionResult<TAction>` type — this lib stays loose.
+ *
+ * HTTP actions are rejected at the backend and never reach this code path.
+ */
+export type ExecuteActionResult = Record<string, unknown>;
+
+/**
+ * Triggers a pre-existing Metabase action. The curried `(store) => fn`
+ * shape mirrors `createDashboard` / `queryQuestion` / `queryMetric` so the
+ * package hook can read `executeAction(reduxStore)({...})` off
+ * `window.METABASE_EMBEDDING_SDK_BUNDLE`. The store isn't actually used
+ * today — the call is a same-origin POST — but the signature is preserved
+ * for parity with the other bundle utilities.
+ */
+export const executeAction =
+ (_reduxStore: SdkStore) =>
+ async ({
+ actionId,
+ parameters = {},
+ }: ExecuteActionParams): Promise<ExecuteActionResult> => {
+ return await POST(`/api/action/${actionId}/execute`)({ parameters });
+ };
diff --git a/frontend/src/embedding-sdk-bundle/types/action.ts b/frontend/src/embedding-sdk-bundle/types/action.ts
new file mode 100644
index 00000000000..ee12de6ae5f
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/types/action.ts
@@ -0,0 +1,3 @@
+import type { SdkEntityId } from "embedding-sdk-bundle/types/entity";
+
+export type SdkActionId = number | SdkEntityId;
diff --git a/frontend/src/embedding-sdk-bundle/types/index.ts b/frontend/src/embedding-sdk-bundle/types/index.ts
index e12eb46a71e..d60b4f0a9d0 100644
--- a/frontend/src/embedding-sdk-bundle/types/index.ts
+++ b/frontend/src/embedding-sdk-bundle/types/index.ts
@@ -1,3 +1,4 @@
+export type * from "./action";
export type * from "./auth-config";
export type * from "./collection";
export type * from "./dashboard";
diff --git a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
index 1b776ab9c86..976d9561959 100644
--- a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
+++ b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
@@ -12,6 +12,10 @@ import type { StaticQuestion } from "embedding-sdk-bundle/components/public/Stat
import type { EditableDashboard } from "embedding-sdk-bundle/components/public/dashboard/EditableDashboard";
import type { InteractiveDashboard } from "embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard";
import type { StaticDashboard } from "embedding-sdk-bundle/components/public/dashboard/StaticDashboard";
+import type {
+ ExecuteActionParams,
+ ExecuteActionResult,
+} from "embedding-sdk-bundle/lib/execute-action";
import type { SdkStore, SdkStoreState } from "embedding-sdk-bundle/store/types";
import type {
CreateDashboardValues,
@@ -65,6 +69,9 @@ type ReduxStoreUtilityFunctionExports = {
createDashboard: ReduxStoreUtilityFunction<
(params: CreateDashboardValues) => Promise<MetabaseDashboard>
>;
+ executeAction: ReduxStoreUtilityFunction<
+ (params: ExecuteActionParams) => Promise<ExecuteActionResult>
+ >;
};
type ReduxStoreSelectorsExports = {
diff --git a/frontend/src/metabase-types/api/dataset.ts b/frontend/src/metabase-types/api/dataset.ts
index fe87cf82b01..8445da3f9a8 100644
--- a/frontend/src/metabase-types/api/dataset.ts
+++ b/frontend/src/metabase-types/api/dataset.ts
@@ -20,6 +20,9 @@ import type { DownloadPermission } from "./permissions";
import type { DatasetQuery, DatetimeUnit, DimensionReference } from "./query";
import type { TableId } from "./table";
+/**
+ * @inline
+ */
export type RowValue = string | number | null | boolean | object;
export type RowValues = RowValue[];
diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.clj
index 6474c6c212f..8aee2396097 100644
--- a/src/metabase/actions_rest/api.clj
+++ b/src/metabase/actions_rest/api.clj
@@ -7,6 +7,7 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.collections.models.collection :as collection]
+ [metabase.eid-translation.core :as eid-translation]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.permissions.core :as perms]
[metabase.public-sharing.validation :as public-sharing.validation]
@@ -197,6 +198,30 @@
api/read-check
(actions/fetch-values (json/decode parameters))))
+(defn- remap-parameter-keys
+ "Translate incoming `parameters` keys to the destination parameter `:id` the
+ downstream executor expects.
+
+ Query-action parameters have UUID `:id`s with human-readable `:slug` aliases;
+ the FE typically sends keys by `:slug` (that's what shows up in the typed
+ schema export and in the action editor UI). Implicit-action parameters use
+ a slug-form value as their `:id`, so the keys already match.
+
+ Resolution order per incoming key:
+ 1. Already matches a destination `:id` → passed through.
+ 2. Matches a destination `:slug` → remapped to that parameter's `:id`.
+ 3. No match → passed through unchanged so the downstream validator still
+ reports it as 'no destination parameter found'."
+ [{action-params :parameters} parameters]
+ (let [valid-ids (into #{} (map :id) action-params)
+ slug->id (into {} (keep (fn [p] (when-let [s (:slug p)] [s (:id p)]))) action-params)]
+ (update-keys parameters
+ (fn [k]
+ (cond
+ (contains? valid-ids k) k
+ (contains? slug->id k) (get slug->id k)
+ :else k)))))
+
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
;;
@@ -206,11 +231,12 @@
`parameters` should be the mapped dashboard parameters with values."
[{:keys [id]} :- [:map
- [:id ::actions.schema/id]]
+ [:id [:or ::actions.schema/id ms/NanoIdString]]]
_query-params
{:keys [parameters], :as _body} :- [:maybe [:map
[:parameters {:optional true} [:maybe [:map-of :keyword any?]]]]]]
- (let [{:keys [type] :as action} (api/read-check (actions/select-action :id id :archived false))]
+ (let [resolved-id (eid-translation/->id-or-404 :action id)
+ {:keys [type] :as action} (api/read-check (actions/select-action :id resolved-id :archived false))]
(when (= type :http)
(throw (ex-info (tru "HTTP actions are not supported.")
{:type :http
@@ -219,5 +245,7 @@
{:event :action-executed
:source :model_detail
:type type
- :action_id id})
- (actions/execute-action! action (update-keys parameters name))))
+ :action_id resolved-id})
+ (actions/execute-action! action
+ (remap-parameter-keys action
+ (update-keys parameters name)))))
diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.clj
index b259daf303f..d868a013441 100644
--- a/test/metabase/actions_rest/api_test.clj
+++ b/test/metabase/actions_rest/api_test.clj
@@ -493,6 +493,53 @@
(is (= "Not found."
(mt/user-http-request :crowberto :delete 404 (format "action/%d/public_link" Integer/MAX_VALUE)))))))))
+(deftest remap-parameter-keys-test
+ (testing "remap-parameter-keys translates incoming parameter keys to the destination parameter's :id"
+ (let [action {:parameters [{:id "d800e41d-edde-49cb-b63b-2386aba34334"
+ :slug "id"
+ :name "ID"}
+ {:id "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b"
+ :slug "discount"
+ :name "Discount"}]}]
+ (testing "slug-keyed input is remapped to :id"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys action
+ {"id" 1 "discount" 0.1}))))
+ (testing "already-:id-keyed input is passed through unchanged"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys
+ action
+ {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}))))
+ (testing "display-name keys (`:name`) are NOT accepted — they pass through unchanged"
+ (is (= {"ID" 1 "Discount" 0.1}
+ (#'api.action/remap-parameter-keys action
+ {"ID" 1 "Discount" 0.1}))))
+ (testing "unknown keys pass through unchanged so downstream validation still fires"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "bogus" 42}
+ (#'api.action/remap-parameter-keys action
+ {"id" 1 "bogus" 42}))))
+ (testing "a mix of :id and :slug keys resolve together"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys
+ action
+ {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "discount" 0.1}))))
+ (testing "empty parameters map → empty result"
+ (is (= {}
+ (#'api.action/remap-parameter-keys action {}))))
+ (testing "implicit-action style (no :slug) — :id-keyed input still passes through"
+ (let [implicit-action {:parameters [{:id "name" :name "Name"}
+ {:id "email" :name "Email"}]}]
+ (is (= {"name" "Foo" "email" "[email protected]"}
+ (#'api.action/remap-parameter-keys
+ implicit-action
+ {"name" "Foo" "email" "[email protected]"}))))))))
+
(deftest execute-action-test
(mt/with-actions-test-data-and-actions-enabled
(mt/with-actions [{:keys [action-id]} unshared-action-opts]
@@ -521,6 +568,24 @@
(format "action/%s/execute" action-id)
{:parameters {:id 1 :name "European"}})))))))
+(deftest execute-action-by-entity-id-test
+ (mt/with-actions-test-data-and-actions-enabled
+ (mt/with-actions [{:keys [action-id]} unshared-action-opts]
+ (let [entity-id (t2/select-one-fn :entity_id :model/Action :id action-id)]
+ (testing "Action can be executed by entity_id"
+ (is (=? {:rows-affected 1}
+ (mt/user-http-request :crowberto
+ :post 200
+ (format "action/%s/execute" entity-id)
+ {:parameters {:id 1 :name "European"}}))))
+ (testing "Unknown entity_id returns 404"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto
+ :post 404
+ (format "action/%s/execute"
+ "AAAAAAAAAAAAAAAAAAAAA")
+ {:parameters {:id 1 :name "European"}}))))))))
+
(deftest execute-action-test-3
(mt/with-actions-test-data-and-actions-enabled
(mt/with-actions [{:keys [action-id]} unshared-action-opts]