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
Allow MCP to create text cards and headings on dashboards (#77362)
Chris Truter8e13d485ecae
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex dc3ff3dc840..ed284454e66 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -180,6 +180,7 @@:model/Collection:model/Dashboard:model/DashboardCard+ :model/DashboardTab:model/Database:model/Table:model/User}}@@ -1343,6 +1344,8 @@:model-imports #{:model/Card:model/Collection:model/Dashboard+ :model/DashboardCard+ :model/DashboardTab:model/Database:model/Field:model/Glossarydiff --git a/resources/metabot/skills/read-resource.md b/resources/metabot/skills/read-resource.mdindex 4a471e18469..29944fea8ab 100644--- a/resources/metabot/skills/read-resource.md+++ b/resources/metabot/skills/read-resource.md@@ -140,7 +140,7 @@ You can request multiple resources in one call by providing a list of URIs (max## Dashboard resources- `metabase://dashboard/{id}` — dashboard details-- `metabase://dashboard/{id}/items` — cards on the dashboard (each rendered as a `metabase://question/{id}` URI you can drill into)+- `metabase://dashboard/{id}/items` — everything on the dashboard in layout order: question cards (each rendered as a `metabase://question/{id}` URI you can drill into) plus headings, text cards, and action buttons**Examples:**- Want to understand what a dashboard contains before recommending it? → `metabase://dashboard/158`@@ -148,6 +148,7 @@ You can request multiple resources in one call by providing a list of URIs (max**Best Practices:**- Treat dashboards as containers — when search returns a dashboard hit (`is_container="true"`), use `/items` to list its cards instead of re-searching for the same concept.+- Every dashcard entry carries a `dashcard_id` — the handle `update_dashboard` `remove`/`move`/`update_text` mutations take. Headings and text cards show as `virtual_heading`/`virtual_text` with their text as the description; action buttons show as `action` (with a `uri` to their backing model when readable). On multi-tab dashboards the list opens with a `<tabs>` block naming every tab — empty ones included — with the `tab_id` that `add` mutations accept, and dashcard entries carry their tab's `tab_id`, grouped in tab order.- Fetch dashboard details to confirm it contains the information the user is looking for before recommending it.- Prefer verified dashboards when they match the user's request.diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex c896100c99d..f30f315760b 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -15,6 +15,7 @@[metabase.collections.models.collection :as collection][metabase.dashboards.autoplace :as autoplace][metabase.dashboards.models.dashboard :as dashboard]+ [metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.events.core :as events][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]@@ -1183,6 +1184,23 @@;;; ------------------------------------------------ Create Dashboard -----------------------------------------------+(defn- size-override+ "Optional explicit size from the LLM. Returns {:width :height} or nil to fall back to defaults."+ [display-size]+ (case display-size+ "wide" {:width 18 :height 6}+ "tall" {:width 9 :height 12}+ "full" {:width 24 :height 9}+ nil))++(defn- autoplaced-position+ "Grid position for a new dashcard: the LLM's explicit `display-size` if given, otherwise the+ default size for `display`."+ [placed display display-size]+ (if-let [{:keys [width height]} (size-override display-size)]+ (autoplace/get-position-for-new-dashcard placed width height autoplace/default-grid-width)+ (autoplace/get-position-for-new-dashcard placed display)))+(mr/def ::create-dashboard-request[:map[:name ms/NonBlankString]@@ -1190,6 +1208,18 @@[:collection_id {:optional true} [:maybe ms/PositiveInt]][:question_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]])+(mr/def ::dashboard-tab+ [:map+ [:id ms/PositiveInt]+ [:name :string]])++(defn- dashboard-tabs+ "The dashboard's tabs as `{:id :name}` in display order, [] when it has none."+ [dashboard-id]+ (mapv #(select-keys % [:id :name])+ (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id+ {:order-by [[:position :asc] [:id :asc]]})))+(mr/def ::create-dashboard-response[:map[:id ms/PositiveInt]@@ -1198,7 +1228,8 @@[:collection_id [:maybe ms/PositiveInt]][:collection_path :string][:description [:maybe :string]]- [:dashcard_ids [:sequential ms/PositiveInt]]])+ [:dashcard_ids [:sequential ms/PositiveInt]]+ [:tabs [:sequential ::dashboard-tab]]])(api.macros/defendpoint :post "/v1/dashboard" :- ::create-dashboard-response"Create a new dashboard, optionally populated with saved questions.@@ -1215,6 +1246,8 @@"Cards are auto-positioned on the dashboard grid. ""If you omit collection_id it's saved to the user's personal collection; ""pass an explicit null to save it to the root collection. "+ "To add section headings or narrative text cards, follow up with "+ "update_dashboard. ""Report the saved location from the response `collection_path`. ""Returns the dashboard URL.")}}[_route-params@@ -1242,7 +1275,7 @@(when (seq cards)(reduce (fn [placed card](let [display (or (:display card) :table)- position (autoplace/get-position-for-new-dashcard placed display)]+ position (autoplaced-position placed display nil)](t2/insert-returning-instance!:model/DashboardCard(merge position {:dashboard_id (:id dash)@@ -1258,31 +1291,59 @@:collection_id (:collection_id dash):collection_path (collection-path (:collection_id dash)):description (:description dash)- :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id (:id dash)))})))+ ;; select-fn-vec returns nil, not [], when there are no rows+ :dashcard_ids (or (t2/select-fn-vec :id :model/DashboardCard :dashboard_id (:id dash)+ {:order-by [[:row :asc] [:col :asc]]})+ [])+ :tabs (dashboard-tabs (:id dash))})));;; ------------------------------------------------- Update Dashboard -----------------------------------------------(mr/def ::dashcard-mutation"One dashcard mutation. Discriminated on `:action`:- - `add` : requires `card_id`. Auto-positioned. Optional `display_size`(\"wide\", \"tall\", or \"full\").- - `remove` : requires `dashcard_id`.- - `move` : requires `dashcard_id` and `position` (\"top\" or \"bottom\")."+ - `add` : requires `card_id`. Auto-positioned. Optional `display_size` (\"wide\", \"tall\", or \"full\").+ - `add_heading` : requires `text`. Adds a full-width section heading.+ - `add_text` : requires `text` (Markdown). Adds a text card. Optional `display_size`+ (\"wide\", \"tall\", or \"full\").+ - `update_text` : requires `dashcard_id` and `text`. Replaces a heading or text card's text+ in place, keeping its position and size.+ - `remove` : requires `dashcard_id`.+ - `move` : requires `dashcard_id` and `position` (\"top\" or \"bottom\").++ The add actions take an optional `tab_id` (a tab on this dashboard); omitted, new cards land on+ the dashboard's first tab."[:multi {:dispatch :action}- ["add" [:map- [:action [:= "add"]]- [:card_id ms/PositiveInt]- [:display_size {:optional true} [:maybe [:enum "wide" "tall" "full"]]]]]- ["remove" [:map- [:action [:= "remove"]]- [:dashcard_id ms/PositiveInt]]]- ["move" [:map- [:action [:= "move"]]- [:dashcard_id ms/PositiveInt]- [:position [:enum "top" "bottom"]]]]])+ ;; Branches are closed so an inapplicable key (e.g. `display_size` on `add_heading`, which is+ ;; always full-width) fails validation instead of being silently ignored.+ ["add" [:map {:closed true}+ [:action [:= "add"]]+ [:card_id ms/PositiveInt]+ [:display_size {:optional true} [:maybe [:enum "wide" "tall" "full"]]]+ [:tab_id {:optional true} [:maybe ms/PositiveInt]]]]+ ["add_heading" [:map {:closed true}+ [:action [:= "add_heading"]]+ [:text ms/NonBlankString]+ [:tab_id {:optional true} [:maybe ms/PositiveInt]]]]+ ["add_text" [:map {:closed true}+ [:action [:= "add_text"]]+ [:text ms/NonBlankString]+ [:display_size {:optional true} [:maybe [:enum "wide" "tall" "full"]]]+ [:tab_id {:optional true} [:maybe ms/PositiveInt]]]]+ ["update_text" [:map {:closed true}+ [:action [:= "update_text"]]+ [:dashcard_id ms/PositiveInt]+ [:text ms/NonBlankString]]]+ ["remove" [:map {:closed true}+ [:action [:= "remove"]]+ [:dashcard_id ms/PositiveInt]]]+ ["move" [:map {:closed true}+ [:action [:= "move"]]+ [:dashcard_id ms/PositiveInt]+ [:position [:enum "top" "bottom"]]]]])(mr/def ::update-dashboard-request"Patch shape for `update_dashboard`. Metadata fields and an optional `dashcards` list of- add/remove/move mutations applied in order."+ add/add_heading/add_text/update_text/remove/move mutations applied in order."[:map[:name {:optional true} [:maybe ms/NonBlankString]][:description {:optional true} [:maybe :string]]@@ -1292,7 +1353,8 @@(mr/def ::update-dashboard-response"Returned by `update_dashboard`. `:dashcard_ids` is the post-mutation list of dashcard- ids in row/col order so the LLM can confirm what landed on the dashboard."+ ids in row/col order so the LLM can confirm what landed on the dashboard. `:tabs` lists+ the dashboard's tabs in display order — the ids a mutation's `tab_id` accepts."[:map[:id ms/PositiveInt][:name ms/NonBlankString]@@ -1300,16 +1362,24 @@[:collection_path :string][:description [:maybe :string]][:archived :boolean]- [:dashcard_ids [:sequential ms/PositiveInt]]])--(defn- size-override- "Optional explicit size from the LLM. Returns {:width :height} or nil to fall back to defaults."- [display-size]- (case display-size- "wide" {:width 18 :height 6}- "tall" {:width 9 :height 12}- "full" {:width 24 :height 9}- nil))+ [:dashcard_ids [:sequential ms/PositiveInt]]+ [:tabs [:sequential ::dashboard-tab]]])++(defn- insert-new-dashcard!+ "Insert a new dashcard at `position-fields` on `tab-id` and record it in the mutation `state`.+ Goes through [[dashboard-card/create-dashboard-cards!]] so model-level invariants (e.g. no+ document-backed cards on dashboards) are enforced. The returned instance (with its :id) goes+ into :placed so later mutations in the batch — notably a `move` to \"top\", which shifts every+ other card by id — can address it."+ [state dashboard-id tab-id position-fields columns]+ (let [new-dashcard (first (dashboard-card/create-dashboard-cards!+ [(merge position-fields+ {:dashboard_id dashboard-id+ :dashboard_tab_id tab-id}+ columns)]))]+ (swap! state #(-> %+ (update :placed conj new-dashcard)+ (update :added conj new-dashcard)))))(defn- apply-dashcard-mutations!"Apply a sequence of LLM-friendly dashcard mutations. Returns {:added [...] :removed [...] :moved [...]}.@@ -1318,73 +1388,130 @@- `card_id` that doesn't exist or the user can't read -> 404 / 403 via `api/read-check`.- `dashcard_id` that isn't on this dashboard -> 404 via `api/check-404`.- Autoplace state walks the current dashcards list as we add, so each new card gets a unique slot."+ Autoplace state walks the current dashcards list as we add, so each new card gets a unique slot.+ Placement is per-tab: adds go on the mutation's `tab_id` (default: the first tab) and only+ collide with that tab's cards; a move only reflows cards sharing the moved card's tab."[dashboard-id mutations]- (let [current (t2/select :model/DashboardCard :dashboard_id dashboard-id)- state (atom {:placed (vec current)- :added []- :removed []- :moved []})]- (doseq [[mutation-index {:keys [action card_id dashcard_id display_size position] :as mutation}]+ (let [current (t2/select :model/DashboardCard :dashboard_id dashboard-id)+ ;; one fetch serves the default tab, per-mutation tab_id validation, and collision grouping+ tab-ids (t2/select-pks-vec :model/DashboardTab :dashboard_id dashboard-id+ {:order-by [[:position :asc] [:id :asc]]})+ ;; new dashcards land on the first tab, alongside any nil-tab dashcards, which the+ ;; frontend renders there; nil when the dashboard has no tabs+ default-tab-id (first tab-ids)+ tab-id? (set tab-ids)+ ;; A tab_id that isn't a tab on this dashboard -> 404, so a typo can't silently create a+ ;; dashcard that no tab displays.+ target-tab-id (fn [tab-id]+ (if tab-id+ (do (api/check-404 (tab-id? tab-id)) tab-id)+ default-tab-id))+ ;; Dashcards with a nil tab id still render on a tabbed dashboard's first tab, so for+ ;; collision/reflow purposes they count as first-tab cards.+ effective-tab (fn [dashcard] (or (:dashboard_tab_id dashcard) default-tab-id))+ on-tab (fn [placed tab-id] (filterv #(= (effective-tab %) tab-id) placed))+ state (atom {:placed (vec current)+ :added []+ :removed []+ :moved []})]+ (doseq [[mutation-index {:keys [action card_id dashcard_id display_size position text tab_id] :as mutation}](map-indexed vector mutations)](try(case action"add"- (let [card (api/read-check :model/Card card_id)- display (or (:display card) :table)- override (size-override display_size)- position-fields (if override- (autoplace/get-position-for-new-dashcard- (:placed @state) (:width override) (:height override)- autoplace/default-grid-width)- (autoplace/get-position-for-new-dashcard- (:placed @state) display))- new-dashcard (first (t2/insert-returning-instances!- :model/DashboardCard- (merge position-fields- {:dashboard_id dashboard-id- :card_id card_id})))]- (swap! state #(-> %- (update :placed conj position-fields)- (update :added conj new-dashcard))))+ (let [card (api/read-check :model/Card card_id)+ ;; A card internal to a different dashboard (a dashboard question) can't be added+ ;; here — mirrors the REST dashcard-creation gate.+ _ (api/check (or (nil? (:dashboard_id card))+ (= (:dashboard_id card) dashboard-id))+ [400 "Can't add a question that is internal to another dashboard."])+ ;; Archived cards can't be added — except a question internal to THIS dashboard:+ ;; it was auto-archived when its last dashcard was removed, and re-adding it+ ;; unarchives it via the internal-question sync after the mutations.+ ;; TODO (Chris 2026-07-10) -- this surfaces as check-not-archived's standard 404,+ ;; matching REST; a 400 naming the archived card would guide an LLM caller better.+ _ (when-not (= (:dashboard_id card) dashboard-id)+ (api/check-not-archived card))+ display (or (:display card) :table)+ tab-id (target-tab-id tab_id)]+ (insert-new-dashcard! state dashboard-id tab-id+ (autoplaced-position (on-tab (:placed @state) tab-id) display display_size)+ {:card_id card_id}))++ "add_heading"+ (let [tab-id (target-tab-id tab_id)]+ (insert-new-dashcard! state dashboard-id tab-id+ (autoplaced-position (on-tab (:placed @state) tab-id) :heading nil)+ {:visualization_settings (dashboard-card/virtual-card-settings "heading" text)}))++ "add_text"+ (let [tab-id (target-tab-id tab_id)]+ (insert-new-dashcard! state dashboard-id tab-id+ (autoplaced-position (on-tab (:placed @state) tab-id) :text display_size)+ {:visualization_settings (dashboard-card/virtual-card-settings "text" text)}))++ "update_text"+ (let [existing (api/check-404+ (t2/select-one :model/DashboardCard+ :id dashcard_id :dashboard_id dashboard-id))+ vs (:visualization_settings existing)+ display (some-> (get-in vs [:virtual_card :display]) name)]+ (api/check (or (contains? #{"heading" "text"} display)+ ;; legacy text cards predate virtual_card and carry only a :text setting+ (and (nil? display)+ (nil? (:card_id existing))+ (nil? (:action_id existing))+ (string? (:text vs))))+ [400 "Only heading and text cards support update_text."])+ ;; In-place: position and size stay put, unlike a remove + add_* round-trip.+ (t2/update! :model/DashboardCard dashcard_id+ {:visualization_settings (assoc vs :text text)}))"remove"(let [existing (api/check-404(t2/select-one :model/DashboardCard:id dashcard_id :dashboard_id dashboard-id))]- (t2/delete! :model/DashboardCard :id dashcard_id)+ ;; Model-level delete also cleans up orphaned inline parameters and pulse cards.+ (dashboard-card/delete-dashboard-cards! [dashcard_id])(swap! state #(-> %(update :placed (fn [cards] (vec (remove (comp #{dashcard_id} :id) cards))))(update :removed conj existing))))"move"- (let [existing (api/check-404- (t2/select-one :model/DashboardCard- :id dashcard_id :dashboard_id dashboard-id))+ (let [existing (api/check-404+ (t2/select-one :model/DashboardCard+ :id dashcard_id :dashboard_id dashboard-id))+ ;; A move only makes sense relative to the moved card's own tab: collision checks+ ;; and the move-to-top reflow must not touch cards on other tabs. Compared via+ ;; `effective-tab` so nil-tab dashcards group with the first tab they render on.+ same-tab? #(= (effective-tab %) (effective-tab existing));; Strip the moved card from the placed list while we recompute its position,;; otherwise autoplace will treat it as still occupying its old slot.- other-placed (vec (remove (comp #{dashcard_id} :id) (:placed @state)))- new-pos (case position- "top" {:row 0 :col 0- :size_x (:size_x existing) :size_y (:size_y existing)}- "bottom" (autoplace/get-position-for-new-dashcard- other-placed- (:size_x existing) (:size_y existing)- autoplace/default-grid-width))]- ;; "top" parks the card at row 0; everything else has to shift down by the+ others (vec (remove (comp #{dashcard_id} :id) (:placed @state)))+ tab-placed (filterv same-tab? others)+ new-pos (case position+ "top" {:row 0 :col 0+ :size_x (:size_x existing) :size_y (:size_y existing)}+ ;; Not first-fit autoplace — that would re-fill the slot the moved card+ ;; just vacated. "bottom" means below the tab's bottom edge.+ "bottom" {:row (transduce (map #(+ (:row %) (:size_y %))) max 0 tab-placed)+ :col (:col existing)+ :size_x (:size_x existing) :size_y (:size_y existing)})+ shifted? (fn [c] (and (= position "top") (same-tab? c)))]+ ;; "top" parks the card at row 0; everything else on its tab has to shift down by the;; moved card's height or we get overlapping dashcards (review finding #2).(when (= position "top")(let [shift (:size_y existing)]- (doseq [{:keys [id row]} other-placed]+ (doseq [{:keys [id row]} tab-placed](t2/update! :model/DashboardCard id {:row (+ row shift)}))))(t2/update! :model/DashboardCard dashcard_id(select-keys new-pos [:row :col]))(swap! state #(-> %(assoc :placed- (conj (if (= position "top")- (mapv (fn [c] (update c :row + (:size_y existing)))- other-placed)- other-placed)+ (conj (mapv (fn [c]+ (cond-> c+ (shifted? c) (update :row + (:size_y existing))))+ others)(merge existing (select-keys new-pos [:row :col]))))(update :moved conj (merge existing new-pos))))))(catch Exception e@@ -1396,22 +1523,43 @@:mutation-index mutation-index:mutation mutation)e)))))+ ;; Adding/removing dashcards can orphan (or resurrect) dashboard questions — cards internal to+ ;; this dashboard. Sync their archived state from the final dashcard set, like the REST path.+ (when (or (seq (:added @state)) (seq (:removed @state)))+ (dashboard/archive-or-unarchive-internal-dashboard-questions!+ dashboard-id (t2/select :model/DashboardCard :dashboard_id dashboard-id)))(select-keys @state [:added :removed :moved])))(api.macros/defendpoint :put "/v1/dashboard/:id" :- ::update-dashboard-response"Update a dashboard. Patch semantics - only fields you pass are changed.Metadata: `name`, `description`, `collection_id`, `archived`. Dashcard mutations- are submitted under `dashcards` as a list of `{action: add|remove|move, ...}`- entries applied in order. `add` requires `card_id`; `remove` and `move` require- `dashcard_id`."+ are submitted under `dashcards` as a list of+ `{action: add|add_heading|add_text|update_text|remove|move, ...}` entries applied in+ order. `add` requires `card_id`; `add_heading` and `add_text` require `text` (Markdown+ for text cards); `update_text`, `remove`, and `move` require `dashcard_id`."{:scope metabot/agent-dashboard-update:tool {:name "update_dashboard":description (str "Update a dashboard. Patch semantics - only fields you pass are changed. ""Set collection_id to move it. Set archived true to archive. ""Use dashcards to add, remove, or move cards: ""[{\"action\":\"add\",\"card_id\":42},{\"action\":\"remove\",\"dashcard_id\":101}]. "- "Get dashcard_ids by reading metabase://dashboard/{id}/items via read_resource.")}}+ "add_heading adds a full-width section heading and add_text adds a "+ "Markdown text card, both from a \"text\" field: "+ "[{\"action\":\"add_heading\",\"text\":\"Revenue\"},"+ "{\"action\":\"add_text\",\"text\":\"Orders *grew 12%* this quarter.\"}]. "+ "update_text rewrites an existing heading or text card in place "+ "(keeping its position) from dashcard_id and text. "+ "Mutations apply in order. New cards auto-place into the first free "+ "grid slot (left-to-right, top-to-bottom), so cards may sit side by "+ "side; a full-width heading always starts its own row, so lead each "+ "section with add_heading to build a sectioned layout. "+ "Add actions take an optional tab_id; omitted, new cards land on the "+ "dashboard's first tab. The response tabs lists the dashboard's tabs "+ "in display order. "+ "The response dashcard_ids lists all dashcards in row/col order; "+ "metabase://dashboard/{id}/items (via read_resource) shows each "+ "dashcard with its dashcard_id.")}}[{:keys [id]} :- [:map [:id ms/PositiveInt]]_query-paramsbody :- ::update-dashboard-request]@@ -1421,10 +1569,26 @@(contains? body :description) (assoc :description (:description body))(contains? body :collection_id) (assoc :collection_id (:collection_id body))(contains? body :archived) (assoc :archived (boolean (:archived body))))+ ;; Keep `archived_directly` in sync (and drop any `collection_id` sent alongside an+ ;; archive), mirroring the REST PUT-dashboard path.+ ;; TODO (Chris 2026-07-10) -- the drop is silent: archive + move in one request returns+ ;; 200 but discards the move. Matching REST for now; rejecting the combination with a 400+ ;; may serve LLM callers better.+ updates (api/updates-with-archived-directly current-dash updates);; A move requires write on BOTH source and target collection. `api/write-check :model/Dashboard`;; above only covered the source entity. Mirror the REST endpoint's gate._ (collection/check-allowed-to-change-collection current-dash updates)mutations (:dashcards body)+ ;; Card mutations on an archived dashboard are rejected, like the REST path. That includes+ ;; a dashboard being archived by THIS request — otherwise the post-mutation+ ;; internal-question sync could unarchive dashboard questions on a just-archived dashboard.+ _ (when (seq mutations)+ ;; unless THIS request unarchives it first — restore-and-edit is one call,+ ;; and the update runs before the mutations inside the transaction+ (when-not (false? (:archived updates))+ (api/check-not-archived current-dash))+ (api/check (not (true? (:archived updates)))+ [400 "Can't modify dashcards while archiving the dashboard."]))result (t2/with-transaction [_conn](when (seq updates)(dashboard/cascade-card-state-from-dashboard-update! current-dash updates)@@ -1461,7 +1625,11 @@:collection_path (collection-path (:collection_id updated)):description (:description updated):archived (boolean (:archived updated))- :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id id))})))+ ;; select-fn-vec returns nil, not [], when there are no rows+ :dashcard_ids (or (t2/select-fn-vec :id :model/DashboardCard :dashboard_id id+ {:order-by [[:row :asc] [:col :asc]]})+ [])+ :tabs (dashboard-tabs id)})));;; ------------------------------------------------ Create Collection -----------------------------------------------diff --git a/src/metabase/agent_api/reference.md b/src/metabase/agent_api/reference.mdindex 6306136e715..92400e8f79f 100644--- a/src/metabase/agent_api/reference.md+++ b/src/metabase/agent_api/reference.md@@ -516,15 +516,37 @@ Response:"name": "Revenue Dashboard","collection_id": 7,"description": "...",- "dashcard_ids": [101, 102]+ "dashcard_ids": [101, 102],+ "tabs": []}```### PUT /v1/dashboard/{id}-Update a dashboard's metadata. Patch semantics. Setting `collection_id`-moves the dashboard (and its cards). Setting `archived: true` archives the-dashboard and cascades to its cards.+Update a dashboard's metadata and cards. Patch semantics. Setting+`collection_id` moves the dashboard (and its cards). Setting `archived: true`+archives the dashboard and cascades to its cards.++Dashcard mutations go under `dashcards` and are applied in order:++- `add` adds a saved question by `card_id` (optional `display_size`:+ `"wide"`, `"tall"`, or `"full"`)+- `add_heading` adds a full-width section heading from `text`+- `add_text` adds a Markdown text card from `text` (optional `display_size`:+ `"wide"`, `"tall"`, or `"full"`)+- `update_text` replaces the text of an existing heading or text card+ (`dashcard_id` and `text`), keeping its position and size+- `remove` removes a dashcard by `dashcard_id`+- `move` moves a dashcard by `dashcard_id` to `position` `"top"` or `"bottom"`++The add actions also take an optional `tab_id` (a tab on this dashboard);+omitted, new cards land on the dashboard's first tab. The response `tabs`+lists the dashboard's tabs in display order.++New cards are auto-placed into the first free grid slot, scanning+left-to-right then top-to-bottom, so two half-width cards can end up side by+side. A full-width heading always starts its own row — lead each section with+`add_heading` to build a sectioned, top-to-bottom layout.Request:@@ -533,19 +555,29 @@ Request:"name": "Renamed Dashboard","description": "...","collection_id": 7,- "archived": false+ "archived": false,+ "dashcards": [+ { "action": "add_heading", "text": "Revenue" },+ { "action": "add", "card_id": 42 },+ { "action": "add_text", "text": "Orders *grew 12%* this quarter." },+ { "action": "remove", "dashcard_id": 101 }+ ]}```-Response:+Response (`dashcard_ids` lists all dashcards on the dashboard after the+mutations, in row/col order — new headings and text cards included):```json{"id": 7,"name": "Renamed Dashboard","collection_id": 7,+ "collection_path": "Our analytics / Finance","description": "...",- "archived": false+ "archived": false,+ "dashcard_ids": [103, 102, 104],+ "tabs": [{ "id": 9, "name": "Overview" }, { "id": 10, "name": "Detail" }]}```diff --git a/src/metabase/dashboards/models/dashboard_card.clj b/src/metabase/dashboards/models/dashboard_card.cljindex 9735e667a84..94ee27b1781 100644--- a/src/metabase/dashboards/models/dashboard_card.clj+++ b/src/metabase/dashboards/models/dashboard_card.clj@@ -77,6 +77,20 @@(m/update-existing :parameter_mappings parameters/normalize-parameter-mappings)(m/update-existing :visualization_settings mi/normalize-visualization-settings))))+(defn virtual-card-settings+ "`visualization_settings` for a virtual dashcard — a dashcard with no backing card, such as a text+ card or heading. `display` is the virtual display type as a string (\"text\", \"heading\", ...).+ Mirrors the shape the frontend saves; see `createVirtualCard` in+ frontend/src/metabase/common/utils/dashboard.ts."+ [display text]+ (cond-> {:virtual_card {:name nil+ :display display+ :visualization_settings {}+ :archived false}+ :text text}+ ;; headings render without a card background, matching the frontend default+ (= display "heading") (assoc :dashcard.background false)))+(defmethod serdes/hash-fields :model/DashboardCard[_dashboard-card][(serdes/hydrated-hash :card) ; :card is optional, eg. text cardsdiff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex a6306b317b1..0c78664f9f7 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -569,22 +569,77 @@{:structured-output (assoc dashboard :result-type :entity)}{:status-code 404 :output (:output result)})))-(defn- fetch-dashboard-items [id-str query-params]+(defn- present-non-question-dashcard+ "Dashcards not rendered as a saved question — virtual cards (headings, text, links, ...) and+ action buttons (which may reference a backing model via `card_id` but render as a button).+ They carry their `dashcard_id` — the handle `update_dashboard` remove/move/update_text+ mutations take. The card's text (or a link card's target) renders as the item body via+ `:description`."+ [{:keys [id action_id visualization_settings]}]+ (let [display (some-> (get-in visualization_settings [:virtual_card :display]) name)]+ ;; action_id wins over the virtual display: frontend-created action buttons carry BOTH an+ ;; action_id and a virtual_card with display "action", and should read as one type.+ {:type (cond+ action_id "action"+ display (str "virtual_" display)+ :else "virtual_dashcard")+ :dashcard_id id+ ;; action buttons carry their visible label here; nil for virtual cards+ :name (:button.label visualization_settings)+ ;; external link URLs only: an entity link's stored :link :entity snapshot (name etc.) may+ ;; describe something this user can't read, so rendering it would bypass the read-check the+ ;; REST path applies via the :dashcard/linkcard-info hydration+ :description (or (:text visualization_settings)+ (get-in visualization_settings [:link :url]))}))++(defn- fetch-dashboard-items+ "One item per dashcard in row/col (layout) order, each carrying the `dashcard_id` that+ `update_dashboard` remove/move/update_text mutations take. On a tabbed dashboard the items come+ grouped by tab (nil-tab dashcards belong to the first tab, where the frontend renders them),+ each carries its `tab_id`, and the response's `:tabs` lists every tab — empty ones included —+ in display order. Card-backed dashcards keep the card fields; virtual dashcards (headings,+ text, links, ...) render their text; action buttons keep a `uri` to their backing model when+ it's readable. Dashcards whose card is archived or unreadable are omitted."+ [id-str query-params](let [dashboard-id (parse-long id-str)_ (api/read-check :model/Dashboard dashboard-id)- cards (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- {:where [:and- [:= :archived false]- [:exists {:select 1- :from [[:report_dashboardcard :dc]]- :where [:and- [:= :dc.card_id :report_card.id]- [:= :dc.dashboard_id dashboard-id]]}]]- :order-by [[:%lower.name :asc]]})- (filter mi/can-read?)- (mapv present-card))]- (list-result :dashboard-items cards query-params)))+ tabs (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id+ {:order-by [[:position :asc] [:id :asc]]})+ dashcards (t2/select [:model/DashboardCard :id :card_id :action_id :dashboard_tab_id+ :visualization_settings]+ :dashboard_id dashboard-id+ {:order-by [[:row :asc] [:col :asc]]})+ card-ids (into #{} (keep :card_id) dashcards)+ readable (when (seq card-ids)+ (->> (t2/select [:model/Card :id :name :type :description :card_schema+ :collection_id :database_id :table_id]+ :id [:in card-ids]+ :archived false)+ (filter mi/can-read?)+ (into {} (map (juxt :id identity)))))+ ->item (fn [{:keys [id card_id action_id] :as dashcard}]+ ;; action_id wins over card_id: an action button may reference its backing+ ;; model through card_id but renders as a button — with a uri to that model+ ;; so it stays drillable.+ (if (and card_id (not action_id))+ (when-let [card (get readable card_id)]+ (assoc (present-card card) :dashcard_id id))+ (cond-> (present-non-question-dashcard dashcard)+ (get readable card_id) (assoc :uri (:uri (present-card (get readable card_id)))))))+ items (if (seq tabs)+ ;; group by tab without emitting tab pseudo-items — those would inflate the+ ;; paginated total; the tab list rides on the response as `:tabs` instead.+ ;; `sort-by` is stable, so the SQL row/col ordering survives within each+ ;; tab; a nil tab id means the frontend renders the card on the first tab.+ (let [tab-pos (into {} (map-indexed (fn [i {:keys [id]}] [id i])) tabs)+ eff-tab #(or (:dashboard_tab_id %) (:id (first tabs)))]+ (into []+ (keep (fn [dashcard]+ (some-> (->item dashcard) (assoc :tab_id (eff-tab dashcard)))))+ (sort-by (comp tab-pos eff-tab) dashcards)))+ (into [] (keep ->item) dashcards))]+ (cond-> (list-result :dashboard-items items query-params)+ (seq tabs) (update :structured-output assoc :tabs (mapv #(select-keys % [:id :name]) tabs)))));; ----- Dispatch -----diff --git a/src/metabase/metabot/tools/shared/llm_shape.clj b/src/metabase/metabot/tools/shared/llm_shape.cljindex 00ecaa291bf..47fb68bce0d 100644--- a/src/metabase/metabot/tools/shared/llm_shape.clj+++ b/src/metabase/metabot/tools/shared/llm_shape.clj@@ -610,6 +610,8 @@Matches Python Dashboard.llm_representation exactly."[{:keys [id name description verified collection dashcards]}];; Group cards by tab and sort+ ;; TODO (Chris 2026-07-09) -- tabs sort by raw id here but by position in+ ;; resources/fetch-dashboard-items; align on position(let [tabs (group-by :dashboard_tab_id dashcards)sorted-tabs (sort-by first tabs)tabs-xml (when (seq dashcards)@@ -859,7 +861,7 @@(def ^:private item-attr-keys"Attributes rendered as XML attrs on each <item> element. Order matters for stable output."- [:type :id :name :uri :database_id :collection_id :table_id+ [:type :id :dashcard_id :tab_id :name :uri :database_id :collection_id :table_id:schema :display_name :authority_level :is_personal :path :location:engine :timestamp])@@ -889,13 +891,22 @@:page 1:pages 1}+ An optional `:tabs` vector of `{:id .. :name ..}` (dashboard items) renders as a `<tabs>`+ block ahead of the items; items reference tabs via their `tab_id` attribute.+Output shape:<list type=\"databases\" total=\"5\" page=\"1\" pages=\"1\" showing=\"5\" truncated=\"false\"><item type=\"database\" id=\"1\" name=\"Sample\" uri=\"metabase://database/1\">Description</item>...</list>"- [{:keys [list-type items total page pages]}]+ [{:keys [list-type items total page pages tabs]}](let [type-attr (clojure.core/name (or list-type :items))+ tabs-xml (when (seq tabs)+ (str "<tabs>\n"+ (str/join "\n" (map (fn [{:keys [id name]}]+ (str " <tab tab_id=\"" id "\" name=\"" (escape-xml name) "\"/>"))+ tabs))+ "\n</tabs>"))item-xml (str/join "\n" (map list-item->xml items))showing (count items)truncated (< page pages)@@ -907,6 +918,7 @@"\" pages=\"" (or pages 1)"\" showing=\"" showing"\" truncated=\"" (boolean truncated) "\">\n"+ (when tabs-xml (str tabs-xml "\n"))(when (seq items) (str item-xml "\n"))(when note (str note "\n"))"</list>")))diff --git a/src/metabase/xrays/automagic_dashboards/populate.clj b/src/metabase/xrays/automagic_dashboards/populate.cljindex a286050e3ed..143bf0415b8 100644--- a/src/metabase/xrays/automagic_dashboards/populate.clj+++ b/src/metabase/xrays/automagic_dashboards/populate.clj@@ -6,6 +6,7 @@[medley.core :as m][metabase.api.common :as api][metabase.appearance.core :as appearance]+ [metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.lib-be.core :as lib-be][metabase.lib.schema :as lib.schema][metabase.queries.core :as queries]@@ -176,11 +177,7 @@(merge (dashcard-defaults){:creator_id api/*current-user-id*:visualization_settings (merge- {:text text- :virtual_card {:name nil- :display :text- :dataset_query {}- :visualization_settings {}}}+ (dashboard-card/virtual-card-settings "text" text)visualization-settings):col y:row xdiff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex 2d6aeebfa6d..b94a4fdb6c3 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -1370,6 +1370,299 @@(is (= 2 (count dashcards)))(is (= 2 (count (set positions))) "Each dashcard should have a unique row/col")))))+(deftest update-dashboard-dashcards-add-heading-test+ (testing "Add a heading - a full-width virtual dashcard with no backing card"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Heading Target"}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Revenue"}]})]+ (is (= 1 (count (:dashcard_ids resp))))+ (is (=? {:card_id nil+ :row 0+ :col 0+ :size_x 24+ :size_y 1+ :visualization_settings {:virtual_card {:display "heading"}+ :text "Revenue"+ :dashcard.background false}}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id)))))))++(deftest update-dashboard-dashcards-add-text-test+ (testing "Add a Markdown text card - a virtual dashcard with no backing card"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Text Target"}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text" :text "Orders *grew 12%*."}]})]+ (is (= 1 (count (:dashcard_ids resp))))+ (is (=? {:card_id nil+ :size_x 12+ :size_y 3+ :visualization_settings {:virtual_card {:display "text"}+ :text "Orders *grew 12%*."}}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id))))))+ (testing "display_size overrides the default text-card size"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Text Size Target"}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text" :text "Full width" :display_size "full"}]})+ (is (=? {:size_x 24 :size_y 9}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id))))))++(deftest update-dashboard-dashcards-narrative-layout-test+ (testing "Interleaved heading + card + text mutations autoplace in order without overlap"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Narrative Layout"}+ :model/Card {card-id :id} {:name "Chart"+ :dataset_query (orders-count-query)+ :display :table}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Section 1"}+ {:action "add" :card_id card-id}+ {:action "add_text" :text "Narrative under the chart."}]})+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dash-id {:order-by [[:row :asc]]})+ heading (first dashcards)+ chart (second dashcards)]+ (is (= 3 (count dashcards)))+ ;; heading sits on top, the chart starts below it+ (is (= 0 (:row heading)))+ (is (>= (:row chart) (+ (:row heading) (:size_y heading))))+ ;; no two dashcards share a position+ (is (= 3 (count (set (map (juxt :row :col) dashcards)))))))))++(deftest update-dashboard-dashcards-virtual-card-validation-test+ (testing "add_text and add_heading require non-blank text"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Text Validation"}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text"}]})+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text ""}]})+ (is (not (t2/exists? :model/DashboardCard :dashboard_id dash-id)))))+ (testing "add_heading rejects display_size instead of silently ignoring it (headings are always full-width)"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Heading Size Validation"}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "KPIs" :display_size "wide"}]})+ (is (not (t2/exists? :model/DashboardCard :dashboard_id dash-id))))))++(deftest update-dashboard-dashcards-add-then-move-top-test+ (testing "A card added earlier in the batch reflows when a later move-to-top shifts the tab"+ ;; Regression: :placed used to record the just-inserted dashcard without its :id, so the+ ;; move-to-top shift ran `(t2/update! :model/DashboardCard nil ...)` — a silent no-op — and the+ ;; new card ended up overlapping the moved one.+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Add Then Move Top"}+ :model/Card {card-id :id} {:name "existing" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 12 :size_x 12 :size_y 5}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text" :text "note"}+ {:action "move" :dashcard_id dc-id :position "top"}]})+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dash-id)+ moved (first (filter (comp #{dc-id} :id) dashcards))+ text-card (first (remove (comp #{dc-id} :id) dashcards))]+ (is (= [0 0] ((juxt :row :col) moved)))+ (is (>= (:row text-card) (+ (:row moved) (:size_y moved)))+ "the just-added text card must sit below the moved card, not overlap it")))))++(deftest update-dashboard-dashcards-add-on-tabbed-dashboard-test+ (testing "New headings/text cards land on the dashboard's first tab and only collide with its cards"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Tabbed Target"}+ :model/DashboardTab {tab1-id :id} {:dashboard_id dash-id :name "One" :position 0}+ :model/DashboardTab {tab2-id :id} {:dashboard_id dash-id :name "Two" :position 1}+ :model/Card {card-id :id} {:name "on tab two" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab2-id :card_id card-id+ :row 0 :col 0 :size_x 24 :size_y 4}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Tab one section"}]})]+ (is (=? {:tabs [{:id tab1-id :name "One"} {:id tab2-id :name "Two"}]}+ resp)+ "the response lists the tabs in display order"))+ (is (=? {:dashboard_tab_id tab1-id+ ;; the full-width card on tab 2 must not block row 0 of tab 1+ :row 0}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id :card_id nil)))+ (testing "an explicit tab_id overrides the first-tab default and collides with that tab's cards"+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text" :text "On tab two" :tab_id tab2-id}]})+ (is (=? {:dashboard_tab_id tab2-id+ ;; placed below tab 2's existing full-width 4-row card+ :row 4}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id+ :card_id nil :dashboard_tab_id tab2-id))))+ (testing "a tab_id that isn't a tab on this dashboard is a 404"+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Nope" :tab_id 999999}]})))))++(deftest update-dashboard-dashcards-nil-tab-collision-test+ (testing "A nil-tab dashcard on a tabbed dashboard blocks first-tab placement (it renders there)"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Nil Tab Collision"}+ :model/DashboardTab {tab1-id :id} {:dashboard_id dash-id :name "One" :position 0}+ :model/DashboardTab _ {:dashboard_id dash-id :name "Two" :position 1}+ :model/Card {card-id :id} {:name "legacy" :dataset_query (orders-count-query) :display :table}+ ;; predates the tabs: no dashboard_tab_id, but the frontend renders it on tab 1+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id nil :card_id card-id+ :row 0 :col 0 :size_x 24 :size_y 4}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Below the legacy card"}]})+ (is (=? {:dashboard_tab_id tab1-id+ :row 4}+ (t2/select-one :model/DashboardCard :dashboard_id dash-id :card_id nil))+ "the heading must land below the nil-tab card, not on top of it"))))++(deftest update-dashboard-restore-and-edit-test+ (testing "unarchiving and mutating dashcards in the same request works — restore-and-edit is one call"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Restore And Edit" :archived true}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:archived false+ :dashcards [{:action "add_heading" :text "Back from the trash"}]})+ (is (false? (t2/select-one-fn :archived :model/Dashboard :id dash-id)))+ (is (t2/exists? :model/DashboardCard :dashboard_id dash-id)))))++(deftest update-dashboard-lifecycle-checks-test+ (testing "dashcard mutations on an archived dashboard are rejected"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Archived Dash" :archived true}+ :model/Card {card-id :id} {:name "c" :dataset_query (orders-count-query) :display :table}]+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id card-id}]})))+ (testing "adding an archived card is rejected"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Live Dash"}+ :model/Card {card-id :id} {:name "archived c" :dataset_query (orders-count-query)+ :display :table :archived true}]+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id card-id}]})+ (is (not (t2/exists? :model/DashboardCard :dashboard_id dash-id)))))+ (testing "adding a question internal to another dashboard is rejected"+ (mt/with-temp [:model/Dashboard {other-dash :id} {:name "Owner Dash"}+ :model/Dashboard {dash-id :id} {:name "Target Dash"}+ :model/Card {card-id :id} {:name "dq" :dataset_query (orders-count-query)+ :display :table :dashboard_id other-dash}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id card-id}]})))+ (testing "an internal dashboard question archived by its own removal can be re-added, and unarchives"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "DQ Roundtrip"}+ :model/Card {card-id :id} {:name "internal q" :dataset_query (orders-count-query)+ :display :table :dashboard_id dash-id}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 12 :size_y 4}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "remove" :dashcard_id dc-id}]})+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id))+ "removing the last dashcard archives the internal dashboard question")+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id card-id}]})+ (is (false? (t2/select-one-fn :archived :model/Card :id card-id))+ "re-adding it unarchives the internal dashboard question")+ (is (= 1 (t2/count :model/DashboardCard :dashboard_id dash-id)))))+ (testing "archiving and mutating dashcards in one request is rejected"+ ;; the post-mutation internal-question sync could otherwise unarchive dashboard questions+ ;; on the dashboard this same request just archived+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Archive Plus Mutate"}+ :model/Card {dq-id :id} {:name "internal q" :dataset_query (orders-count-query)+ :display :table :dashboard_id dash-id}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id dq-id+ :row 0 :col 0 :size_x 12 :size_y 4}+ :model/Card {add-id :id} {:name "to add" :dataset_query (orders-count-query)+ :display :table}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:archived true+ :dashcards [{:action "add" :card_id add-id}]})+ (is (false? (t2/select-one-fn :archived :model/Dashboard :id dash-id))+ "the rejected request must not have archived the dashboard")+ (is (t2/exists? :model/DashboardCard :id dc-id))))+ (testing "archiving via the agent endpoint records archived_directly, like the REST path"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "To Archive"}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:archived true})+ (is (true? (t2/select-one-fn :archived_directly :model/Dashboard :id dash-id))))))++(deftest update-dashboard-dashcards-move-bottom-test+ (testing "Moving a card to the bottom places it below the tab's bottom edge, not back into its old slot"+ ;; Regression: "bottom" used first-fit autoplace over the layout minus the moved card, so a card+ ;; moved from the top would be re-placed straight into the gap it had just vacated.+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Move Bottom"}+ :model/Card {card-id :id} {:name "c" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {a-dc :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 12 :size_y 4}+ :model/DashboardCard {b-dc :id} {:dashboard_id dash-id :card_id card-id+ :row 4 :col 0 :size_x 12 :size_y 4}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "move" :dashcard_id a-dc :position "bottom"}]})+ (let [a (t2/select-one :model/DashboardCard :id a-dc)+ b (t2/select-one :model/DashboardCard :id b-dc)]+ (is (>= (:row a) (+ (:row b) (:size_y b)))+ "the moved card must land below the other card's bottom edge")))))++(deftest update-dashboard-dashcard-ids-row-col-order-test+ (testing "Response dashcard_ids come back in row/col order, not insertion order"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Ordered Ids"}+ :model/Card {card-id :id} {:name "c" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {a-dc :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 12 :size_y 4}+ :model/DashboardCard {b-dc :id} {:dashboard_id dash-id :card_id card-id+ :row 4 :col 0 :size_x 12 :size_y 4}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "move" :dashcard_id b-dc :position "top"}]})]+ (is (= [b-dc a-dc] (:dashcard_ids resp))+ "after moving b to the top it should be listed first")))))++(deftest update-dashboard-dashcards-update-text-test+ (testing "update_text replaces a text card's text in place, keeping position and size"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Retext Target"}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id nil+ :row 5 :col 3 :size_x 12 :size_y 3+ :visualization_settings+ {:virtual_card {:display "text"}+ :text "Old narrative."}}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "update_text" :dashcard_id dc-id :text "New narrative."}]})+ (is (=? {:row 5+ :col 3+ :size_x 12+ :size_y 3+ :visualization_settings {:virtual_card {:display "text"}+ :text "New narrative."}}+ (t2/select-one :model/DashboardCard :id dc-id)))))+ (testing "update_text works on headings too"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Retitle Target"}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_heading" :text "Old Title"}]})+ dc-id (first (:dashcard_ids resp))]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "update_text" :dashcard_id dc-id :text "New Title"}]})+ (is (=? {:visualization_settings {:virtual_card {:display "heading"}+ :text "New Title"}}+ (t2/select-one :model/DashboardCard :id dc-id))))))+ (testing "update_text works on a legacy text card that predates virtual_card settings"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Legacy Retext"}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id nil+ :row 0 :col 0 :size_x 12 :size_y 3+ :visualization_settings {:text "legacy words"}}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "update_text" :dashcard_id dc-id :text "fresh words"}]})+ (is (=? {:visualization_settings {:text "fresh words"}}+ (t2/select-one :model/DashboardCard :id dc-id)))))+ (testing "update_text on a card-backed dashcard is a 400"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Retext Chart"}+ :model/Card {card-id :id} {:name "chart" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 12 :size_y 9}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "update_text" :dashcard_id dc-id :text "nope"}]})))+ (testing "update_text on another dashboard's dashcard is a 404"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Retext Mine"}+ :model/Dashboard {other-id :id} {:name "Retext Other"}+ :model/DashboardCard {dc-id :id} {:dashboard_id other-id :card_id nil+ :row 0 :col 0 :size_x 24 :size_y 1+ :visualization_settings+ {:virtual_card {:display "heading"}+ :text "elsewhere"}}]+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "update_text" :dashcard_id dc-id :text "nope"}]}))))++(deftest update-dashboard-dashcards-remove-virtual-card-test+ (testing "A text card can be removed by dashcard_id like any other dashcard"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Remove Text Card"}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add_text" :text "temporary"}]})+ dashcard-id (first (:dashcard_ids resp))]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "remove" :dashcard_id dashcard-id}]})+ (is (not (t2/exists? :model/DashboardCard :dashboard_id dash-id)))))))+(deftest update-dashboard-dashcards-remove-test(testing "Remove a dashcard"(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Remove"}@@ -1378,7 +1671,7 @@:row 0 :col 0 :size_x 12 :size_y 9}](mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id){:dashcards [{:action "remove" :dashcard_id dashcard-id}]})- (is (zero? (count (t2/select :model/DashboardCard :dashboard_id dash-id)))))))+ (is (not (t2/exists? :model/DashboardCard :dashboard_id dash-id))))))(deftest update-dashboard-dashcards-move-top-test(testing "Move a dashcard to the top"diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex b515183a284..692ba46fdf3 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -749,9 +749,12 @@_ (reset! dash-id (:id dash-data))_ (is (= (format "https://stats.metabase.test/dashboard/%d" @dash-id)(:url dash-data)))- _ (call-tool session-id "update_dashboard"+ dash-update (call-tool session-id "update_dashboard"{:id (:id dash-data)- :description "Smoke updated dashboard"})+ :description "Smoke updated dashboard"+ :dashcards [{:action "add_heading" :text "Smoke Section"}+ {:action "add_text" :text "Smoke *narrative*"}]})+ _ (is (= 2 (count (:dashcard_ids dash-update))))coll-data (call-tool session-id "create_collection"{:name "Smoke Collection"})](reset! coll-id (:id coll-data)))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex c7da8dc9119..ba6b6525a21 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -656,11 +656,128 @@(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {}:model/Card {card-id :id} {:name "Dash card"}- :model/DashboardCard _ {:dashboard_id dash-id :card_id card-id}]- (testing "metabase://dashboard/{id}/items returns cards on the dashboard"+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id}]+ (testing "metabase://dashboard/{id}/items returns each dashcard with its dashcard_id"(let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "Dash card"))- (is (str/includes? output (str "uri=\"metabase://question/" card-id "\""))))))))+ (is (str/includes? output (str "uri=\"metabase://question/" card-id "\"")))+ (is (str/includes? output (str "dashcard_id=\"" dc-id "\""))))))))++(deftest read-dashboard-items-groups-by-tab-test+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardTab {tab1-id :id} {:dashboard_id dash-id :name "Tab One" :position 0}+ :model/DashboardTab {tab2-id :id} {:dashboard_id dash-id :name "Tab Two" :position 1}+ :model/DashboardTab _ {:dashboard_id dash-id :name "Empty Tab" :position 2}+ ;; the second tab's card sits at row 0, above the first tab's card at row 1 —+ ;; a flat row/col sort would list it first+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab2-id+ :card_id nil :row 0 :col 0 :size_x 24 :size_y 1+ :visualization_settings {:virtual_card {:display "heading"}+ :text "Second Tab Heading"}}+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab1-id+ :card_id nil :row 1 :col 0 :size_x 24 :size_y 1+ :visualization_settings {:virtual_card {:display "heading"}+ :text "First Tab Heading"}}+ ;; predates the tabs: nil tab id, but the frontend renders it on the first tab+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id nil+ :card_id nil :row 0 :col 0 :size_x 24 :size_y 1+ :visualization_settings {:virtual_card {:display "heading"}+ :text "Legacy Heading"}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})+ idx #(str/index-of output %)]+ (testing "a <tabs> block lists every tab in display order, empty ones included"+ (is (< (idx "Tab One") (idx "Tab Two") (idx "Empty Tab"))))+ (testing "dashcards come grouped by tab, not interleaved by raw row/col"+ (is (< (idx "Legacy Heading") (idx "First Tab Heading") (idx "Second Tab Heading"))))+ (testing "items carry the tab_id that add mutations accept; nil-tab dashcards get the first tab's"+ ;; tab1: its <tab> element + the legacy (nil-tab) heading + the first-tab heading+ (is (= 3 (count (re-seq (re-pattern (str "tab_id=\"" tab1-id "\"")) output))))+ (is (= 2 (count (re-seq (re-pattern (str "tab_id=\"" tab2-id "\"")) output)))))))))++(deftest read-dashboard-items-includes-virtual-dashcards-test+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id+ :card_id nil+ :row 0 :col 0 :size_x 24 :size_y 1+ :visualization_settings+ {:virtual_card {:display "heading"}+ :text "Revenue Section"}}]+ (testing "virtual (heading/text) dashcards are listed with the dashcard_id that remove/move mutations take"+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "virtual_heading"))+ (is (str/includes? output "Revenue Section"))+ (is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))))))+ (testing "a cardless dashcard without virtual_card settings still gets a generic item"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id+ :card_id nil+ :row 0 :col 0 :size_x 4 :size_y 1+ :visualization_settings {}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "virtual_dashcard"))+ (is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))))))+ (testing "an action-button dashcard is listed as an action item with its dashcard_id"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-actions [{:keys [action-id]} {:type :query :visualization_settings {}}]+ ;; the frontend stores action buttons with BOTH an action_id and a virtual_card whose+ ;; display is "action" — the type must come out as "action", not "virtual_action"+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id+ :card_id nil+ :action_id action-id+ :row 0 :col 0 :size_x 4 :size_y 1+ :visualization_settings+ {:virtual_card {:display "action"}}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "type=\"action\""))+ (is (str/includes? output (str "dashcard_id=\"" dc-id "\""))))))))+ (testing "an action dashcard that also references its backing model card still reads as an action"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-actions [{model-id :id} {:type :model+ :dataset_query (let [mp (mt/metadata-provider)]+ (lib/query mp (lib.metadata/table mp (mt/id :venues))))}+ {:keys [action-id]} {:type :query :visualization_settings {}}]+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id+ :card_id model-id+ :action_id action-id+ :row 0 :col 0 :size_x 4 :size_y 1+ :visualization_settings+ {:button.label "Create Row"}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "type=\"action\""))+ (is (str/includes? output "name=\"Create Row\""))+ (is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))+ (testing "the backing model stays drillable via the item's uri"+ (is (str/includes? output (str "uri=\"metabase://model/" model-id "\"")))))))))+ (testing "a link card renders its target URL as the item body"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard _ {:dashboard_id dash-id+ :card_id nil+ :row 0 :col 0 :size_x 4 :size_y 1+ :visualization_settings+ {:virtual_card {:display "link"}+ :link {:url "https://status.example.com"}}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "virtual_link"))+ (is (str/includes? output "https://status.example.com"))))))+ (testing "an entity link card does NOT leak the stored target snapshot (it bypasses read-checks)"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Dashboard {dash-id :id} {}+ :model/DashboardCard _ {:dashboard_id dash-id+ :card_id nil+ :row 0 :col 0 :size_x 4 :size_y 1+ :visualization_settings+ {:virtual_card {:display "link"}+ :link {:entity {:model "card" :id 12345+ :name "Secret Question"}}}}]+ (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (is (str/includes? output "virtual_link"))+ (is (not (str/includes? output "Secret Question"))))))))(deftest read-user-recents-test(mt/with-current-user (mt/user->id :crowberto)