Skip to content

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

Tell Metabot what to do when it can't save a chart

Andrei Simionescu90a166e38c51
diff --git a/src/metabase/metabot/tools/save_entity.clj b/src/metabase/metabot/tools/save_entity.clj
index 64adbc49955..333a07224c7 100644
--- a/src/metabase/metabot/tools/save_entity.clj
+++ b/src/metabase/metabot/tools/save_entity.clj
@@ -9,6 +9,7 @@
only be called when the user asks to save the chart."
(:require
[metabase.api.common :as api]
+ [metabase.app-db.core :as mdb]
[metabase.collections.models.collection :as collection]
[metabase.documents.core :as documents]
[metabase.events.core :as events]
@@ -17,21 +18,43 @@
[metabase.metabot.db :as metabot.db]
[metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
+ [metabase.metabot.tools.core :as tools]
+ [metabase.metabot.tools.error :as tools.error]
+ [metabase.metabot.tools.recoverable.common :as recoverable.common]
[metabase.metabot.tools.shared :as shared]
- [metabase.metabot.tools.util :as metabot.tools.u]
[metabase.queries.core :as queries]
[metabase.query-permissions.core :as query-perms]
[metabase.util.i18n :refer [tru]]
- [metabase.util.malli :as mu]
+ [metabase.util.log :as log]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
+(def ^:private chart-id-schema
+ "A chart ID must fit `report_card.metabot_chart_id`, a `varchar(36)`."
+ [:string {:min 1 :max 36}])
+
+(defn- h2-app-db?
+ "Return whether the app DB is H2, which counts VARCHAR limits in UTF-16 units.
+ PostgreSQL and MySQL count Unicode code points."
+ []
+ (= :h2 (mdb/db-type)))
+
(def ^:private save-entity-schema
[:map {:closed true}
- ;; stamped onto report_card.metabot_chart_id, a varchar(36) — clamp to fit
- [:chart_id [:string {:min 1 :max 36}]]
- [:name :string]
+ [:chart_id chart-id-schema]
+ [:name [:and {:json-schema {:type "string" :minLength 1 :maxLength 254}}
+ :string
+ [:fn {:error/fn (fn [{:keys [value]} _]
+ (if (mr/validate ms/NonBlankString value)
+ (str "must contain 1 to 254 "
+ (if (h2-app-db?) "UTF-16 code units" "Unicode code points"))
+ "must be a non-blank string"))}
+ (fn [^String s]
+ (and (mr/validate ms/NonBlankString s)
+ (<= (if (h2-app-db?) (.length s) (.codePointCount s 0 (.length s))) 254)))]]]
[:description :string]
[:destination
[:multi {:dispatch :target_type}
@@ -50,22 +73,124 @@
[:document_id :int]
[:position {:optional true} [:maybe :int]]]]]]])
-(defn- agent-error! [msg]
- (throw (ex-info msg {:agent-error? true :status-code 400})))
+(tools/defrecoverable no-personal-collection!
+ "The user has no personal collection to use when `collection_id` is omitted."
+ {:payload [:map {:closed true}]}
+ [_]
+ {:message "The user has no personal collection, so `collection_id` can't be omitted."
+ :recovery [{:uses #{"read_resource"}
+ :text (str "Read `metabase://collections?tree=true` with `read_resource` and pass the ID of a"
+ " collection with `can_write=true`.")}
+ {:uses #{}
+ :text "Or ask the user which collection to save it to."}]})
+
+(tools/defrecoverable destination-not-writable!
+ "The user can see the destination but cannot save to it."
+ {:payload [:or
+ [:map {:closed true}
+ [:kind [:enum :collection :dashboard :document]]
+ [:id :int]
+ [:has-personal-collection? :boolean]]
+ ;; The root collection has no ID.
+ [:map {:closed true}
+ [:kind [:= :collection]]
+ [:has-personal-collection? :boolean]]]
+ :status-code 403}
+ [{:keys [kind id has-personal-collection?]}]
+ {:message (str "The user doesn't have permission to save to "
+ (if id (str (name kind) " " id) "the root collection") ".")
+ :recovery [(if has-personal-collection?
+ {:uses #{}
+ :text (str "Tell the user and offer to save the chart to their personal collection."
+ " Omit `collection_id` from a collection destination to use it.")}
+ {:uses #{}
+ :text "Choose another collection, or ask the user which collection to save the chart to."})
+ {:uses #{"read_resource"}
+ :text (str "To offer another collection, read `metabase://collections?tree=true` with"
+ " `read_resource` and pick one with `can_write=true`.")}]})
+
+(defn- check-writable!
+ "Convert a 403 from `check` into [[destination-not-writable!]].
+ `check` must be a write or create permission check for `destination`."
+ [destination check]
+ (try
+ (check)
+ (catch clojure.lang.ExceptionInfo e
+ (if (= 403 (:status-code (ex-data e)))
+ (destination-not-writable!
+ (assoc destination :has-personal-collection?
+ (some? (collection/user->personal-collection api/*current-user-id*))))
+ (throw e)))))
+
+(tools/defrecoverable save-rejected!
+ "The save request was rejected with an API client error."
+ {:payload [:map {:closed true} [:message :string]]}
+ [{:keys [message]}]
+ {:message message :recovery []})
+
+(defn- do-with-save-rejections
+ "Return `thunk`'s result, converting undeclared API 4xx failures into recoverable save errors."
+ [thunk]
+ (try
+ (thunk)
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)
+ status-code (:status-code data)]
+ (if (and (not (contains? data tools.error/error-key))
+ (int? status-code) (<= 400 status-code 499))
+ (save-rejected! {:message (ex-message e)})
+ (throw e))))))
+
+(tools/defrecoverable invalid-query!
+ "The query cannot be saved until its invalid content is corrected."
+ {:payload [:map {:closed true} [:message :string]]}
+ [{:keys [message]}]
+ {:message message
+ :recovery [{:uses #{"construct_notebook_query"}
+ :text (str "Use `construct_notebook_query` to make a chart without the invalid query content,"
+ " then retry with its chart ID.")}]})
+
+(defn- check-query-permissions!
+ "Require permission to run `dataset-query`.
+ A permission refusal ends the turn; invalid query content can be corrected by the agent."
+ [dataset-query]
+ (try
+ (query-perms/check-run-permissions-for-query dataset-query)
+ (catch clojure.lang.ExceptionInfo e
+ (let [status-code (:status-code (ex-data e))]
+ (cond
+ (= 403 status-code)
+ (tools/unrecoverable!
+ ::no-query-permission
+ {:user-message (tru "You can''t save this chart because you don''t have permission to run its query.")
+ :cause e})
+
+ (and (int? status-code) (<= 400 status-code 499))
+ (invalid-query! {:message (ex-message e)})
+
+ :else
+ (throw e))))))
+
+(defn- chart-query
+ "Return the query for `chart`, or nil if none is available."
+ [chart]
+ (or (first (:queries chart))
+ (get (shared/current-queries-state) (:query_id chart))))
(defn- resolve-chart
"Look up the generated chart from agent memory and return the pieces needed to
build a card: a legacy `dataset_query` and a `display` keyword. Mirrors the
lookup in `edit_chart` / `links/resolve-chart-link`."
[chart-id]
- (let [chart (get (shared/current-charts-state) chart-id)
- query (or (first (:queries chart))
- (get (shared/current-queries-state) (:query_id chart)))]
+ (let [charts (shared/current-charts-state)
+ chart (get charts chart-id)
+ query (chart-query chart)]
(when-not query
- (agent-error!
- (tru (str "No generated chart found with id `{0}`. Create a chart with "
- "`construct_notebook_query` first, then save it using the id it returns.")
- chart-id)))
+ (recoverable.common/unknown-chart-id!
+ {:chart-id chart-id
+ :available (sort (for [[id held] charts
+ :when (and (mr/validate chart-id-schema id) (chart-query held))]
+ id))}))
;; agent-created charts carry the display in `:visualization_settings :chart_type`;
;; charts seeded from the frontend viewing context (`seed-charts`) leave that nil
;; and keep the raw config under `:chart_config` instead
@@ -78,9 +203,7 @@
(or (:id (collection/user->personal-collection api/*current-user-id*))
;; API-key users have no personal collection; without this check the nil would
;; silently save into the root collection instead
- (agent-error!
- (tru (str "The current user has no personal collection. Pass an explicit "
- "`collection_id` (or `null` for the root collection) instead.")))))
+ (no-personal-collection! {})))
(defn- collection-name
"Current display name of a collection target, for the LLM-facing save summary.
@@ -90,13 +213,34 @@
(:name (collection/root-collection-with-ui-details nil))
(metabot.db/collection-name collection-id)))
+(tools/defrecoverable destination-archived!
+ "The destination is in the trash."
+ {:payload [:map {:closed true}
+ [:kind [:enum :dashboard :document]]
+ [:id :int]]
+ :status-code 404}
+ [{:keys [kind id]}]
+ {:message (str (case kind :dashboard "Dashboard" :document "Document") " " id " is in the trash.")
+ :recovery [{:uses #{}
+ :text "Ask the user to restore it or choose another destination."}]})
+
+(defn- check-not-archived!
+ "Reject a destination in the trash and return it otherwise."
+ [destination entity]
+ (when (:archived entity)
+ (destination-archived! destination))
+ entity)
+
(defn- save-to-collection!
[{:keys [name description dataset_query display destination]}]
(let [collection-id (if (contains? destination :collection_id)
(:collection_id destination)
(personal-collection-id))]
- (query-perms/check-run-permissions-for-query dataset_query)
- (api/create-check :model/Card {:collection_id collection-id})
+ (when collection-id
+ (tools/with-entity {:kind :collection :id collection-id}
+ (api/read-check :model/Collection collection-id)))
+ (check-writable! (cond-> {:kind :collection} collection-id (assoc :id collection-id))
+ #(api/create-check :model/Card {:collection_id collection-id}))
(let [card (queries/create-card!
{:name name
:description description
@@ -113,11 +257,12 @@
(defn- save-to-dashboard!
[{:keys [name description dataset_query display destination]}]
- (let [dashboard-id (:dashboard_id destination)]
- (when-not dashboard-id
- (agent-error! (tru "A `dashboard_id` is required when saving to a dashboard.")))
- (query-perms/check-run-permissions-for-query dataset_query)
- (api/write-check :model/Dashboard dashboard-id)
+ (let [dashboard-id (:dashboard_id destination)
+ dashboard (check-not-archived!
+ {:kind :dashboard :id dashboard-id}
+ (tools/with-entity {:kind :dashboard :id dashboard-id}
+ (api/read-check :model/Dashboard dashboard-id)))]
+ (check-writable! {:kind :dashboard :id dashboard-id} #(api/write-check dashboard))
(let [card (queries/create-card!
{:name name
:description description
@@ -134,70 +279,85 @@
(defn- save-to-document!
[{:keys [name description dataset_query display destination]}]
- (let [document-id (:document_id destination)]
- (when-not document-id
- (agent-error! (tru "A `document_id` is required when saving to a document.")))
- (query-perms/check-run-permissions-for-query dataset_query)
- (let [document (api/write-check (documents/get-document document-id :log-view? false))
- _ (api/check-not-archived document)
- card (queries/create-card!
- {:name name
- :description description
- :dataset_query dataset_query
- :display display
- :visualization_settings {}
- :collection_id (:collection_id document)
- :document_id document-id}
- {:id api/*current-user-id*}
- :delay-event)]
+ (let [document-id (:document_id destination)
+ document (check-not-archived!
+ {:kind :document :id document-id}
+ (tools/with-entity {:kind :document :id document-id}
+ (documents/get-document document-id :log-view? false)))]
+ (check-writable! {:kind :document :id document-id} #(api/write-check document))
+ (let [card (queries/create-card!
+ {:name name
+ :description description
+ :dataset_query dataset_query
+ :display display
+ :visualization_settings {}
+ :collection_id (:collection_id document)
+ :document_id document-id}
+ {:id api/*current-user-id*}
+ :delay-event)]
(documents/add-card-to-document! document-id (:id card) (:position destination))
{:card card
:destination {:type "document" :id document-id}
:destination-name (:name document)
:link (str "metabase://document/" document-id)})))
-(mu/defn ^{:tool-name "save_entity"
- :scope scope/agent-question-create}
- save-entity-tool
- "Save a chart you previously created into a collection, a dashboard, or a document.
-
- ONLY call this when the user explicitly asks to save, keep, or add the chart
- somewhere. Reference the chart by the `chart_id` you were given when it was
- created. Provide a `name` and a concise `description` for the saved question
- (reuse the chart's description).
-
- Choose a `destination`:
- - To save into a collection, set `target_type` to `collection` and pass a
- `collection_id`. Inspect available collections first with
- `read_resource` on `metabase://collections?tree=true`. Omit `collection_id`
- to use the user's personal collection; pass `null` for the root collection.
- - To add it to a dashboard, set `target_type` to `dashboard` and pass a
- `dashboard_id`. Find dashboards with your search/discovery tool — if that tool is
- `search`, restrict `entity_types` to the `dashboard` type. Only offer or use results
- with `can_write=true`; results
- with `can_write=false` are visible but read-only and cannot be save destinations.
- - To embed it in a document, set `target_type` to `document` and pass a
- `document_id`. Find documents the same way — with `search`, restrict `entity_types` to
- the `document` type, just as you would use the `dashboard` type to find dashboards. Search
- using any name or topic the user provided. Before calling `save_entity`, you MUST call
- `read_resource` on `metabase://document/{id}` for the selected result and inspect its
- contents. Only save after that read succeeds and reports `can_write=true`. If it returns
- `can_write=false`, an error, or Not found,
- discard that search result and do not call `save_entity` with its id. If there are
- multiple plausible targets, ask the user which one they mean. Optionally pass `position` — the 0-based index among the
- document's top-level blocks where the chart is inserted (`0` puts it at the
- very top). Omit `position` to append the chart at the end. To pick a
- meaningful position, first inspect the document's blocks with
- `read_resource` on `metabase://document/{id}`.
-
- If your only discovery tool returns library data entities (tables, models, metrics) rather
- than saved content, dashboards and documents aren't discoverable that way — save to a
- collection instead, or ask the user for the dashboard or document they mean.
-
- After saving, tell the user where it went and share the returned link."
- [{:keys [chart_id destination description] question-name :name} :- save-entity-schema]
+(defn- publish-card-create!
+ "Publish the `:event/card-create` event for a card that has already been committed.
+ Log failures without throwing."
+ [card]
(try
+ (events/publish-event! :event/card-create {:object card :user-id api/*current-user-id*})
+ (catch Exception e
+ ;; The agent may retry a failed call and save a second copy of the card.
+ (log/error e "Failed to publish the card-create event for a card saved by Metabot" {:card-id (:id card)}))))
+
+(def ^:private tool-description
+ "Describe how to call `save_entity`."
+ (str
+ "Save a chart to a collection, dashboard or document. Use a chart that you previously created.\n"
+ "\n"
+ "ONLY call this when the user explicitly asks to save, keep or add the chart somewhere.\n"
+ "Use the `chart_id` that you received when the chart was created. Provide a `name` and a concise\n"
+ "`description` for the saved question, reusing the chart's description.\n"
+ "\n"
+ "Choose a `destination`:\n"
+ "- To save into a collection, set `target_type` to `collection` and pass a\n"
+ " `collection_id`. Inspect available collections first with\n"
+ " `read_resource` on `metabase://collections?tree=true`. Omit `collection_id`\n"
+ " to use the user's personal collection; pass `null` for the root collection.\n"
+ "- To add it to a dashboard, set `target_type` to `dashboard` and pass a\n"
+ " `dashboard_id`. Find dashboards with your search or discovery tool. If you use `search`,\n"
+ " restrict `entity_types` to the `dashboard` type. Only offer or use results with `can_write=true`;\n"
+ " results with `can_write=false` are visible but read-only and cannot be save destinations.\n"
+ "- To embed it in a document, set `target_type` to `document` and pass a\n"
+ " `document_id`. Find documents with your search or discovery tool. If you use `search`,\n"
+ " restrict `entity_types` to the `document` type and search using any name or topic that the\n"
+ " user provided. Before calling `save_entity`, you MUST call `read_resource` on\n"
+ " `metabase://document/{id}` for the selected result and inspect its contents. Only save after\n"
+ " that read succeeds and reports `can_write=true`. If it returns `can_write=false`, an error\n"
+ " or Not found, discard the result and do not call `save_entity` with its ID. Ask the user\n"
+ " which document they mean if several results are plausible. You can pass `position`, the\n"
+ " 0-based index among the document's top-level blocks where the chart is inserted (`0` puts\n"
+ " it at the top). Omit `position` to append the chart at the end. Read the document's blocks\n"
+ " with `read_resource` on `metabase://document/{id}` before choosing a position.\n"
+ "\n"
+ "If your only discovery tool returns library data entities (tables, models or metrics), it\n"
+ "cannot find dashboards or documents. Save to a collection instead, or ask the user for the\n"
+ "dashboard or document they mean.\n"
+ "\n"
+ "After saving, tell the user where it went and share the returned link."))
+
+(defrecord SaveEntityTool []
+ tools/Tool
+ (declaration [_]
+ {:name "save_entity"
+ :description tool-description
+ :scope scope/agent-question-create
+ :args save-entity-schema})
+
+ (handle [_ {:keys [chart_id destination description] question-name :name} _ctx]
(let [{:keys [dataset_query display]} (resolve-chart chart_id)
+ _ (check-query-permissions! dataset_query)
args {:name question-name
:description description
:dataset_query dataset_query
@@ -210,16 +370,16 @@
;; event is delayed until after the transaction commits so subscribers see
;; the card.
{:keys [card link destination-name] saved-destination :destination}
- (t2/with-transaction [_conn]
- (let [saved (case (:target_type destination)
- "collection" (save-to-collection! args)
- "dashboard" (save-to-dashboard! args)
- "document" (save-to-document! args))]
- (when-let [conversation-id (shared/current-conversation-id)]
- (metabot.db/link-card-to-conversation! (:id (:card saved)) conversation-id chart_id))
- saved))
- _ (events/publish-event! :event/card-create
- {:object card :user-id api/*current-user-id*})
+ (do-with-save-rejections
+ #(t2/with-transaction [_conn]
+ (let [saved (case (:target_type destination)
+ "collection" (save-to-collection! args)
+ "dashboard" (save-to-dashboard! args)
+ "document" (save-to-document! args))]
+ (when-let [conversation-id (shared/current-conversation-id)]
+ (metabot.db/link-card-to-conversation! (:id (:card saved)) conversation-id chart_id))
+ saved)))
+ _ (publish-card-create! card)
instruction-text (te/lines
(str "Saved \"" question-name "\" to " destination-name ".")
""
@@ -238,6 +398,8 @@
:destination saved-destination
;; markdown entity link the chain-of-thought renders
;; as the settled "Saved …" step label
- :title (te/link question-name link)})]})
- (catch Exception e
- (metabot.tools.u/handle-agent-or-api-error e))))
+ :title (te/link question-name link)})]})))
+
+(def save-entity-tool
+ "Save a chart from this conversation as a question in a collection, dashboard or document."
+ (->SaveEntityTool))
diff --git a/test/metabase/metabot/tools/save_entity_test.clj b/test/metabase/metabot/tools/save_entity_test.clj
index f3987fa2874..ece0da47b5e 100644
--- a/test/metabase/metabot/tools/save_entity_test.clj
+++ b/test/metabase/metabot/tools/save_entity_test.clj
@@ -1,15 +1,32 @@
(ns metabase.metabot.tools.save-entity-test
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
+ [malli.json-schema :as mjs]
+ [metabase.api-scope.core :as api-scope]
+ [metabase.app-db.core :as mdb]
+ [metabase.documents.core :as documents]
+ [metabase.events.core :as events]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.metabot.scope :as scope]
+ [metabase.metabot.test-util :as test-util]
+ [metabase.metabot.tools :as metabot.tools]
+ [metabase.metabot.tools.core :as tools.core]
+ [metabase.metabot.tools.error :as tools.error]
+ [metabase.metabot.tools.recoverable.common :as recoverable.common]
[metabase.metabot.tools.save-entity :as save-entity]
[metabase.metabot.tools.shared :as shared]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.queries.core :as queries]
[metabase.test :as mt]
[metabase.util.json :as json]
+ [metabase.util.malli.registry :as mr]
[toucan2.core :as t2]))
+(set! *warn-on-reflection* true)
+
(defn- venues-query []
(lib/query (mt/metadata-provider)
(lib.metadata/table (mt/metadata-provider) (mt/id :venues))))
@@ -39,13 +56,29 @@
:visualization_settings {:chart_type "bar"}}}}
:context {}})))
+(def ^:private chart-args
+ {:chart_id "c-1"
+ :name "Venues by price"
+ :description "Count of venues grouped by price."})
+
+(def ^:private tool-names
+ "List the tools needed to show every recovery step in these tests."
+ #{"search" "read_resource" "construct_notebook_query" "create_chart"})
+
+(defn- call-save-entity [args]
+ (test-util/call-tool save-entity/save-entity-tool args))
+
(defn- save! [destination]
(binding [shared/*memory-atom* (chart-memory)]
- (save-entity/save-entity-tool
- {:chart_id "c-1"
- :name "Venues by price"
- :description "Count of venues grouped by price."
- :destination destination})))
+ (call-save-entity (assoc chart-args :destination destination))))
+
+(defn- failure
+ "Return the error class and code, plus any recoverable error text shown to the model."
+ ([destination]
+ (failure (chart-memory) (assoc chart-args :destination destination)))
+ ([memory args]
+ (binding [shared/*memory-atom* memory]
+ (test-util/tool-failure save-entity/save-entity-tool args tool-names))))
(deftest save-to-collection-test
(mt/with-current-user (mt/user->id :crowberto)
@@ -74,7 +107,7 @@
(mt/with-model-cleanup [:model/Card]
(mt/with-temp [:model/Collection coll {:name "Persisted charts"}]
(let [result (binding [shared/*memory-atom* (rehydrated-chart-memory)]
- (save-entity/save-entity-tool
+ (call-save-entity
{:chart_id "c-1"
:name "Venues by price"
:description "Count of venues grouped by price."
@@ -89,7 +122,7 @@
:model/MetabotConversation {convo-id :id} {:user_id (mt/user->id :crowberto)}]
(let [memory (doto (chart-memory) (swap! assoc :conversation-id convo-id))
result (binding [shared/*memory-atom* memory]
- (save-entity/save-entity-tool
+ (call-save-entity
{:chart_id "c-1"
:name "Venues by price"
:description "Count of venues grouped by price."
@@ -155,7 +188,7 @@
:chart_config {:display_type "line"}}}}
:context {}})
result (binding [shared/*memory-atom* memory]
- (save-entity/save-entity-tool
+ (call-save-entity
{:chart_id "c-2"
:name "Seeded chart"
:description "Seeded from the viewing context."
@@ -204,37 +237,277 @@
(second (:content document-ast))]
(get-in (t2/select-one :model/Document :id (:id doc)) [:document :content])))))))))
-(deftest save-to-document-requires-id-test
- (mt/with-current-user (mt/user->id :crowberto)
- (testing "a missing document_id fails destination schema validation"
- (is (thrown-with-msg? clojure.lang.ExceptionInfo
- #"document_id"
- (save! {:target_type "document"}))))))
+(deftest ^:parallel arguments-the-schema-refuses-test
+ (testing "a document destination needs a document_id"
+ (is (=? #"Invalid tool arguments: `destination` .*"
+ (test-util/tool-boundary-error "save_entity" #'save-entity/save-entity-tool
+ (assoc chart-args :destination {:target_type "document"})))))
+ (testing "a name must fit the application database column"
+ (is (=? #"Invalid tool arguments: `name` must contain 1 to 254 .*"
+ (test-util/tool-boundary-error "save_entity" #'save-entity/save-entity-tool
+ (assoc chart-args
+ :name (apply str (repeat 255 "x"))
+ :destination {:target_type "collection"}))))))
-(deftest unknown-chart-test
- (mt/with-current-user (mt/user->id :crowberto)
- (testing "a missing chart id returns an agent-facing error and creates nothing"
- (let [result (binding [shared/*memory-atom* (chart-memory)]
- (save-entity/save-entity-tool
- {:chart_id "does-not-exist"
- :name "x"
- :description "y"
- :destination {:target_type "collection" :collection_id nil}}))]
- (is (nil? (:data-parts result)))
- (is (re-find #"No generated chart found" (:output result)))))))
-
-(deftest save-entity-errors-test
- (testing "a dashboard that doesn't exist goes back to the agent as output"
- (mt/with-current-user (mt/user->id :crowberto)
- (is (= "Not found." (:output (save! {:target_type "dashboard" :dashboard_id Integer/MAX_VALUE}))))))
- (testing "a collection the user can't write to goes back to the agent as output"
+(deftest ^:parallel name-length-matches-app-db-test
+ (let [args-schema (:args (tools.core/declaration save-entity/save-entity-tool))
+ ^String ducks (apply str (repeat 128 "\uD83E\uDD86"))]
+ (is (= [256 128] [(.length ducks) (.codePointCount ducks 0 (.length ducks))]))
+ (doseq [db-type [:h2 :postgres :mysql]]
+ (testing (str "the name limit matches " db-type)
+ (mt/with-dynamic-fn-redefs [mdb/db-type (constantly db-type)]
+ (is (= (not= :h2 db-type)
+ (mr/validate args-schema (assoc chart-args :name ducks :destination {:target_type "collection"})))))))
+ (testing "the tool schema gives the LLM the same name length limit"
+ (is (= {:type "string" :minLength 1 :maxLength 254}
+ (get-in (mjs/transform args-schema) [:properties :name]))))))
+
+(deftest ^:parallel unknown-chart-test
+ (let [args (assoc chart-args :chart_id "c-9" :destination {:target_type "collection" :collection_id nil})]
+ (testing "an unknown chart ID produces a recoverable error that lists the available IDs"
+ (is (=? {:class :recoverable
+ :code ::recoverable.common/unknown-chart-id
+ :text (str "No chart with ID \"c-9\" exists in this conversation. The available chart IDs are c-1.\n"
+ "To make a new chart, call `construct_notebook_query` and use the chart ID that it returns.\n"
+ "To chart a query from this conversation, call `create_chart` with its"
+ " query ID.")}
+ (failure (chart-memory) args))))
+ (testing "charts without a query or with an ID longer than 36 characters are not offered"
+ (let [long-id (apply str (repeat 37 "a"))
+ memory (doto (chart-memory)
+ (swap! update-in [:state :charts] assoc
+ "c-2" {:chart_id "c-2" :queries [nil]}
+ long-id {:chart_id long-id :queries [(venues-query)]}))]
+ (is (str/includes? (:text (failure memory args)) "The available chart IDs are c-1.\n"))))
+ (testing "the error says when the conversation has no charts"
+ (is (str/includes? (:text (failure (atom {}) args)) "No charts have been created in this conversation yet.")))))
+
+(deftest no-personal-collection-test
+ (mt/with-temp [:model/User {user-id :id} {:type :api-key}]
+ (mt/with-current-user user-id
+ (testing "a user without a personal collection gets instructions for choosing a collection"
+ (is (= {:class :recoverable
+ :code ::save-entity/no-personal-collection
+ :text (str "The user has no personal collection, so `collection_id` can't be omitted.\n"
+ "Read `metabase://collections?tree=true` with `read_resource` and pass the ID of a"
+ " collection with `can_write=true`.\n"
+ "Or ask the user which collection to save it to.")}
+ (failure {:target_type "collection"})))))))
+
+(deftest unreadable-destination-test
+ (testing "a destination that is hidden from the user or does not exist is reported as not found"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection hidden {}
+ :model/Dashboard trashed-dash {:collection_id (:id hidden) :archived true}
+ :model/Document trashed-doc {:collection_id (:id hidden)
+ :archived true :document document-ast}]
+ (doseq [[user target-type id] [[:rasta "collection" (:id hidden)]
+ [:rasta "dashboard" (:id trashed-dash)]
+ [:rasta "document" (:id trashed-doc)]
+ [:crowberto "dashboard" Integer/MAX_VALUE]
+ [:crowberto "document" Integer/MAX_VALUE]]
+ :let [entity (str (str/capitalize target-type) " " id)]]
+ (testing (str (name user) " saving to " entity)
+ (mt/with-current-user (mt/user->id user)
+ (is (=? {:class :recoverable
+ :code ::recoverable.common/not-found
+ :text #(str/starts-with? % (str entity " was not found."))}
+ (failure {:target_type target-type, (keyword (str target-type "_id")) id})))))))))))
+
+(deftest read-only-destination-test
+ (testing "a read-only destination produces a recoverable error that offers another collection"
(mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}
+ :model/Dashboard dash {:collection_id (:id coll)}
+ :model/Document doc {:collection_id (:id coll) :document document-ast}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll)
+ (mt/with-current-user (mt/user->id :rasta)
+ (doseq [[destination noun] [[{:target_type "collection" :collection_id (:id coll)}
+ (str "collection " (:id coll))]
+ [{:target_type "collection" :collection_id nil} "the root collection"]
+ [{:target_type "dashboard" :dashboard_id (:id dash)}
+ (str "dashboard " (:id dash))]
+ [{:target_type "document" :document_id (:id doc)}
+ (str "document " (:id doc))]]]
+ (testing noun
+ (is (= {:class :recoverable
+ :code ::save-entity/destination-not-writable
+ :text (str "The user doesn't have permission to save to " noun ".\n"
+ "Tell the user and offer to save the chart to their personal collection."
+ " Omit `collection_id` from a collection destination to use it.\n"
+ "To offer another collection, read `metabase://collections?tree=true` with"
+ " `read_resource` and pick one with `can_write=true`.")}
+ (failure destination)))))
+ (testing "no card is saved in the read-only collection"
+ (is (not (t2/exists? :model/Card :collection_id (:id coll)))))))))))
+
+(deftest unrunnable-query-test
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-current-user (mt/user->id :rasta)
+ (testing "a chart cannot be saved when the user lacks permission to run its query"
+ (is (= {:class :unrecoverable
+ :code ::save-entity/no-query-permission
+ :user-message "You can't save this chart because you don't have permission to run its query."}
+ (tools.error/classify
+ (is (thrown? clojure.lang.ExceptionInfo (save! {:target_type "collection"}))))))))))
+
+(defn- invoke-save-entity
+ "Call `save_entity` with `args` through the tool runtime, in a conversation whose memory is `memory`, and return the
+ outcome. The profile also offers the tools that the recovery steps name."
+ ([args]
+ (invoke-save-entity (chart-memory) args))
+ ([memory args]
+ (let [entries (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (metabot.tools/->entries [#'save-entity/save-entity-tool
+ #'metabot.tools/construct-notebook-query-tool
+ #'metabot.tools/create-chart-tool]
+ memory nil :internal))]
+ ((:fn (get entries "save_entity")) args))))
+
+(deftest unknown-chart-among-many-test
+ (testing "with more than 30 charts, the error lists the first 30 and counts the rest, so the recovery steps fit"
+ (let [query (venues-query)
+ ids (map #(format "%08d-0000-4000-8000-000000000000" %) (range 120))
+ memory (atom {:state {:charts (into {} (map (fn [id] [id {:chart_id id :queries [query]}])) ids)}})]
+ (is (= {:output (str "No chart with ID \"c-9\" exists in this conversation. The available chart IDs are "
+ (str/join ", " (take 30 ids)) " and 90 more.\n"
+ "To make a new chart, call `construct_notebook_query` and use the chart ID that it returns.\n"
+ "To chart a query from this conversation, call `create_chart` with its query ID.")
+ :error {:class :recoverable :code ::recoverable.common/unknown-chart-id}}
+ (invoke-save-entity memory (assoc chart-args
+ :chart_id "c-9"
+ :destination {:target_type "collection" :collection_id nil})))))))
+
+(deftest card-create-event-failure-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
(mt/with-temp [:model/Collection coll {}]
- (mt/with-current-user (mt/user->id :rasta)
- (is (= "You don't have permissions to do that."
- (:output (save! {:target_type "collection" :collection_id (:id coll)}))))))))
- (testing "an unexpected error propagates to the agent loop"
+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic _event]
+ (when (= :event/card-create topic)
+ (throw (ex-info "A subscriber failed." {}))))]
+ (testing "the save succeeds and creates one card even when a card-create subscriber fails"
+ (let [outcome (invoke-save-entity
+ (assoc chart-args :destination {:target_type "collection" :collection_id (:id coll)}))]
+ (is (nil? (:error outcome)))
+ (is (= [(get-in outcome [:structured-output :card-id])]
+ (t2/select-pks-vec :model/Card :collection_id (:id coll)))))))))))
+
+(deftest undeclared-failure-test
+ (testing "an unexpected failure ends the turn without reaching the model"
(mt/with-dynamic-fn-redefs [queries/create-card! (fn [& _] (throw (ex-info "boom" {})))]
(mt/with-current-user (mt/user->id :crowberto)
- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"
- (save! {:target_type "collection" :collection_id nil})))))))
+ (is (= {:class :unrecoverable :code :internal}
+ (failure {:target_type "collection" :collection_id nil})))))))
+
+(deftest transaction-api-error-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}
+ :model/Document doc {:document document-ast}]
+ (testing "4xx failures during card creation reach the agent with their message"
+ (doseq [status [400 403 404 409 422 499]]
+ (mt/with-dynamic-fn-redefs [queries/create-card!
+ (fn [& _]
+ (throw (ex-info "Uses content that is not remote synced."
+ {:status-code status})))]
+ (is (=? {:error {:class :recoverable :code ::save-entity/save-rejected}
+ :output #"Uses content that is not remote synced\."}
+ (invoke-save-entity
+ (assoc chart-args :destination {:target_type "collection" :collection_id (:id coll)})))))))
+ (testing "a failed document insertion rolls back the card and returns its reason"
+ (mt/with-dynamic-fn-redefs [documents/add-card-to-document!
+ (fn [& _]
+ (throw (ex-info "Uses content that is not remote synced."
+ {:status-code 400})))]
+ (is (=? {:error {:class :recoverable :code ::save-entity/save-rejected}
+ :output #"Uses content that is not remote synced\."}
+ (invoke-save-entity
+ (assoc chart-args :destination {:target_type "document" :document_id (:id doc)}))))
+ (is (not (t2/exists? :model/Card :document_id (:id doc))))))))))
+
+(deftest transaction-server-error-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-dynamic-fn-redefs [queries/create-card!
+ (fn [& _] (throw (ex-info "Private save failure." {:status-code 500})))]
+ (is (= {:error {:class :unrecoverable :code :internal}
+ :output "This call failed and the user was shown the error (:internal). Don't retry it."}
+ (invoke-save-entity (assoc chart-args :destination {:target_type "collection"})))))))
+
+(deftest sensitive-query-test
+ (let [provider (mt/metadata-provider)
+ query (-> (lib/query provider (lib.metadata/table provider (mt/id :users)))
+ (lib/filter (lib/= (lib.metadata/field provider (mt/id :users :password)) "secret")))
+ memory (chart-memory)]
+ (swap! memory assoc-in [:state :charts "c-1" :queries] [query])
+ (mt/with-current-user (mt/user->id :rasta)
+ (testing "a sensitive-field refusal reaches the agent as a query error it can fix"
+ (is (=? {:error {:class :recoverable :code ::save-entity/invalid-query}
+ :output #(str/starts-with? % "This query refers to a field that is not available for querying.")}
+ (invoke-save-entity memory (assoc chart-args :destination {:target_type "collection"}))))))))
+
+(deftest read-only-destination-without-personal-collection-test
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/User {user-id :id} {:type :api-key}
+ :model/Collection coll {}
+ :model/Dashboard dash {:collection_id (:id coll)}
+ :model/Document doc {:collection_id (:id coll) :document document-ast}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll)
+ (mt/with-current-user user-id
+ (doseq [destination [{:target_type "collection" :collection_id (:id coll)}
+ {:target_type "collection" :collection_id nil}
+ {:target_type "dashboard" :dashboard_id (:id dash)}
+ {:target_type "document" :document_id (:id doc)}]]
+ (let [{:keys [class code text]} (failure destination)]
+ (is (= [:recoverable ::save-entity/destination-not-writable] [class code]))
+ (is (str/includes? text "`can_write=true`"))
+ (is (str/includes? text "ask the user"))
+ (is (not (str/includes? text "personal collection")))))))))
+
+(deftest h2-emoji-name-test
+ (when (= :h2 (mdb/db-type))
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}]
+ (doseq [[question-name expected-class] [[(apply str (repeat 140 "\uD83E\uDD86")) :validation]
+ [(apply str (repeat 128 "\uD83E\uDD86")) :validation]
+ [(apply str (repeat 127 "\uD83E\uDD86")) nil]
+ [(apply str (repeat 254 "x")) nil]]]
+ (let [outcome (invoke-save-entity
+ (assoc chart-args
+ :name question-name
+ :destination {:target_type "collection" :collection_id (:id coll)}))]
+ (is (= expected-class (get-in outcome [:error :class])))
+ (when-not expected-class
+ (is (= question-name
+ (t2/select-one-fn :name :model/Card :id (get-in outcome [:structured-output :card-id])))))))
+ (is (= 2 (t2/count :model/Card :collection_id (:id coll)))))))))
+
+(deftest trashed-destination-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Dashboard dash {:archived true}
+ :model/Document doc {:archived true :document document-ast}]
+ (doseq [[kind id] [["dashboard" (:id dash)] ["document" (:id doc)]]]
+ (is (= {:class :recoverable
+ :code ::save-entity/destination-archived
+ :text (str (str/capitalize kind) " " id " is in the trash.\n"
+ "Ask the user to restore it or choose another destination.")}
+ (failure {:target_type kind (keyword (str kind "_id")) id}))))
+ (is (not (t2/exists? :model/Card :dashboard_id (:id dash))))
+ (is (not (t2/exists? :model/Card :document_id (:id doc))))))))
+
+(deftest blank-name-test
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection coll {}]
+ (doseq [question-name ["" " " "\t\r\n"]]
+ (let [outcome (invoke-save-entity
+ (assoc chart-args
+ :name question-name
+ :destination {:target_type "collection" :collection_id (:id coll)}))]
+ (is (= {:class :validation :code :invalid-arguments} (:error outcome)))
+ (is (= "Invalid tool arguments: `name` must be a non-blank string; received a string."
+ (:output outcome)))))
+ (is (not (t2/exists? :model/Card :collection_id (:id coll))))))))